Skip to main content
Glama

ssh_exec

Execute commands on remote SSH servers using natural language, with options for connection selection, working directory, and timeout.

Instructions

Execute a command on an SSH server

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesCommand to execute
connectionIdNoConnection ID (optional, uses most recent if not provided)
timeoutNoCommand timeout in milliseconds (optional)
cwdNoWorking directory (optional)

Implementation Reference

  • src/index.ts:80-105 (registration)
    Tool registration for ssh_exec in ListToolsRequestSchema handler. Defines name, description, and inputSchema with parameters: command (required), connectionId, timeout, cwd (all optional).
    {
      name: 'ssh_exec',
      description: 'Execute a command on an SSH server',
      inputSchema: {
        type: 'object',
        properties: {
          command: {
            type: 'string',
            description: 'Command to execute',
          },
          connectionId: {
            type: 'string',
            description: 'Connection ID (optional, uses most recent if not provided)',
          },
          timeout: {
            type: 'number',
            description: 'Command timeout in milliseconds (optional)',
          },
          cwd: {
            type: 'string',
            description: 'Working directory (optional)',
          },
        },
        required: ['command'],
      },
    },
  • Main handler for ssh_exec tool call in CallToolRequestSchema switch statement. Extracts command, connectionId, timeout, cwd from args and delegates to sshManager.exec().
    case 'ssh_exec': {
      const command = args.command as string;
      const connectionId = args.connectionId as string | undefined;
      const timeout = args.timeout as number | undefined;
      const cwd = args.cwd as string | undefined;
      try {
        const result = await sshManager.exec(command, connectionId, { timeout, cwd });
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(result, null, 2),
            },
          ],
        };
      } catch (err: unknown) {
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({ error: err instanceof Error ? err.message : String(err) }, null, 2),
            },
          ],
          isError: true,
        };
      }
    }
  • Core exec method in SSHManager class. Finds the connection (by ID or most recent), checks if busy, optionally changes directory via shell-escaped cd, executes command via ssh2 Client.exec(), collects stdout/stderr/exitCode/duration, and handles timeouts.
    async exec(
      command: string,
      connectionId?: string,
      options?: { timeout?: number; cwd?: string }
    ): Promise<ExecResult> {
      const conn = this.getConnection(connectionId);
      if (!conn) {
        throw new Error('No connection available');
      }
      if (conn.isBusy) {
        throw new Error('Connection is busy');
      }
    
      conn.isBusy = true;
      conn.lastActivity = new Date();
      const startTime = Date.now();
    
      // Log command execution if enabled
      if (this.logCommands) {
        console.error(`[SSH] Executing: ${command}${options?.cwd ? ` (cwd: ${options.cwd})` : ''}`);
      }
    
      try {
        // Use shell escape to prevent command injection
        const fullCommand = options?.cwd
          ? `cd ${shellEscape(options.cwd)} && ${command}`
          : command;
    
        return await new Promise((resolve, reject) => {
          const timeoutMs = options?.timeout || this.commandTimeout;
          const timeout = setTimeout(() => {
            reject(new Error('Command timeout'));
          }, timeoutMs);
    
          conn.client.exec(fullCommand, (err, stream) => {
            if (err) {
              clearTimeout(timeout);
              reject(err);
              return;
            }
    
            let stdout = '';
            let stderr = '';
            let exitCode = 0;
    
            stream.on('data', (data: Buffer) => {
              stdout += data.toString();
            });
    
            stream.stderr.on('data', (data: Buffer) => {
              stderr += data.toString();
            });
    
            stream.on('close', (code: number | null) => {
              clearTimeout(timeout);
              exitCode = code ?? 0;
              resolve({
                stdout,
                stderr,
                exitCode,
                duration: Date.now() - startTime,
              });
            });
          });
        });
      } finally {
        conn.isBusy = false;
        conn.lastActivity = new Date();
    
        // Log completion if enabled
        if (this.logCommands) {
          console.error(`[SSH] Command completed in ${Date.now() - startTime}ms`);
        }
      }
    }
  • shellEscape helper function used in exec to prevent command injection by wrapping values in single quotes and escaping embedded single quotes.
    function shellEscape(value: string): string {
      // Use single quotes and escape any single quotes inside
      return "'" + value.replace(/'/g, "'\\''") + "'";
    }
  • ExecResult type definition for the return value of ssh_manager.exec(): stdout, stderr, exitCode, and duration.
    export interface ExecResult {
      stdout: string;
      stderr: string;
      exitCode: number;
      duration: number;
    }
Behavior2/5

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

No annotations exist, so the description must carry the full burden. It only states 'Execute a command' without disclosing side effects, required permissions, or behavior when connectionId is missing. The schema indicates default behavior (most recent connection), but the description omits this.

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

Conciseness3/5

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

The description is a single sentence with no waste, but it is too brief given the tool's complexity. It front-loads purpose but lacks structure for additional context.

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?

With 4 parameters, no output schema, and no annotations, the description is incomplete. It fails to explain return values (e.g., stdout, exit code) or the need for an existing connection, which is critical for effective use.

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?

Schema description coverage is 100%, so parameters are documented. The description adds no extra meaning beyond the schema, earning a baseline 3.

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 action: 'Execute a command on an SSH server'. It distinguishes from sibling tools (e.g., ssh_connect, ssh_add_server) which manage connections rather than execute commands.

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?

No guidance is provided on when to use this tool. It does not mention prerequisites (e.g., an existing connection via ssh_connect) or alternatives (e.g., using ssh_connect for connecting).

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/hydroCoderClaud/mcpHydroSSH'

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