使用说明
壳牌MCP服务器
此项目实现了一个允许执行任意shell命令的模型上下文协议(MCP)服务器。它提供了一个单一的工具, run_shell_command,它接受命令字符串、可选的当前工作目录(CWD)和可选的环境变量,然后返回命令的退出代码、标准输出(stdout)和标准错误(stderr)。
特性
- 执行任何shell命令。
- 为命令指定自定义的当前工作目录(CWD)。
- 将自定义环境变量传递给命令。
- 返回结构化输出,包括退出代码、stdout和stderr。
- 优雅地处理命令执行错误。
工具: run_shell_command
描述
执行给定的shell命令并返回其输出和状态。
输入架构
该工具需要一个具有以下字段的JSON对象:
command(字符串, 必需的):要执行的shell命令(例如。,"ls -la").这应该是一个命令字符串,包括任何参数。cwd(string,可选):命令的当前工作目录。如果没有提供,该命令将在MCP服务器进程的默认工作目录中运行。env(object,可选):为命令设置的环境变量(字符串的键值对)的记录(例如。,{"NODE_ENV": "development"}).这些将与MCP服务器的环境变量合并,请求定义的变量优先。
输出模式
该工具返回一个具有以下结构的JSON对象:
export interface ShellCommandResponse {
/** The exit code of the executed command. 0 typically indicates success. */
exit_code: number;
/** The standard output (stdout) from the command. */
stdout: string;
/** The standard error (stderr) from the command. */
stderr: string;
}
领域:
exit_code(number):命令的退出代码。stdout(string):命令的标准输出。stderr(string):命令的标准错误输出。
示例用法
请求:
{
"tool_name": "run_shell_command",
"tool_input": {
"command": "echo Hello MCP && ls non_existent_file",
"cwd": "/tmp"
}
}
预期响应(示例):
{
"content": [
{
"type": "text",
"text": "{\"exit_code\":1,\"stdout\":\"Hello MCP\\n\",\"stderr\":\"ls: non_existent_file: No such file or directory\\n\"}"
}
]
}
(注:实际 stderr 留言为 ls 可能因操作系统而异。)
设置和运行服务器
此服务器是使用Bun和TypeScript构建的。
-
先决条件:
- Bun(参见 Bun的官方文件 用于安装)
-
安装依赖关系: 导航到项目根目录并运行:
bun install -
运行服务器: 要启动MCP服务器,请执行:
bun run index.ts服务器将在stdio上监听MCP请求。
运行测试
该项目使用Vitest进行测试。
-
确保安装了依赖项:
bun install -
运行测试:
bun test这将执行中定义的测试套件
index.test.ts.
依赖项
@modelcontextprotocol/sdk:用于MCP服务器和类型定义。execa:用于稳定执行shell命令。zod:用于模式定义和验证。
开发说明
- 服务器使用
execa随着reject: false以确保它始终捕获stdout,stderr,以及exitCode,即使命令失败。 - 请求中传递的环境变量与服务器的进程环境合并,在发生冲突时,请求定义的变量优先。