MCP Code Mode
Enables AI agents to write and execute Python code in an isolated sandbox that can orchestrate multiple MCP tool calls, reducing context window bloat and improving efficiency for complex workflows.
README
MCP Code Mode
Prototype implementation for the Code Execution MCP Server with DSpy. The "Code Execution with MCP" architecture combines the strengths of Large Language Models at code generation with the Model Context Protocol for tool integration. This system enables an AI agent to write Python code that runs in an isolated sandbox while seamlessly calling external MCP tools.
Quick Start
1. Installation
Requires Python 3.11+ and Node.js 20+.
# Create virtual environment
python3.11 -m venv .venv
source .venv/bin/activate
# Install dependencies
pip install -e .[dev]
# Install Node.js dependencies for reference servers
npm install -g npm@latest
2. Configuration
Copy the example environment file and configure secrets:
cp .env.example .env
Configure your MCP servers in mcp_servers.json:
{
"servers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/your-working-folder"],
"description": "Local file system operations"
}
}
}
3. Running the Server
Launch the Code Execution MCP server:
python -m mcp_code_mode.executor_server
4. Verification
Verify your setup by running the debug executor script. This script simulates an MCP client, connects to the server, and runs a test task to ensure the agent and tools are working correctly.
Before running the script:
- Configure the MCP servers you want to interact with in
mcp_servers.json. - Define the specific task you want the agent to perform by editing the
taskvariable inscripts/debug_executor.py.
python scripts/debug_executor.py
Development Commands
| Command | Description |
|---|---|
pytest |
Run all tests |
ruff check . |
Lint the codebase |
black . |
Format the codebase |
mypy src |
Type check the source |
python scripts/test_dspy_sandbox.py |
Sanity check the sandbox |
python scripts/debug_executor.py |
Integration test with mock client |
Execution Environment & Guardrails
By default, the system uses a Local Python Executor (LocalPythonExecutor) which runs code in the same process as the server. This is necessary because the strict Pyodide sandbox has limitations with network I/O, preventing it from calling back to other MCP tools in some environments.
Guardrails
Even with the local executor, the system enforces policies before code execution:
- Limits: 8k characters / 400 lines max.
- Imports: Allowlist only (
json,math,re,datetime, etc.). - Tokens: Disallows potentially dangerous tokens (
subprocess,exec,eval).
Violations return a POLICY_VIOLATION error.
Note: You can force the use of the Pyodide sandbox by setting
MCP_EXECUTOR=pyodide, but this may break tool calls depending on your environment.
Architecture
Overview
┌─────────────────────────────────────────────────────────────┐
│ MCP Client (Claude, etc.) │
└────────────────────────┬────────────────────────────────────┘
│ MCP Protocol (stdio/HTTP/SSE)
▼
┌─────────────────────────────────────────────────────────────┐
│ FastMCP Server │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ @mcp.tool │ │
│ │ async def execute_code(code: str): │ │
│ │ # 1. Execute in Local Executor (default) │ │
│ │ result = await executor.run(code) │ │
│ │ return result │ │
│ └──────────────────────────────────────────────────────┘ │
└────────────────────────┬────────────────────────────────────┘
│
▼
┌──────────────────────────────┐
│ Execution Engine: │
│ • LocalPythonExecutor │
│ (or Pyodide Sandbox) │
└──────────────────────────────┘
Why Code Mode?
Traditional MCP implementations face critical challenges:
- Context Window Bloat: Every tool definition consumes tokens, limiting scalability.
- Token Cost: Multiple back-and-forth tool calls are expensive.
- Latency: Sequential tool invocations create cumulative delays.
- Composability: Complex workflows require many discrete steps.
Code Mode addresses these by leveraging what LLMs excel at: writing code. Rather than making multiple tool calls, the agent writes a Python script that orchestrates all necessary operations internally.
Core Components
-
The Executor Server (FastMCP) (
src/mcp_code_mode/executor_server.py) The server exposes anexecute_codetool backed by a Python executor (Local or Pyodide). Usesfastmcpto handle the MCP protocol anddspyfor execution logic. -
Configuration-Driven Discovery (
mcp_servers.json) The system usesmcp_servers.jsonto explicitly configure which MCP servers to connect to. Loaded bysrc/mcp_code_mode/mcp_manager.py. -
Tool Schema Formatting (
src/mcp_code_mode/tool_formatter.py) Formats discovered MCP tools into readable documentation that gets passed to the code generation LLM, so it knows what tools exist. -
Context Injection The formatted tool schemas are passed as an input field to the LLM. The LLM knows tool names, parameters, and usage examples before it writes the code.
Information Flow
1. mcp_servers.json (Defines servers)
↓
2. MCPServerManager.initialize()
├─ Connect to configured servers
├─ Call list_tools() on each
└─ Convert to DSpy tools
↓
3. ToolSchemaFormatter.format_for_llm()
└─ Creates readable documentation
↓
4. CodeExecutionAgent
└─ Stores both callable tools and schemas
↓
5. Agent Generation
└─ Passes tool_context to LLM
↓
6. Code Execution
└─ Code runs in sandbox, calling actual tools via MCP
Troubleshooting
Timeout Issues: If the interpreter times out, it may enter a bad state. Currently, the best fix is to restart the server or reconnect the client to get a fresh interpreter instance.
Missing Tools:
Ensure mcp_servers.json paths are correct and that you have run npm install if using Node-based servers.
References
mcp-code-mode
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。