Skip to main content
Glama

ssh_connect

Establish a secure SSH connection to a remote server. Provide the server ID from the list of servers, and optionally set a connection timeout.

Instructions

Connect to an SSH server

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
serverIdYesServer ID from ssh_list_servers
timeoutNoConnection timeout in milliseconds (optional)

Implementation Reference

  • src/index.ts:62-79 (registration)
    Tool registration: 'ssh_connect' is registered in the ListToolsRequestSchema handler with name, description, and inputSchema (requires serverId, optional timeout).
    {
      name: 'ssh_connect',
      description: 'Connect to an SSH server',
      inputSchema: {
        type: 'object',
        properties: {
          serverId: {
            type: 'string',
            description: 'Server ID from ssh_list_servers',
          },
          timeout: {
            type: 'number',
            description: 'Connection timeout in milliseconds (optional)',
          },
        },
        required: ['serverId'],
      },
    },
  • Tool handler: The 'ssh_connect' case in CallToolRequestSchema. It looks up the server config by serverId, calls sshManager.connect(serverConfig), and returns the connectionId on success or an error on failure.
    case 'ssh_connect': {
      const serverId = args.serverId as string;
      const serverConfig = config.servers.find(s => s.id === serverId);
      if (!serverConfig) {
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({ error: `Server ${serverId} not found` }, null, 2),
            },
          ],
          isError: true,
        };
      }
      try {
        const connectionId = await sshManager.connect(serverConfig);
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({ connectionId, status: 'connected' }, null, 2),
            },
          ],
        };
      } catch (err: unknown) {
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({ error: err instanceof Error ? err.message : String(err) }, null, 2),
            },
          ],
          isError: true,
        };
      }
    }
  • Type definition: SSHConnection interface used by the connect method to store connection state (id, serverId, client, timestamps, isBusy, serverConfig).
    export interface SSHConnection {
      id: string;
      serverId: string;
      client: Client;
      connectedAt: Date;
      lastActivity: Date;
      isBusy: boolean;
      serverConfig?: ServerConfig;  // For auto-reconnect
    }
  • Helper: SSHManager.connect() method - the actual SSH connection logic using ssh2 Client. Handles max connections check, timeout, auth methods (agent/key/password), keepalive, and stores the connection.
    /**
     * Connect to an SSH server.
     * @param serverConfig - The server configuration containing connection details
     * @returns A promise that resolves to the connection ID
     * @throws Error if max connections limit is reached or connection fails
     */
    async connect(serverConfig: ServerConfig): Promise<string> {
      // Check max connections limit
      if (this.connections.size >= this.maxConnections) {
        throw new Error(`Max connections limit reached (${this.maxConnections})`);
      }
    
      const connectionId = uuidv4();
      const client = new Client();
    
      return new Promise((resolve, reject) => {
        const timeoutMs = serverConfig.connectTimeout || 30000;
        let isResolved = false;
    
        const timeout = setTimeout(() => {
          if (!isResolved) {
            client.end();  // Clean up resources on timeout
            reject(new Error('Connection timeout'));
          }
        }, timeoutMs);
    
        client.on('ready', () => {
          clearTimeout(timeout);
          isResolved = true;
          const connection: SSHConnection = {
            id: connectionId,
            serverId: serverConfig.id,
            client,
            connectedAt: new Date(),
            lastActivity: new Date(),
            isBusy: false,
            serverConfig: { ...serverConfig },  // Store for auto-reconnect
          };
          this.connections.set(connectionId, connection);
          this.lastConnectionId = connectionId;
          resolve(connectionId);
        });
    
        client.on('error', (err) => {
          clearTimeout(timeout);
          if (!isResolved) {
            reject(err);
          }
        });
    
        // Handle connection end/close
        const handleConnectionClose = () => {
          if (this.logCommands) {
            console.error(`[SSH] Connection ${connectionId} closed`);
          }
          this.connections.delete(connectionId);
          if (this.lastConnectionId === connectionId) {
            const remaining = Array.from(this.connections.keys());
            this.lastConnectionId = remaining.length > 0 ? remaining[remaining.length - 1] : null;
          }
        };
    
        client.on('end', handleConnectionClose);
        client.on('close', handleConnectionClose);
    
        // Build connect options
        const connectOptions: ConnectConfig = {
          host: serverConfig.host,
          port: serverConfig.port,
          username: serverConfig.username,
        };
    
        // Auth method
        if (serverConfig.authMethod === 'agent') {
          connectOptions.agent = this.getAgentPath();
          connectOptions.agentForward = true;
        } else if (serverConfig.authMethod === 'key' && serverConfig.privateKeyPath) {
          const keyPath = expandUser(serverConfig.privateKeyPath);
          connectOptions.privateKey = fs.readFileSync(keyPath);
        } else if (serverConfig.authMethod === 'password' && serverConfig.password) {
          connectOptions.password = serverConfig.password;
        }
    
        if (serverConfig.keepaliveInterval !== undefined) {
          connectOptions.keepaliveInterval = serverConfig.keepaliveInterval;
        } else if (this.keepaliveInterval > 0) {
          connectOptions.keepaliveInterval = this.keepaliveInterval;
        }
    
        client.connect(connectOptions);
      });
    }
  • Type definition: ServerConfig interface defines the structure needed for ssh_connect's serverId lookup, including host, port, username, authMethod, privateKeyPath, etc.
    export interface ServerConfig {
      id: string;
      name: string;
      host: string;
      port: number;
      username: string;
      authMethod: 'agent' | 'key' | 'password';
      privateKeyPath?: string;
      password?: string;
      connectTimeout?: number;
      keepaliveInterval?: number;
    }
Behavior2/5

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

With no annotations, the description carries full burden but only states 'Connect to an SSH server'. It does not disclose whether this establishes a persistent session, modifies state, requires authentication, or what the side effects are. The behavior is underspecified for a potentially stateful operation.

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, concise sentence with no superfluous words. It is front-loaded with the action and resource. Every word earns its place.

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 tool's likely stateful nature and lack of output schema, the description is incomplete. It does not mention connection life cycle, success/failure behavior, or how this tool relates to siblings like ssh_exec or ssh_disconnect. More context is needed for an agent to use it correctly.

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 coverage is 100%, so the input schema already documents both parameters adequately. The description adds no additional meaning beyond the schema. Baseline score of 3 is appropriate as the description does not enhance understanding of parameter semantics.

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 ('Connect') and resource ('SSH server'), making the primary function evident. However, it does not differentiate from siblings like ssh_disconnect or ssh_exec, which are clearly separate actions, but the purpose is still unambiguous.

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 usage guidance is provided. The description does not indicate when to use this tool versus alternatives (e.g., use this before ssh_exec, or when to use ssh_connect vs ssh_list_servers). An agent would have no context on prerequisites or order of operations.

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