[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"tool-universal-tool-calling-protocol--code-mode":3,"similar-universal-tool-calling-protocol--code-mode":99},{"id":4,"github_repo":5,"name":6,"description_en":7,"description_zh":8,"ai_summary_zh":9,"readme_en":10,"readme_zh":11,"quickstart_zh":12,"use_case_zh":13,"hero_image_url":14,"owner_login":15,"owner_name":16,"owner_avatar_url":17,"owner_bio":18,"owner_company":19,"owner_location":19,"owner_email":19,"owner_twitter":19,"owner_website":20,"owner_url":21,"languages":22,"stars":35,"forks":36,"last_commit_at":37,"license":38,"difficulty_score":39,"env_os":40,"env_gpu":41,"env_ram":41,"env_deps":42,"category_tags":46,"github_topics":48,"view_count":55,"oss_zip_url":19,"oss_zip_packed_at":19,"status":56,"created_at":57,"updated_at":58,"faqs":59,"releases":88},2520,"universal-tool-calling-protocol\u002Fcode-mode","code-mode","🔌 Plug-and-play library to enable agents to call MCP and UTCP tools via code execution. ","code-mode 是一款专为 AI 智能体设计的开源库，旨在通过代码执行的方式，让智能体能够高效调用 MCP（模型上下文协议）和 UTCP（通用工具调用协议）工具。只需几行代码，即可将复杂的工具调用流程转化为简单的代码执行任务，实现“即插即用”的集成体验。\n\n传统的大语言模型在直接调用大量工具时，往往面临上下文冗长、步骤繁琐且容易出错的问题。code-mode 巧妙地解决了这一痛点：它不再向模型暴露成百上千个独立的工具接口，而是提供一个统一的代码执行环境。由于大模型在生成代码方面表现卓越，这种方式让模型能够通过编写 TypeScript 代码来一次性编排和执行多个工具操作，从而大幅减少交互迭代次数。\n\n数据显示，在处理复杂任务时，code-mode 相比传统方法可提升高达 88% 的执行效率，并显著降低 API 调用成本。其核心技术亮点包括支持动态工具发现（仅加载所需工具）、批量处理优势以及避免重复上下文处理的计算效率优化。\n\n这款工具非常适合开发者、AI 工程师及研究人员使用，特别是那些正在构建需要频繁与外部系统交互的智能体应用的人群。如果你希望提升 AI 智能体在处理多步工作流时","code-mode 是一款专为 AI 智能体设计的开源库，旨在通过代码执行的方式，让智能体能够高效调用 MCP（模型上下文协议）和 UTCP（通用工具调用协议）工具。只需几行代码，即可将复杂的工具调用流程转化为简单的代码执行任务，实现“即插即用”的集成体验。\n\n传统的大语言模型在直接调用大量工具时，往往面临上下文冗长、步骤繁琐且容易出错的问题。code-mode 巧妙地解决了这一痛点：它不再向模型暴露成百上千个独立的工具接口，而是提供一个统一的代码执行环境。由于大模型在生成代码方面表现卓越，这种方式让模型能够通过编写 TypeScript 代码来一次性编排和执行多个工具操作，从而大幅减少交互迭代次数。\n\n数据显示，在处理复杂任务时，code-mode 相比传统方法可提升高达 88% 的执行效率，并显著降低 API 调用成本。其核心技术亮点包括支持动态工具发现（仅加载所需工具）、批量处理优势以及避免重复上下文处理的计算效率优化。\n\n这款工具非常适合开发者、AI 工程师及研究人员使用，特别是那些正在构建需要频繁与外部系统交互的智能体应用的人群。如果你希望提升 AI 智能体在处理多步工作流时的稳定性与速度，或者想简化 MCP\u002FUTCP 工具的集成过程，code-mode 提供了一个优雅且高效的解决方案。它不仅降低了开发门槛，还让智能体从笨拙的“工具调用者”进化为高效的“代码执行者”。","\u003Cdiv align=\"center\">\n\u003C!-- \u003Cimg alt=\"utcp code mode banner\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Funiversal-tool-calling-protocol_code-mode_readme_a2cdcbe15d05.png\" width=\"80%\" style=\"margin: 20px auto;\"> -->\n\n\u003Ch1 align=\"center\">🤖 Code-Mode Library: First library for tool calls via code execution\u003C\u002Fh1>\n\u003Cp align=\"center\">\n    \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol\">\n        \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Ffollowers\u002Funiversal-tool-calling-protocol?label=Follow%20Org&logo=github\" \u002F>\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fdt\u002F@utcp\u002Fcode-mode\" title=\"PyPI Version\">\n        \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fdt\u002F@utcp\u002Fcode-mode\"\u002F>\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol\u002Fcode-mode\u002Fblob\u002Fmain\u002FLICENSE\" alt=\"License\">\n        \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Flicense\u002Funiversal-tool-calling-protocol\u002Fcode-mode\" \u002F>\u003C\u002Fa>\n \n  [![npm](https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fv\u002F@utcp\u002Fcode-mode)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@utcp\u002Fcode-mode)\n\u003C\u002Fp>\n\u003C\u002Fdiv>\n\n> Transform your AI agents from clunky tool callers into efficient code executors — in just 3 lines.\n\n## Why This Changes Everything\n\nLLMs excel at writing code but struggle with tool calls. Instead of exposing hundreds of tools directly, give them ONE tool that executes TypeScript code with access to your entire toolkit.\n\n[Apple](https:\u002F\u002Fmachinelearning.apple.com\u002Fresearch\u002Fcodeact), [Cloudflare](https:\u002F\u002Fblog.cloudflare.com\u002Fcode-mode\u002F), and [Anthropic](https:\u002F\u002Fwww.anthropic.com\u002Fengineering\u002Fcode-execution-with-mcp) say that Code-Mode is a more efficient way to approach tool calling compared to the traditional dump function information and then extract a JSON for function calling.\n\n## Benchmarks\n\nIndependent [Python benchmark study](https:\u002F\u002Fgithub.com\u002Fimran31415\u002Fcodemode_python_benchmark) validates the performance claims with **$9,536\u002Fyear cost savings** at 1,000 scenarios\u002Fday:\n\n| Scenario Complexity | Traditional | Code Mode | **Improvement** |\n|---------------------|-------------|-----------|----------------|\n| **Simple (2-3 tools)** | 3 iterations | 1 execution | **67% faster** |\n| **Medium (4-7 tools)** | 8 iterations | 1 execution | **75% faster** |\n| **Complex (8+ tools)** | 16 iterations | 1 execution | **88% faster** |\n\n### **Why Code Mode Dominates:**\n\n   **Batching Advantage** - Single code block replaces multiple API calls  \n   **Cognitive Efficiency** - LLMs excel at code generation vs. tool orchestration  \n   **Computational Efficiency** - No context re-processing between operations\n\n# Getting Started\n\n[\u003Cimg width=\"2606\" height=\"1445\" alt=\"Frame 4 (4)\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Funiversal-tool-calling-protocol_code-mode_readme_8af664bc0344.png\" \u002F>\n](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=zsMjkPzmqhA)\n\n## Get Started in 3 Lines\n\n```typescript\nimport { CodeModeUtcpClient } from '@utcp\u002Fcode-mode';\n\nconst client = await CodeModeUtcpClient.create();                    \u002F\u002F 1. Initialize\nawait client.registerManual({ name: 'github', \u002F* MCP config *\u002F });  \u002F\u002F 2. Add tools  \nconst { result } = await client.callToolChain(`\u002F* TypeScript *\u002F`);   \u002F\u002F 3. Execute code\n```\n\nThat's it. Your AI agent can now execute complex workflows in a single request instead of dozens.\n\n## What You Get\n\n### **Progressive Tool Discovery**\n```typescript\n\u002F\u002F Agent discovers tools dynamically, loads only what it needs\nconst tools = await client.searchTools('github pull request');\n\u002F\u002F Instead of 500 tool definitions → 3 relevant tools\n```\n\n### **Natural Code Execution**  \n```typescript\nconst { result, logs } = await client.callToolChain(`\n  \u002F\u002F Chain multiple operations in one request\n  const pr = await github.get_pull_request({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  const comments = await github.get_pull_request_comments({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  const reviews = await github.get_pull_request_reviews({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  \n  \u002F\u002F Process data efficiently in-sandbox\n  return {\n    title: pr.title,\n    commentCount: comments.length,\n    approvals: reviews.filter(r => r.state === 'APPROVED').length\n  };\n`);\n\u002F\u002F Single API call replaces 15+ traditional tool calls\n```\n\n### **Auto-Generated TypeScript Interfaces**\n```typescript\nnamespace github {\n  interface get_pull_requestInput {\n    \u002F** Repository owner *\u002F\n    owner: string;\n    \u002F** Repository name *\u002F \n    repo: string;\n    \u002F** Pull request number *\u002F\n    pull_number: number;\n  }\n}\n```\n\n## Enterprise-Ready\n\n- **Secure VM Sandboxing** – Node.js isolates prevent unauthorized access\n- **Timeout Protection** – Configurable execution limits prevent runaway code  \n- **Complete Observability** – Full console output capture and error handling\n- **Zero External Dependencies** – Tools only accessible through registered UTCP\u002FMCP servers\n- **Runtime Introspection** – Dynamic interface discovery for adaptive workflows\n\nIf you're working at an enterprise, and need support, book a consultation [here](https:\u002F\u002Fbevel.neetocal.com\u002Fmeeting-with-ali).\n## Universal Protocol Support\n\nWorks with **any tool ecosystem:**\n\n| Protocol | Description | Usage |\n|----------|-------------|-------|\n| **MCP** | Model Context Protocol servers | `call_template_type: 'mcp'` |\n| **HTTP** | REST APIs with auto-discovery | `call_template_type: 'http'` |  \n| **File** | Local JSON\u002FYAML configurations | `call_template_type: 'file'` |\n| **CLI** | Command-line tool execution | `call_template_type: 'cli'` |\n\n## Installation\n\n```bash\nnpm install @utcp\u002Fcode-mode\n```\n\n## Even Easier: Ready-to-Use MCP Server\n\n**Want Code Mode without any setup?** Use our plug-and-play MCP server with Claude Desktop or any MCP client:\n\n```json\n{\n  \"mcpServers\": {\n    \"code-mode\": {\n      \"command\": \"npx\",\n      \"args\": [\"@utcp\u002Fcode-mode-mcp\"],\n      \"env\": {\n        \"UTCP_CONFIG_FILE\": \"\u002Fpath\u002Fto\u002Fyour\u002F.utcp_config.json\"\n      }\n    }\n  }\n}\n```\n\n**That's it!** No installation, no Node.js knowledge required. The [Code Mode MCP Server](https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol\u002Fcode-mode\u002Ftree\u002Fmain\u002Fcode-mode-mcp) automatically:\n- Downloads and runs the latest version via `npx`\n- Loads your tool configurations from JSON\n- Provides code execution capabilities to Claude Desktop\n- Gives you `call_tool_chain` as an MCP tool for TypeScript execution\n\n**Perfect for non-developers** who want Code Mode power in Claude Desktop!\n\n## Direct TypeScript Usage\n\n### 1. **MCP Server Integration**\nConnect to any Model Context Protocol server:\n\n```typescript\nimport { CodeModeUtcpClient } from '@utcp\u002Fcode-mode';\n\nconst client = await CodeModeUtcpClient.create();\n\n\u002F\u002F Connect to GitHub MCP server\nawait client.registerManual({\n  name: 'github',\n  call_template_type: 'mcp',\n  config: {\n    mcpServers: {\n      github: {\n        command: 'docker',\n        args: ['run', '-i', '--rm', '-e', 'GITHUB_PERSONAL_ACCESS_TOKEN', 'mcp\u002Fgithub'],\n        env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN }\n      }\n    }\n  }\n});\n```\n\n### 2. **Execute Multi-Step Workflows**\nReplace 15+ tool calls with a single code execution:\n\n```typescript\nconst { result, logs } = await client.callToolChain(`\n  \u002F\u002F Traditional: 4 separate API round trips → Code Mode: 1 execution\n  const pr = await github.get_pull_request({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  const comments = await github.get_pull_request_comments({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  const reviews = await github.get_pull_request_reviews({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  const files = await github.get_pull_request_files({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  \n  \u002F\u002F Process data in-sandbox (no token overhead)\n  const summary = {\n    title: pr.title,\n    state: pr.state,\n    author: pr.user.login,\n    stats: {\n      comments: comments.length,\n      reviews: reviews.length, \n      filesChanged: files.length,\n      approvals: reviews.filter(r => r.state === 'APPROVED').length\n    },\n    topDiscussion: comments.slice(0, 3).map(c => ({\n      author: c.user.login,\n      preview: c.body.substring(0, 100) + '...'\n    }))\n  };\n  \n  console.log(\\`PR \"\\${pr.title}\" analysis complete\\`);\n  return summary;\n`);\n\nconsole.log('Analysis Result:', result);\n\u002F\u002F console output: 'PR \"Fix memory leak in hooks\" analysis complete'\n```\n\n---\n\n## Advanced Features\n\n### **Multi-Protocol Tool Chains**\nMix and match different tool ecosystems in a single execution:\n\n```typescript\n\u002F\u002F Register multiple tool sources\nawait client.registerManual({ name: 'github', call_template_type: 'mcp', \u002F* config *\u002F });\nawait client.registerManual({ name: 'slack', call_template_type: 'http', \u002F* config *\u002F });\nawait client.registerManual({ name: 'db', call_template_type: 'file', file_path: '.\u002Fdb-tools.json' }); \u002F\u002F This loads a UTCP manual from a json file\n\nconst result = await client.callToolChain(`\n  \u002F\u002F Fetch PR data from GitHub (MCP)\n  const pr = await github.get_pull_request({ owner: 'company', repo: 'api', pull_number: 42 });\n  \n  \u002F\u002F Query deployment status from database (File)\n  const deployment = await db.get_deployment_status({ pr_id: pr.id });\n  \n  \u002F\u002F Send notification to Slack (HTTP)\n  await slack.post_message({\n    channel: '#releases',\n    text: \\`PR #42 \"\\${pr.title}\" deployed to \\${deployment.environment}\\`\n  });\n  \n  return { pr: pr.title, environment: deployment.environment };\n`);\n```\n\n### **Runtime Interface Introspection**\nTools can dynamically discover and adapt to available interfaces:\n\n```typescript\nconst result = await client.callToolChain(`\n  \u002F\u002F Discover available tools at runtime\n  console.log('Available interfaces:', __interfaces);\n  \n  \u002F\u002F Get specific tool interface for validation\n  const prInterface = __getToolInterface('github.get_pull_request');\n  console.log('PR tool expects:', prInterface);\n  \n  \u002F\u002F Use interface info for dynamic workflows\n  const hasSlackTools = __interfaces.includes('namespace slack');\n  if (hasSlackTools) {\n    await slack.post_message({ channel: '#dev', text: 'Analysis complete' });\n  }\n  \n  return { toolsAvailable: hasSlackTools };\n`);\n```\n\n### **Context-Efficient Data Processing**\nProcess large datasets without bloating the model's context:\n\n```typescript\nconst result = await client.callToolChain(`\n  \u002F\u002F Fetch large dataset\n  const allIssues = await github.list_repository_issues({ owner: 'facebook', repo: 'react' });\n  console.log('Fetched', allIssues.length, 'total issues');\n  \n  \u002F\u002F Process efficiently in-sandbox\n  const criticalBugs = allIssues\n    .filter(issue => issue.labels.some(l => l.name === 'bug'))\n    .filter(issue => issue.labels.some(l => l.name === 'high priority'))\n    .map(issue => ({\n      number: issue.number,\n      title: issue.title,\n      author: issue.user.login,\n      daysOld: Math.floor((Date.now() - new Date(issue.created_at)) \u002F (1000 * 60 * 60 * 24))\n    }))\n    .sort((a, b) => b.daysOld - a.daysOld);\n  \n  \u002F\u002F Only return processed summary (not 10,000 raw issues)\n  return {\n    totalIssues: allIssues.length,\n    criticalBugs: criticalBugs.slice(0, 10), \u002F\u002F Top 10 oldest critical bugs\n    summary: \\`Found \\${criticalBugs.length} critical bugs, oldest is \\${criticalBugs[0]?.daysOld} days old\\`\n  };\n`);\n```\n\n### **Error Handling & Observability**\nBuilt-in error handling with complete execution transparency:\n\n```typescript\nconst { result, logs } = await client.callToolChain(`\n  try {\n    console.log('Starting multi-step workflow...');\n    \n    const data = await external_api.fetch_data({ id: 'user-123' });\n    console.log('Data fetched successfully');\n    \n    const processed = await data_processor.transform(data);\n    console.warn('Processing completed with', processed.warnings.length, 'warnings');\n    \n    return processed;\n  } catch (error) {\n    console.error('Workflow failed:', error.message);\n    throw error; \u002F\u002F Propagates to outer error handling\n  }\n`, 30000); \u002F\u002F 30-second timeout\n\n\u002F\u002F Complete observability\nconsole.log('Result:', result);\nconsole.log('Execution logs:', logs);\n\u002F\u002F ['Starting multi-step workflow...', 'Data fetched successfully', '[WARN] Processing completed with 2 warnings']\n```\n\n### **Custom Timeouts**\nConfigure execution limits for different workload types:\n\n```typescript\n\u002F\u002F Quick operations (5 seconds)\nconst quickResult = await client.callToolChain(`return await ping.check();`, 5000);\n\n\u002F\u002F Heavy data processing (2 minutes) \nconst heavyResult = await client.callToolChain(`\n  const bigData = await database.export_full_dataset();\n  return await analytics.process_dataset(bigData);\n`, 120000);\n```\n\n---\n\n## AI Agent Integration\n\nPlug-and-play with any AI framework. The built-in prompt template handles all the complexity:\n\n```typescript\nimport { CodeModeUtcpClient } from '@utcp\u002Fcode-mode';\n\nconst systemPrompt = `\nYou are an AI assistant with access to tools via UTCP CodeMode.\n${CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE}\nAdditional instructions...\n`;\n\n\u002F\u002F Works with any AI library\nconst response = await openai.chat.completions.create({\n  model: 'gpt-4',\n  messages: [\n    { role: 'system', content: systemPrompt },\n    { role: 'user', content: 'Analyze the latest PR in microsoft\u002Fvscode' }\n  ]\n});\n```\n\n**The template provides comprehensive guidance on:**\n- Tool discovery workflow (`searchTools` → `__interfaces` → `callToolChain`)\n- Hierarchical access patterns (`manual.tool()` syntax)  \n- Interface introspection (`__getToolInterface()`)\n- Error handling and best practices\n\n---\n\n## API Reference\n\n### **Core Methods**\n\n#### `callToolChain(code: string, timeout?: number)`\nExecute TypeScript code with full tool access and observability.\n- **Returns**: `{result: any, logs: string[]}` with execution result and captured console output\n- **Default timeout**: 30 seconds\n\n#### `getAllToolsTypeScriptInterfaces()`\nGenerate complete TypeScript interfaces for IDE integration.\n- **Returns**: String containing all interface definitions with namespaces\n\n#### `searchTools(query: string)` *(from UtcpClient)*\nDiscover tools using natural language queries.\n- **Returns**: Array of relevant tools with descriptions and interfaces\n\n### **Static Methods**\n\n#### `CodeModeUtcpClient.create(root_dir?, config?)`\nCreate a new client instance with optional configuration.\n\n#### `CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE`\nProduction-ready prompt template for AI agents.\n\n---\n\n## Security & Performance\n\n### **Secure by Design**\n- **Node.js VM sandboxing** – Isolated execution context\n- **No filesystem access** – Tools only through registered servers  \n- **Timeout protection** – Configurable execution limits\n- **Zero network access** – No external dependencies or API keys exposed\n\n### **Performance Optimized**\n- **Minimal memory footprint** – VM contexts are lightweight\n- **Efficient tool caching** – TypeScript interfaces cached automatically\n- **Streaming console output** – Real-time log capture without buffering\n- **Identifier sanitization** – Handles invalid TypeScript identifiers gracefully\n\n---\n\n## Development Experience\n\n### **IDE Integration**\nGenerate TypeScript definitions for full IntelliSense support:\n\n```bash\n# Generate tool interfaces  \nconst interfaces = await client.getAllToolsTypeScriptInterfaces();\nawait fs.writeFile('generated-tools.d.ts', interfaces);\n\n# Add to tsconfig.json\n{\n  \"compilerOptions\": {\n    \"typeRoots\": [\".\u002Fgenerated-tools.d.ts\"]\n  }\n}\n```\n\n### **Debug & Monitor**\nBuilt-in observability for production deployments:\n\n```typescript\nconst { result, logs } = await client.callToolChain(userCode);\n\n\u002F\u002F Ship logs to your monitoring system\nlogs.forEach(log => {\n  if (log.startsWith('[ERROR]')) monitoring.error(log);\n  if (log.startsWith('[WARN]')) monitoring.warn(log);\n});\n```\n\n---\n\n\n### **Benchmark Methodology**\nThe [comprehensive Python study](https:\u002F\u002Fgithub.com\u002Fimran31415\u002Fcodemode_python_benchmark) tested **16 realistic scenarios** across:\n- **Financial workflows** (invoicing, expense tracking)  \n- **DevOps operations** (deployments, monitoring)\n- **Data processing** (analysis, reporting)\n- **Business automation** (CRM, notifications)\n\n**Models tested:** Claude Haiku, Gemini Flash  \n**Pricing basis:** $0.25\u002F1M input, $1.25\u002F1M output tokens  \n**Scale:** 1,000 scenarios\u002Fday = $9,536\u002Fyear savings with Code Mode\n\n## Learn More\n\n- **[Cloudflare Research](https:\u002F\u002Fblog.cloudflare.com\u002Fcode-mode\u002F)** – Original code mode whitepaper\n- **[Anthropic Study](https:\u002F\u002Fwww.anthropic.com\u002Fengineering\u002Fcode-execution-with-mcp)** – MCP code execution benefits\n- **[Python Benchmark Study](https:\u002F\u002Fgithub.com\u002Fimran31415\u002Fcodemode_python_benchmark)** – Comprehensive performance analysis\n- **[UTCP Specification](https:\u002F\u002Futcp.io)** – Official TypeScript implementation  \n- **[Report Issues](https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol\u002Fcode-mode\u002Fissues)** – Bug reports and feature requests\n\n## License\n\n**MPL-2.0** – Open source with commercial-friendly terms.\n","\u003Cdiv align=\"center\">\n\u003C!-- \u003Cimg alt=\"utcp code mode banner\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Funiversal-tool-calling-protocol_code-mode_readme_a2cdcbe15d05.png\" width=\"80%\" style=\"margin: 20px auto;\"> -->\n\n\u003Ch1 align=\"center\">🤖 Code-Mode 库：首个通过代码执行进行工具调用的库\u003C\u002Fh1>\n\u003Cp align=\"center\">\n    \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol\">\n        \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Ffollowers\u002Funiversal-tool-calling-protocol?label=Follow%20Org&logo=github\" \u002F>\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fdt\u002F@utcp\u002Fcode-mode\" title=\"PyPI Version\">\n        \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fdt\u002F@utcp\u002Fcode-mode\"\u002F>\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol\u002Fcode-mode\u002Fblob\u002Fmain\u002FLICENSE\" alt=\"License\">\n        \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Flicense\u002Funiversal-tool-calling-protocol\u002Fcode-mode\" \u002F>\u003C\u002Fa>\n \n  [![npm](https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fv\u002F@utcp\u002Fcode-mode)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@utcp\u002Fcode-mode)\n\u003C\u002Fp>\n\u003C\u002Fdiv>\n\n> 仅需三行代码，即可将您的 AI 代理从笨拙的工具调用者转变为高效的代码执行者。\n\n## 为什么这会彻底改变一切\n\n大语言模型擅长编写代码，但在工具调用方面却表现不佳。与其直接暴露数百种工具，不如为它们提供一个能够执行 TypeScript 代码并访问您整个工具集的单一工具。\n\n[Apple](https:\u002F\u002Fmachinelearning.apple.com\u002Fresearch\u002Fcodeact)、[Cloudflare](https:\u002F\u002Fblog.cloudflare.com\u002Fcode-mode\u002F) 和 [Anthropic](https:\u002F\u002Fwww.anthropic.com\u002Fengineering\u002Fcode-execution-with-mcp) 都认为，与传统的先传递函数信息再提取 JSON 进行调用的方式相比，Code-Mode 是一种更高效的工具调用方法。\n\n## 基准测试\n\n独立的 [Python 基准研究](https:\u002F\u002Fgithub.com\u002Fimran31415\u002Fcodemode_python_benchmark) 证实了其性能优势，在每天 1,000 个场景下可节省 **$9,536\u002F年**：\n\n| 场景复杂度 | 传统方式 | Code Mode | **提升幅度** |\n|---------------------|-------------|-----------|----------------|\n| **简单（2-3 个工具）** | 3 次迭代 | 1 次执行 | **快 67%** |\n| **中等（4-7 个工具）** | 8 次迭代 | 1 次执行 | **快 75%** |\n| **复杂（8 个以上工具）** | 16 次迭代 | 1 次执行 | **快 88%** |\n\n### **为什么 Code Mode 占据主导地位：**\n\n   **批处理优势** - 单一代码块取代多次 API 调用  \n   **认知效率** - 大语言模型擅长代码生成而非工具编排  \n   **计算效率** - 无需在每次操作之间重新处理上下文\n\n# 开始使用\n\n[\u003Cimg width=\"2606\" height=\"1445\" alt=\"Frame 4 (4)\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Funiversal-tool-calling-protocol_code-mode_readme_8af664bc0344.png\" \u002F>\n](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=zsMjkPzmqhA)\n\n## 三步快速入门\n\n```typescript\nimport { CodeModeUtcpClient } from '@utcp\u002Fcode-mode';\n\nconst client = await CodeModeUtcpClient.create();                    \u002F\u002F 1. 初始化\nawait client.registerManual({ name: 'github', \u002F* MCP 配置 *\u002F });  \u002F\u002F 2. 添加工具  \nconst { result } = await client.callToolChain(`\u002F* TypeScript *\u002F`);   \u002F\u002F 3. 执行代码\n```\n\n就这么简单。您的 AI 代理现在只需一次请求就能执行复杂的流程，而不再需要发出数十次请求。\n\n## 您将获得的内容\n\n### **渐进式工具发现**\n```typescript\n\u002F\u002F 代理动态发现工具，只加载所需内容\nconst tools = await client.searchTools('github pull request');\n\u002F\u002F 从 500 种工具定义变为仅需 3 种相关工具\n```\n\n### **自然的代码执行**  \n```typescript\nconst { result, logs } = await client.callToolChain(`\n  \u002F\u002F 在一次请求中串联多个操作\n  const pr = await github.get_pull_request({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  const comments = await github.get_pull_request_comments({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  const reviews = await github.get_pull_request_reviews({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  \n  \u002F\u002F 在沙盒环境中高效处理数据\n  return {\n    title: pr.title,\n    commentCount: comments.length,\n    approvals: reviews.filter(r => r.state === 'APPROVED').length\n  };\n`);\n\u002F\u002F 一次 API 调用即可替代 15 次以上的传统工具调用\n```\n\n### **自动生成的 TypeScript 接口**\n```typescript\nnamespace github {\n  interface get_pull_requestInput {\n    \u002F** 仓库所有者 *\u002F\n    owner: string;\n    \u002F** 仓库名称 *\u002F \n    repo: string;\n    \u002F** 拉取请求编号 *\u002F\n    pull_number: number;\n  }\n}\n```\n\n## 企业级就绪\n\n- **安全的 VM 沙箱** – Node.js 隔离机制防止未经授权的访问\n- **超时保护** – 可配置的执行限制防止失控代码运行  \n- **全面可观性** – 完整的控制台输出捕获和错误处理\n- **零外部依赖** – 工具仅可通过注册的 UTCP\u002FMCP 服务器访问\n- **运行时内省** – 动态接口发现支持自适应工作流\n\n如果您在企业工作并需要支持，请在此预约咨询 [这里](https:\u002F\u002Fbevel.neetocal.com\u002Fmeeting-with-ali)。\n## 通用协议支持\n\n适用于 **任何工具生态系统：**\n\n| 协议 | 描述 | 使用方式 |\n|----------|-------------|-------|\n| **MCP** | 模型上下文协议服务器 | `call_template_type: 'mcp'` |\n| **HTTP** | 具有自动发现功能的 REST API | `call_template_type: 'http'` |  \n| **文件** | 本地 JSON\u002FYAML 配置 | `call_template_type: 'file'` |\n| **CLI** | 命令行工具执行 | `call_template_type: 'cli'` |\n\n## 安装\n\n```bash\nnpm install @utcp\u002Fcode-mode\n```\n\n## 更轻松：开箱即用的 MCP 服务器\n\n**想无需任何设置就使用 Code Mode 吗？** 使用我们的即插即用 MCP 服务器，配合 Claude Desktop 或任何 MCP 客户端：\n\n```json\n{\n  \"mcpServers\": {\n    \"code-mode\": {\n      \"command\": \"npx\",\n      \"args\": [\"@utcp\u002Fcode-mode-mcp\"],\n      \"env\": {\n        \"UTCP_CONFIG_FILE\": \"\u002Fpath\u002Fto\u002Fyour\u002F.utcp_config.json\"\n      }\n    }\n  }\n}\n```\n\n**就这么简单！** 无需安装，也不需要掌握 Node.js 知识。[Code Mode MCP 服务器](https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol\u002Fcode-mode\u002Ftree\u002Fmain\u002Fcode-mode-mcp) 会自动：\n- 通过 `npx` 下载并运行最新版本\n- 从 JSON 文件加载您的工具配置\n- 为 Claude Desktop 提供代码执行能力\n- 为您提供用于 TypeScript 执行的 `call_tool_chain` MCP 工具\n\n**非常适合希望在 Claude Desktop 中使用 Code Mode 功能的非开发者！**\n\n## 直接使用 TypeScript\n\n### 1. **MCP 服务器集成**\n连接到任何模型上下文协议服务器：\n\n```typescript\nimport { CodeModeUtcpClient } from '@utcp\u002Fcode-mode';\n\nconst client = await CodeModeUtcpClient.create();\n\n\u002F\u002F 连接到 GitHub 的 MCP 服务器\nawait client.registerManual({\n  name: 'github',\n  call_template_type: 'mcp',\n  config: {\n    mcpServers: {\n      github: {\n        command: 'docker',\n        args: ['run', '-i', '--rm', '-e', 'GITHUB_PERSONAL_ACCESS_TOKEN', 'mcp\u002Fgithub'],\n        env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN }\n      }\n    }\n  }\n});\n```\n\n### 2. 执行多步骤工作流\n用一次代码执行替代15次以上的工具调用：\n\n```typescript\nconst { result, logs } = await client.callToolChain(`\n  \u002F\u002F 传统方式：4次独立的API往返 → 代码模式：1次执行\n  const pr = await github.get_pull_request({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  const comments = await github.get_pull_request_comments({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  const reviews = await github.get_pull_request_reviews({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  const files = await github.get_pull_request_files({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  \n  \u002F\u002F 在沙箱中处理数据（无需额外的令牌开销）\n  const summary = {\n    title: pr.title,\n    state: pr.state,\n    author: pr.user.login,\n    stats: {\n      comments: comments.length,\n      reviews: reviews.length, \n      filesChanged: files.length,\n      approvals: reviews.filter(r => r.state === 'APPROVED').length\n    },\n    topDiscussion: comments.slice(0, 3).map(c => ({\n      author: c.user.login,\n      preview: c.body.substring(0, 100) + '...'\n    }))\n  };\n  \n  console.log(\\`PR \"\\${pr.title}\" analysis complete\\`);\n  return summary;\n`);\n\nconsole.log('分析结果:', result);\n\u002F\u002F 控制台输出：'PR \"修复hooks中的内存泄漏\" 分析完成'\n```\n\n---\n\n## 高级功能\n\n### 多协议工具链\n在一次执行中混合使用不同的工具生态系统：\n\n```typescript\n\u002F\u002F 注册多个工具源\nawait client.registerManual({ name: 'github', call_template_type: 'mcp', \u002F* 配置 *\u002F });\nawait client.registerManual({ name: 'slack', call_template_type: 'http', \u002F* 配置 *\u002F });\nawait client.registerManual({ name: 'db', call_template_type: 'file', file_path: '.\u002Fdb-tools.json' }); \u002F\u002F 从JSON文件加载UTCP手册\n\nconst result = await client.callToolChain(`\n  \u002F\u002F 从GitHub获取PR数据（MCP）\n  const pr = await github.get_pull_request({ owner: 'company', repo: 'api', pull_number: 42 });\n  \n  \u002F\u002F 从数据库查询部署状态（File）\n  const deployment = await db.get_deployment_status({ pr_id: pr.id });\n  \n  \u002F\u002F 向Slack发送通知（HTTP）\n  await slack.post_message({\n    channel: '#releases',\n    text: \\`PR #42 \"\\${pr.title}\" 已部署到 \\${deployment.environment}\\`\n  });\n  \n  return { pr: pr.title, environment: deployment.environment };\n`);\n```\n\n### 运行时接口自省\n工具可以动态发现并适应可用的接口：\n\n```typescript\nconst result = await client.callToolChain(`\n  \u002F\u002F 运行时发现可用工具\n  console.log('可用接口:', __interfaces);\n  \n  \u002F\u002F 获取特定工具接口进行验证\n  const prInterface = __getToolInterface('github.get_pull_request');\n  console.log('PR工具期望的接口:', prInterface);\n  \n  \u002F\u002F 使用接口信息构建动态工作流\n  const hasSlackTools = __interfaces.includes('namespace slack');\n  if (hasSlackTools) {\n    await slack.post_message({ channel: '#dev', text: '分析完成' });\n  }\n  \n  return { toolsAvailable: hasSlackTools };\n`);\n```\n\n### 上下文高效的数据处理\n在不增加模型上下文负担的情况下处理大型数据集：\n\n```typescript\nconst result = await client.callToolChain(`\n  \u002F\u002F 获取大型数据集\n  const allIssues = await github.list_repository_issues({ owner: 'facebook', repo: 'react' });\n  console.log('已获取', allIssues.length, '个问题');\n  \n  \u002F\u002F 在沙箱中高效处理\n  const criticalBugs = allIssues\n    .filter(issue => issue.labels.some(l => l.name === 'bug'))\n    .filter(issue => issue.labels.some(l => l.name === '高优先级'))\n    .map(issue => ({\n      number: issue.number,\n      title: issue.title,\n      author: issue.user.login,\n      年龄: Math.floor((Date.now() - new Date(issue.created_at)) \u002F (1000 * 60 * 60 * 24))\n    }))\n    .sort((a, b) => b.年龄 - a.年龄);\n  \n  \u002F\u002F 只返回处理后的摘要，而非1万条原始问题\n  return {\n    totalIssues: allIssues.length,\n    criticalBugs: criticalBugs.slice(0, 10), \u002F\u002F 最古老的10个严重问题\n    summary: \\`发现了 \\${criticalBugs.length} 个严重问题，最老的已有 \\${criticalBugs[0]?.年龄} 天\\`\n  };\n`);\n```\n\n### 错误处理与可观ility\n内置错误处理机制，提供完整的执行透明度：\n\n```typescript\nconst { result, logs } = await client.callToolChain(`\n  try {\n    console.log('开始多步工作流程...');\n    \n    const data = await external_api.fetch_data({ id: 'user-123' });\n    console.log('数据获取成功');\n    \n    const processed = await data_processor.transform(data);\n    console.warn('处理完成，共遇到', processed.warnings.length, '条警告');\n    \n    return processed;\n  } catch (error) {\n    console.error('工作流程失败:', error.message);\n    throw error; \u002F\u002F 将错误传递给外部错误处理机制\n  }\n`, 30000); \u002F\u002F 30秒超时\n\n\u002F\u002F 完整的可观ility\nconsole.log('结果:', result);\nconsole.log('执行日志:', logs);\n\u002F\u002F ['开始多步工作流程...', '数据获取成功', '[WARN] 处理完成，共遇到2条警告']\n```\n\n### 自定义超时\n为不同类型的负载配置执行限制：\n\n```typescript\n\u002F\u002F 快速操作（5秒）\nconst quickResult = await client.callToolChain(`return await ping.check();`, 5000);\n\n\u002F\u002F 重型数据处理（2分钟） \nconst heavyResult = await client.callToolChain(`\n  const bigData = await database.export_full_dataset();\n  return await analytics.process_dataset(bigData);\n`, 120000);\n```\n\n---\n\n## AI代理集成\n可与任何AI框架即插即用。内置提示模板处理所有复杂性：\n\n```typescript\nimport { CodeModeUtcpClient } from '@utcp\u002Fcode-mode';\n\nconst systemPrompt = `\n你是一个拥有通过UTCP CodeMode访问工具能力的AI助手。\n${CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE}\n其他指令...\n`;\n\n\u002F\u002F 适用于任何AI库\nconst response = await openai.chat.completions.create({\n  model: 'gpt-4',\n  messages: [\n    { role: 'system', content: systemPrompt },\n    { role: 'user', content: '分析microsoft\u002Fvscode中的最新PR' }\n  ]\n});\n```\n\n**该模板提供了全面的指导：**\n- 工具发现工作流程（`searchTools` → `__interfaces` → `callToolChain`）\n- 层次化访问模式（`manual.tool()`语法）\n- 接口自省（`__getToolInterface()`）\n- 错误处理和最佳实践\n\n---\n\n## API参考\n\n### **核心方法**\n\n#### `callToolChain(code: string, timeout?: number)`\n以完整的工具访问权限和可观ability执行 TypeScript 代码。\n- **返回值**：包含执行结果和捕获的控制台输出的 `{result: any, logs: string[]}`\n- **默认超时时间**：30秒\n\n#### `getAllToolsTypeScriptInterfaces()`\n生成用于 IDE 集成的完整 TypeScript 接口。\n- **返回值**：包含所有命名空间接口定义的字符串\n\n#### `searchTools(query: string)` *(来自 UtcpClient)*\n通过自然语言查询发现工具。\n- **返回值**：包含描述和接口的相关工具数组\n\n### **静态方法**\n\n#### `CodeModeUtcpClient.create(root_dir?, config?)`\n创建新的客户端实例，可选配置。\n\n#### `CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE`\n适用于 AI 代理的生产就绪提示模板。\n\n---\n\n## 安全与性能\n\n### **设计安全**\n- **Node.js VM 沙箱** – 隔离的执行上下文\n- **无文件系统访问权限** – 工具仅通过注册的服务端访问\n- **超时保护** – 可配置的执行限制\n- **零网络访问** – 不暴露外部依赖或 API 密钥\n\n### **性能优化**\n- **最小内存占用** – VM 上下文轻量级\n- **高效的工具缓存** – TypeScript 接口自动缓存\n- **流式控制台输出** – 实时日志捕获，无需缓冲\n- **标识符净化** – 能够优雅地处理无效的 TypeScript 标识符\n\n---\n\n## 开发体验\n\n### **IDE 集成**\n生成 TypeScript 定义以实现完整的 IntelliSense 支持：\n\n```bash\n# 生成工具接口  \nconst interfaces = await client.getAllToolsTypeScriptInterfaces();\nawait fs.writeFile('generated-tools.d.ts', interfaces);\n\n# 添加到 tsconfig.json\n{\n  \"compilerOptions\": {\n    \"typeRoots\": [\".\u002Fgenerated-tools.d.ts\"]\n  }\n}\n```\n\n### **调试与监控**\n内置可观ability，适用于生产部署：\n\n```typescript\nconst { result, logs } = await client.callToolChain(userCode);\n\n\u002F\u002F 将日志发送到你的监控系统\nlogs.forEach(log => {\n  if (log.startsWith('[ERROR]')) 监控.error(log);\n  if (log.startsWith('[WARN]')) 监控.warn(log);\n});\n```\n\n---\n\n\n### **基准测试方法**\n[全面的 Python 研究](https:\u002F\u002Fgithub.com\u002Fimran31415\u002Fcodemode_python_benchmark) 测试了 **16 个真实场景**，涵盖：\n- **金融工作流**（开票、费用跟踪）\n- **DevOps 运维**（部署、监控）\n- **数据处理**（分析、报告）\n- **业务自动化**（CRM、通知）\n\n**测试模型**：Claude Haiku、Gemini Flash  \n**定价依据**：输入 0.25 美元\u002F100 万 token，输出 1.25 美元\u002F100 万 token  \n**规模**：每天 1,000 个场景，使用 Code Mode 每年可节省 9,536 美元\n\n## 了解更多\n\n- **[Cloudflare Research](https:\u002F\u002Fblog.cloudflare.com\u002Fcode-mode\u002F)** – 原始 Code Mode 白皮书\n- **[Anthropic 研究](https:\u002F\u002Fwww.anthropic.com\u002Fengineering\u002Fcode-execution-with-mcp)** – MCP 代码执行的优势\n- **[Python 基准研究](https:\u002F\u002Fgithub.com\u002Fimran31415\u002Fcodemode_python_benchmark)** – 全面的性能分析\n- **[UTCP 规范](https:\u002F\u002Futcp.io)** – 官方 TypeScript 实现\n- **[提交问题](https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol\u002Fcode-mode\u002Fissues)** – Bug 报告和功能请求\n\n## 许可证\n\n**MPL-2.0** – 开源且对商业友好。","# Code-Mode 快速上手指南\n\nCode-Mode 是一个通过代码执行来实现工具调用的开源库。它允许 AI Agent 将复杂的工具调用逻辑转化为一段 TypeScript 代码一次性执行，从而显著减少 API 交互次数，提升效率并降低成本。\n\n## 环境准备\n\n*   **Node.js**: 建议安装最新 LTS 版本（支持 TypeScript 运行环境）。\n*   **包管理器**: npm、yarn 或 pnpm。\n*   **前置知识**: 基本的 TypeScript\u002FJavaScript 编程能力。\n\n## 安装步骤\n\n在项目根目录下运行以下命令安装核心库：\n\n```bash\nnpm install @utcp\u002Fcode-mode\n```\n\n> **提示**：如果你希望直接在 Claude Desktop 等 MCP 客户端中使用而无需编写代码，可以使用现成的 MCP Server（无需安装 Node.js 依赖）：\n> ```json\n> {\n>   \"mcpServers\": {\n>     \"code-mode\": {\n>       \"command\": \"npx\",\n>       \"args\": [\"@utcp\u002Fcode-mode-mcp\"],\n>       \"env\": {\n>         \"UTCP_CONFIG_FILE\": \"\u002Fpath\u002Fto\u002Fyour\u002F.utcp_config.json\"\n>       }\n>     }\n>   }\n> }\n> ```\n\n## 基本使用\n\n只需三步即可让 AI Agent 具备通过代码执行复杂工作流的能力。\n\n### 1. 初始化客户端与注册工具\n\n首先创建客户端实例，并注册你需要使用的工具源（例如 MCP 服务器、HTTP API 等）。以下以连接 GitHub MCP 服务器为例：\n\n```typescript\nimport { CodeModeUtcpClient } from '@utcp\u002Fcode-mode';\n\n\u002F\u002F 1. 初始化客户端\nconst client = await CodeModeUtcpClient.create();\n\n\u002F\u002F 2. 注册工具（此处以 MCP 协议为例）\nawait client.registerManual({\n  name: 'github',\n  call_template_type: 'mcp',\n  config: {\n    mcpServers: {\n      github: {\n        command: 'docker',\n        args: ['run', '-i', '--rm', '-e', 'GITHUB_PERSONAL_ACCESS_TOKEN', 'mcp\u002Fgithub'],\n        env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN }\n      }\n    }\n  }\n});\n```\n\n### 2. 执行代码链 (Call Tool Chain)\n\n使用 `callToolChain` 方法传入一段 TypeScript 代码。Agent 将在沙箱环境中执行这段代码，自动调用已注册的工具，并返回结果。\n\n```typescript\n\u002F\u002F 3. 执行代码\nconst { result, logs } = await client.callToolChain(`\n  \u002F\u002F 在单次请求中串联多个操作\n  const pr = await github.get_pull_request({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  const comments = await github.get_pull_request_comments({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });\n  \n  \u002F\u002F 在沙箱内高效处理数据，避免上下文膨胀\n  return {\n    title: pr.title,\n    commentCount: comments.length,\n    author: pr.user.login\n  };\n`);\n\nconsole.log('执行结果:', result);\nconsole.log('运行日志:', logs);\n```\n\n### 核心优势\n\n*   **批量执行**：单个代码块替代多次 API 往返，简单场景速度提升 67%，复杂场景提升 88%。\n*   **动态发现**：支持运行时接口自省（`__interfaces`），Agent 可动态感知可用工具。\n*   **安全沙箱**：基于 Node.js 隔离环境，提供超时保护和完整的错误捕获。","某后端工程师需要开发一个自动化脚本，用于每日从 GitHub 拉取特定项目的 Pull Request 数据，结合 Jira 上的任务状态进行交叉验证，并将最终报告同步至 Slack 频道。\n\n### 没有 code-mode 时\n- **交互繁琐且缓慢**：LLM 必须通过传统的函数调用模式，依次单独调用 GitHub API、Jira API 和 Slack API。每步操作都需要等待模型生成 JSON 参数并解析返回结果，导致整个流程需经历十几次往返交互。\n- **上下文窗口压力大**：每次工具调用后，完整的工具定义和中间结果都要重新填入提示词中。随着步骤增加，上下文迅速膨胀，不仅消耗大量 Token，还容易因超出长度限制而丢失早期关键信息。\n- **逻辑编排易出错**：让 LLM 直接协调多个独立工具的执行顺序极其困难。模型常出现参数传递错误（如将 PR 号错传给 Jira），或在处理条件分支（如“若 Jira 状态为 Done 则发送 Slack”）时产生幻觉，导致脚本频繁中断。\n- **调试与维护成本高**：一旦流程失败，开发者难以定位是模型理解偏差还是工具参数错误，排查过程如同在黑盒中摸索，严重拖慢开发迭代速度。\n\n### 使用 code-mode 后\n- **单次执行高效完成**：工程师只需让 LLM 生成一段包含所有逻辑的 TypeScript 代码。code-mode 将这段代码作为单一工具执行，一次性完成数据抓取、逻辑判断和消息发送，将原本十几次的交互压缩为一次请求。\n- **显著降低资源消耗**：由于无需在每次调用间重复注入庞大的工具描述信息，Token 用量大幅减少。基准测试显示，在复杂场景下可节省高达 88% 的处理时间，直接转化为真金白银的成本节约。\n- **利用编码优势提升准确率**：LLM 擅长编写代码而非 orchestration（编排）。通过代码执行，模型可以利用标准的编程语法（如 if-else、循环）精确控制业务逻辑，彻底解决了多工具协作中的参数错位和流程混乱问题。\n- **原生支持动态发现**：code-mode 允许代理按需搜索和加载工具，无需预先暴露数百个工具定义。这不仅简化了初始化配置，还让 Agent 能更专注地处理核心业务逻辑。\n\ncode-mode 通过将“工具调用”转化为“代码执行”，充分发挥了 LLM 的编程特长，以极简的架构实现了复杂工作流的高效、稳定自动化。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Funiversal-tool-calling-protocol_code-mode_a2cdcbe1.png","universal-tool-calling-protocol","Universal Tool Calling Protocol","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Funiversal-tool-calling-protocol_bcc4d40a.png","",null,"utcp.io","https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol",[23,27,31],{"name":24,"color":25,"percentage":26},"Python","#3572A5",45.7,{"name":28,"color":29,"percentage":30},"TypeScript","#3178c6",40,{"name":32,"color":33,"percentage":34},"JavaScript","#f1e05a",14.3,1416,96,"2026-04-02T14:42:24","MPL-2.0",1,"Linux, macOS, Windows","未说明",{"notes":43,"python":41,"dependencies":44},"该工具是一个 TypeScript\u002FNode.js 库，而非 Python 项目。主要依赖 Node.js 环境运行。支持通过 MCP、HTTP、文件或 CLI 协议集成工具。提供安全的 VM 沙箱执行环境，具备超时保护和完整的日志观测能力。可通过 npx 直接作为 MCP 服务器使用，无需复杂安装。",[45],"@utcp\u002Fcode-mode",[47],"Agent",[49,50,51,52,53,54],"ai-agents","codemode","mcp","model-context-protocol","toolchain","utcp",2,"ready","2026-03-27T02:49:30.150509","2026-04-06T05:15:32.923877",[60,65,70,75,80,84],{"id":61,"question_zh":62,"answer_zh":63,"source_url":64},11622,"为什么在 Kilo Code 或 Antigravity 中使用 MCP 服务器时会报 JSON 解析错误（Unexpected token）？","这是因为 UTCP MCP 服务器输出的调试日志干扰了严格的 JSON 响应解析。Kilo Code 和 Antigravity 等客户端对工具响应的格式要求非常严格，期望纯 JSON，而服务器输出了额外的调试文本。\n\n解决方法是创建一个静默日志的文件（例如 `node-silent.js`），内容如下：\n```javascript\nconsole.log = console.error;\n```\n\n然后在 MCP 配置中通过 `NODE_OPTIONS` 注入该文件，并指定配置文件路径：\n```json\n{\n  \"mcpServers\": {\n    \"code-mode\": {\n      \"command\": \"npx\",\n      \"args\": [\"@utcp\u002Fcode-mode-mcp\"],\n      \"env\": {\n        \"NODE_OPTIONS\": \"--require \u002Fpath\u002Fto\u002Fyour\u002Fnode-silent.js\",\n        \"UTCP_CONFIG_FILE\": \"\u002Fpath\u002Fto\u002Fyour\u002F.utcp_config.json\"\n      }\n    }\n  }\n}\n```","https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol\u002Fcode-mode\u002Fissues\u002F21",{"id":66,"question_zh":67,"answer_zh":68,"source_url":69},11623,"调用 MCP 工具时，应该使用点号（.）还是下划线（_）连接名称？","实际调用时应使用下划线。虽然 UTCP 内部使用 \"manual_name.tool_name\" 的格式来命名空间，且列表工具可能显示为点号分隔，但在转换为 TypeScript 接口时，由于点号不是合法的函数名符号，会被转换为下划线。\n\n例如，如果工具名为 `server_name.mcp_tool_name`，在代码中调用时应使用：\n`await mcp_name.server_name_mcp_tool_name`\n\n而不是 `await mcp_name.server_name.mcp_tool_name`。这是一个已知的提示误导问题，实际实现需遵循 TypeScript 命名规范。","https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol\u002Fcode-mode\u002Fissues\u002F15",{"id":71,"question_zh":72,"answer_zh":73,"source_url":74},11624,"Node.js 的 vm 模块是否安全？如果不安全，有什么替代方案？","Node.js 的 `vm` 模块并不安全，官方文档明确指出它不是一种安全机制，不应被用于运行不受信任的代码，否则可能导致 LLM 被越狱。\n\n建议的替代方案是使用 `isolated-vm` 库。它可以提供更安全的隔离环境来执行用户代码。维护者在评论中提供了基于 `isolated-vm` 的运行时代码示例，包括设置内存限制（默认 128MB）和超时时间（默认 30秒），并将用户代码包裹在异步函数中以捕获错误。","https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol\u002Fcode-mode\u002Fissues\u002F6",{"id":76,"question_zh":77,"answer_zh":78,"source_url":79},11625,"如何处理包含数千个工具的大型工具集，以避免 LLM 上下文溢出并提高准确性？","可以使用语义搜索预过滤（Semantic Search Pre-filtering）和重排序（Reranking）功能。UTCP 已经支持自定义搜索策略。\n\n通过在配置中启用语义预过滤，可以将成千上万的工具缩小到几十个最相关的子集，然后再交给 Code Mode 处理。这不仅能减少 LLM 的 Token 消耗，还能避免“上下文腐烂”（Context Rot）问题。\n\n配置示例（`.utcp_config.json`）：\n```json\n{\n  \"semantic_pre_filter\": {\n    \"enabled\": true,\n    \"rerank\": {\n      \"enabled\": true\n    }\n  }\n}\n```\n此外，MCP-use 等实现也具备类似的语义搜索工具过滤能力。","https:\u002F\u002Fgithub.com\u002Funiversal-tool-calling-protocol\u002Fcode-mode\u002Fissues\u002F14",{"id":81,"question_zh":82,"answer_zh":83,"source_url":69},11626,"UTCP 中的工具名称是如何映射到 TypeScript 函数名的？","UTCP 使用 `manual_name.tool_name` 的格式对工具进行命名空间管理。对于 MCP 工具，`tool_name` 通常是 `server_name.mcp_tool_name`。\n\n当这些名称转换为 TypeScript 代码时：\n1. `manual_name` 成为命名空间（namespace）或对象属性。\n2. 内部的工具名因为包含点号（`.`），而点号在 JavaScript\u002FTypeScript 函数名中非法，所以会被转换为下划线（`_`）。\n\n因此，最终生成的函数名格式为 `server_name_mcp_tool_name`。开发者在编写代码或调试时应注意这一转换规则，不要直接使用点号调用深层嵌套的方法。",{"id":85,"question_zh":86,"answer_zh":87,"source_url":64},11627,"如何禁用 code-mode 插件在 MCP 服务器中的日志输出？","目前可以通过 Node.js 的环境变量技巧来禁用控制台日志输出，从而避免破坏 JSON 响应格式。\n\n具体步骤：\n1. 创建一个 JS 文件（如 `node-silent.js`），内容为 `console.log = console.error;`。\n2. 在启动 MCP 服务器时，设置环境变量 `NODE_OPTIONS` 为 `--require \u002Fpath\u002Fto\u002Fnode-silent.js`。\n\n这样可以重定向标准输出，确保只返回有效的 JSON 数据给客户端。维护者也在 TODO 中提到未来会考虑在插件层面直接提供禁用日志的选项。",[89,94],{"id":90,"version":91,"summary_zh":92,"released_at":93},62113,"v1.0.6","🐍 **宣布 Code Mode 的 Python 库**\n\nCode Mode 现在同时支持 Python 和 TypeScript！这种强大的工具调用代码执行方式，如今已覆盖两种最流行的 AI 开发语言。\n\n## 新功能\n\n**Python 库（PyPI 上的 `code-mode`）**\n- 功能与 TypeScript 库完全对齐\n- 原生 Python async\u002Fawait 语法\n- 使用 RestrictedPython 进行进程沙箱隔离\n- 自动生成 TypedDict 接口\n- 保持相同的 60% 以上的 token 节省和性能提升\n\n## 为什么这很重要：多语言 AI 开发\n\nAI 团队通常会分为两派：一派使用 Python（用于数据科学、机器学习框架），另一派使用 TypeScript（用于 Web 服务、工具开发）。现在，您可以在两个生态系统中都使用 Code Mode：\n\n**Python 团队：**\n```python\nfrom utcp_code_mode import CodeModeUtcpClient\n\nclient = await CodeModeUtcpClient.create()\nawait client.register_manual({'name': 'github', ...})\nresult = await client.call_tool_chain(\"# Python 代码在这里\")\n```\n\n**TypeScript 团队：**\n```typescript\nimport { CodeModeUtcpClient } from '@utcp\u002Fcode-mode';\n\nconst client = await CodeModeUtcpClient.create();\nawait client.registerManual({ name: 'github', ... });\nconst { result } = await client.callToolChain(`\u002F* TypeScript *\u002F`);\n```\n\n## ✨ v2.0.0 中的亮点\n\n### Python 库（新） \n- **包名：** PyPI 上的 `code-mode`（v0.0.3）\n- **安全执行：** 使用 RestrictedPython 进行进程沙箱隔离\n- **原生 Python 接口：** 自动生成 TypedDict 定义\n- **企业级特性：** 超时保护、控制台捕获、无网络访问\n- **通用协议支持：** 支持 MCP、HTTP、文件、CLI 等多种来源\n\n### TypeScript 库（稳定版）\n- **包名：** npm 上的 `@utcp\u002Fcode-mode`（v1.0.4）\n- **虚拟机沙箱：** 使用 Node.js 隔离执行上下文\n- **TypeScript 接口：** 自动生成类型定义\n- **生产就绪：** 已应用于企业级部署\n\n### 两款库共有的特性：\n- 通过 `search_tools` 实现渐进式工具发现\n- 运行时内省（`__interfaces`、`__get_tool_interface`）\n- 多协议支持（MCP、HTTP、文件、CLI）\n- 完整可观测性（日志 + 结果）\n- 经验证的相比传统工具调用可减少 60% 以上的 token 消耗\n\n## 🧪 快速入门\n\n### Python\n```bash\npip install code-mode\n```\n\n```python\nfrom utcp_code_mode import CodeModeUtcpClient\n\nclient = await CodeModeUtcpClient.create()\nawait client.register_manual({'name': 'github', 'call_template_type': 'mcp', ...})\nresult = await client.call_tool_chain('''\npr = await github.get_pull_request(owner='microsoft', repo='vscode', pull_number=1234)\nreturn {\"title\": pr[\"title\"], \"state\": pr[\"state\"]}\n''')\n```\n\n### TypeScript\n```bash\nnpm install @utcp\u002Fcode-mode\n```\n\n```typescript\nimport { CodeModeUtcpClient } from '@utcp\u002Fcode-mode';\n\nconst client = await CodeModeUtcpClient.create();\nawait client.registerManual({ name: 'github', call_template_type: 'mcp', ... });\nconst { result } = await client.callToolChain(`\n  const pr = await github.get_pull_request({ owner","2025-11-23T12:50:02",{"id":95,"version":96,"summary_zh":97,"released_at":98},62114,"v1.0.5","## 🚀 UTCP 代码模式：首个让智能体通过代码执行调用工具的库\n\n代码模式是一个即插即用的库，它允许 AI 智能体通过 TypeScript 代码执行来调用 **MCP 和 UTCP 工具**，而无需在数十种脆弱的工具定义之间来回切换。\n\n**理念：**  \n大语言模型在编写代码方面远胜于编排复杂的多步工具调用链。因此，与其直接暴露数百种工具，不如为模型提供 **一个** 强大的工具：一个拥有访问你整个工具生态权限的 TypeScript 沙盒。\n\n本仓库提供了这个沙盒以及围绕它的配套组件。\n\n---\n\n## ⚡ 为什么这很有趣：将 Token 使用量降低超过 60%\n\n根据 Apple、Cloudflare、Anthropic 的已发表研究以及独立基准测试，基于代码执行的工作流可以带来以下优势：\n\n- 对于多步工作流，减少 API 轮次\n- 降低 Token 使用量（无需反复填充上下文）\n- 更符合大语言模型的“认知”模式（编写代码，而非 JSON 工具图）\n\n代码模式为 **UTCP + MCP** 封装了这一模式：\n\n- 单一客户端\n- 支持多种工具生态系统（MCP、HTTP、文件型、CLI）\n- 在安全的虚拟机中以单个 TypeScript 程序的形式执行\n\n---\n\n## ✨ v0.1.0 版本亮点\n\n**核心功能：**\n\n- `CodeModeUtcpClient`：用于连接 UTCP\u002FMCP 工具\n- 安全的 Node.js 虚拟机沙盒，用于执行 TypeScript 代码\n- 简单的 `callToolChain(code, timeout?)` API，可一次性运行多步工作流\n\n**工具与发现机制：**\n\n- `registerManual`：用于注册来自 MCP、HTTP、文件型或 CLI 源的工具\n- `searchTools` 以及运行时接口内省（`__interfaces`、`__getToolInterface`），支持渐进式工具发现\n- 自动生成工具的 TypeScript 接口，使智能体能够对自身的调用进行类型检查\n\n**企业级特性：**\n\n- 每次调用可设置执行超时\n- 完整捕获控制台日志（结果之外还包含 `logs`）\n- 除通过已注册工具外，无直接网络访问权限\n- 可与现有 MCP 服务器及 UTCP 配置无缝兼容\n\n---\n\n## 🧪 快速入门（3 行代码）\n\n安装：\n\n```bash\nnpm install @utcp\u002Fcode-mode\n```\n\n使用：\n\n```ts\nimport { CodeModeUtcpClient } from '@utcp\u002Fcode-mode';\n\nconst client = await CodeModeUtcpClient.create();                    \u002F\u002F 1. 初始化\nawait client.registerManual({ name: 'github', \u002F* MCP 配置 *\u002F });   \u002F\u002F 2. 注册工具\nconst { result } = await client.callToolChain(`\u002F* TypeScript *\u002F`);   \u002F\u002F 3. 执行代码\n```\n\n现在，你的智能体可以用一次代码执行替代整个工具调用图。\n\n---\n\n👉 **请给本仓库点个 Star，以便关注开发进展并表明此项目很有价值。** 早期反馈和问题尤其欢迎。","2025-11-15T14:31:07",[100,111,120,128,141,149],{"id":101,"name":102,"github_repo":103,"description_zh":104,"stars":105,"difficulty_score":106,"last_commit_at":107,"category_tags":108,"status":56},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,3,"2026-04-05T11:01:52",[109,110,47],"开发框架","图像",{"id":112,"name":113,"github_repo":114,"description_zh":115,"stars":116,"difficulty_score":55,"last_commit_at":117,"category_tags":118,"status":56},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",138956,"2026-04-05T11:33:21",[109,47,119],"语言模型",{"id":121,"name":122,"github_repo":123,"description_zh":124,"stars":125,"difficulty_score":55,"last_commit_at":126,"category_tags":127,"status":56},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107662,"2026-04-03T11:11:01",[109,110,47],{"id":129,"name":130,"github_repo":131,"description_zh":132,"stars":133,"difficulty_score":55,"last_commit_at":134,"category_tags":135,"status":56},2268,"ML-For-Beginners","microsoft\u002FML-For-Beginners","ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程，旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周，包含 26 节精炼课程和 52 道配套测验，内容涵盖从基础概念到实际应用的完整流程，有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。\n\n无论是希望转型的开发者、需要补充算法背景的研究人员，还是对人工智能充满好奇的普通爱好者，都能从中受益。课程不仅提供了清晰的理论讲解，还强调动手实践，让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持，通过自动化机制提供了包括简体中文在内的 50 多种语言版本，极大地降低了全球不同背景用户的学习门槛。此外，项目采用开源协作模式，社区活跃且内容持续更新，确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路，ML-For-Beginners 将是理想的起点。",84991,"2026-04-05T10:45:23",[110,136,137,138,47,139,119,109,140],"数据工具","视频","插件","其他","音频",{"id":142,"name":143,"github_repo":144,"description_zh":145,"stars":146,"difficulty_score":106,"last_commit_at":147,"category_tags":148,"status":56},3128,"ragflow","infiniflow\u002Fragflow","RAGFlow 是一款领先的开源检索增强生成（RAG）引擎，旨在为大语言模型构建更精准、可靠的上下文层。它巧妙地将前沿的 RAG 技术与智能体（Agent）能力相结合，不仅支持从各类文档中高效提取知识，还能让模型基于这些知识进行逻辑推理和任务执行。\n\n在大模型应用中，幻觉问题和知识滞后是常见痛点。RAGFlow 通过深度解析复杂文档结构（如表格、图表及混合排版），显著提升了信息检索的准确度，从而有效减少模型“胡编乱造”的现象，确保回答既有据可依又具备时效性。其内置的智能体机制更进一步，使系统不仅能回答问题，还能自主规划步骤解决复杂问题。\n\n这款工具特别适合开发者、企业技术团队以及 AI 研究人员使用。无论是希望快速搭建私有知识库问答系统，还是致力于探索大模型在垂直领域落地的创新者，都能从中受益。RAGFlow 提供了可视化的工作流编排界面和灵活的 API 接口，既降低了非算法背景用户的上手门槛，也满足了专业开发者对系统深度定制的需求。作为基于 Apache 2.0 协议开源的项目，它正成为连接通用大模型与行业专有知识之间的重要桥梁。",77062,"2026-04-04T04:44:48",[47,110,109,119,139],{"id":150,"name":151,"github_repo":152,"description_zh":153,"stars":154,"difficulty_score":106,"last_commit_at":155,"category_tags":156,"status":56},2181,"OpenHands","OpenHands\u002FOpenHands","OpenHands 是一个专注于 AI 驱动开发的开源平台，旨在让智能体（Agent）像人类开发者一样理解、编写和调试代码。它解决了传统编程中重复性劳动多、环境配置复杂以及人机协作效率低等痛点，通过自动化流程显著提升开发速度。\n\n无论是希望提升编码效率的软件工程师、探索智能体技术的研究人员，还是需要快速原型验证的技术团队，都能从中受益。OpenHands 提供了灵活多样的使用方式：既可以通过命令行（CLI）或本地图形界面在个人电脑上轻松上手，体验类似 Devin 的流畅交互；也能利用其强大的 Python SDK 自定义智能体逻辑，甚至在云端大规模部署上千个智能体并行工作。\n\n其核心技术亮点在于模块化的软件智能体 SDK，这不仅构成了平台的引擎，还支持高度可组合的开发模式。此外，OpenHands 在 SWE-bench 基准测试中取得了 77.6% 的优异成绩，证明了其解决真实世界软件工程问题的能力。平台还具备完善的企业级功能，支持与 Slack、Jira 等工具集成，并提供细粒度的权限管理，适合从个人开发者到大型企业的各类用户场景。",70612,"2026-04-05T11:12:22",[119,47,109,138]]