使用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秒 | \ |
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)
______________________________________________________________________
## 资源
- [人类工程学:使用MCP执行代码](https://www.anthropic.com/engineering/code-execution-with-mcp)
- [模型上下文协议文档](https://modelcontextprotocol.io/)
- [MCP服务器示例](https://github.com/modelcontextprotocol/servers)
______________________________________________________________________
## 许可证
麻省理工学院