code2mcp

code2mcp

Enables execution of TypeScript code to call MCP tools instead of direct tool calls, reducing token usage by up to 98% while orchestrating complex multi-tool workflows through secure sandboxed code execution.

Category
访问服务器

README

code2mcp - Code Mode MCP Server

Execute TypeScript code to call MCP tools instead of using direct tool calls. Based on Cloudflare's revolutionary Code Mode pattern.

What is Code Mode?

Instead of exposing MCP tools directly to the LLM (which wastes tokens and struggles with complex tools), Code Mode:

  1. Converts MCP tools into TypeScript APIs with full type definitions
  2. Has the LLM write code that calls those APIs
  3. Executes code in a secure sandbox with access only to specified MCP servers
  4. Returns only the final results to the LLM, not intermediate data

Benefits

  • 98% token reduction for complex multi-tool workflows
  • Better tool understanding: LLMs are trained on millions of TypeScript examples
  • Handle complex tools: Full APIs vs simplified tool schemas
  • Secure execution: Sandboxed code, no network/filesystem access
  • API keys hidden: Keys stored in orchestrator, never exposed to LLM

Installation

# Clone or create project
npm install

# Build (TypeScript compilation only)
npm run build

# Build with API generation (recommended for first-time setup)
npm run build:full

Note: build:full generates TypeScript API files from your MCP servers, which helps Claude understand parameter names and types. See IMPROVEMENTS.md for details.

Configuration

1. Pre-Configured MCP Servers ✅

Already configured and ready to use! Five MCP servers are pre-configured:

  1. Context7 - Data storage and context management
  2. Playwright - Browser automation and web scraping
  3. Bright Data - Proxy network and geo-distributed scraping
  4. Chrome DevTools - Chrome DevTools Protocol integration
  5. Firecrawl - Advanced web crawling and content extraction

See CONFIGURED_SERVERS.md for details on each server.

To add more servers, edit src/index.ts and modify the MCP_SERVERS array:

const MCP_SERVERS: MCPServerConfig[] = [
  // ... existing 5 servers ...
  {
    name: 'your-server',
    transport: 'stdio',
    command: 'npx',
    args: ['your-mcp-package'],
    env: {},
  },
];

2. Set Environment Variables

cp .env.example .env
# Edit .env with your API keys

3. Register with Claude Code

Add to ~/.claude.json:

{
  "mcpServers": {
    "code2mcp": {
      "command": "node",
      "args": ["/absolute/path/to/code2mcp/build/index.js"],
      "env": {
        "LOG_LEVEL": "info",
        "WEATHER_API_KEY": "your_key_here"
      }
    }
  }
}

Usage

Example 1: Simple Tool Call

User: "What's the weather?"

Claude writes:

const weather = await __mcp_call('weather__get_current', { 
  city: 'San Francisco' 
});
console.log(`Temperature: ${weather.temperature}°F`);

Output:

=== Execution Logs ===
Temperature: 65°F

=== Result ===
(undefined)

Execution time: 234ms

Example 2: Multi-Step Workflow (Token Savings!)

User: "Get my Google Doc and update Salesforce"

Claude writes:

// Fetch document (potentially 50,000 tokens)
const doc = await __mcp_call('google_drive__get_document', {
  documentId: 'abc123'
});

// Update Salesforce (large document stays in sandbox!)
await __mcp_call('salesforce__update_record', {
  objectType: 'Lead',
  recordId: 'xyz789',
  data: {
    Notes: doc.content  // 50K tokens never enter Claude's context!
  }
});

console.log('Updated Salesforce with document content');

Key Benefit: The 50,000-token document never enters Claude's context. Only the logs are returned!

Example 3: Complex Orchestration

// Get all files modified in last week
const files = await __mcp_call('google_drive__list_files', {
  modifiedAfter: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()
});

console.log(`Found ${files.length} files`);

