Skip to main content
Glama
lgariv
by lgariv

Run Remote Command

ssh_run

Execute remote commands on servers via SSH to run non-interactive tasks and retrieve execution results including output, errors, and status codes.

Instructions

Runs a non-interactive command remotely over SSH and returns stdout, stderr, and exit code

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesCommand to run remotely

Implementation Reference

  • The main handler function for the 'ssh_run' tool. It establishes an SSH connection, executes the provided command using runRemoteCommand, formats the output as JSON, and handles errors.
    async ({ command }) => {
      try {
        const ssh = await createSshConnection();
        try {
          const result = await runRemoteCommand(ssh, command);
          ssh.end();
          const text = JSON.stringify(
            { command, ...result, stdout: result.stdout.trim(), stderr: result.stderr.trim() },
            null,
            2
          );
          return { content: [{ type: "text", text }] };
        } finally {
          ssh.end();
        }
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return { content: [{ type: "text", text: `SSH command failed: ${message}` }], isError: true };
      }
    }
  • Input schema for the 'ssh_run' tool defining the 'command' parameter using Zod.
    inputSchema: { command: z.string().min(1).describe("Command to run remotely") },
  • src/index.ts:111-138 (registration)
    Registration of the 'ssh_run' tool on the McpServer instance, including schema and handler.
    server.registerTool(
      "ssh_run",
      {
        title: "Run Remote Command",
        description: "Runs a non-interactive command remotely over SSH and returns stdout, stderr, and exit code",
        inputSchema: { command: z.string().min(1).describe("Command to run remotely") },
      },
      async ({ command }) => {
        try {
          const ssh = await createSshConnection();
          try {
            const result = await runRemoteCommand(ssh, command);
            ssh.end();
            const text = JSON.stringify(
              { command, ...result, stdout: result.stdout.trim(), stderr: result.stderr.trim() },
              null,
              2
            );
            return { content: [{ type: "text", text }] };
          } finally {
            ssh.end();
          }
        } catch (error) {
          const message = error instanceof Error ? error.message : String(error);
          return { content: [{ type: "text", text: `SSH command failed: ${message}` }], isError: true };
        }
      }
    );
  • Helper function to execute a command over an established SSH connection and capture stdout, stderr, and exit code.
    async function runRemoteCommand(ssh: SSHClient, command: string): Promise<{ exitCode: number; stdout: string; stderr: string }>{
      return await new Promise((resolve, reject) => {
        ssh.exec(command, (err: Error | undefined, stream: ClientChannel) => {
          if (err) return reject(err);
          let stdout = "";
          let stderr = "";
          stream
            .on("close", (code: number) => {
              resolve({ exitCode: code ?? 0, stdout, stderr });
            })
            .on("data", (data: Buffer) => {
              stdout += data.toString();
            })
            .stderr.on("data", (data: Buffer) => {
              stderr += data.toString();
            });
        });
      });
    }
  • Helper function to create and connect an SSH client using environment variables.
    async function createSshConnection(): Promise<SSHClient> {
      const env = getEnv();
      const ssh = new SSHClient();
      const config: ConnectConfig = {
        host: env.SSH_HOST,
        port: Number(env.SSH_PORT),
        username: env.SSH_USERNAME,
        password: env.SSH_PASSWORD,
        readyTimeout: 15000,
        tryKeyboard: false,
        algorithms: {
          // Keep defaults; allow host key algo negotiation modern-first
        },
      };
      await new Promise<void>((resolve, reject) => {
        ssh
          .on("ready", () => resolve())
          .on("error", (err: Error) => reject(err))
          .connect(config);
      });
      return ssh;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool returns 'stdout, stderr, and exit code', which is useful, but lacks critical details like authentication requirements (e.g., SSH key or password), error handling (e.g., connection failures), rate limits, or whether it modifies remote systems. For a tool that executes remote commands, this is a significant gap in safety and operational context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the core functionality ('runs a non-interactive command remotely over SSH') and includes the return values. There is zero wasted text, and every word earns its place by conveying essential information without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of SSH command execution (involving remote systems, authentication, and potential side effects), the description is incomplete. With no annotations to cover safety or behavioral traits, and no output schema to detail return values beyond a brief mention, the description fails to provide enough context for safe and effective use. It should address authentication, error scenarios, or destructive potential.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, with the single parameter 'command' well-documented in the schema. The description adds no additional meaning beyond what the schema provides (e.g., no examples, constraints, or usage tips for the command parameter). Given the high schema coverage, a baseline score of 3 is appropriate as the description doesn't compensate but also doesn't detract.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('runs a non-interactive command remotely over SSH') and the resource ('command'), distinguishing it from the sibling tool 'ssh_test_connection' which likely tests connectivity rather than executing commands. The verb+resource combination is precise and unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus the sibling 'ssh_test_connection' or any alternatives. It mentions 'non-interactive' but doesn't explain when interactive commands might be needed or what other tools could handle them. No usage context or exclusions are provided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/lgariv/ssh-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server