Skip to main content
Glama
mfangtao

SSH MCP Server

by mfangtao

execute_ssh_command

Run commands on remote servers using SSH with support for password and private key authentication. Simplifies remote server management through the Model Context Protocol (MCP).

Instructions

Execute command on remote server via SSH

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYes
connectionYes

Implementation Reference

  • The core handler function that creates an SSH client connection using ssh2, executes the provided command, captures stdout, stderr, and exit code, and resolves with SSHCommandResult.
    private executeSSHCommand(
      config: SSHConnectionConfig,
      command: string
    ): Promise<SSHCommandResult> {
      return new Promise((resolve, reject) => {
        const conn = new Client();
        let stdout = '';
        let stderr = '';
        let code: number | null = null;
    
        conn.on('ready', () => {
          conn.exec(command, (err, stream) => {
            if (err) {
              conn.end();
              return reject(err);
            }
    
            stream
              .on('close', (exitCode: number) => {
                code = exitCode;
                conn.end();
                resolve({ stdout, stderr, code });
              })
              .on('data', (data: string) => {
                stdout += data;
              })
              .stderr.on('data', (data: string) => {
                stderr += data;
              });
          });
        }).on('error', (err) => {
          reject(err);
        });
    
        const connectOptions: any = {
          host: config.host,
          port: config.port || 22,
          username: config.username,
        };
    
        if (config.password) {
          connectOptions.password = config.password;
        } else if (config.privateKey) {
          connectOptions.privateKey = config.privateKey;
        }
    
        conn.connect(connectOptions);
      });
    }
  • The MCP CallTool request handler that validates the tool name 'execute_ssh_command', extracts arguments, calls executeSSHCommand, and formats the response content based on success or failure.
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name !== 'execute_ssh_command') {
        throw new McpError(
          ErrorCode.MethodNotFound,
          `Unknown tool: ${request.params.name}`
        );
      }
    
      if (!request.params.arguments) {
        throw new McpError(ErrorCode.InvalidParams, 'Missing arguments');
      }
      
      const { connection, command } = request.params.arguments as {
        connection: SSHConnectionConfig;
        command: string;
      };
      
      if (!connection || !command) {
        throw new McpError(ErrorCode.InvalidParams, 'Missing connection or command');
      }
      
      const result = await this.executeSSHCommand(connection, command);
    
      if (result.code !== 0) {
        return {
          content: [
            {
              type: 'text',
              text: `Command failed with code ${result.code}\nSTDERR: ${result.stderr}`,
            },
          ],
          isError: true,
        };
      }
    
      return {
        content: [
          {
            type: 'text',
            text: result.stdout,
          },
        ],
      };
    });
  • The tool definition including name, description, and detailed inputSchema for SSH connection configuration and command.
    {
      name: 'execute_ssh_command',
      description: 'Execute command on remote server via SSH',
      inputSchema: {
        type: 'object',
        properties: {
          connection: {
            type: 'object',
            properties: {
              host: { type: 'string' },
              port: { type: 'number', default: 22 },
              username: { type: 'string' },
              password: { type: 'string' },
              privateKey: { type: 'string' },
            },
            required: ['host', 'username'],
          },
          command: { type: 'string' },
        },
        required: ['connection', 'command'],
      },
    },
  • src/index.ts:47-72 (registration)
    Registers the 'execute_ssh_command' tool by handling ListToolsRequestSchema and returning the tool list.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        {
          name: 'execute_ssh_command',
          description: 'Execute command on remote server via SSH',
          inputSchema: {
            type: 'object',
            properties: {
              connection: {
                type: 'object',
                properties: {
                  host: { type: 'string' },
                  port: { type: 'number', default: 22 },
                  username: { type: 'string' },
                  password: { type: 'string' },
                  privateKey: { type: 'string' },
                },
                required: ['host', 'username'],
              },
              command: { type: 'string' },
            },
            required: ['connection', 'command'],
          },
        },
      ],
    }));
  • TypeScript interface defining the structure of the SSH command execution result.
    interface SSHCommandResult {
      stdout: string;
      stderr: string;
      code: number | null;
    }
  • TypeScript interface defining the SSH connection configuration.
    interface SSHConnectionConfig {
      host: string;
      port?: number;
      username: string;
      password?: string;
      privateKey?: string;
    }
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. While 'execute command' implies a potentially risky operation, it doesn't mention security implications, permission requirements, error handling, or output characteristics. This leaves significant gaps for a tool that interacts with remote systems.

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 zero wasted words. It's appropriately sized and front-loaded with the essential information about what the tool does.

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?

For a tool that executes commands on remote servers (a complex, potentially dangerous operation) with no annotations, no output schema, and 0% schema description coverage, the description is severely incomplete. It lacks crucial information about security, permissions, error handling, and what the tool returns.

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

Parameters2/5

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

The schema has 0% description coverage, so the description must compensate but fails to do so. It mentions neither of the two parameters ('command' and 'connection') nor their nested properties, leaving all parameter meaning undocumented.

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 command') and target ('on remote server via SSH'), providing a specific verb+resource combination. However, without sibling tools, it cannot demonstrate differentiation from alternatives, so it doesn't reach the highest score.

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 alternatives, prerequisites, or contextual constraints. It simply states what the tool does without any 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

Related 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/mfangtao/mcp-ssh-server'

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