使用说明
使用MCP执行代码
由Paul Brower于2026年1月24日上午11:59创建
通过让模型编写代码而不是进行单独的工具调用,大大加快了人工智能辅助的批处理操作。
此存储库探索 使用MCP执行代码 Anthropic工程博客中的模式,以及你可以自己运行的工作示例。
问题
当你让人工智能助手一次处理一条记录时,速度非常慢:
User: "Update the status on these 50 records"
AI: [calls tool to find record 1]
AI: [calls tool to update record 1]
AI: [calls tool to find record 2]
AI: [calls tool to update record 2]
... repeat 48 more times ...
每次工具调用都需要一次完整的往返:模型推理→ API调用→ 工具执行→ 响应解析→ 再次进行模型推理。在我们的测试中, 每次工具调用大约需要4秒对于50条记录,每条记录有2个电话,这是 约7分钟.
解决方案
让AI编写执行批处理操作的代码,而不是逐一调用工具:
// One tool call that runs this code:
for (const id of recordIds) {
const record = await memory.openNodes([id]);
await memory.addObservations([{ entityName: id, contents: ['status: processed'] }]);
}
结果:1毫秒内记录50条,而不是7分钟。
为什么这很重要
| 好处 | 说明 |
|---|---|
| 速度 | 消除迭代操作的模型往返 |
| 代币效率 | 将更少的工具定义加载到上下文中(减少约95%) |
| 减少上下文腐烂 | 更少的来回意味着更清晰的对话历史 |
| 天然成分 | 循环、条件和数据转换在代码中是很自然的 |
| 可扩展性 | 在不增加上下文的情况下处理数百个工具 |
何时使用每种方法
| 使用直接工具调用 | 使用代码执行 |
|---|---|
| 探索和发现 | 批处理操作(“对于每个X,做Y”) |
| 一次性查询 | 复杂的过滤和转换 |
| 学习数据结构 | 多步骤工作流程 |
| 简单操作 | 对多条记录的操作 |
实验
实验1:批量记录更新
测试迭代内存操作的直接工具调用和代码执行之间的性能差异。
结果摘要
| 度量 | 直接工具调用 | 代码执行 | 改进 |
|---|---|---|---|
| 5次迭代 | 42.7秒 | <1毫秒 | 快42000倍 |
| 50次迭代 | 约7分钟 | 1毫秒 | 约430000倍快 |
| 每批工具调用 | 每次迭代2次 | 共1次 | 减少90-99% |
| 上下文中的工具标记 | ~6000 | ~300 | 95%减少 |
关键发现
模型往返是瓶颈,而不是工具执行。 每次直接工具调用大约需要4.3秒(模型推理+API延迟+MCP执行)。代码执行消除了迭代操作的这种情况。
亲自进行实验
先决条件
- Node.js 18+
- 克劳德代码 命令行界面
- npm
设置
-
克隆仓库
git clone https://github.com/yourusername/code-mode.git cd code-mode -
安装依赖项
npm install -
构建项目
npm run build -
配置MCP服务器
创建或更新
.mcp.json在项目根目录中:{ "mcpServers": { "code_mode_memory": { "type": "stdio", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-memory"], "env": { "MEMORY_FILE_PATH": "/path/to/code-mode/code-mode-memory.jsonl" } }, "code_executor": { "type": "stdio", "command": "node", "args": ["dist/mcp-server/index.js"], "cwd": "/path/to/code-mode" } } }替换
/path/to/code-mode根据您的实际项目路径。 -
重新启动Claude代码 获取新的MCP配置
运行测试
测试内存包装库:
npm test
测试代码执行器:
npm run test:executor
在Claude代码中使用代码执行器
配置后,您可以使用 execute_code 克劳德代码中的工具:
// Example: Count active records
const graph = await memory.readGraph();
const activeCount = graph.entities.filter(entity =>
entity.observations.some(obs => obs === "status: active")
).length;
console.log(`Active records: ${activeCount}`);
代码在沙盒环境中执行,可以访问内存操作,但限制系统访问。
项目结构
code-mode/
├── servers/memory/ # TypeScript wrappers for memory MCP tools
│ ├── types.ts # Type definitions
│ ├── client.ts # MCP client interface
│ ├── operations.ts # Tool wrapper functions
│ └── index.ts # Public exports
├── executor/ # Code execution sandbox
│ ├── sandbox.ts # VM-based sandboxed execution
│ └── index.ts # Executor entry point
├── mcp-server/ # MCP server exposing execute_code tool
│ └── index.ts # Server implementation
├── test/ # Test files
├── code-mode-memory.jsonl # Test data (50 sample records)
├── Experiment1.md # Detailed experiment documentation
└── mcp-config.example.json # Example MCP configuration
运作原理
1.工具包装
我们不公开原始的MCP工具,而是创建类型化的TypeScript包装器:
// Direct MCP call (verbose, untyped)
mcp__code_mode_memory__read_graph()
// Wrapper (clean, typed)
await memory.readGraph()
2.沙盒执行
代理生成的代码在Node.js VM沙箱中运行,具有:
- 访问内存工具包装器
- 控制台输出捕获
- 超时保护
- 无文件系统或网络访问
3.单一工具调用
这 execute_code MCP工具接受JavaScript代码并在沙箱中运行:
Model → execute_code("...loop over 50 records...") → Sandbox executes all iterations → Single result
与直接工具调用相比:
Model → tool call → result → Model → tool call → result → ... (100 round trips)
资源
许可证
麻省理工学院
