使用MCP执行代码-模板库
一个生产就绪的模板,用于使用 使用MCP执行代码 图案。该工具使AI代理能够通过安全的沙盒代码执行动态发现和执行MCP工具。
🌟 主要特点
- 动态工具发现 -在运行时发现的工具使用
list_mcp_tools()和get_mcp_tool_details()(无静态文件) - 安全沙盒执行 -基于Docker的隔离,具有资源限制、只读文件系统和网络限制
- PII保护 -敏感数据的自动标记化/去标记化
- 持久技能 -
/skills可重用代理代码目录 - 临时工作区 -
/workspace临时任务文件目录 - 多回合对话 -支持复杂的代理工作流
- 可扩展架构 -易于定制和扩展
💡 为什么要执行代码?
代币效率问题传统的人工智能代理必须用自然语言描述每一个计算步骤,消耗了宝贵的上下文窗口空间。处理1000条记录可能需要50000个令牌来描述转换。
解决方案代码执行允许代理编写和运行代码,将计算委托给传统软件,同时将智能集中在高级推理上。同样的1000条记录任务只使用了大约500个代码令牌。
主要优势:
- 📊 可扩展性:在令牌限制内处理任何复杂的任务
- 🔄 可重用性:将代码保存到
/skills以备将来使用 - 🔒 隐私:PII在达到LLM之前被标记
- 🎯 可靠性:确定性代码执行与自然语言描述
📖 阅读完整的哲学 docs/PHILOSOPHY.md -基于Anthropic的研究,解释了这种架构背后的“原因”。🏗️ 建筑
┌─────────────────────────────────────────────────────────────┐
│ User / Application │
└────────────────────┬────────────────────────────────────────┘
│ HTTP Request
▼
┌─────────────────────────────────────────────────────────────┐
│ Agent Orchestrator │
│ ┌──────────────┐ ┌──────────────┐ ┌─────────────────┐ │
│ │ AgentManager │◄─┤ PII Censor │◄─┤ MCP Client │ │
│ └──────┬───────┘ └──────────────┘ └─────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ LLM Provider │ (OpenAI, Anthropic, etc.) │
│ └──────┬───────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────┐ │
│ │ Sandbox Manager (Docker) │ │
│ └──────┬───────────────────────────┘ │
└─────────┼────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Secure Docker Container │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Agent Code Execution │ │
│ │ - Runtime API (callMCPTool, fs, utils) │ │
│ │ - Dynamic Tool Discovery │ │
│ │ - /skills (persistent, mounted) │ │
│ │ - /workspace (ephemeral, mounted) │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ Security: Non-root user, read-only rootfs, resource limits │
└─────────────────────────────────────────────────────────────┘
│
│ Authenticated API Call
▼
┌─────────────────────────────────────────────────────────────┐
│ MCP Servers │
│ (File System, Databases, APIs, Custom Tools) │
└─────────────────────────────────────────────────────────────┘🚀 快速开始
先决条件
- Node.js>=18.0.0
- Docker(用于沙盒执行)
- TypeScript知识
安装
# Clone the repository
git clone
cd code-execution-with-MCP
# Install dependencies
npm install
# Build the project
npm run build
# Build the Docker sandbox image
npm run build-sandbox
# Create required directories
npm run prepare-workspace
# Start the server
npm start发展
# Run in development mode with auto-reload
npm run dev
# Type checking only
npm run type-check
# Clean build artifacts
npm run clean📁 项目结构
mcp-code-exec-harness/
├── src/
│ ├── agent_orchestrator/ # Main agent logic
│ │ ├── AgentManager.ts # Agent execution loop
│ │ └── prompt_templates.ts # System prompts
│ │
│ ├── sandbox_manager/ # Secure code execution
│ │ ├── SandboxManager.ts # Abstract interface
│ │ └── DockerSandbox.ts # Docker implementation
│ │
│ ├── mcp_client/ # MCP communication
│ │ ├── McpClient.ts # MCP server client
│ │ └── PiiCensor.ts # PII tokenization
│ │
│ ├── agent_runtime/ # Sandbox runtime API
│ │ └── runtime_api.ts # Injected helper functions
│ │
│ ├── tools_interface/ # Dynamic tool discovery
│ │ └── DynamicToolManager.ts
│ │
│ └── index.ts # Main server entry point
│
├── servers/ # MCP server collection (NEW!)
│ ├── official/ # Official MCP servers
│ ├── archived/ # Archived reference servers
│ ├── community/ # Community-contributed servers
│ ├── README.md # Server collection documentation
│ ├── catalog.json # Structured server index
│ └── QUICKSTART.md # Quick start guide
│
├── skills/ # Persistent agent skills (user-specific)
├── workspace/ # Ephemeral execution workspace
├── Dockerfile.sandbox # Secure sandbox container
├── package.json
├── tsconfig.json
└── README.md🔧 配置
环境变量
创建一个 .env 根目录中的文件:
# Server Configuration
PORT=3000
NODE_ENV=development
# Sandbox Configuration
SANDBOX_IMAGE=sandbox-image-name
SANDBOX_TIMEOUT_MS=30000
SANDBOX_MEMORY_MB=100
SANDBOX_CPU_QUOTA=50000
# LLM Provider (configure for your provider)
LLM_API_KEY=your-api-key-here
LLM_MODEL=your-model-name
# MCP Servers (customize for your setup)
# Add your MCP server configurations here自定义代理
- 实施LLM集成 -编辑
src/agent_orchestrator/AgentManager.ts:
async function callLLM(prompt: string, tools: any[]): Promise {
// Add your LLM API call here
// Examples: OpenAI, Anthropic, Google Gemini, etc.
}- 连接MCP服务器 -编辑
src/mcp_client/McpClient.ts:
private initializeServers(): void {
// Add your MCP server connections
// Use @modelcontextprotocol/sdk
}- 自定义系统提示 -编辑
src/agent_orchestrator/prompt_templates.ts
- 调整沙盒安全 -编辑
src/sandbox_manager/DockerSandbox.ts
🔐 安全功能
沙箱隔离
- 非根执行 -运行为
sandboxuser - 只读根文件系统 -防止系统修改
- 资源限制 -CPU和内存限制
- 网络限制 -可配置的网络访问
- 能力下降 -最小容器权限
PII保护
自动检测和标记:
- 电子邮件地址
- 电话号码
- 社会安全号码
- 信用卡号码
- 网际协议地址
- 自定义模式(可扩展)
认证
- 沙盒的会话特定身份验证令牌↔ 主机通信
- 在生产部署中验证令牌
📚 用法示例
提出请求
curl -X POST http://localhost:3000/task \
-H "Content-Type: application/json" \
-d '{
"userId": "user123",
"task": "Analyze the latest sales data and create a summary report"
}'代理代码示例
代理编写如下代码(在沙盒中执行):
// 1. Discover available tools
const tools = await list_mcp_tools();
console.log("Available tools:", tools);
// 2. Get tool details
const dbTool = await get_mcp_tool_details("database__query");
console.log("Tool info:", dbTool.description);
// 3. Execute tools
const salesData = await callMCPTool("database__query", {
query: "SELECT * FROM sales WHERE date > '2024-01-01'"
});
// 4. Process data in code
const summary = salesData.reduce((acc, sale) => {
acc.total += sale.amount;
acc.count += 1;
return acc;
}, { total: 0, count: 0 });
// 5. Save to skills for reuse
await fs.writeFile('/skills/sales_summary.js', `
module.exports = async function summarizeSales(data) {
return data.reduce((acc, sale) => {
acc.total += sale.amount;
acc.count += 1;
return acc;
}, { total: 0, count: 0 });
};
`);
// 6. Return results
return { summary, totalSales: summary.total, count: summary.count };🛠️ 扩展模板
MCP服务器集合
此存储库包括以下内容的综合集合 18台MCP服务器 为渐进式发现而组织:
- 📦 7官方服务器 -文件系统、Git、内存、提取、一切、时间、顺序思维
- 🗄️ 5台存档服务器 -PostgreSQL、Redis、SQLite、Puppeteer、Sentry
- 🌍 6个社区服务器 -MongoDB、GreptimeDB、非结构化、Semgrep、MCP安装程序、PostgreSQL社区分叉
快速入门:
# Browse the server collection
cd servers/
# Read the documentation
cat README.md
# Check the quick start guide
cat QUICKSTART.md
# View the structured catalog
cat catalog.json文档:
servers/README.md-完整的服务器收集文档servers/QUICKSTART.md-常见用例快速入门指南servers/catalog.json-用于程序化发现的结构化服务器索引- 特定类别的自述文件
servers/official/,servers/archived/,以及servers/community/
添加新的MCP服务器
// In src/mcp_client/McpClient.ts
async addServer(config: MCPServerConfig): Promise {
const client = new Client({
name: config.name,
version: '1.0.0'
}, {
capabilities: { tools: {} }
});
const transport = new StdioClientTransport({
command: config.command,
args: config.args
});
await client.connect(transport);
// Discover and register tools
const tools = await client.listTools();
tools.forEach(tool => this.registerTool(tool));
}集合中服务器的示例配置:
// Filesystem server (official)
await this.addServer({
name: 'filesystem',
command: 'npx',
args: ['@modelcontextprotocol/server-filesystem', '/workspace', '/skills']
});
// MongoDB server (community)
await this.addServer({
name: 'mongodb',
command: 'npx',
args: ['-y', 'mongodb-mcp-server', '--readOnly'],
env: { MDB_MCP_CONNECTION_STRING: process.env.MONGODB_URI }
});
// Git server (official)
await this.addServer({
name: 'git',
command: 'npx',
args: ['mcp-server-git']
});自定义PII模式
// In your code
const piiCensor = new PiiCensor();
piiCensor.addPattern('custom_id', /\bID-\d{6}\b/g);替代沙盒实现
扩展 SandboxManager 创建自定义执行环境:
- 基于WebAssembly的沙盒
- 云功能执行
- 基于过程的隔离
🧪 测试
# Test the sandbox
curl -X POST http://localhost:3000/task \
-H "Content-Type: application/json" \
-d '{
"userId": "test",
"task": "Write a simple hello world function and save it to skills"
}'
# Check health
curl http://localhost:3000/health📖 文件和参考
核心文件
- 哲学.md - ⭐ 从这里开始! 基于Anthropic的研究,解释代码执行、令牌效率和设计原则背后的“原因”
- 快速启动.md -5分钟后开始跑步
- 建筑.md -对系统组件进行深入的技术研究
- 安全.md -安全最佳实践和强化检查表
- 部署.md -生产部署指南(Docker、K8s、云)
- API示例.md -使用示例和模式
技能与示例
- 技能/示例/ -遵循拟人技能模式的示例技能
- template-skill/ -创建新技能的模板 - data-processor/ -令牌高效数据转换示例
外部参考
- 使用MCP执行代码 -Anthropic的工程博客文章描述了动态执行模型和哲学
- 人类技能库 -扩展代理功能的开源技能示例
- 为现实世界的代理人配备代理人技能 -持久代理能力背后的哲学
- 模型上下文协议文档 -MCP规范和指南
- **** -集装箱安全加固
🤝 贡献与社区协作
这是一个代表 新范式 在人工智能代理开发中,代码执行、安全性和持久性功能无缝协作。我们相信,这种方法有可能改变人工智能代理的大规模构建和部署方式。
我们邀请您一起构建这个
开源社区是推进这一范式的基础。我们欢迎各种形式的捐款:
我们正在寻求帮助的领域
- LLM集成 -添加对更多提供商的支持(Claude、GPT-4、Gemini、Llama等)
- MCP服务器连接器 -为流行服务(数据库、API、文件系统)构建适配器
- 安全加固 -审核沙盒,提出额外的安全措施
- 性能优化 -容器池、缓存策略、资源调优
- 监测和可观察性 -Prometheus度量、日志记录、分布式跟踪
- 技能库 -为社区创建可重用的、特定领域的技能
- 文档 -教程、部署指南、最佳实践
- 测试与示例 -集成测试、实际用例、基准测试
- 替代沙盒 -WebAssembly、云功能、进程隔离实现
- 前端用户界面 -仪表板、技能资源管理器、任务监控界面
如何做出贡献
- 分叉和定制 -从这个模板开始,针对您的特定用例
- 分享改进 -提交具有通用增强功能的PR
- 培养技能 -创建可重用技能并提交到社区技能库
- 报告问题 -帮助我们识别漏洞和安全问题
- 讨论想法 -加入关于架构和设计的对话
- 编写文档 -帮助他人理解并采用该模式
愿景
我们正在建设一个未来:
- 🧠 AI代理规模 通过代码执行超越令牌限制
- 🔄 技能积累 随着时间的推移,使代理不断变得更聪明
- 🔒 隐私是内置的 具有自动PII保护功能
- 🛡️ 安全是分层的 具有多种防御机制
- 🌐 工具是动态发现的,不是静态配置的
- 📚 社区驱动 共享技能和最佳实践
为您的组织定制指南
根据您的特定需求自定义此模板:
- 实施LLM集成 -选择您首选的提供商
- 连接您的MCP服务器 -连接您的工具和数据源
- 自定义安全策略 -根据您的威胁模型进行调整
- 扩展PII检测 -为您的域添加模式
- 添加监控和日志记录 -与您的可观察性堆栈集成
- 培养特定领域的技能 -创建组织的能力库
- 分享回来 -贡献通用改进以帮助社区
社区资源
- 问题与讨论 -提问、提出功能、讨论架构
- 技能库 -贡献可重复使用的技能
skills/examples/ - 文档 -帮助改进指南和示例
- 合作伙伴关系 -就更大的倡议进行合作
认可
贡献者将在以下方面得到认可:
- 项目自述
- 发布说明
- 社区名人堂
- 在社区活动中发言的机会
______________________________________________________________________
我们可以共同构建下一代人工智能代理基础设施。 无论你是人工智能研究员、DevOps工程师、安全专家还是全栈开发人员,你的贡献都有一席之地。加入我们,共同推进这一范式!
📝 许可证
MIT许可证-有关详细信息,请参阅许可证文件
⚠️ 重要说明
- 所有项目:搜索
TODO代码中需要实现的区域的注释 - 安全:在生产部署之前审查并加强安全设置
- LLM集成:LLM调用函数是提供程序的占位符实现
- MCP服务器:提供了模拟实现-用实际的MCP连接替换
- 生产就绪:生产使用所需的额外硬化(监控、错误处理、缩放)
______________________________________________________________________
采用MCP模式的代码执行构建,用于动态、安全的AI代理工作流。
