返回市场
代码模式

代码模式

作者:universal-tool-calling-protocol1016 星标更新:2025-11-23

项目介绍

<div align="center"> <!-- <img alt="utcp code mode banner" src="https://github.com/user-attachments/assets/77723130-ecbc-4d1d-9e9b-20f978882699" width="80%" style="margin: 20px auto;"> --> <h1 align="center">🤖 Code-Mode库:通过代码执行进行工具调用的第一个库</h1> <p align="center"> <a href="https://github.com/universal-tool-calling-protocol"> <img src="https://img.shields.io/github/followers/universal-tool-calling-protocol?label=关注组织&logo=github" /></a> <a href="https://img.shields.io/npm/dt/@utcp/code-mode" title="PyPI版本"> <img src="https://img.shields.io/npm/dt/@utcp/code-mode"/></a> <a href="https://github.com/universal-tool-calling-protocol/code-mode/blob/main/LICENSE" alt="许可证"> <img src="https://img.shields.io/github/license/universal-tool-calling-protocol/code-mode" /></a>

npm

</p> </div>

将您的AI代理从笨拙的工具调用者转变为高效的代码执行者——只需3行代码。

为什么这改变了所有事情

大型语言模型(LLMs)擅长编写代码,但在工具调用方面却表现不佳。与其直接暴露数百个工具,不如给它们一个能够执行具有访问整个工具包权限的TypeScript代码的单一工具。

AppleCloudflareAnthropic 表示,与传统的将函数信息转储并提取JSON以进行函数调用相比,Code-Mode是一种更有效的工具调用方法。

基准测试

独立的Python基准研究验证了性能声明,在每天1,000种场景下节省了每年9,536美元的成本:

场景复杂度传统方式Code Mode改进
简单(2-3个工具)3次迭代1次执行快67%
中等(4-7个工具)8次迭代1次执行快75%
复杂(8个及以上工具)16次迭代1次执行快88%

为什么Code Mode占据主导地位:

批处理优势 - 单个代码块替代多个API调用
认知效率 - LLMs在代码生成方面表现出色,而不是工具编排
计算效率 - 操作之间无需重新处理上下文

快速开始

<img width="2606" height="1445" alt="Frame 4 (4)" src="https://gips1.baidu.com/it/u=392914137,998454735&fm=3081&app=3081&f=PNG?w=2606&h=1445" />

在3行代码内开始

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

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

就这样。您的AI代理现在可以在单个请求中执行复杂的流程,而不需要几十个请求。

您将获得什么

渐进式工具发现

// 代理动态发现工具,仅加载所需内容
const tools = await client.searchTools('github pull request');
// 从500个工具定义 → 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+的传统工具调用

自动生成TypeScript接口

namespace github {
  interface get_pull_requestInput {
    /** 仓库拥有者 */
    owner: string;
    /** 仓库名称 */ 
    repo: string;
    /** 拉取请求编号 */
    pull_number: number;
  }
}

企业级准备

  • 安全VM沙箱 – Node.js隔离防止未经授权的访问
  • 超时保护 – 可配置的执行限制防止失控代码
  • 完全可观测性 – 完整的控制台输出捕获和错误处理
  • 零外部依赖 – 工具仅可通过注册的UTCP/MCP服务器访问
  • 运行时内省 – 动态接口发现以适应工作流

如果您在企业工作,并需要支持,请预约咨询这里

通用协议支持

适用于任何工具生态系统

协议描述使用
MCP模型上下文协议服务器call_template_type: 'mcp'
HTTP自动发现的REST APIcall_template_type: 'http'
文件本地JSON/YAML配置call_template_type: 'file'
CLI命令行工具执行call_template_type: 'cli'

安装

npm install @utcp/code-mode

更简单:即用型MCP服务器

想要无需设置的Code Mode? 使用我们的即插即用MCP服务器与Claude Desktop或其他MCP客户端:

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

就这样! 不需要安装,不需要Node.js知识。Code Mode MCP服务器自动:

  • 通过npx下载并运行最新版本
  • 从JSON加载您的工具配置
  • 向Claude Desktop提供代码执行能力
  • 提供call_tool_chain作为MCP工具用于TypeScript执行

