Skip to main content
Glama
simon-ami

Windows CLI MCP Server

by simon-ami

ssh_execute

Execute commands on remote hosts via SSH to manage systems, run scripts, or retrieve information from connected devices.

Instructions

Execute a command on a remote host via SSH

Example usage:

{
  "connectionId": "raspberry-pi",
  "command": "uname -a"
}

Configuration required in config.json:

{
  "ssh": {
    "enabled": true,
    "connections": {
      "raspberry-pi": {
        "host": "raspberrypi.local",
        "port": 22,
        "username": "pi",
        "password": "raspberry"
      }
    }
  }
}

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
connectionIdYesID of the SSH connection to use
commandYesCommand to execute

Implementation Reference

  • Main handler for the ssh_execute tool: validates input, retrieves SSH connection from pool, executes command, handles response and logging.
    case "ssh_execute": {
      if (!this.config.ssh.enabled) {
        throw new McpError(
          ErrorCode.InvalidRequest,
          "SSH support is disabled in configuration"
        );
      }
    
      const args = z.object({
        connectionId: z.string(),
        command: z.string()
      }).parse(request.params.arguments);
    
      const connectionConfig = this.config.ssh.connections[args.connectionId];
      if (!connectionConfig) {
        throw new McpError(
          ErrorCode.InvalidRequest,
          `Unknown SSH connection ID: ${args.connectionId}`
        );
      }
    
      try {
        // Validate command
        this.validateCommand('cmd', args.command);
    
        const connection = await this.sshPool.getConnection(args.connectionId, connectionConfig);
        const { output, exitCode } = await connection.executeCommand(args.command);
    
        // Store in history if enabled
        if (this.config.security.logCommands) {
          this.commandHistory.push({
            command: args.command,
            output,
            timestamp: new Date().toISOString(),
            exitCode,
            connectionId: args.connectionId
          });
    
          if (this.commandHistory.length > this.config.security.maxHistorySize) {
            this.commandHistory = this.commandHistory.slice(-this.config.security.maxHistorySize);
          }
        }
    
        return {
          content: [{
            type: "text",
            text: output || 'Command completed successfully (no output)'
          }],
          isError: exitCode !== 0,
          metadata: {
            exitCode,
            connectionId: args.connectionId
          }
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        if (this.config.security.logCommands) {
          this.commandHistory.push({
            command: args.command,
            output: `SSH error: ${errorMessage}`,
            timestamp: new Date().toISOString(),
            exitCode: -1,
            connectionId: args.connectionId
          });
        }
        throw new McpError(
          ErrorCode.InternalError,
          `SSH error: ${errorMessage}`
        );
      }
    }
  • Input schema definition for ssh_execute tool specifying connectionId and command parameters.
    inputSchema: {
      type: "object",
      properties: {
        connectionId: {
          type: "string",
          description: "ID of the SSH connection to use",
          enum: Object.keys(this.config.ssh.connections)
        },
        command: {
          type: "string",
          description: "Command to execute"
        }
      },
      required: ["connectionId", "command"]
    }
  • src/index.ts:356-399 (registration)
    Registration of ssh_execute tool in the list of available tools, including name, description, and schema.
            {
              name: "ssh_execute",
              description: `Execute a command on a remote host via SSH
    
    Example usage:
    \`\`\`json
    {
      "connectionId": "raspberry-pi",
      "command": "uname -a"
    }
    \`\`\`
    
    Configuration required in config.json:
    \`\`\`json
    {
      "ssh": {
        "enabled": true,
        "connections": {
          "raspberry-pi": {
            "host": "raspberrypi.local",
            "port": 22,
            "username": "pi",
            "password": "raspberry"
          }
        }
      }
    }
    \`\`\``,
              inputSchema: {
                type: "object",
                properties: {
                  connectionId: {
                    type: "string",
                    description: "ID of the SSH connection to use",
                    enum: Object.keys(this.config.ssh.connections)
                  },
                  command: {
                    type: "string",
                    description: "Command to execute"
                  }
                },
                required: ["connectionId", "command"]
              }
            },
  • Core SSH command execution logic using ssh2 Client.exec, capturing stdout/stderr and exit code.
    async executeCommand(command: string): Promise<{ output: string; exitCode: number }> {
      this.lastActivity = Date.now();
    
      // Check connection and attempt reconnect if needed
      if (!this.isConnected) {
        await this.connect();
      }
    
      return new Promise((resolve, reject) => {
        this.client.exec(command, (err, stream) => {
          if (err) {
            reject(err);
            return;
          }
    
          let output = '';
          let errorOutput = '';
    
          stream
            .on('data', (data: Buffer) => {
              output += data.toString();
            })
            .stderr.on('data', (data: Buffer) => {
              errorOutput += data.toString();
            });
    
          stream.on('close', (code: number) => {
            this.lastActivity = Date.now();
            resolve({
              output: output || errorOutput,
              exitCode: code || 0
            });
          });
        });
      });
    }
  • SSHConnectionPool method to acquire or create and connect an SSHConnection instance.
    async getConnection(connectionId: string, config: SSHConnectionConfig): Promise<SSHConnection> {
      let connection = this.connections.get(connectionId);
      
      if (!connection) {
        connection = new SSHConnection(config);
        this.connections.set(connectionId, connection);
        await connection.connect();
      } else if (!connection.isActive()) {
        await connection.connect();
      }
    
      return connection;
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

A3.8/5.0
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It mentions that SSH must be enabled in config.json and gives an example connection, which is useful. However, it does not disclose the command execution behavior (e.g., output format, error handling, potential destructive side-effects) or that it uses the specified password for authentication.

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

Conciseness4/5

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

The description is structured and efficient, with a one-sentence purpose followed by illustrative JSON examples. The config block is large but necessary to show the setup requirements. No wasted words.

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

Completeness3/5

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

With no output schema and no annotations, the description should explain what the tool returns or what 'execute' entails. It does neither, though it does provide configuration context. For a command execution tool, the lack of mention of output or error behavior leaves a moderate gap.

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

Parameters4/5

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

The input schema descriptions are minimal ('Command to execute', 'ID of the SSH connection to use'). The description adds meaningful value by showing an example usage and the config structure, clarifying that connectionId refers to a key in the 'connections' object and command is a shell string.

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 'Execute a command on a remote host via SSH', using a specific verb and resource. It distinguishes itself from sibling tools like ssh_disconnect (manage connection) and get_command_history (retrieve history).

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

Usage Guidelines3/5

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

The description provides a concrete example and configuration requirement, implying when to use the tool (when you have a configured SSH connection and need to run a command). However, it does not explicitly state when to use it over alternatives like execute_command, nor does it provide exclusion criteria.

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