MCP代码模式-Python实现
“LLM比直接调用工具更擅长编写代码” --Cloudflare工程团队
此存储库实现了 代码模式 概念从 Anthropic的MCP文章 和 Cloudflare的代码模式博客文章,演示了将MCP工具转换为Python API如何显著提高LLM性能。
______________________________________________________________________
什么是代码模式?
问题: 传统的工具调用要求LLM:
- 学习合成工具调用语法
- 为多步骤任务进行多次往返
- 将中间结果传递回神经网络
- 使用许多/复杂的工具
解决方案: 代码模式利用了LLM最强大的能力——编写代码:
- 转换MCP工具→ 熟悉的Python API
- LLM使用API生成代码(一次调用)
- 直接执行代码(多次工具调用,无LLM往返)
- 结果流经变量,而不是神经网络
______________________________________________________________________
性能比较
传统MCP方法
User: "Compare weather in Austin and London"
Step 1: LLM → Tool call: get_weather("Austin")
Step 2: Result → Back through LLM (costs tokens!)
Step 3: LLM → Tool call: get_weather("London")
Step 4: Result → Back through LLM (costs tokens!)
Step 5: LLM → Generate comparison
Total: 3+ LLM calls, high token usage, slow代码模式方法
User: "Compare weather in Austin and London"
Step 1: LLM → Generate Python code:
austin = WeatherService.get_weather("Austin, TX")
london = WeatherService.get_weather("London, UK")
print(f"Difference: {austin['temp'] - london['temp']} degrees")
Step 2: Execute code directly (NO LLM involved!)
→ Calls both tools
→ Calculates difference
→ Prints result
Total: 1 LLM call, minimal tokens, fast结果: 34华氏度的差异是在没有任何LLM参与的情况下计算的!
______________________________________________________________________
存储库结构
mcp_context_save/
├── mcp_to_python_api.py # Universal MCP → Python API converter
├── mcp_code_executor.py # Code execution engine
├── mcp_with_llm.py # Real LLM integration
├── simple_demo.py # Educational demonstration
├── example_real_mcp_usage.py # Real-world examples
├── generated_mcp_api.py # Auto-generated API (output)
│
└── Documentation/
├── README.md # This file
├── MCP_TO_PYTHON_API_FLOW.md # Complete flow explanation
├── REAL_MCP_SERVER_INTEGRATION.md # Integration guide
├── EXECUTOR_INTERCEPTION_EXPLAINED.md # How execution works
└── PRACTICAL_USE_CASES.md # Real-world examples______________________________________________________________________
快速开始
1.运行简单演示
python simple_demo.py这表明:
- 传统与代码模式比较
- 天气比较示例
- 多步计算示例
输出:
Weather Report:
Austin: 93 degrees fahrenheit - sunny
London: 15 degrees celsius - rainy
Comparison:
Austin: 93.0 F
London: 59.0 F (converted from 15 C)
-> Austin is warmer by 34.0 degrees F2.从MCP工具生成Python API
python mcp_to_python_api.py它的作用:
- 连接到模拟MCP服务器(天气+计算器)
- 通过以下方式检索工具定义
tools/list - 生成Python API代码
- 保存到
generated_mcp_api.py
输出文件 (generated_mcp_api.py):
from typing import Any, Dict, List, Optional
class WeatherService:
@staticmethod
def get_weather(location: str, units: Optional[str] = None) -> Dict[str, Any]:
"""Get current weather for a location"""
pass
class Calculator:
@staticmethod
def calculate(operation: str, a: float, b: float) -> Dict[str, Any]:
"""Perform mathematical calculations"""
pass3.与Real LLM一起使用
# Set your API key
set OPENAI_API_KEY=your-key-here
# or
set ANTHROPIC_API_KEY=your-key-here
# Run interactive mode
python mcp_with_llm.py互动环节:
> What's the weather in London?
[LLM generates code]
result = WeatherService.get_weather(location="London, UK")
print(f"Temperature: {result['temperature']}°{result['unit']}")
[Execution]
Temperature: 15°celsius______________________________________________________________________
核心组件
1.MCP到Python API转换器
文件: mcp_to_python_api.py
它的作用:
- 连接到MCP服务器(stdio、HTTP或JSON)
- 呼叫
tools/list获取工具定义 - 使用类型提示和文档字符串生成Python API
- 另存为可导入的Python模块
用途:
import asyncio
from mcp_to_python_api import MCPToPythonAPI
async def main():
converter = MCPToPythonAPI()
# Connect to MCP server
await converter.add_server_from_command(
"weather",
["python", "weather_mcp_server.py"]
)
# Generate API
converter.save_api_code("weather_api.py")
await converter.close_all()
asyncio.run(main())请参阅: MCP_TO_PYTHON_API_FLOW.md 详细解释。
2.安全的Python执行器
文件: mcp_code_executor.py
它的作用:
- 创建沙盒Python环境
- 将MCP绑定作为动态类注入
- 拦截MCP工具的方法调用和路由
- 安全执行LLM生成的代码
关键创新:
# When LLM generates:
result = WeatherService.get_weather(location="Austin")
# Executor intercepts and routes to actual MCP tool:
weather_tool.execute(location="Austin")
# Returns real data without LLM involvement!请参阅: 执行_交互_解释.md 适合深潜。
3.法学硕士整合
文件: mcp_with_llm.py
它的作用:
- 与OpenAI或Anthropic API集成
- 使用生成的Python API构建系统提示
- 处理用户请求
- 执行生成的代码
系统提示结构:
You are a helpful assistant. You have access to these APIs:
[Generated Python API code here]
When the user asks questions, write Python code using these APIs.______________________________________________________________________
主要优势
1.处理更多工具
- 传统: LLM努力使用10多种工具
- 代码模式: 轻松处理50多种工具(只是更多方法)
2.更好的链条
- 传统: LLM的每个结果(昂贵)
- 代码模式: 直接变量传递(免费)
3.执行速度更快
- 传统: 多次LLM往返
- 代码模式: 单代码生成+直接执行
4.成本更低
- 传统: 高令牌使用率(通过LLM获得的结果)
- 代码模式: 令牌使用率低(仅最终输出)
5.能力更强
- 传统: 合成工具调用示例
- 代码模式: 数十亿个真正的Python示例在训练中
______________________________________________________________________
文档
完整指南
- 10步流程图 - 详细的代码分解 - JSON-RPC通信说明 - 类型转换逻辑 - 完整的示例跟踪
- 官方MCP服务器(文件系统、GitHub等) - 创建自定义Python MCP服务器 - 基于HTTP的MCP服务器 - 多台服务器组合 - 调试提示
- 如何拦截方法调用 - 动态类创建 - 关闭魔法 - exec()沙盒环境 - 安全注意事项 - 逐步跟踪
- 数据分析管道 - DevOps自动化 - 电子商务订单处理 - 研究助理 - 多云基础设施
______________________________________________________________________
真实世界的例子
示例1:多步计算
# LLM generates:
step1 = Calculator.calculate(operation="add", a=10, b=20)
step2 = Calculator.calculate(operation="multiply", a=step1['result'], b=5)
step3 = Calculator.calculate(operation="subtract", a=step2['result'], b=15)
print(f"Final: {step3['result']}")
# Executes in one go:
# Step 1: 10 + 20 = 30
# Step 2: 30 * 5 = 150
# Step 3: 150 - 15 = 135
# Final: 135中间步骤没有LLM往返!
示例2:天气比较
# LLM generates:
austin = WeatherService.get_weather(location="Austin, TX")
london = WeatherService.get_weather(location="London, UK")
# Compare (convert celsius to fahrenheit)
london_f = (london['temperature'] * 9/5) + 32 if london['unit'] == 'celsius' else london['temperature']
if austin['temperature'] > london_f:
print(f"Austin is warmer by {austin['temperature'] - london_f:.1f}°F")所有计算都在代码中进行,而不是通过LLM!
示例3:DevOps自动化
# LLM generates complete workflow:
status = Monitoring.get_service_status("api-service")
errors = Monitoring.get_error_count("api-service", "1h")
if errors['count'] > 100:
issue = Github.create_issue(
repo="company/api",
title=f"High error rate: {errors['count']} errors",
body=f"Status: {status}\\nErrors: {errors}"
)
Slack.send_message(
channel="eng-alerts",
text=f"Alert! {errors['count']} errors. Issue: {issue['url']}"
)在一次执行中实现复杂的多服务协调!
______________________________________________________________________
建筑
┌────────────────────────────────────────────────────────────┐
│ User Request │
└─────────────────────┬──────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────┐
│ LLM (OpenAI/Anthropic/etc.) │
│ │
│ System Prompt includes: │
│ - Generated Python API documentation │
│ - Usage examples │
│ │
│ Generates: Python code using familiar APIs │
└─────────────────────┬──────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────┐
│ SafePythonExecutor │
│ │
│ • Sandboxed environment │
│ • MCP bindings injected as classes │
│ • Intercepts method calls │
└─────────────────────┬──────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────┐
│ MCP Servers │
│ │
│ • Weather Service │
│ • Calculator Service │
│ • Database Service │
│ • ... (any MCP server) │
└────────────────────────────────────────────────────────────┘______________________________________________________________________
创建自己的MCP服务器
看 REAL_MCP_SERVER_集成.md 完整的指南。
快速模板:
#!/usr/bin/env python3
import json
import sys
class MyMCPServer:
def get_tools_list(self):
return {
"tools": [
{
"name": "my_tool",
"description": "What my tool does",
"inputSchema": {
"type": "object",
"properties": {
"param1": {"type": "string", "description": "..."}
},
"required": ["param1"]
}
}
]
}
def my_tool(self, param1):
# Your implementation
return {"result": "..."}
def call_tool(self, name, arguments):
if name == "my_tool":
return self.my_tool(**arguments)
raise ValueError(f"Unknown tool: {name}")
def handle_request(self, request):
method = request.get("method")
params = request.get("params", {})
req_id = request.get("id")
try:
if method == "tools/list":
result = self.get_tools_list()
elif method == "tools/call":
result = self.call_tool(params["name"], params["arguments"])
else:
return {"jsonrpc": "2.0", "id": req_id,
"error": {"code": -32601, "message": f"Unknown method: {method}"}}
return {"jsonrpc": "2.0", "id": req_id, "result": result}
except Exception as e:
return {"jsonrpc": "2.0", "id": req_id,
"error": {"code": -32603, "message": str(e)}}
def run(self):
while True:
try:
line = sys.stdin.readline()
if not line:
break
request = json.loads(line)
response = self.handle_request(request)
sys.stdout.write(json.dumps(response) + "\n")
sys.stdout.flush()
except Exception as e:
sys.stderr.write(f"Error: {e}\n")
if __name__ == "__main__":
MyMCPServer().run()______________________________________________________________________
安全说明
当前的沙盒仅用于演示!
用于生产用途:
- 使用Docker容器
- 使用gVisor或Firecracker
- 实施适当的资源限制
- 添加网络隔离
- 使用只读文件系统
看 执行_交互_解释.md 关于安全细节。
______________________________________________________________________
为什么这有效
核心见解
LLMs接受过以下方面的培训:
- 数十亿 真正的Python代码行数
- 数千 不同的Python API
- 百万 代码示例
但仅限于:
- 合成的 工具调用示例
- 有限的 工具调用模式
- 最近 除了培训
结果: LLMs擅长Python,但在工具调用方面很困难。
解决方案: 让他们做他们擅长的事情——写代码!
来自Cloudflare的文章
“让法学硕士用工具调用来完成任务,就像让莎士比亚上一个月的普通话课,然后让他用它写一部戏剧。这不会是他最好的作品。”
代码模式让莎士比亚用英语(Python)写作!
______________________________________________________________________
参考文献
______________________________________________________________________
许可证
MIT许可证-请参阅许可证文件
______________________________________________________________________
贡献
欢迎投稿!感兴趣的领域:
- 其他MCP服务器示例
- 安全改进
- 性能优化
- 文档改进
- 真实世界的用例示例
______________________________________________________________________
总结
此存储库演示了 LLM比调用工具更擅长编写代码通过将MCP工具转换为熟悉的Python API,我们实现了:
- 快3倍 执行(无法学硕士往返)
- 便宜10倍 令牌使用情况(通过LLM没有中间结果)
- 更好的操控 复杂、多步骤的工作流程
- 更多工具 支持(50+vs 10)
- 更清晰的代码 这更容易调试
LLM工具使用的未来是 代码生成,不 工具调用!
