Skip to main content
Glama

ssh_connect

Establish SSH connections to remote servers using saved server configurations. This tool enables secure command execution and server management through Claude Code.

Instructions

Connect to an SSH server

Input Schema

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

Implementation Reference

  • The 'ssh_connect' request handler in src/index.ts. It retrieves the server configuration, calls sshManager.connect(), and handles the connection response.
    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,
        };
      }
    }
  • The actual implementation of the connection logic using the ssh2 library. It handles the promise-based connection process and stores the connection in a Map.
    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);
      });
    }
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 but discloses almost nothing about behavior: it does not state whether the connection persists for subsequent tool calls, what authentication method is used, what error conditions to expect, or what the return value indicates (no output schema exists).

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?

Extremely brief at four words with no filler, but arguably too terse for the complexity of SSH connection management. The single sentence is front-loaded with the verb, earning points for structure despite under-specification.

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?

Inadequate for a connection-oriented tool with no output schema and no annotations. Critical missing context includes: session persistence model (does it affect subsequent ssh_exec calls?), connection lifecycle, and relationship to the sibling tool ssh_disconnect.

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 description coverage is 100%, documenting both serverId (referencing ssh_list_servers) and timeout. The description adds no additional parameter context, syntax guidance, or examples beyond what the schema already provides, meeting the baseline expectation.

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

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

States the basic action (Connect) and resource (SSH server) clearly, but fails to differentiate from siblings like ssh_add_server or clarify that this establishes a session to an existing configured server rather than creating a new configuration.

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?

Provides no guidance on when to use this tool versus alternatives (e.g., ssh_exec which may handle its own connection), nor does it mention prerequisites such as needing to call ssh_add_server first or obtain a serverId from ssh_list_servers.

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