MCP 终端服务器
一个实现了模型上下文协议 (MCP) 的安全终端执行服务器。该服务器提供受控的命令执行功能,并具有安全功能和资源限制。
特征
- 命令执行:执行带有输出捕获和错误处理的 shell 命令
- 安全控制:限制允许的命令并防止命令注入
- 资源控制:
- MCP 协议支持:
发展
本地设置
# Clone the repository
git clone https://github.com/RinardNick/mcp-terminal.git
cd mcp-terminal
# Create and activate virtual environment using uv
uv venv
source .venv/bin/activate # or .venv\Scripts\activate on Windows
# Install development dependencies
uv pip install -e ".[dev]"
发布到 PyPI
# Build the package
uv pip install build
python -m build
# Upload to PyPI
uv pip install twine
python -m twine upload dist/*
使用 MCP Inspector 进行测试
MCP Inspector 工具可用于测试服务器实现:
# Install inspector
npm install -g @modelcontextprotocol/inspector
# Test server
npx @modelcontextprotocol/inspector python3 src/mcp_terminal/server.py --allowed-commands "python,pip,git,ls,cd"
运行测试
# Run all tests
pytest tests/
# Run specific test file
pytest tests/test_terminal.py
# Run with coverage
pytest --cov=mcp_terminal tests/
与 Claude Desktop 一起使用
一旦包发布到 PyPI:
- 安装 UV (如果尚未安装):
- 使用 UV 安装包:
uv pip install mcp-terminal
- 配置 Claude Desktop :编辑您的 Claude Desktop 配置文件(在 macOS 上通常位于
~/Library/Application Support/Claude/claude_desktop_config.json
):{
"mcpServers": {
"terminal": {
"command": "uv",
"args": [
"pip",
"run",
"mcp-terminal",
"--allowed-commands",
"python,pip,git,ls,cd",
"--timeout-ms",
"30000",
"--max-output-size",
"1048576"
]
}
}
}
协议实现
服务器实现了具有以下功能的模型上下文协议(MCP):
能力广告
{
"protocol": "1.0.0",
"name": "terminal",
"version": "1.1.0",
"capabilities": {
"execute": {
"description": "Execute a terminal command",
"parameters": {
"command": {
"type": "string",
"description": "The command to execute"
}
},
"returns": {
"type": "object",
"properties": {
"exitCode": { "type": "number" },
"stdout": { "type": "string" },
"stderr": { "type": "string" },
"startTime": { "type": "string" },
"endTime": { "type": "string" }
}
}
}
}
}
消息格式
要求:
{
"type": "execute",
"data": {
"command": "echo 'hello world'"
}
}
回复:
{
"type": "result",
"data": {
"command": "echo 'hello world'",
"exitCode": 0,
"stdout": "hello world\n",
"stderr": "",
"startTime": "2024-01-20T12:34:56.789Z",
"endTime": "2024-01-20T12:34:56.790Z"
}
}
错误:
{
"type": "error",
"data": {
"message": "command not allowed"
}
}
安全注意事项
- 命令验证:
- 只能执行允许的命令
- Shell 操作员被阻止
- 阻止命令注入尝试
- 资源保护:
- 命令超时防止挂起
- 输出大小限制可防止内存耗尽
- 所有失败情况的错误处理
- 最佳实践:
- 在生产环境中始终设置
allowed-commands
- 使用保守的超时和大小限制
- 监控命令执行日志
贡献
- 分叉存储库
- 创建你的功能分支(
git checkout -b feature/amazing-feature
) - 提交您的更改(
git commit -m 'Add some amazing feature'
) - 推送到分支(
git push origin feature/amazing-feature
) - 打开拉取请求
执照
该项目根据 MIT 许可证获得许可 - 有关详细信息,请参阅LICENSE文件。