universal-tool-calling-protocol/code-mode · 上手攻略

  • 仓库:universal-tool-calling-protocol/code-mode
  • 链接:https://github.com/universal-tool-calling-protocol/code-mode
  • 分类:ai-agent
  • 作者:Tom
  • 更新:2026-08-22

是什么

Code Mode(@utcp/code-mode)是让 AI Agent 通过执行代码而非传统 JSON tool-calling 来调用工具的库。核心思路:给 Agent 一个能写 TypeScript 代码的沙盒执行环境,Agent 在代码里直接调用 MCP/UTCP 工具,一行代码替代传统方案的 15+ 次工具调用轮次。

Apple ML、Cloudflare、Anthropic 都发文推荐此方案优于传统 JSON tool calling。

解决什么问题

传统 Agent 工具调用:每个工具都要传完整 schema → LLM 提取 JSON 参数 → 解析 → 调用 → 返回 → 循环。工具一多,LLM 要在大量 function definitions 里挑,迭代次数多、上下文浪费大。

Code Mode 把这个过程变为:LLM 写一段 TypeScript 代码 → 沙盒执行 → 多个工具调用在一次请求内完成。

性能数据(据独立 Python benchmark,不确定是否经过同行评审,⚠️ 仅供参考):

场景复杂度 传统方式迭代次数 Code Mode 执行次数 提升
简单(2-3 工具) 3 次 1 次 67% 加速
中等(4-7 工具) 8 次 1 次 75% 加速
复杂(8+ 工具) 16 次 1 次 88% 加速

据同一 benchmark,1000 场景/天可节省 $9,536/年 API 费用(⚠️ 数字来源单一,未独立验证)。

快速安装

# NPM 包
npm install @utcp/code-mode

# MCP 协议支持(可选)
npm install @utcp/mcp

核心用法

基础三行模式

import { CodeModeUtcpClient } from '@utcp/code-mode';

const client = await CodeModeUtcpClient.create();  // 1. 初始化
await client.registerManual({ name: 'github', /* MCP config */ });  // 2. 注册工具
const { result } = await client.callToolChain(`/* TypeScript 代码 */`);  // 3. 执行

工具链一次调用

const { result, logs } = await client.callToolChain(`
  const pr = await github.get_pull_request({
    owner: 'microsoft',
    repo: 'vscode',
    pull_number: 1234
  });
  const comments = await github.get_pull_request_comments({
    owner: 'microsoft',
    repo: 'vscode',
    pull_number: 1234
  });
  const reviews = await github.get_pull_request_reviews({
    owner: 'microsoft',
    repo: 'vscode',
    pull_number: 1234
  });
  return {
    title: pr.title,
    commentCount: comments.length,
    approvals: reviews.filter(r => r.state === 'APPROVED').length
  };
`);
// 一次 API 调用替代 15+ 次传统工具调用

动态工具发现

const tools = await client.searchTools('github pull request');
// 自动从 500 个工具定义中筛选出 3 个相关工具

MCP 服务器接入(TypeScript)

import '@utcp/mcp';  // 注册 'mcp' call template
import { CodeModeUtcpClient } from '@utcp/code-mode';

const client = await CodeModeUtcpClient.create();
await client.registerManual({
  name: 'github',
  call_template_type: 'mcp',
  config: {
    mcpServers: {
      github: {
        transport: 'stdio',
        command: 'docker',
        args: ['run', '-i', '--rm', '-e', 'GITHUB_PERSONAL_ACCESS_TOKEN', 'mcp/github'],
        env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN }
      }
    }
  }
});

CLI 模式(推荐给 Shell Agent 用)

如果 Agent 能跑 shell 命令(Claude Code、Cursor、Codex 等),优先用 CLI,不需要配置 MCP 服务器:

# 发现工具 + 生成 TypeScript 接口
npx -y @utcp/code-mode-cli search "<task>"
# 例:搜索 GitHub 工具
npx -y @utcp/code-mode-cli search "github pull request"

# 执行工具链
npx -y @utcp/code-mode-cli run <<'EOF'
const r = await openlibrary.read_search_json_search_json_get({ q: "tolkien", limit: 3 });
return r.docs.map(b => b.title);
EOF

# 交互式 OAuth 登录
npx -y @utcp/code-mode-cli login <manual>

