MCP代理代码生成器
受以下启发,使用模型上下文协议(MCP)服务器执行代理生成的代码的hello world演示 Anthropic关于使用MCP执行代码的博客文章.
概述
该项目演示了AI代理如何:
- 从多个服务器中发现可用的MCP工具
- 根据自然语言请求生成TypeScript代码
- 执行生成的代码以利用多个MCP
- 将结果返回给用户
代理不直接调用工具,而是编写导入和使用MCP函数的代码,从而允许复杂的数据处理和多工具编排。
建筑
┌─────────────────────────────────────────────────────────────┐
│ User Input │
│ "Get weather in SF and convert to °F" │
└───────────────────────┬─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Agent (Claude) │
│ - Discovers available MCP tools │
│ - Generates TypeScript code to accomplish task │
└───────────────────────┬─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Generated Code │
│ import { getWeather } from './servers/weather/index.js'; │
│ import { multiply, add } from './servers/calculator/...'; │
│ │
│ const weather = await getWeather('San Francisco'); │
│ const f = await add(await multiply(weather.temp, 9/5),32); │
│ return { city: weather.city, fahrenheit: f }; │
└───────────────────────┬─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Code Executor │
│ - Validates code safety │
│ - Executes in isolated environment │
│ - Captures output and logs │
└───────────────────────┬─────────────────────────────────────┘
│
▼
┌──────────────────┬──────────────────┬──────────────────────┐
│ Weather MCP │ Calculator MCP │ Filesystem MCP │
│ - getWeather() │ - add() │ - readFile() │
│ - getForecast() │ - subtract() │ - writeFile() │
│ │ - multiply() │ - listFiles() │
│ │ - divide() │ - deleteFile() │
└──────────────────┴──────────────────┴──────────────────────┘特性
- 多个MCP服务器:包括天气、计算器和文件系统MCP
- 工具发现:自动发现并编目可用工具
- 代码生成:Claude生成TypeScript代码来解决任务
- 安全执行:单独验证和执行生成的代码
- 渐进呈现:仅加载任务所需的工具定义
- 交互模式:与代理聊天以构建复杂的工作流程
入门指南
先决条件
- Node.js 18+
- TypeScript 5+
- 无烟煤API键
安装
- 克隆存储库:
git clone
cd mcp-with-code- 安装依赖项:
npm install- 创建一个
.env使用您的Anthropic API密钥文件:
cp .env.example .env
# Edit .env and add your ANTHROPIC_API_KEY运行示例
运行预定义的示例:
npm run dev这将执行几个示例查询:
- 获取天气并转换温度
- 进行运算
- 将数据保存到文件
- 列出工作区文件
交互模式
启动交互式聊天会话:
npm run dev -- --interactive然后键入自然语言请求,如:
- “获取伦敦的天气并将其保存到weather.json”
- “计算144的平方根”
- “阅读weather.json文件并告诉我温度”
类型 exit 退出或 reset 清除对话历史记录。
项目结构
mcp-with-code/
├── src/
│ ├── servers/ # MCP server implementations
│ │ ├── weather/ # Weather MCP
│ │ │ └── index.ts # Weather tools (getWeather, getForecast)
│ │ ├── calculator/ # Calculator MCP
│ │ │ └── index.ts # Math tools (add, subtract, multiply, etc.)
│ │ └── filesystem/ # Filesystem MCP
│ │ └── index.ts # File tools (readFile, writeFile, etc.)
│ ├── agent.ts # Main agent logic with Claude
│ ├── discovery.ts # Tool discovery system
│ ├── executor.ts # Code execution engine
│ └── index.ts # Application entry point
├── workspace/ # Sandboxed file workspace (created at runtime)
├── temp/ # Temporary code execution files
├── package.json
├── tsconfig.json
└── README.md运作原理
1.工具发现
这 discovery.ts 模块扫描 src/servers/ 目录和摘录:
- 可用的MCP服务器
- 导出的功能(工具)
- 函数签名和参数
- JSDoc描述
2.代理代码生成
当您发送消息时,代理:
- 接收所有可用工具的描述
- 分析您的请求
- 生成导入并使用必要MCP工具的TypeScript代码
- 返回markdown代码块中的代码
3.代码执行
这 executor.ts 模块:
- 验证生成的代码的安全性
- 将其写入临时文件
- 使用执行它
tsx - 捕获输出、日志和错误
- 将结果返回给用户
4.MCP服务器
每个MCP服务器(天气、计算器、文件系统)都提供异步函数,这些函数:
- 由系统自动发现
- 可以导入并在生成的代码中使用
- 模拟真实的MCP服务器交互(用于此演示)
示例执行流程
用户请求:
"Get the weather in San Francisco and convert the temperature to Fahrenheit"生成代码:
import { getWeather } from './servers/weather/index.js';
import { multiply, add } from './servers/calculator/index.js';
const weather = await getWeather('San Francisco');
const fahrenheit = await add(await multiply(weather.temperature, 9/5), 32);
return {
city: weather.city,
celsius: weather.temperature,
fahrenheit: Math.round(fahrenheit * 100) / 100,
condition: weather.condition
};执行日志:
[Weather MCP] Getting weather for San Francisco
[Calculator MCP] Multiplying 18 * 1.8
[Calculator MCP] Adding 32.4 + 32结果:
{
"city": "San Francisco",
"celsius": 18,
"fahrenheit": 64.4,
"condition": "Foggy"
}这种方法的好处
- 代币效率:通过在代码中处理数据而不是传递模型,将上下文大小减少了98%+
- 隐私:敏感数据保留在执行环境中
- 灵活性:代理可以执行复杂的数据转换和多工具编排
- 可扩展性:支持数百种工具,无需压倒性的上下文
- 持久性:生成的代码可以保存和重用
扩展系统
添加新的MCP服务器
- 在中创建新目录
src/servers/:
mkdir src/servers/myserver- 创建一个
index.ts带有导出异步函数的文件:
/**
* My Server MCP
* Description of what this server does
*/
/**
* Do something useful
* @param param1 - First parameter
* @returns Result
*/
export async function doSomething(param1: string): Promise {
// Implementation
return result;
}- 该工具将被自动发现并可供代理使用!
局限性
这是一个hello world演示,但有一些限制:
- 模拟MCP服务器:MCP服务器是模拟的,而不是真正的MCP协议实现
- 基础沙盒:代码执行使用基本验证,而不是完全沙盒
- 没有坚持:对话历史记录仅在内存中
- 有限的错误处理:生产系统需要更稳健的错误处理
实际应用
该架构实现了:
- 数据集成:从Google云端硬盘中提取、处理、推送到Salesforce
- 多步骤工作流:跨越数十种工具的连锁经营
- 复杂的转换:在本地过滤、聚合和处理大型数据集
- 隐私保护人工智能:将敏感数据排除在模型上下文之外
参考文献
许可证
麻省理工学院
贡献
欢迎投稿!这是一个演示项目,旨在帮助理解MCP代码执行模式。
