Skip to main content
Glama

ssh_exec

Execute commands on remote servers through SSH connections to manage systems and run scripts remotely.

Instructions

Execute a command on the remote server

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
connectionIdYesID of an active SSH connection
commandYesCommand to execute
cwdNoWorking directory for the command
timeoutNoCommand timeout in milliseconds

Implementation Reference

  • The core handler function that executes the SSH command on the remote server using ssh2 Client.exec, handles stdout/stderr capture, timeouts, and returns formatted output with exit code.
    private async handleSSHExec(params: any) {
      const { connectionId, command, cwd, timeout = 60000 } = params;
      
      // Check if the connection exists
      if (!this.connections.has(connectionId)) {
        return {
          content: [{ type: "text", text: `No active SSH connection with ID: ${connectionId}` }],
          isError: true
        };
      }
      
      const { conn } = this.connections.get(connectionId)!;
      
      // Execute the command
      try {
        const result: any = await new Promise((resolve, reject) => {
          const execOptions: any = {};
          if (cwd) execOptions.cwd = cwd;
          
          // Set up timeout
          const timeoutId = setTimeout(() => {
            reject(new Error(`Command execution timed out after ${timeout}ms`));
          }, timeout);
          
          conn.exec(command, execOptions, (err: Error | undefined, stream: any) => {
            if (err) {
              clearTimeout(timeoutId);
              return reject(new Error(`Failed to execute command: ${err.message}`));
            }
            
            let stdout = '';
            let stderr = '';
            
            stream.on('close', (code: number, signal: string) => {
              clearTimeout(timeoutId);
              resolve({
                code,
                signal,
                stdout: stdout.trim(),
                stderr: stderr.trim()
              });
            });
            
            stream.on('data', (data: Buffer) => {
              stdout += data.toString();
            });
            
            stream.stderr.on('data', (data: Buffer) => {
              stderr += data.toString();
            });
          });
        });
        
        const output = result.stdout || result.stderr || '(no output)';
        return {
          content: [{ 
            type: "text", 
            text: `Command: ${command}\nExit code: ${result.code}\nOutput:\n${output}` 
          }]
        };
      } catch (error: any) {
        return {
          content: [{ type: "text", text: `Command execution failed: ${error.message}` }],
          isError: true
        };
      }
  • Tool schema definition in server capabilities declaration, specifying input parameters for ssh_exec tool.
    ssh_exec: {
      description: "Execute a command on the remote server",
      inputSchema: {
        type: "object",
        properties: {
          connectionId: {
            type: "string",
            description: "ID of an active SSH connection"
          },
          command: {
            type: "string",
            description: "Command to execute"
          },
          cwd: {
            type: "string",
            description: "Working directory for the command"
          },
          timeout: {
            type: "number",
            description: "Command timeout in milliseconds"
          }
        },
        required: ["connectionId", "command"]
      }
  • src/index.ts:274-291 (registration)
    Registration and dispatching logic in CallToolRequestSchema handler; routes 'ssh_exec' calls to the handleSSHExec method.
    if (toolName.startsWith('ssh_')) {
      switch (toolName) {
        case 'ssh_connect':
          return this.handleSSHConnect(request.params.arguments);
        case 'ssh_exec':
          return this.handleSSHExec(request.params.arguments);
        case 'ssh_upload_file':
          return this.handleSSHUpload(request.params.arguments);
        case 'ssh_download_file':
          return this.handleSSHDownload(request.params.arguments);
        case 'ssh_list_files':
          return this.handleSSHListFiles(request.params.arguments);
        case 'ssh_disconnect':
          return this.handleSSHDisconnect(request.params.arguments);
        default:
          throw new Error(`Unknown SSH tool: ${toolName}`);
      }
    }
  • Tool schema returned by ListToolsRequestSchema handler for ssh_exec.
    {
      name: 'ssh_exec',
      description: 'Execute a command on the remote server',
      inputSchema: {
        type: 'object',
        properties: {
          connectionId: { type: 'string', description: 'ID of an active SSH connection' },
          command: { type: 'string', description: 'Command to execute' },
          cwd: { type: 'string', description: 'Working directory for the command' },
          timeout: { type: 'number', description: 'Command timeout in milliseconds' }
        },
        required: ['connectionId', 'command']
      }
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 action but lacks critical details: it doesn't mention security implications, permission requirements, output format (e.g., stdout/stderr), error handling, or that it might affect the remote system. This is inadequate for a mutation tool with zero annotation coverage.

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 with no wasted words. It's front-loaded with the core action, making it easy to parse quickly, which is ideal for conciseness.

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 (executing commands on a remote server), lack of annotations, and no output schema, the description is incomplete. It fails to address behavioral aspects like safety, output, or error handling, which are crucial for an agent to use this tool effectively in context with siblings.

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%, so all parameters are documented in the schema. The description adds no additional meaning beyond implying command execution, which the schema already covers with parameter descriptions. This meets the baseline of 3 when the schema does the heavy lifting.

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

Purpose4/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') and target ('on the remote server'), which distinguishes it from siblings like ssh_connect or ssh_upload_file. However, it doesn't explicitly differentiate from potential command-execution alternatives in the sibling list, keeping it at 4 rather than 5.

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 versus alternatives. It doesn't mention prerequisites (e.g., needing an active SSH connection via ssh_connect), exclusions, or comparisons to other command-related tools, leaving the agent to infer usage context.

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/mixelpixx/SSH-MCP'

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