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']
      }

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