关于 [Anthropic] MCP代码执行 的解释与总结
根据您的查询 “[Anthropic] MCP代码执行”,这似乎指的是 Anthropic 公司于 2025 年 11 月 4 日发布的工程博客文章:《Code execution with MCP: Building more efficient agents》(代码执行与 MCP:构建更高效的智能体)。这篇文章介绍了如何使用 Model Context Protocol (MCP) 结合代码执行来优化 AI 智能体(agents)的工具调用效率,减少 token 消耗(从 15 万降至 2 千,节省 98.7% 的时间和成本)。
MCP 是一个开放标准,用于将 AI 智能体连接到外部系统(如工具、数据服务)。文章的核心是解决 MCP 在工具数量增多时的痛点:工具定义过多导致上下文窗口过载,以及中间结果反复传递增加延迟和成本。解决方案是通过 代码执行(code execution)模式,让智能体生成代码来调用 MCP 工具,而不是直接工具调用。
主要问题与挑战
- 工具定义过载上下文窗口:传统方式将所有工具描述加载到模型上下文中,导致 token 消耗巨大(例如,连接数千工具可能需处理数十万 token)。
- 中间工具结果消耗 token:如从 Google Drive 获取文档并更新到 Salesforce 时,整个文档内容需多次通过模型上下文,容易超出窗口限制或出错。
传统架构示意图(文章描述):
- MCP 客户端加载所有工具定义到模型上下文。
- 模型直接调用工具,每次调用和结果都需通过模型循环处理。
解决方案:代码执行 + MCP
将 MCP 服务器呈现为代码 API 文件树结构,让智能体编写代码调用工具。这样:
- 只加载需要的工具定义(通过文件系统浏览或搜索)。
- 在执行环境中处理数据(过滤、聚合),只返回精简结果给模型。
文件树示例(TypeScript):
servers
├── google-drive
│ ├── getDocument.ts
│ └── index.ts
├── salesforce
│ ├── updateRecord.ts
│ └── index.ts
└── ... (其他服务器)
工具文件示例(getDocument.ts):
// ./servers/google-drive/getDocument.ts
import { callMCPTool } from "../../../client.js";
interface GetDocumentInput {
documentId: string;
}
interface GetDocumentResponse {
content: string;
}
/* Read a document from Google Drive */
export async function getDocument(input: GetDocumentInput): Promise<GetDocumentResponse> {
return callMCPTool<GetDocumentResponse>('google_drive__get_document', input);
}
智能体生成的代码示例(处理 Google Drive 到 Salesforce 的任务):
// Read transcript from Google Docs and add to Salesforce prospect
import * as gdrive from './servers/google-drive';
import * as salesforce from './servers/salesforce';
const transcript = (await gdrive.getDocument({ documentId: 'abc123' })).content;
await salesforce.updateRecord({
objectType: 'SalesMeeting',
recordId: '00Q5f000001abcXYZ',
data: { Notes: transcript }
});
- 发现工具:智能体通过列出
./servers/目录或使用search_tools工具查找相关工具。 - 减少 token:从 150,000 降至 2,000,节省 98.7%。
优势
- 渐进式披露(Progressive Disclosure):模型按需读取工具文件,或使用
search_tools工具(可指定细节级别:仅名称、描述或完整定义)。 - 上下文高效的工具结果:在代码中过滤大数据集,只返回摘要给模型。
示例(处理 10,000 行表格):
const allRows = await gdrive.getSheet({ sheetId: 'abc123' });
const pendingOrders = allRows.filter(row => row["Status"] === 'pending');
console.log(`Found ${pendingOrders.length} pending orders`);
console.log(pendingOrders.slice(0, 5)); // 只返回前 5 行
- 更强大的控制流:使用循环、条件、错误处理,而非多次工具调用。
示例(轮询 Slack 通知):
let found = false;
while (!found) {
const messages = await slack.getChannelHistory({ channel: 'C123456' });
found = messages.some(m => m.text.includes('deployment complete'));
if (!found) await new Promise(r => setTimeout(r, 5000));
}
console.log('Deployment notification received');
- 隐私保护操作:在执行环境中处理敏感数据,使用 tokenization(如将邮箱替换为
[EMAIL_1]),模型只看到占位符。 - 状态持久化和技能:保存文件跨执行(如 CSV),或创建可复用函数(技能文件夹 + SKILL.md 描述)。
权衡与注意事项
- 优势:减少 token、降低延迟、提升工具组合能力。
- 缺点:需要安全代码执行环境(沙盒、资源限制、监控),增加运维复杂性。简单任务仍可使用传统工具调用。
- Cloudflare 也独立发现了类似方法,称为 “Code Mode”。
实践建议
- 实现时,使用文件系统呈现工具 API。
- 社区可分享经验,推动 MCP 生态发展。
文章作者:Adam Jones 和 Conor Kelly,感谢多位反馈者。
如果您需要:
- 具体实现代码(TypeScript/Python 示例)。
- 与 jQuery EasyUI 结合的演示(例如,在 DataGrid 中动态排序 MCP 数据)。
- 更多细节或工具调用演示,请提供更多信息!