MCP编码模式
沙盒环境中MCP代码模式概念的开源、不可知的实现。
灵感来源:
- Cloudflare的代码模式 -将MCP工具转换为TypeScript API
- 使用MCP执行Anthropic的代码 -安全代码执行模式
什么是代码模式?
传统的MCP(模型上下文协议)用法将工具直接暴露给LLM,要求它们进行显式的工具调用。然而,正如 Cloudflare发现, LLM更擅长编写代码来调用MCP,而不是直接调用MCP.
为什么是代码模式?
- LLMs擅长编写代码:他们已经接受了数百万个真实世界的TypeScript示例的训练,但只有合成的工具调用示例
- 处理更复杂的工具:当工具以TypeScript API的形式呈现时,LLM可以使用更大、更复杂的工具集
- 高效的多步骤操作:LLM可以编写将多个调用链接在一起的代码,而不是通过LLM上下文反馈每个工具的结果
- 更好的推理:编写代码是LLM比结构化工具调用更自然的问题解决模式
运作原理
这个库实现了一个复杂的6步流水线:
User Query → Pseudocode Plan → Tool Filtering → TypeScript Generation
→ Code Implementation → Compilation → Sandboxed Execution建筑
该系统采用 三位专业法学硕士:
- 战略法学硕士:高级规划和伪代码生成(能力最强的模型)
- 微型LLM:快速过滤大型工具目录(轻量级、快速型号)
- 主要法学硕士:代码生成和实现(有能力的编码模型)
执行流程
- 生成伪代码 (战略LLM):创建高级执行计划
- 筛选工具 (Tiny LLM):从潜在的数千个选项中智能地选择相关工具
- 生成TypeScript接口:将筛选的MCP工具转换为TypeScript API定义
- 实施代码 (主LLM):使用生成的API编写实际的TypeScript代码
- 验证编译:确保执行前的类型安全
- 在沙盒中执行:在安全、隔离的环境中运行代码
安装
npm install mcp-codemode快速开始
import { CodeModeMCP } from 'mcp-codemode';
import { OpenRouterClient } from 'mcp-codemode/model_clients';
import { ComposioProvider } from 'mcp-codemode/mcp_providers';
import { E2BRunEnvironment } from 'mcp-codemode/run_environments';
// Initialize OpenRouter client for LLM access
const openRouterClient = new OpenRouterClient();
// Setup Composio with your project
const composioProvider = new ComposioProvider({
projectId: 'your-project-id', // Optional: configure with connectedAccountId and userId
});
// Configure with three specialized LLMs
const codeMode = new CodeModeMCP({
llms: {
tinyLLM: openRouterClient.getLLM('openai/gpt-oss-20b'), // Fast filtering model
mainLLM: openRouterClient.getLLM('openai/gpt-oss-120b'), // Code generation model
strategyLLM: openRouterClient.getLLM('anthropic/claude-sonnet-4.5') // Strategic planning
},
tools: await composioProvider.getTools({
toolkits: ['slack', 'gmail', 'github'] // Specify the toolkits you need
}),
runEnvironment: new E2BRunEnvironment(), // Secure cloud sandbox
logPath: './prompt_logs' // Optional: log all LLM interactions
});
// Execute a complex multi-step task
const result = await codeMode.runMCPCode({
query: "get all channels from slack, and send a message to every channel that start with 'test', set an emoji on each message in channels that start with the letter 'e'",
maxToolCalls: 100,
totalExecutionTimeout: 60,
toolCallTimeout: 10
});
console.log(`Execution: ${result.resultType}`);
console.log(`Duration: ${result.totalDurationMs}ms`);主要特点
🎯 智能工具过滤
Tiny LLM有可能提供数千种工具,可以快速筛选出仅相关的工具,从而减少上下文大小并提高准确性。
🏗️ 类型安全代码生成
所有生成的代码都是TypeScript,在执行前进行完整的类型检查,及早发现错误。
🔒 安全沙盒
支持多种执行环境:
- 本地:Node.js进程隔离
- 苯甲酸雌二醇:用于生产的云沙盒
- 自定义:实施你自己的
IRunEnvironment
📊 综合可观察性
- 每个管道步骤的详细时间报告
- 可选记录所有LLM提示和响应
- 调试执行跟踪
🔌 灵活的体系结构
- MCP提供商不确定:与Composio、Pipedream或定制提供商合作
- 模型不可知:使用OpenAI、OpenRouter或任何遵循接口的LLM
- 环境不可知:在本地或云中运行
配置选项
CodeModeMCPConfig
interface CodeModeMCPConfig {
llms: {
tinyLLM: LLMFunction; // Fast filtering model
mainLLM: LLMFunction; // Code generation model
strategyLLM: LLMFunction; // Planning model
};
tools?: ToolCatalog; // Hierarchical tool catalog
mcpProvider?: IMCPProvider; // Optional MCP provider
runEnvironment?: IRunEnvironment; // Execution sandbox
logPath?: string; // Optional logging directory
}运行MCPCode选项
interface RunMCPCodeOptions {
query?: string; // User task description
maxToolCalls: number; // Limit on tool invocations
totalExecutionTimeout: number; // Overall timeout (seconds)
toolCallTimeout: number; // Per-tool timeout (seconds)
maxToolsPerPrompt?: number; // Tools per filtering batch (default: 20)
maxConcurrentThreads?: number; // Parallel filtering threads (default: 5)
includeDescriptionsInFilter?: boolean; // Include tool descriptions in logs
}高级用法
自定义LLM集成
import { LLMFunction } from 'mcp-codemode/model_clients';
const myCustomLLM: LLMFunction = async (prompt: string): Promise => {
// Your LLM integration here
const response = await myLLMService.complete(prompt);
return response.text;
};
const codeMode = new CodeModeMCP({
llms: {
strategyLLM: myCustomLLM,
tinyLLM: myCustomLLM,
mainLLM: myCustomLLM
},
// ... other config
});自定义运行环境
import { IRunEnvironment } from 'mcp-codemode/run_environments';
class MyCustomEnvironment implements IRunEnvironment {
async execute(code: string): Promise {
// Your execution logic
}
}工具目录管理
// List all available tools
const toolPaths = codeMode.listToolPaths();
console.log(toolPaths); // ['slack.message.send', 'github.issues.create', ...]
// Get a specific tool
const tool = codeMode.getTool('slack.message.send');
// Update the catalog
codeMode.setToolCatalog(newCatalog);项目结构
src/
├── CodeModeMCP.ts # Main orchestrator class
├── steps/ # Pipeline steps
│ ├── generatePseudocode.ts
│ ├── filterTools.ts
│ ├── generateToolsCode.ts
│ ├── implementCode.ts
│ └── executeCode.ts
├── model_clients/ # LLM integrations
│ ├── openai.ts
│ └── openrouter.ts
├── run_environments/ # Execution sandboxes
│ ├── local.ts
│ └── e2b.ts
└── mcp_providers/ # MCP server integrations
├── composio.ts
└── pipedream.ts为什么这很重要
随着MCP采用率的增长,代理将可以访问数百或数千个工具。传统的工具调用方法在规模上会崩溃:
- 上下文限制:无法在提示中容纳所有工具定义
- 选择不当:LLM很难从许多选项中选择合适的工具
- 低效的链接:每个工具结果必须通过LLM往返
代码模式通过利用LLM最擅长的东西来解决这些问题: 编写代码该库提供了一个模块化、可扩展且与平台无关的生产就绪实现。
贡献
这是一个完全免费且对协作开放的存储库。欢迎投稿!
- 报告问题
- 提交拉取请求
- 提出改进建议
- 分享您的用例
许可证
麻省理工学院