# 完整 prompt 引导(让 CLI 自动发现工具并生成配置)
npx -y @utcp/code-mode-cli prompt

UTCP CLI 架构:Agent 通过 shell 调用 CLI,CLI 写 .utcp_config.json 配置文件并执行,全程不需要配置环境变量。

MCP Server 模式(给 Claude Desktop 等纯 MCP 客户端)

{
  "mcpServers": {
    "code-mode": {
      "command": "npx",
      "args": ["@utcp/code-mode-mcp"],
      "env": {
        "UTCP_CONFIG_FILE": "/path/to/your/.utcp_config.json"
      }
    }
  }
}

⚠️ MCP Server 模式需要提前准备好 .utcp_config.json 配置文件,不自动生成。

支持的协议

协议 说明
MCP @utcp/mcp Model Context Protocol 服务器
HTTP @utcp/http REST API 自动发现
File @utcp/text 本地 JSON/YAML 配置
CLI @utcp/cli 命令行工具执行

⚠️ 各协议插件包的具体包名需参考 README 原文,以上为推断名称。

安全特性

  • VM 沙盒隔离:Node.js isolate 防止未授权访问
  • 超时保护:可配置执行时间上限,防止无限循环
  • 完整日志:捕获所有 console 输出和错误
  • 零外部依赖:工具只能通过注册的 UTCP/MCP 服务器访问

典型适用场景

  • 复杂多步 Agent 工作流:一次代码执行替代传统方案多次工具调用轮次
  • 工具数量大的 Agent:500+ 工具定义时,动态发现 3 个相关工具比全部传给 LLM 更高效
  • 需要组合多个 API 结果的查询:一次执行里串联 GitHub PR + 评论 + 审查
  • Shell 可用的编码 Agent:Claude Code、Cursor 等优先用 UTCP CLI,完全不需要 MCP 配置

坑与注意

  1. ⚠️ MCP 服务器需自行搭建:README 没有提供开箱即用的 MCP 服务器,需要自己准备 GitHub、Slack 等工具的 MCP 实现。
  2. TypeScript 代码生成质量依赖 LLM:如果 LLM 生成的代码有 bug,整个工具链失败,比传统 tool calling 的错误定位更复杂。
  3. 沙盒安全边界:Node.js isolate 安全性不如完整 VM,生产环境高权限工具需谨慎。
  4. ⚠️ MCP Server 模式配置复杂:需要手动写 .utcp_config.json,不如 CLI 模式开箱即用。
  5. @utcp/code-mode-cli 推荐给 shell agent:README 明确说"prefer CLI whenever the agent has shell access",这是官方最佳实践。
  6. Azure API Key 泄露风险:生产环境 .utcp_config.json 包含敏感密钥,需要纳入密钥管理。

与同类对比

方案 原理 优势 劣势
Code Mode / UTCP LLM 写代码执行 一次多工具、LLM 擅长代码 需要沙盒、代码质量依赖 LLM
传统 JSON Tool Calling LLM 提取 JSON 参数 直观、调试简单 工具多时上下文爆炸、多次迭代
Anthropic MCP 标准化工具协议 统一生态 仍是传统 tool calling 模式
LangChain Tools JSON Schema 定义 生态成熟 同样多次迭代问题

Code Mode 的本质是让 LLM 用它最擅长的方式(写代码)来做事,而不是让它学习另一种格式(JSON 参数提取)。

一句话推荐结论

Anthropic/Cloudflare/Apple 联合背书的 Agent 工具调用新范式,Code Mode 把"JSON 参数提取"换成"写 TypeScript 执行",适合工具多、调用链复杂的 AI Agent 场景;Shell Agent 优先用 UTCP CLI,三行代码搞定接入。

来源

  • GitHub README:https://github.com/universal-tool-calling-protocol/code-mode
  • NPM 包:https://www.npmjs.com/package/@utcp/code-mode
  • Cloudflare 官方博客:https://blog.cloudflare.com/code-mode/
  • Anthropic 工程博客:https://www.anthropic.com/engineering/code-execution-with-mcp
  • Apple ML 研究:https://machinelearning.apple.com/research/codeact
  • 独立 Benchmark:https://github.com/imran31415/codemode_python_benchmark