Skip to main content
Glama
weidwonder

Terminal MCP Server

execute_command

Execute system commands locally or on remote hosts via SSH using the Terminal MCP Server. Supports persistent sessions and environment variables for consistent terminal environments.

Instructions

Execute commands on remote hosts or locally (This tool can be used for both remote hosts and the current machine)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesCommand to execute. Before running commands, it's best to determine the system type (Mac, Linux, etc.)
envNoEnvironment variables
hostNoHost to connect to (optional, if not provided the command will be executed locally)
sessionNoSession name, defaults to 'default'. The same session name will reuse the same terminal environment for 20 minutes, which is useful for operations requiring specific environments like conda.default
usernameNoUsername for SSH connection (required when host is specified)

Implementation Reference

  • Core handler function that executes the command either locally using child_process.exec or remotely via SSH2 with advanced session management, interactive shell support, environment variable persistence across calls in the same session, and timeout handling.
    async executeCommand(
      command: string,
      options: {
        host?: string;
        username?: string;
        session?: string;
        env?: Record<string, string>;
      } = {}
    ): Promise<{stdout: string; stderr: string}> {
      const { host, username, session = 'default', env = {} } = options;
      const sessionKey = this.getSessionKey(host, session);
    
      // 如果指定了host,则使用SSH执行命令
      if (host) {
        if (!username) {
          throw new Error('Username is required when using SSH');
        }
        
        let sessionData = this.sessions.get(sessionKey);
        
        // 检查会话是否存在且有效
        let needNewConnection = false;
        if (!sessionData || sessionData.host !== host) {
          needNewConnection = true;
        } else if (sessionData.client) {
          // 检查客户端是否仍然连接
          if (sessionData.client.listenerCount('ready') === 0 && sessionData.client.listenerCount('data') === 0) {
            log.info(`Session ${sessionKey} disconnected, reconnecting`);
            needNewConnection = true;
          }
        } else {
          needNewConnection = true;
        }
        
        // 如果需要新连接,则创建
        if (needNewConnection) {
          log.info(`Creating new connection for command execution: ${sessionKey}`);
          await this.connect(host, username, session);
          sessionData = this.sessions.get(sessionKey);
        } else {
          log.info(`Reusing existing session for command execution: ${sessionKey}`);
        }
        
        if (!sessionData || !sessionData.client) {
          throw new Error(`无法创建到 ${host} 的SSH会话`);
        }
        
        this.resetTimeout(sessionKey);
    
        // 检查是否有交互式shell可用
        if (sessionData.shellReady && sessionData.shell) {
          log.info(`Executing command using interactive shell: ${command}`);
          return new Promise((resolve, reject) => {
            let stdout = "";
            let stderr = "";
            let commandFinished = false;
            const uniqueMarker = `CMD_END_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
            
            // 构建环境变量设置命令
            const envSetup = Object.entries(env)
              .map(([key, value]) => `export ${key}="${String(value).replace(/"/g, '\\"')}"`)
              .join(' && ');
            
            // 如果有环境变量,先设置环境变量,再执行命令
            const fullCommand = envSetup ? `${envSetup} && ${command}` : command;
            
            // 添加数据处理器
            const dataHandler = (data: Buffer) => {
              const str = data.toString();
              log.debug(`Shell数据: ${str}`);
              
              if (str.includes(uniqueMarker)) {
                // 命令执行完成
                commandFinished = true;
                
                // 提取命令输出(从命令开始到标记之前的内容)
                const lines = stdout.split('\n');
                let commandOutput = '';
                let foundCommand = false;
                
                for (const line of lines) {
                  if (foundCommand) {
                    if (line.includes(uniqueMarker)) {
                      break;
                    }
                    commandOutput += line + '\n';
                  } else if (line.includes(fullCommand)) {
                    foundCommand = true;
                  }
                }
                
                // 解析输出
                resolve({ stdout: commandOutput.trim(), stderr });
                
                // 移除处理器
                sessionData.shell.removeListener('data', dataHandler);
                clearTimeout(timeout);
              } else if (!commandFinished) {
                stdout += str;
              }
            };
            
            // 添加错误处理器
            const errorHandler = (err: Error) => {
              stderr += err.message;
              reject(err);
              sessionData.shell.removeListener('data', dataHandler);
              sessionData.shell.removeListener('error', errorHandler);
            };
            
            // 监听数据和错误
            sessionData.shell.on('data', dataHandler);
            sessionData.shell.on('error', errorHandler);
            
            // 执行命令并添加唯一标记
            // 使用一个更明确的方式来执行命令和捕获输出
            sessionData.shell.write(`echo "Starting command execution: ${fullCommand}"\n`);
            sessionData.shell.write(`${fullCommand}\n`);
            sessionData.shell.write(`echo "${uniqueMarker}"\n`);
            
            // 设置超时
            const timeout = setTimeout(() => {
              if (!commandFinished) {
                stderr += "Command execution timed out";
                resolve({ stdout, stderr });
                sessionData.shell.removeListener('data', dataHandler);
                sessionData.shell.removeListener('error', errorHandler);
              }
            }, 30000); // 30秒超时
          });
        } else {
          log.info(`Executing command using exec: ${command}`);
          return new Promise((resolve, reject) => {
            // 构建环境变量设置命令
            const envSetup = Object.entries(env)
              .map(([key, value]) => `export ${key}="${String(value).replace(/"/g, '\\"')}"`)
              .join(' && ');
            
            // 如果有环境变量,先设置环境变量,再执行命令
            const fullCommand = envSetup ? `${envSetup} && ${command}` : command;
            
            sessionData?.client?.exec(`/bin/bash --login -c "${fullCommand.replace(/"/g, '\\"')}"`, (err, stream) => {
              if (err) {
                reject(err);
                return;
              }
    
              let stdout = "";
              let stderr = '';
    
              stream
                .on("data", (data: Buffer) => {
                  this.resetTimeout(sessionKey);
                  stdout += data.toString();
                })
                .stderr.on('data', (data: Buffer) => {
                  stderr += data.toString();
                })
                .on('close', () => {
                  resolve({ stdout, stderr });
                })
                .on('error', (err) => {
                  reject(err);
                });
            });
          });
        }
      } 
      // 否则在本地执行命令
      else {
        // 在本地执行命令时,也使用会话机制来保持环境变量
        log.info(`Executing command using local session: ${sessionKey}`);
        
        // 检查是否已有本地会话
        let sessionData = this.sessions.get(sessionKey);
        let sessionEnv = {};
        
        if (!sessionData) {
          // 为本地会话创建一个空条目,以便跟踪超时
          sessionData = {
            client: null,
            connection: null,
            timeout: null,
            host: undefined,
            env: { ...env } // 保存初始环境变量
          };
          this.sessions.set(sessionKey, sessionData);
          log.info(`Creating new local session: ${sessionKey}`);
          sessionEnv = env;
        } else {
          log.info(`Reusing existing local session: ${sessionKey}`);
          // 合并现有会话环境变量和新的环境变量
          if (!sessionData.env) {
            sessionData.env = {};
          }
          sessionData.env = { ...sessionData.env, ...env };
          sessionEnv = sessionData.env;
          // 更新会话
          this.sessions.set(sessionKey, sessionData);
        }
        
        this.resetTimeout(sessionKey);
        
        return new Promise((resolve, reject) => {
          // 构建环境变量,优先级:系统环境变量 < 会话环境变量 < 当前命令环境变量
          const envVars = { ...process.env, ...sessionEnv };
          
          // 执行命令
          log.info(`Executing local command: ${command}`);
          exec(command, { env: envVars }, (error, stdout, stderr) => {
            if (error && error.code !== 0) {
              // 我们不直接拒绝,而是返回错误信息作为stderr
              resolve({ stdout, stderr: stderr || error.message });
            } else {
              resolve({ stdout, stderr });
            }
          });
        });
      }
    }
  • Input schema and description for the 'execute_command' tool, provided in the ListTools response.
      {
        name: "execute_command",
        description: "Execute commands on remote hosts or locally (This tool can be used for both remote hosts and the current machine)",
        inputSchema: {
          type: "object",
          properties: {
            host: {
              type: "string",
              description: "Host to connect to (optional, if not provided the command will be executed locally)"
            },
            username: {
              type: "string",
              description: "Username for SSH connection (required when host is specified)"
            },
            session: {
              type: "string",
              description: "Session name, defaults to 'default'. The same session name will reuse the same terminal environment for 20 minutes, which is useful for operations requiring specific environments like conda.",
              default: "default"
            },
            command: {
              type: "string",
              description: "Command to execute. Before running commands, it's best to determine the system type (Mac, Linux, etc.)"
            },
            env: {
              type: "object",
              description: "Environment variables",
              default: {}
            }
          },
          required: ["command"]
        }
      }
    ]
  • src/index.ts:47-84 (registration)
    Registration of the 'execute_command' tool via the ListToolsRequestSchema handler, listing the tool with its schema.
    server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: "execute_command",
            description: "Execute commands on remote hosts or locally (This tool can be used for both remote hosts and the current machine)",
            inputSchema: {
              type: "object",
              properties: {
                host: {
                  type: "string",
                  description: "Host to connect to (optional, if not provided the command will be executed locally)"
                },
                username: {
                  type: "string",
                  description: "Username for SSH connection (required when host is specified)"
                },
                session: {
                  type: "string",
                  description: "Session name, defaults to 'default'. The same session name will reuse the same terminal environment for 20 minutes, which is useful for operations requiring specific environments like conda.",
                  default: "default"
                },
                command: {
                  type: "string",
                  description: "Command to execute. Before running commands, it's best to determine the system type (Mac, Linux, etc.)"
                },
                env: {
                  type: "object",
                  description: "Environment variables",
                  default: {}
                }
              },
              required: ["command"]
            }
          }
        ]
      };
    });
  • MCP CallTool request handler specifically for the 'execute_command' tool, which parses input, validates, calls CommandExecutor.executeCommand, and formats the response.
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
      try {
        if (request.params.name !== "execute_command") {
          throw new McpError(ErrorCode.MethodNotFound, "Unknown tool");
        }
        
        const host = request.params.arguments?.host ? String(request.params.arguments.host) : undefined;
        const username = request.params.arguments?.username ? String(request.params.arguments.username) : undefined;
        const session = String(request.params.arguments?.session || "default");
        const command = String(request.params.arguments?.command);
        if (!command) {
          throw new McpError(ErrorCode.InvalidParams, "Command is required");
        }
        const env = request.params.arguments?.env || {};
    
        // 如果指定了host但没有指定username
        if (host && !username) {
          throw new McpError(ErrorCode.InvalidParams, "Username is required when host is specified");
        }
    
        try {
          const result = await commandExecutor.executeCommand(command, {
            host,
            username,
            session,
            env: env as Record<string, string>
          });
          
          return {
            content: [{
              type: "text",
              text: `Command Output:\nstdout: ${result.stdout}\nstderr: ${result.stderr}`
            }]
          };
        } catch (error) {
          if (error instanceof Error && error.message.includes('SSH')) {
            throw new McpError(
              ErrorCode.InternalError,
              `SSH connection error: ${error.message}. Please ensure SSH key-based authentication is set up.`
            );
          }
          throw error;
        }
      } catch (error) {
        if (error instanceof McpError) {
          throw error;
        }
        throw new McpError(
          ErrorCode.InternalError,
          error instanceof Error ? error.message : String(error)
        );
      }
    });
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. It mentions that commands can be executed remotely or locally and hints at session reuse for 20 minutes, but it lacks critical details such as security implications, error handling, output format, or potential side effects. This leaves significant gaps for a tool that executes arbitrary commands.

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 a single, efficient sentence that front-loads the core functionality. It avoids unnecessary details and stays focused on the tool's scope, though it could be slightly more structured by explicitly separating remote and local use cases.

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 complexity of executing commands (which can have security and system impacts), the lack of annotations, and no output schema, the description is insufficient. It fails to address critical aspects like return values, error conditions, or safety warnings, making it incomplete for informed tool usage.

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?

The input schema has 100% description coverage, so the baseline is 3. The description does not add any meaningful parameter semantics beyond what is already documented in the schema, such as explaining the 'command' parameter's system dependencies or the 'session' parameter's environmental implications in more depth.

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 tool's purpose as executing commands on remote hosts or locally, specifying both the verb ('execute') and the resource ('commands'). It distinguishes between remote and local execution contexts. However, without sibling tools, it cannot demonstrate differentiation from alternatives, preventing a perfect score.

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 implies usage by mentioning both remote and local contexts, but it does not provide explicit guidance on when to choose one over the other or any prerequisites. For example, it notes host is optional for local execution but does not clarify when remote execution is preferable or what conditions might affect it.

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/weidwonder/terminal-mcp-server'

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