Python脚本执行服务

一个通过MCP协议提供Python代码执行功能的服务器,支持远程脚本运行与结果返回。

  • by Drahoxx
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 Drahoxx/python-mcp

使用说明

Python MCP服务器

一个MCP(模型上下文协议)服务器,它公开了一个 run_script 通过子进程执行Python代码的工具。

安装

uv sync

用法

运行服务器

uv run python server.py

克劳德桌面/克劳德代码

claude mcp add --transport stdio --scope user python-runner -- uvx --from git+https://github.com/Drahoxx/python-mcp python-mcp

或者对于本地安装:

claude mcp add --transport stdio --scope user python-runner -- uv run --directory /path/to/python-mcp python-mcp

开源代码

增添 ~/.config/opencode/opencode.json:

{
  "mcpServers": {
    "python-runner": {
      "command": "uvx",
      "args": ["--from", "git+https://github.com/Drahoxx/python-mcp", "python-mcp"]
    }
  }
}

或者对于本地安装:

{
  "mcpServers": {
    "python-runner": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/python-mcp", "python-mcp"]
    }
  }
}

通用MCP客户端

添加到MCP客户端配置中:

{
  "mcpServers": {
    "python-runner": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/python-mcp", "python", "server.py"]
    }
  }
}

工具: run_script

执行Python代码并返回结果。

参数

名称 类型 默认值 描述
code str 必需 要执行的Python代码
timeout int 30 执行超时(秒)

回应

返回一个JSON字符串,其中包含:

字段 类型 描述
success bool 执行是否成功(退出代码0)
stdout str 捕获的标准输出
stderr str 捕获的标准错误
error str | null 如果失败,则显示错误消息/回溯
return_code int 进程退出代码(-1表示超时)

示例

成功执行:

run_script('print("hello")')
# {"success": true, "stdout": "hello\n", "stderr": "", "error": null, "return_code": 0}

语法错误:

run_script('print(')
# {"success": false, "stdout": "", "stderr": "...", "error": "SyntaxError...", "return_code": 1}

运行时错误:

run_script('1/0')
# {"success": false, "stdout": "", "stderr": "...", "error": "ZeroDivisionError...", "return_code": 1}

超时:

run_script('import time; time.sleep(60)', timeout=2)
# {"success": false, "stdout": "", "stderr": "", "error": "Execution timed out after 2 seconds", "return_code": -1}

发展

运行测试

uv run pytest

运行测试并覆盖

uv run pytest --cov=server