非常适合非开发者,他们希望在Claude Desktop中使用Code Mode功能!

直接TypeScript使用

1. MCP服务器集成

连接到任何模型上下文协议服务器:

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

const client = await CodeModeUtcpClient.create();

// 连接到GitHub MCP服务器
await client.registerManual({
  name: 'github',
  call_template_type: 'mcp',
  config: {
    mcpServers: {
      github: {
        command: 'docker',
        args: ['run', '-i', '--rm', '-e', 'GITHUB_PERSONAL_ACCESS_TOKEN', 'mcp/github'],
        env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN }
      }
    }
  }
});

2. 执行多步骤工作流

用一次代码执行替换15+工具调用:

const { result, logs } = await client.callToolChain(`
  // 传统:4次单独的API往返 → Code Mode:1次执行
  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 });
  const files = await github.get_pull_request_files({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 });
  
  // 在沙箱中处理数据(无令牌开销)
  const summary = {
    title: pr.title,
    state: pr.state,
    author: pr.user.login,
    stats: {
      comments: comments.length,
      reviews: reviews.length, 
      filesChanged: files.length,
      approvals: reviews.filter(r => r.state === 'APPROVED').length
    },
    topDiscussion: comments.slice(0, 3).map(c => ({
      author: c.user.login,
      preview: c.body.substring(0, 100) + '...'
    }))
  };
  
  console.log(\`PR "\${pr.title}"分析完成\`);
  return summary;
`);

console.log('分析结果:', result);
// 控制台输出:'PR "修复钩子中的内存泄漏"分析完成'

高级特性

多协议工具链

在一个执行中混合匹配不同的工具生态系统:

// 注册多个工具源
await client.registerManual({ name: 'github', call_template_type: 'mcp', /* 配置 */ });
await client.registerManual({ name: 'slack', call_template_type: 'http', /* 配置 */ });
await client.registerManual({ name: 'db', call_template_type: 'file', file_path: './db-tools.json' }); // 从json文件加载UTCP手动配置

const result = await client.callToolChain(`
  // 从GitHub(MCP)获取拉取请求数据
  const pr = await github.get_pull_request({ owner: '公司', repo: 'api', pull_number: 42 });
  
  // 查询数据库中的部署状态(文件)
  const deployment = await db.get_deployment_status({ pr_id: pr.id });
  
  // 向Slack发送通知(HTTP)
  await slack.post_message({
    channel: '#releases',
    text: \`PR #42 "\${pr.title}"已部署到\${deployment.environment}\`
  });
  
  return { pr: pr.title, environment: deployment.environment };
`);

运行时接口内省

工具可以动态发现并适应可用接口:

const result = await client.callToolChain(`
  // 运行时发现可用工具
  console.log('可用接口:', __interfaces);
  
  // 获取特定工具接口进行验证
  const prInterface = __getToolInterface('github.get_pull_request');
  console.log('拉取请求工具期望:', prInterface);
  
  // 使用接口信息进行动态工作流
  const hasSlackTools = __interfaces.includes('命名空间slack');
  if (hasSlackTools) {
    await slack.post_message({ channel: '#dev', text: '分析完成' });
  }
  
  return { 工具可用: hasSlackTools };
`);

上下文高效数据处理

处理大数据集而不使模型的上下文膨胀:

const result = await client.callToolChain(`
  // 获取大型数据集
  const allIssues = await github.list_repository_issues({ owner: 'facebook', repo: 'react' });
  console.log('获取', allIssues.length, '总问题数');
  
  // 在沙箱中高效处理
  const criticalBugs = allIssues
    .filter(issue => issue.labels.some(l => l.name === 'bug'))
    .filter(issue => issue.labels.some(l => l.name === '高优先级'))
    .map(issue => ({
      number: issue.number,
      title: issue.title,
      author: issue.user.login,
      daysOld: Math.floor((Date.now() - new Date(issue.created_at)) / (1000 * 60 * 60 * 24))
    }))
    .sort((a, b) => b.daysOld - a.daysOld);
  
  // 只返回处理过的摘要(不是10,000个原始问题)
  return {
    总问题数: allIssues.length,
    关键错误: criticalBugs.slice(0, 10), // 最老的10个关键错误
    摘要: \`找到\${criticalBugs.length}个关键错误,最老的是\${criticalBugs[0]?.daysOld}天前\`
  };
`);