// Process each file
for (const file of files) {
  const doc = await __mcp_call('google_drive__get_document', {
    documentId: file.id
  });
  
  // Analyze sentiment (simple keyword matching)
  const sentiment = analyzeSentiment(doc.content);
  
  console.log(`${file.title}: ${sentiment}`);
}

function analyzeSentiment(text) {
  const positive = (text.match(/great|excellent|success/gi) || []).length;
  const negative = (text.match(/issue|problem|failure/gi) || []).length;
  return positive - negative;
}

This kind of complex orchestration would be impossible with standard MCP tool calling!

Architecture

┌─────────────────────────────────────┐
│   Claude Code (MCP Client)          │
│   Sees: ONE tool (execute_code)     │
└──────────────┬──────────────────────┘
               │ Writes TypeScript code
               ▼
    ┌──────────────────────────────────┐
    │   code2mcp Server                │
    │   - Compiles TypeScript          │
    │   - Executes in Node.js VM       │
    │   - Injects __mcp_call binding   │
    └──────────────┬───────────────────┘
                   │ Routes tool calls
                   ▼
    ┌──────────────────────────────────┐
    │   MCP Orchestrator               │
    │   - Manages MCP server conns     │
    │   - Stores API keys              │
    │   - Routes to correct server     │
    └──────────────┬───────────────────┘
                   │
         ┌─────────┴─────────┬──────────┐
         ▼                   ▼          ▼
    ┌─────────┐      ┌──────────┐  ┌─────────┐
    │ Google  │      │Salesforce│  │ Weather │
    │ Drive   │      │          │  │   MCP   │
    │ MCP     │      │   MCP    │  │         │
    └─────────┘      └──────────┘  └─────────┘

Development

# Development mode with hot reload
npm run dev

# Build
npm run build

# Test with MCP Inspector
npm run inspector

# Generate TypeScript APIs manually
npm run generate-apis

Security

The sandbox provides basic isolation:

  • ✅ No network access (fetch, XMLHttpRequest, WebSocket blocked)
  • ✅ No filesystem access (fs, path blocked)
  • ✅ No process access (child_process, process blocked)
  • ✅ Only __mcp_call() binding available
  • ✅ API keys stored in orchestrator, never in sandbox
  • ✅ Timeout enforcement (default 30s)

Note: This uses Node.js built-in vm module, which provides basic isolation but is not as secure as isolated-vm or Deno. For production use, consider:

  1. Using Deno with strict permissions
  2. Using isolated-vm with older Node.js version (v20)
  3. Running in a containerized environment
  4. Deploying to Cloudflare Workers (best isolation)

Token Usage Comparison

Standard MCP (Direct Tool Calling)

Tool definitions: 10K tokens (50 tools × 200 tokens)
Intermediate results: 40K tokens (large documents)
Conversation: 50K tokens
────────────────────────────────────────────────
Total: ~100K tokens

Code Mode

Code written by LLM: 2K tokens
Execution logs: 1K tokens
Conversation: 50K tokens
────────────────────────────────────────────────
Total: ~53K tokens

Token Reduction: 47% for simple workflows, 98% for complex workflows!

Documentation

See /DOCS folder for complete architecture documentation:

  • DOCS/Architecture/SYSTEM_MAP.md - Complete architecture overview
  • DOCS/Architecture/CODE_STRUCTURE.md - File organization
  • DOCS/Etc/CODE_MODE_IMPLEMENTATION_PLAN.md - Detailed implementation plan

References

License

ISC

Contributing

Contributions welcome! This is a reference implementation of the Code Mode pattern.

Roadmap

  • [ ] Configuration file support (vs hardcoded in src/index.ts)
  • [ ] Deno sandbox implementation for better security
  • [ ] TypeScript API browser/explorer
  • [ ] Support for HTTP/WebSocket MCP transports
  • [ ] Streaming execution logs
  • [ ] Code templates library
  • [ ] Performance optimizations
  • [ ] Comprehensive test suite

Built with ❤️ implementing Cloudflare's Code Mode pattern

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选