有状态的Python REPL MCP服务器
一种模型上下文协议(MCP)服务器,为有状态的Python REPL提供对其他MCP工具的编程访问。持久执行Python代码,并通过预注入直接从代码调用外部MCP服务器(如GitHub、Playwright等) mcp 客户端对象。
特性
- 正式执行:变量、导入和函数定义在执行过程中保持不变
- MCP工具集成:通过编程方式调用其他MCP工具
mcp.tools.server.method(...) - 自动连接:从自动连接到MCP服务器
.mcp.json启动时 - 输出捕获:完整的stdout、stderr、异常和返回值
- HTTP和标准传输:端口8000上的默认HTTP/SSE,Claude Desktop的stdio回退
- 无沙盒:完全Python访问权限(仅供本地使用)
安装
克劳德代码(推荐)
一个安装命令:
claude mcp add python-repl -- uvx --from git+https://github.com/iota-uz/repl-mcp repl-mcp就是这样。REPL现在可以在Claude Code中使用。
Codex CLI
codex mcp add python-repl -- uvx --from git+https://github.com/iota-uz/repl-mcp repl-mcp克劳德桌面版
添加到 ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"python-repl": {
"command": "uvx",
"args": ["--from", "git+https://github.com/iota-uz/repl-mcp", "repl-mcp"]
}
}
}手动安装
For development or running standalone
先决条件: 安装 紫外线:
curl -LsSf https://astral.sh/uv/install.sh | sh设置:
git clone https://github.com/iota-uz/repl-mcp
cd repl-mcp
uv sync
uv run repl-mcp --help快速开始
1.配置MCP服务器(可选)
创建 .mcp.json 在项目根目录中,启动时自动连接到MCP服务器:
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GH_TOKEN}"
}
},
"playwright": {
"url": "http://localhost:3001/sse"
}
}
}2.启动服务器
# Using UV (recommended - handles dependencies automatically)
uv run repl-mcp --port 8000
# Or activate venv first
source .venv/bin/activate
repl-mcp --port 8000
# Stdio mode (for Claude Desktop integration)
uv run repl-mcp --transport stdio3.使用克劳德代码
服务器公开了一个MCP工具:
execute_python(code, reset=False, inject=None)-在持久REPL中执行Python
在REPL内部,使用 %help 对于文档, object? 快速帮助,以及 %who 列出变量。
用法示例
具有状态持久性的基本执行
# First execution
execute_python(code="x = 42")
# Variable persists in next execution
execute_python(code="print(x)") # Output: 42
# Functions and imports persist too
execute_python(code="""
import json
def greet(name):
return f"Hello, {name}!"
""")
execute_python(code="print(greet('World'))") # Output: Hello, World!使用自动连接的MCP服务器
如果你有 .mcp.json 配置后,服务器自动可用:
# GitHub already connected via .mcp.json
execute_python(code="""
# Discover available tools
tools = mcp.discover_tools()
print(f"Connected servers: {list(tools.keys())}")
""")
# Call GitHub tools directly
execute_python(code="""
result = mcp.tools.github.create_issue(
owner="myuser",
repo="myrepo",
title="Test issue from REPL",
body="This was created programmatically!"
)
print(f"Created issue: {result}")
""")与MCP服务器的运行时连接
您还可以动态连接到服务器,而无需 .mcp.json:
# Connect to GitHub at runtime
connect_mcp_servers(servers={
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GH_TOKEN}"
}
}
})
# List what's available
list_connected_servers()
# Use the connected server
execute_python(code="""
issues = mcp.tools.github.list_issues(
owner="myuser",
repo="myrepo",
state="open"
)
print(f"Open issues: {len(issues)}")
""")使用MCP工具进行批量操作
# Create multiple GitHub issues programmatically
execute_python(code="""
for i in range(5):
result = mcp.tools.github.create_issue(
owner="myuser",
repo="myrepo",
title=f"Auto-generated issue {i}",
body=f"This is issue number {i}"
)
print(f"Created: {result['url']}")
""")错误处理
# Execution continues after errors
execute_python(code="1 / 0") # Returns exception info
# Namespace is preserved
execute_python(code="print(x)") # Still works, x=42 from earlier重置命名空间
# Reset clears all variables except 'mcp'
execute_python(code="y = 100", reset=True)
# Previous variables are gone
execute_python(code="print(x)") # Error: x not defined
# But mcp object is preserved
execute_python(code="print(mcp.discover_tools())") # Still works配置
命令行选项
repl-mcp --help
Options:
--transport {stdio,sse} Transport type (default: sse)
--port PORT Port for SSE transport (default: 8000)
--host HOST Host for SSE transport (default: 0.0.0.0)
--config PATH Path to .mcp.json config (default: .mcp.json)
--no-autoconnect Disable auto-connecting to servers from .mcp.json环境变量
GH_TOKEN-GitHub个人访问令牌(如果使用GitHub MCP)- MCP服务器所需的其他环境变量
建筑
Claude ←→ FastMCP Server ←→ REPL Engine ←→ MCP Client Wrapper ←→ External MCP Servers
(execute_python) (exec code) (tool calling) (github, etc)组件
- repl_mcp_server.py -FastMCP服务器公开工具
- repl_engine.py -具有持久命名空间的有状态执行
- mcp_client_wrapper.py -异步MCP SDK上的同步包装器
- models.py -Pydantic数据模型
关键设计决策
- UV便携式 -单命令执行,自动依赖管理
- 混合MCP配置 -支持
.mcp.json自动连接+运行时connect_mcp_servers() - 干净命名空间 -只有
mcp对象预注入(无库预加载) - HTTP优先 -默认SSE传输,stdio作为回退
- 同步MCP包装器 -使用同步API包装异步SDK以方便REPL
- 动态工具访问 -直观
mcp.tools.server.method(...)语法 - 无限制执行 -完全Python访问权限(仅限本地使用)
- 结构化输出 -始终返回结构化JSON,从不向MCP层抛出
api参考
execute_python
使用预注入的实用程序在持久REPL环境中执行Python代码。
参数:
code(str):要执行的Python代码reset(bool,可选):执行前重置命名空间(默认值:False)inject(dict,可选):要注入命名空间的变量
退货:
{
"success": bool,
"stdout": str,
"stderr": str,
"return_value": str | None,
"exception": {
"type": str,
"message": str,
"traceback": str,
"hints": list[str], # Helpful suggestions
"similar_names": list[str] # For typo detection
} | None,
"execution_time_ms": float,
"namespace_vars": dict[str, str],
"warnings": list[{
"category": str,
"message": str,
"suggestion": str
}]
}REPL功能:
%help-完整文档object?-快速文档字符串(IPython风格)%who/%whos-列出变量%history-执行历史%reset-清除命名空间
安全警告
⚠️ 警告:此服务器不受限制地执行任意Python代码。
- 仅限本地使用 -不要暴露在网络中
- 单用户 -无身份验证或隔离
- 完全系统访问 -可以读/写文件、进行网络调用、运行命令
- 对于生产使用,在具有资源限制的隔离容器中运行
发展
运行测试
# Install dev dependencies
uv sync --extra dev
# Run unit tests
uv run pytest tests/
# Run specific test file
uv run pytest tests/test_repl_engine.py -v
# Run example scripts (integration tests)
bash examples/run_all_examples.sh项目结构
repl_mcp/
├── src/repl_mcp/
│ ├── __init__.py
│ ├── models.py # Pydantic data models
│ ├── repl_engine.py # Stateful execution engine
│ ├── mcp_client_wrapper.py # Sync MCP client wrapper
│ └── repl_mcp_server.py # FastMCP server
├── tests/
│ ├── test_repl_engine.py
│ ├── test_mcp_wrapper.py
│ └── test_integration.py
├── examples/
│ ├── 01_basic_execution.py
│ ├── 02_error_handling.py
│ ├── 03_mcp_config_file.py
│ ├── 04_runtime_connection.py
│ ├── 05_github_bulk_ops.py
│ └── run_all_examples.sh
├── .mcp.json # MCP server config (auto-connect)
├── config.yaml # Server settings
├── pyproject.toml # UV project config
└── README.md故障排除
服务器无法启动
- 检查UV是否安装:
uv --version - 尝试
uv sync重新安装依赖项 - 检查端口8000未使用:
lsof -i :8000
无法连接到MCP服务器
- 验证服务器命令是否正确
.mcp.json - 检查所需的环境变量是否已设置
- 在服务器输出中查找连接错误
- 尝试手动连接:
npx -y @modelcontextprotocol/server-github
执行失败
- 检查代码中的语法错误
- 验证导入是否可用(在REPL中安装软件包:
execute_python(code="!pip install requests")) - 查看结果中的异常追溯
工具不可用
- 确保服务器已成功连接:
list_connected_servers() - 检查服务器是否正在运行(对于HTTP/SSE服务器)
- 验证身份验证(例如,GitHub的GH_TOKEN)
许可证
麻省理工学院
贡献
欢迎投稿!请打开问题以查找错误或功能请求。