错误处理及可观测性

内置错误处理和完整的执行透明度:

const { result, logs } = await client.callToolChain(`
  try {
    console.log('开始多步骤工作流...');
    
    const data = await external_api.fetch_data({ id: 'user-123' });
    console.log('数据获取成功');
    
    const processed = await data_processor.transform(data);
    console.warn('处理完成,有', processed.warnings.length, '个警告');
    
    return processed;
  } catch (error) {
    console.error('工作流失败:', error.message);
    throw error; // 向外传播错误处理
  }
`, 30000); // 30秒超时

// 完全可观测性
console.log('结果:', result);
console.log('执行日志:', logs);
// ['开始多步骤工作流...', '数据获取成功', '[WARN] 处理完成,有2个警告']

自定义超时

为不同工作负载类型配置执行限制:

// 快速操作(5秒)
const quickResult = await client.callToolChain(`return await ping.check();`, 5000);

// 重型数据处理(2分钟) 
const heavyResult = await client.callToolChain(`
  const bigData = await database.export_full_dataset();
  return await analytics.process_dataset(bigData);
`, 120000);

AI代理集成

与任何AI框架即插即用。内置提示模板处理所有复杂性:

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

const systemPrompt = `
您是一个可以通过UTCP CodeMode访问工具的AI助手。
${CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE}
附加指令...
`;

// 适用于任何AI库
const response = await openai.chat.completions.create({
  model: 'gpt-4',
  messages: [
    { role: 'system', content: systemPrompt },
    { role: 'user', content: '分析microsoft/vscode的最新拉取请求' }
  ]
});

模板提供了全面指导:

  • 工具发现工作流(searchTools__interfacescallToolChain
  • 层次访问模式(manual.tool()语法)
  • 接口内省(__getToolInterface()
  • 错误处理和最佳实践

API参考

核心方法

callToolChain(code: string, timeout?: number)

执行具有完整工具访问和可观测性的TypeScript代码。

  • 返回值:包含执行结果和捕获的控制台输出的{result: any, logs: string[]}
  • 默认超时:30秒

getAllToolsTypeScriptInterfaces()

生成完整的TypeScript接口以支持IDE集成。

  • 返回值:包含所有接口定义及其命名空间的字符串

searchTools(query: string) (来自UtcpClient)

使用自然语言查询发现工具。

  • 返回值:相关工具数组,带有描述和接口

静态方法

CodeModeUtcpClient.create(root_dir?, config?)

创建一个新的客户端实例,可选配置。

CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE

生产就绪的AI代理提示模板。


安全与性能

设计安全

  • Node.js VM沙箱 – 隔离执行上下文
  • 无文件系统访问 – 仅通过注册的服务器访问工具
  • 超时保护 – 可配置的执行限制
  • 零网络访问 – 不暴露外部依赖或API密钥

优化性能

  • 最小内存占用 – VM上下文轻量级
  • 高效的工具缓存 – TypeScript接口自动缓存
  • 流式控制台输出 – 实时日志捕获,不缓冲
  • 标识符净化 – 能够优雅地处理无效的TypeScript标识符

开发体验

IDE集成

生成TypeScript定义以支持完整的IntelliSense:

# 生成工具接口  
const interfaces = await client.getAllToolsTypeScriptInterfaces();
await fs.writeFile('generated-tools.d.ts', interfaces);

# 添加到tsconfig.json
{
  "compilerOptions": {
    "typeRoots": ["./generated-tools.d.ts"]
  }
}

调试与监控

内置可观测性用于生产部署:

const { result, logs } = await client.callToolChain(userCode);

// 将日志发送到您的监控系统
logs.forEach(log => {
  if (log.startsWith('[ERROR]')) monitoring.error(log);
  if (log.startsWith('[WARN]')) monitoring.warn(log);
});

基准测试方法论

全面的Python研究测试了16个现实场景,包括:

  • 金融工作流(发票、费用追踪)
  • DevOps操作(部署、监控)
  • **