在 Claude 开发者平台引入高级工具使用功能

Introducing advanced tool use on the Claude Developer Platform

Anthropic · 2025-11-24 · Anthropic Engineering ↗

打开互动全文版(逐段中英对照 + 针对本篇提问)→

摘要 · Abstract

Anthropic 在 Claude 开发者平台上推出三项高级工具使用功能,以解决智能体扩展到数百乃至数千个工具时传统工具调用方式的局限。文章指出,预先加载全部工具定义会消耗数万个 token,并导致工具选择错误和参数错误;而自然语言工具调用则每次调用都需完整推理,并在上下文中累积中间结果。Tool Search Tool 让 Claude 按需发现工具,将 token 用量降低约 85%,并将 MCP 评测准确率从 49% 提升至 74%(Opus 4)、从 79.5% 提升至 88.1%(Opus 4.5)。Programmatic Tool Calling 让 Claude 在沙箱环境中通过代码编排工具,在复杂研究任务上减少 37% 的 token 消耗,消除冗余推理,并提升知识检索与 GIA 基准的准确率。Tool Use Examples 则新增一项标准,用于在 JSON schema 之外演示有效的工具用法。结论是,这些功能为构建可跨大型工具库工作、又不会使上下文窗口过载的智能体开辟了新的可能。

Anthropic introduces three advanced tool-use features on the Claude Developer Platform to address the limits of conventional tool calling as agents scale to hundreds or thousands of tools. The article argues that loading every tool definition upfront consumes tens of thousands of tokens and causes wrong tool selection and incorrect parameters, while natural language tool invocation forces a full inference pass per call and accumulates intermediate results in context. The Tool Search Tool lets Claude discover tools on demand, cutting token usage by roughly 85 percent and improving MCP evaluation accuracy from 49 to 74 percent for Opus 4 and from 79.5 to 88.1 percent for Opus 4.5. Programmatic Tool Calling lets Claude orchestrate tools through code in a sandboxed environment, reducing token consumption by 37 percent on complex research tasks, eliminating redundant inference passes, and improving accuracy on knowledge retrieval and GIA benchmarks. Tool Use Examples add a standard for demonstrating effective tool usage beyond JSON schemas. The conclusion is that these features open new possibilities for building agents that work across large tool libraries without overloading the context window.

核心贡献 · Key contributions

局限 · Limitations

章节 · Sections(共 22)

全文 · Full text(逐段中英对照)

工具搜索工具 01 Tool Search Tool

2026 年 5 月 18 日:Anthropic 收购 Stainless

May 18, 2026: Anthropic acquires Stainless

AI 智能体的未来,是模型能够在数百乃至数千个工具之间无缝协作。一个 IDE 助手可以集成 git 操作、文件操作、包管理器、测试框架和部署流水线。一个运维协调器可以同时连接 Slack、GitHub、Google Drive、Jira、公司数据库以及数十个 MCP 服务器。

The future of AI agents is one where models work seamlessly across hundreds or thousands of tools. An IDE assistant that integrates git operations, file manipulation, package managers, testing frameworks, and deployment pipelines. An operations coordinator that connects Slack, GitHub, Google Drive, Jira, company databases, and dozens of MCP servers simultaneously.

要构建有效的智能体,它们需要能够使用无限的工具库,而不必事先把每个工具定义都塞进上下文窗口。我们关于在 MCP 中使用代码执行的博客文章讨论了:工具结果和定义有时会在智能体读取请求之前就消耗 50,000+ 个 token。智能体应当按需发现并加载工具,只保留与当前任务相关的内容。

To build effective agents, they need to work with unlimited tool libraries without stuffing every definition into context upfront. Our blog article on using code execution with MCP discussed how tool results and definitions can sometimes consume 50,000+ tokens before an agent reads a request. Agents should discover and load tools on-demand, keeping only what's relevant for the current task.

智能体还需要具备从代码中调用工具的能力。使用自然语言进行工具调用时,每次调用都需要一次完整的推理过程,而且无论中间结果是否有用,它们都会在上下文窗口中堆积。代码天然适合承载编排逻辑,例如循环、条件分支和数据转换。智能体需要能够根据手头任务,在代码执行与推理之间灵活选择。

Agents also need the ability to call tools from code. When using natural language tool calling, each invocation requires a full inference pass, and intermediate results pile up in context whether they're useful or not. Code is a natural fit for orchestration logic, such as loops, conditionals, and data transformations. Agents need the flexibility to choose between code execution and inference based on the task at hand.

智能体还需要从示例中学习正确的工具用法,而不仅仅是依赖 schema 定义。JSON schema 定义了结构上什么是合法的,但无法表达使用模式:何时应包含可选参数、哪些参数组合是合理的,或者你的 API 期望遵循哪些约定。

Agents also need to learn correct tool usage from examples, not just schema definitions. JSON schemas define what's structurally valid, but can't express usage patterns: when to include optional parameters, which combinations make sense, or what conventions your API expects.

今天,我们发布了三项功能来实现这一点:

Today, we're releasing three features that make this possible:

* **工具搜索工具**,它允许 Claude 使用搜索工具来访问数千个工具,而不会消耗其上下文窗口

* **Tool Search Tool**, which allows Claude to use search tools to access thousands of tools without consuming its context window

* **程序化工具调用**,它允许 Claude 在代码执行环境中调用工具,从而减少对模型上下文窗口的影响

* **Programmatic Tool Calling**, which allows Claude to invoke tools in a code execution environment reducing the impact on the model's context window

* **工具使用示例**,它提供了一个通用标准,用于演示如何有效使用给定工具

* **Tool Use Examples**, which provides a universal standard for demonstrating how to effectively use a given tool

在内部测试中,我们发现这些功能帮助我们构建了传统工具使用模式无法实现的东西。例如,**Claude for Excel** 使用程序化工具调用来读取和修改具有数千行的电子表格,而不会使模型的上下文窗口过载。

In internal testing, we've found these features have helped us build things that wouldn't have been possible with conventional tool use patterns. For example, **Claude for Excel** uses Programmatic Tool Calling to read and modify spreadsheets with thousands of rows without overloading the model's context window.

基于我们的经验,我们相信这些功能为使用 Claude 构建应用开辟了新的可能性。

Based on our experience, we believe these features open up new possibilities for what you can build with Claude.

挑战 The challenge

MCP 工具定义提供了重要的上下文,但随着接入的服务器增多,这些 token 会不断累积。考虑一个五服务器配置:

MCP tool definitions provide important context, but as more servers connect, those tokens can add up. Consider a five-server setup:

这意味着在对话尚未开始之前,58 个工具就已消耗约 55K token。再接入 Jira 等更多服务器(仅 Jira 一项就占用约 17K token),token 开销很快就会逼近 100K 以上。在 Anthropic,我们曾见过工具定义在优化前消耗 134K token。

That's 58 tools consuming approximately 55K tokens before the conversation even starts. Add more servers like Jira (which alone uses ~17K tokens) and you're quickly approaching 100K+ token overhead. At Anthropic, we've seen tool definitions consume 134K tokens before optimization.

但 token 成本并非唯一问题。最常见的失败是工具选择错误和参数错误,尤其是当工具名称相似时,例如 notification-send-user 与 notification-send-channel。

But token cost isn't the only issue. The most common failures are wrong tool selection and incorrect parameters, especially when tools have similar names like notification-send-user vs. notification-send-channel.

我们的解决方案 Our solution

Tool Search Tool 不再预先加载全部工具定义,而是按需发现工具。Claude 只会看到当前任务实际需要的工具。

Instead of loading all tool definitions upfront, the Tool Search Tool discovers tools on-demand. Claude only sees the tools it actually needs for the current task.

* 所有工具定义均预先加载(50+ 个 MCP 工具约需 72K 个 token)

* All tool definitions loaded upfront (~72K tokens for 50+ MCP tools)

* 对话历史与系统提示词争夺剩余空间

* Conversation history and system prompt compete for remaining space

* 在任何工作开始之前,上下文总消耗已达约 77K 个 token

* Total context consumption: ~77K tokens before any work begins

* 仅预先加载 Tool Search Tool(约 500 个 token)

* Only the Tool Search Tool loaded upfront (~500 tokens)

* 按需发现工具(3-5 个相关工具,约 3K 个 token)

* Tools discovered on-demand as needed (3-5 relevant tools, ~3K tokens)

* 总上下文消耗:约 8.7K 个 token,保留 95% 的上下文窗口

* Total context consumption: ~8.7K tokens, preserving 95% of context window

这意味着在保持对完整工具库访问的同时,token 使用量减少了 85%。内部测试表明,在处理大型工具库时,MCP 评估的准确率显著提升。启用 Tool Search Tool 后,Opus 4 从 49% 提升至 74%,Opus 4.5 从 79.5% 提升至 88.1%。

This represents an 85% reduction in token usage while maintaining access to your full tool library. Internal testing showed significant accuracy improvements on MCP evaluations when working with large tool libraries. Opus 4 improved from 49% to 74%, and Opus 4.5 improved from 79.5% to 88.1% with Tool Search Tool enabled.

工具搜索工具的工作原理 How the Tool Search Tool works

工具搜索工具让 Claude 动态发现工具,而不是预先加载所有定义。你把所有工具定义都提供给 API,但将工具标记为 `defer_loading: true`,使其可按需被发现。延迟加载的工具最初不会加载到 Claude 的上下文窗口中。Claude 只能看到工具搜索工具本身,以及任何标记为 `defer_loading: false` 的工具(即最关键、最常用的工具)。

The Tool Search Tool lets Claude dynamically discover tools instead of loading all definitions upfront. You provide all your tool definitions to the API, but mark tools with `defer_loading: true` to make them discoverable on-demand. Deferred tools aren't loaded into Claude's context initially. Claude only sees the Tool Search Tool itself plus any tools with `defer_loading: false` (your most critical, frequently-used tools).

当 Claude 需要特定能力时,它会搜索相关工具。工具搜索工具返回匹配工具的引用,这些引用会在 Claude 的上下文窗口中展开为完整定义。

When Claude needs specific capabilities, it searches for relevant tools. The Tool Search Tool returns references to matching tools, which get expanded into full definitions in Claude's context.

例如,如果 Claude 需要与 GitHub 交互,它会搜索“github”,此时只会加载 `github.createPullRequest` 和 `github.listIssues`,而不会加载你在 Slack、Jira 和 Google Drive 中的其他 50 多个工具。

For example, if Claude needs to interact with GitHub, it searches for "github," and only `github.createPullRequest` and `github.listIssues` get loaded—not your other 50+ tools from Slack, Jira, and Google Drive.

这样一来,Claude 既能访问你的完整工具库,又只需为它实际需要的工具支付 token 成本。

This way, Claude has access to your full tool library while only paying the token cost for tools it actually needs.

**提示缓存说明:** 工具搜索工具不会破坏提示缓存,因为延迟加载的工具完全被排除在初始提示之外。它们只有在 Claude 搜索之后才会被添加到上下文中,因此你的系统提示和核心工具定义仍然可缓存。

**Prompt caching note:** The Tool Search Tool doesn't break prompt caching because deferred tools are excluded from the initial prompt entirely. They're only added to context after Claude searches for them, so your system prompt and core tool definitions remain cacheable.

``` { "tools": [ // Include a tool search tool (regex, BM25, or custom) {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"}, // Mark tools for on-demand discovery { "name": "github.createPullRequest", "description": "Create a pull request", "input_schema": {...}, "defer_loading": true } // ... hundreds more deferred tools with defer_loading: true ] } ```

``` { "tools": [ // Include a tool search tool (regex, BM25, or custom) {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"}, // Mark tools for on-demand discovery { "name": "github.createPullRequest", "description": "Create a pull request", "input_schema": {...}, "defer_loading": true } // ... hundreds more deferred tools with defer_loading: true ] } ```

对于 MCP 服务器,你可以推迟加载整个服务器,同时保持特定的高频使用工具处于已加载状态:

For MCP servers, you can defer loading entire servers while keeping specific high-use tools loaded:

``` { "type": "mcp_toolset", "mcp_server_name": "google-drive", "default_config": {"defer_loading": true}, # defer loading the entire server "configs": { "search_files": { "defer_loading": false } // Keep most used tool loaded } } ```

``` { "type": "mcp_toolset", "mcp_server_name": "google-drive", "default_config": {"defer_loading": true}, # defer loading the entire server "configs": { "search_files": { "defer_loading": false } // Keep most used tool loaded } } ```

Claude 开发者平台开箱即用地提供了基于正则表达式和基于 BM25 的搜索工具,但你也可以使用嵌入或其他策略实现自定义搜索工具。

The Claude Developer Platform provides regex-based and BM25-based search tools out of the box, but you can also implement custom search tools using embeddings or other strategies.

何时使用工具搜索工具 When to use the Tool Search Tool

与任何架构决策一样,启用工具搜索工具(Tool Search Tool)都涉及权衡。该功能在工具调用之前增加了一个搜索步骤,因此只有当上下文节省和准确率提升超过额外延迟时,它才能带来最佳 ROI。

Like any architectural decision, enabling the Tool Search Tool involves trade-offs. The feature adds a search step before tool invocation, so it delivers the best ROI when the context savings and accuracy improvements outweigh additional latency.

* 工具定义消耗超过 10K tokens

* Tool definitions consuming >10K tokens

* 遇到工具选择准确率问题

* Experiencing tool selection accuracy issues

* 构建由 MCP 驱动、包含多个服务器的系统

* Building MCP-powered systems with multiple servers

* 所有工具在每个会话中都被频繁使用

* All tools used frequently in every session

挑战 The challenge

随着工作流变得更加复杂,传统的工具调用产生了两个根本问题:

Traditional tool calling creates two fundamental problems as workflows become more complex:

* **中间结果导致的上下文污染**:当 Claude 分析一个 10MB 的日志文件以寻找错误模式时,整个文件都会进入其上下文窗口,尽管 Claude 只需要错误频率的摘要。当从多个表中获取客户数据时,每条记录无论是否相关都会累积在上下文中。这些中间结果消耗了大量的 token 预算,并可能将重要信息完全挤出上下文窗口。

* **Context pollution from intermediate results**: When Claude analyzes a 10MB log file for error patterns, the entire file enters its context window, even though Claude only needs a summary of error frequencies. When fetching customer data across multiple tables, every record accumulates in context regardless of relevance. These intermediate results consume massive token budgets and can push important information out of the context window entirely.

* **推理开销与手动综合**:每次工具调用都需要完整的模型推理过程。收到结果后,Claude 必须“目测”数据以提取相关信息,推理各部分如何组合,并决定下一步做什么——所有这些都通过自然语言处理完成。一个包含五个工具的工作流意味着五次推理过程,加上 Claude 解析每个结果、比较值并综合结论。这既慢又容易出错。

* **Inference overhead and manual synthesis**: Each tool call requires a full model inference pass. After receiving results, Claude must "eyeball" the data to extract relevant information, reason about how pieces fit together, and decide what to do next—all through natural language processing. A five tool workflow means five inference passes plus Claude parsing each result, comparing values, and synthesizing conclusions. This is both slow and error-prone.

我们的解决方案 Our solution

程序化工具调用(Programmatic Tool Calling)使 Claude 能够通过代码而非逐次 API 往返来编排工具。Claude 不再一次请求一个工具、并将每个结果返回其上下文,而是编写代码来调用多个工具、处理它们的输出,并控制哪些信息真正进入其上下文窗口。

Programmatic Tool Calling enables Claude to orchestrate tools through code rather than through individual API round-trips. Instead of Claude requesting tools one at a time with each result being returned to its context, Claude writes code that calls multiple tools, processes their outputs, and controls what information actually enters its context window.

Claude 擅长编写代码;通过让它用 Python 而非自然语言工具调用来表达编排逻辑,可以获得更可靠、更精确的控制流。循环、条件、数据转换和错误处理都在代码中显式表达,而非隐含在 Claude 的推理之中。

Claude excels at writing code, and by letting it express orchestration logic in Python rather than through natural language tool invocations, you get more reliable, precise control flow. Loops, conditionals, data transformations, and error handling are all explicit in code rather than implicit in Claude's reasoning.

示例:预算合规检查 Example: Budget compliance check

考虑一个常见的业务任务:“哪些团队成员超出了他们的第三季度差旅预算?”

Consider a common business task: "Which team members exceeded their Q3 travel budget?"

* get_team_members(department) - 返回团队成员列表,包含 ID 和级别

* get_team_members(department) - Returns team member list with IDs and levels

* get_expenses(user_id, quarter) - 返回某个用户的费用明细项

* get_expenses(user_id, quarter) - Returns expense line items for a user

* get_budget_by_level(level) - 返回某个员工级别的预算限额

* get_budget_by_level(level) - Returns budget limits for an employee level

* 对每个人,获取其第三季度费用 → 20 次工具调用,每次返回 50-100 个明细项(航班、酒店、餐饮、收据)

* For each person, fetch their Q3 expenses → 20 tool calls, each returning 50-100 line items (flights, hotels, meals, receipts)

* 按员工级别获取预算限额

* 按员工级别获取预算限额

* 所有这些都进入 Claude 的上下文:2,000+ 条费用明细项(50 KB+)

* 所有这些都进入 Claude 的上下文:2,000+ 条费用明细项(50 KB+)

* Claude 手动汇总每个人的费用,查找他们的预算,将费用与预算限额进行比较

* Claude 手动汇总每个人的费用,查找他们的预算,将费用与预算限额进行比较

* 更多与模型的往返交互,显著的上下文消耗

* 更多与模型的往返交互,显著的上下文消耗

每个工具结果不再返回给 Claude,而是由 Claude 编写一个 Python 脚本来编排整个工作流。该脚本在代码执行工具(一个沙盒环境)中运行,当需要从你的工具获取结果时暂停。当你通过 API 返回工具结果时,这些结果由脚本处理,而不是由模型消耗。脚本继续执行,Claude 只看到最终输出。

每个工具结果不再返回给 Claude,而是由 Claude 编写一个 Python 脚本来编排整个工作流。该脚本在代码执行工具(一个沙盒环境)中运行,当需要从你的工具获取结果时暂停。当你通过 API 返回工具结果时,这些结果由脚本处理,而不是由模型消耗。脚本继续执行,Claude 只看到最终输出。

以下是 Claude 在预算合规任务中的编排代码示例:

Here's what Claude's orchestration code looks like for the budget compliance task:

``` team = await get_team_members("engineering") # Fetch budgets for each unique level levels = list(set(m["level"] for m in team)) budget_results = await asyncio.gather(*[ get_budget_by_level(level) for level in levels ]) # Create a lookup dictionary: {"junior": budget1, "senior": budget2, ...} budgets = {level: budget for level, budget in zip(levels, budget_results)} # Fetch all expenses in parallel expenses = await asyncio.gather(*[ get_expenses(m["id"], "Q3") for m in team ]) # Find employees who exceeded their travel budget exceeded = [] for member, exp in zip(team, expenses): budget = budgets[member["level"]] total = sum(e["amount"] for e in exp) if total > budget["travel_limit"]: exceeded.append({ "name": member["name"], "spent": total, "limit": budget["travel_limit"] }) print(json.dumps(exceeded)) ```

``` team = await get_team_members("engineering") # Fetch budgets for each unique level levels = list(set(m["level"] for m in team)) budget_results = await asyncio.gather(*[ get_budget_by_level(level) for level in levels ]) # Create a lookup dictionary: {"junior": budget1, "senior": budget2, ...} budgets = {level: budget for level, budget in zip(levels, budget_results)} # Fetch all expenses in parallel expenses = await asyncio.gather(*[ get_expenses(m["id"], "Q3") for m in team ]) # Find employees who exceeded their travel budget exceeded = [] for member, exp in zip(team, expenses): budget = budgets[member["level"]] total = sum(e["amount"] for e in exp) if total > budget["travel_limit"]: exceeded.append({ "name": member["name"], "spent": total, "limit": budget["travel_limit"] }) print(json.dumps(exceeded)) ```

Claude 的上下文仅接收最终结果:两到三名超出预算的人员。2000 多个行项目、中间求和以及预算查找均不会影响 Claude 的上下文,从而将消耗从 200KB 的原始支出数据减少到仅 1KB 的结果。

Claude's context receives only the final result: the two to three people who exceeded their budget. The 2,000+ line items, the intermediate sums, and the budget lookups do not affect Claude's context, reducing consumption from 200KB of raw expense data to just 1KB of results.

* **Token 节省**:通过将中间结果排除在 Claude 的上下文之外,PTC 大幅降低了 token 消耗。在复杂研究任务中,平均使用量从 43,588 个 token 降至 27,297 个 token,减少了 37%。

* **Token savings**: By keeping intermediate results out of Claude's context, PTC dramatically reduces token consumption. Average usage dropped from 43,588 to 27,297 tokens, a 37% reduction on complex research tasks.

* **降低延迟**:每次 API 往返都需要模型推理(数百毫秒到数秒)。当 Claude 在单个代码块中编排 20 多次工具调用时,可消除 19 次以上的推理过程。API 处理工具执行,无需每次都返回模型。

* **Reduced latency**: Each API round-trip requires model inference (hundreds of milliseconds to seconds). When Claude orchestrates 20+ tool calls in a single code block, you eliminate 19+ inference passes. The API handles tool execution without returning to the model each time.

* **更高的准确率**:通过编写显式的编排逻辑,Claude 的错误比用自然语言同时处理多个工具结果时更少。内部知识检索从 25.6% 提升到 28.5%;GIA 基准从 46.5% 提升到 51.2%。

* **Improved accuracy**: By writing explicit orchestration logic, Claude makes fewer errors than when juggling multiple tool results in natural language. Internal knowledge retrieval improved from 25.6% to 28.5%; GIA benchmarks from 46.5% to 51.2%.

生产工作流涉及杂乱数据、条件逻辑以及需要规模化的操作。Programmatic Tool Calling 让 Claude 以编程方式处理这种复杂性,同时将注意力集中在可执行的结果上,而非原始数据处理。

Production workflows involve messy data, conditional logic, and operations that need to scale. Programmatic Tool Calling lets Claude handle that complexity programmatically while keeping its focus on actionable results rather than raw data processing.

1. 将工具标记为可从代码调用 1. Mark tools as callable from code

将 `code_execution` 添加到 tools 中,并将 `allowed_callers` 设置为选择启用的工具,以便进行程序化执行:

Add `code_execution` to tools, and set `allowed_callers` to opt-in tools for programmatic execution:

``` { "tools": [ { "type": "code_execution_20250825", "name": "code_execution" }, { "name": "get_team_members", "description": "Get all members of a department...", "input_schema": {...}, "allowed_callers": ["code_execution_20250825"] # opt-in to programmatic tool calling }, { "name": "get_expenses", ... }, { "name": "get_budget_by_level", ... } ] } ```

``` { "tools": [ { "type": "code_execution_20250825", "name": "code_execution" }, { "name": "get_team_members", "description": "Get all members of a department...", "input_schema": {...}, "allowed_callers": ["code_execution_20250825"] # opt-in to programmatic tool calling }, { "name": "get_expenses", ... }, { "name": "get_budget_by_level", ... } ] } ```

API 会将这些工具定义转换为 Claude 可以调用的 Python 函数。

The API converts these tool definitions into Python functions that Claude can call.

2. Claude 编写编排代码 2. Claude writes orchestration code

Claude 不再逐个请求工具,而是生成 Python 代码:

Instead of requesting tools one at a time, Claude generates Python code:

``` { "type": "server_tool_use", "id": "srvtoolu_abc", "name": "code_execution", "input": { "code": "team = get_team_members('engineering')\n..." # the code example above } } ```

``` { "type": "server_tool_use", "id": "srvtoolu_abc", "name": "code_execution", "input": { "code": "team = get_team_members('engineering')\n..." # the code example above } } ```

3. 工具执行不占用 Claude 的上下文窗口 3. Tools execute without hitting Claude's context

当代码调用 get_expenses() 时,你会收到一个带有 caller 字段的工具请求:

When the code calls get_expenses(), you receive a tool request with a caller field:

``` { "type": "tool_use", "id": "toolu_xyz", "name": "get_expenses", "input": {"user_id": "emp_123", "quarter": "Q3"}, "caller": { "type": "code_execution_20250825", "tool_id": "srvtoolu_abc" } } ```

``` { "type": "tool_use", "id": "toolu_xyz", "name": "get_expenses", "input": {"user_id": "emp_123", "quarter": "Q3"}, "caller": { "type": "code_execution_20250825", "tool_id": "srvtoolu_abc" } } ```

你提供结果,该结果在代码执行环境中处理,而不是在 Claude 的上下文窗口中处理。对于代码中的每次工具调用,这个请求-响应循环都会重复。

You provide the result, which is processed in the Code Execution environment rather than Claude's context. This request-response cycle repeats for each tool call in the code.

4. 只有最终输出进入上下文 4. Only final output enters context

当代码运行结束后,只有代码的运行结果会被返回给 Claude:

When the code finishes running, only the results of the code are returned to Claude:

``` { "type": "code_execution_tool_result", "tool_use_id": "srvtoolu_abc", "content": { "stdout": "[{\"name\": \"Alice\", \"spent\": 12500, \"limit\": 10000}...]" } } ```

``` { "type": "code_execution_tool_result", "tool_use_id": "srvtoolu_abc", "content": { "stdout": "[{\"name\": \"Alice\", \"spent\": 12500, \"limit\": 10000}...]" } } ```

这就是 Claude 所看到的全部内容,而不是处理过程中涉及的 2000 多条费用明细。

This is all Claude sees, not the 2000+ expense line items processed along the way.

何时使用程序化工具调用 When to use Programmatic Tool Calling

程序化工具调用会在你的工作流中增加一个代码执行步骤。当 token 节省、延迟改善和准确率提升都相当可观时,这一额外开销是值得的。

Programmatic Tool Calling adds a code execution step to your workflow. This extra overhead pays off when the token savings, latency improvements, and accuracy gains are substantial.

* 处理大型数据集,且你只需要聚合结果或摘要

* Processing large datasets where you only need aggregates or summaries

* 运行包含三个或更多相互依赖的工具调用的多步工作流

* Running multi-step workflows with three or more dependent tool calls

* 在 Claude 看到工具结果之前对其进行过滤、排序或转换

* Filtering, sorting, or transforming tool results before Claude sees them

* 处理中间数据不应影响 Claude 推理的任务

* Handling tasks where intermediate data shouldn't influence Claude's reasoning

* 在大量条目上运行并行操作(例如检查 50 个端点)

* Running parallel operations across many items (for example, checking 50 endpoints)

* 进行简单的单工具调用

* Making simple single-tool invocations

* 处理需要 Claude 查看并推理所有中间结果的任务

* Working on tasks where Claude should see and reason about all intermediate results

* 运行响应较小的快速查询

* Running quick lookups with small responses

挑战 The challenge

JSON Schema 擅长定义结构——类型、必需字段、允许的枚举值——但它无法表达使用模式:何时包含可选参数、哪些组合有意义,或者你的 API 期望什么约定。

JSON Schema excels at defining structure—types, required fields, allowed enums—but it can't express usage patterns: when to include optional parameters, which combinations make sense, or what conventions your API expects.

``` { "name": "create_ticket", "input_schema": { "properties": { "title": {"type": "string"}, "priority": {"enum": ["low", "medium", "high", "critical"]}, "labels": {"type": "array", "items": {"type": "string"}}, "reporter": { "type": "object", "properties": { "id": {"type": "string"}, "name": {"type": "string"}, "contact": { "type": "object", "properties": { "email": {"type": "string"}, "phone": {"type": "string"} } } } }, "due_date": {"type": "string"}, "escalation": { "type": "object", "properties": { "level": {"type": "integer"}, "notify_manager": {"type": "boolean"}, "sla_hours": {"type": "integer"} } } }, "required": ["title"] } } ```

``` { "name": "create_ticket", "input_schema": { "properties": { "title": {"type": "string"}, "priority": {"enum": ["low", "medium", "high", "critical"]}, "labels": {"type": "array", "items": {"type": "string"}}, "reporter": { "type": "object", "properties": { "id": {"type": "string"}, "name": {"type": "string"}, "contact": { "type": "object", "properties": { "email": {"type": "string"}, "phone": {"type": "string"} } } } }, "due_date": {"type": "string"}, "escalation": { "type": "object", "properties": { "level": {"type": "integer"}, "notify_manager": {"type": "boolean"}, "sla_hours": {"type": "integer"} } } }, "required": ["title"] } } ```

模式定义了什么是有效的,但留下了关键问题未解答:

The schema defines what's valid, but leaves critical questions unanswered:

* **格式歧义:** due_date 应该使用 “2024-11-06”、“Nov 6, 2024”还是 “2024-11-06T00:00:00Z”?

* **Format ambiguity:** Should due_date use "2024-11-06", "Nov 6, 2024", or "2024-11-06T00:00:00Z"?

* **ID 约定:** reporter.id 是 UUID、“USR-12345”还是只是 “12345”?

* **ID conventions:** Is reporter.id a UUID, "USR-12345", or just "12345"?

* **嵌套结构使用:** Claude 何时应该填充 reporter.contact?

* **Nested structure usage:** When should Claude populate reporter.contact?

* **参数相关性:** escalation.level 与 escalation.sla_hours 如何与 priority 相关联?

* **Parameter correlations:** How do escalation.level and escalation.sla_hours relate to priority?

这些歧义可能导致工具调用格式错误以及参数使用不一致。

These ambiguities can lead to malformed tool calls and inconsistent parameter usage.

我们的解决方案 Our solution

工具使用示例允许您直接在工具定义中提供示例工具调用。您无需仅依赖模式,而是向 Claude 展示具体的使用模式:

Tool Use Examples let you provide sample tool calls directly in your tool definitions. Instead of relying on schema alone, you show Claude concrete usage patterns:

``` { "name": "create_ticket", "input_schema": { /* same schema as above */ }, "input_examples": [ { "title": "Login page returns 500 error", "priority": "critical", "labels": ["bug", "authentication", "production"], "reporter": { "id": "USR-12345", "name": "Jane Smith", "contact": { "email": "jane@acme.com", "phone": "+1-555-0123" } }, "due_date": "2024-11-06", "escalation": { "level": 2, "notify_manager": true, "sla_hours": 4 } }, { "title": "Add dark mode support", "labels": ["feature-request", "ui"], "reporter": { "id": "USR-67890", "name": "Alex Chen" } }, { "title": "Update API documentation" } ] } ```

``` { "name": "create_ticket", "input_schema": { /* same schema as above */ }, "input_examples": [ { "title": "Login page returns 500 error", "priority": "critical", "labels": ["bug", "authentication", "production"], "reporter": { "id": "USR-12345", "name": "Jane Smith", "contact": { "email": "jane@acme.com", "phone": "+1-555-0123" } }, "due_date": "2024-11-06", "escalation": { "level": 2, "notify_manager": true, "sla_hours": 4 } }, { "title": "Add dark mode support", "labels": ["feature-request", "ui"], "reporter": { "id": "USR-67890", "name": "Alex Chen" } }, { "title": "Update API documentation" } ] } ```

从这三个示例中,Claude 学习到:

From these three examples, Claude learns:

* **格式约定**:日期使用 YYYY-MM-DD,用户 ID 遵循 USR-XXXXX,标签使用 kebab-case

* **Format conventions**: Dates use YYYY-MM-DD, user IDs follow USR-XXXXX, labels use kebab-case

* **嵌套结构模式**:如何构造带有嵌套 contact 对象的 reporter 对象

* **Nested structure patterns**: How to construct the reporter object with its nested contact object

* **可选参数关联**:关键 bug 具有完整的联系信息 + 具有严格 SLA 的升级;功能请求有 reporter 但没有联系/升级;内部任务只有标题

* **Optional parameter correlations**: Critical bugs have full contact info + escalation with tight SLAs; feature requests have reporter but no contact/escalation; internal tasks have title only

在我们自己的内部测试中,工具使用示例将复杂参数处理上的准确率从 72% 提升到了 90%。

In our own internal testing, tool use examples improved accuracy from 72% to 90% on complex parameter handling.

何时使用工具使用示例 When to use Tool Use Examples

工具使用示例会为工具定义增加 token,因此当准确率提升的收益超过额外成本时,它们最具价值。

Tool Use Examples add tokens to your tool definitions, so they're most valuable when accuracy improvements outweigh the additional cost.

* 复杂的嵌套结构:合法的 JSON 并不代表用法正确

* Complex nested structures where valid JSON doesn't imply correct usage

* 具有大量可选参数、且参数包含模式很重要的工具

* Tools with many optional parameters and inclusion patterns matter

* 具有 schema 未能涵盖的领域特定约定的 API

* APIs with domain-specific conventions not captured in schemas

* 相似工具:示例可说明应使用哪一个(例如 create_ticket 与 create_incident)

* Similar tools where examples clarify which one to use (e.g., create_ticket vs create_incident)

* 用法显而易见的简单单参数工具

* Simple single-parameter tools with obvious usage

* Claude 已经理解的标准格式,如 URL 或电子邮件

* Standard formats like URLs or emails that Claude already understands

* 更适合由 JSON Schema 约束处理的校验问题

* Validation concerns better handled by JSON Schema constraints

最佳实践 Best practices

构建能够执行真实世界动作的智能体,意味着要同时应对规模、复杂性与精度三方面的挑战。这三项特性协同作用,以解决工具使用工作流中的不同瓶颈。以下说明如何有效地将它们结合起来。

Building agents that take real-world actions means handling scale, complexity, and precision simultaneously. These three features work together to solve different bottlenecks in tool use workflows. Here's how to combine them effectively.

分层策略性地使用功能 Layer features strategically

并非每个智能体在处理给定任务时都需要使用全部三项功能。请从你最大的瓶颈入手:

Not every agent needs to use all three features for a given task. Start with your biggest bottleneck:

* 工具定义导致的上下文膨胀 → Tool Search Tool

* Context bloat from tool definitions → Tool Search Tool

* 大型中间结果污染上下文 → Programmatic Tool Calling

* Large intermediate results polluting context → Programmatic Tool Calling

* 参数错误与格式错误的调用 → Tool Use Examples

* Parameter errors and malformed calls → Tool Use Examples

这种聚焦式方法让你能够针对限制智能体性能的具体约束加以解决,而不是一开始就增加复杂性。

This focused approach lets you address the specific constraint limiting your agent's performance, rather than adding complexity upfront.

然后按需分层添加额外功能。这些功能相互补充:Tool Search Tool 确保找到正确的工具,Programmatic Tool Calling 确保高效执行,而 Tool Use Examples 确保正确调用。

Then layer additional features as needed. They're complementary: Tool Search Tool ensures the right tools are found, Programmatic Tool Calling ensures efficient execution, and Tool Use Examples ensure correct invocation.

设置工具搜索工具以提升发现能力 Set up Tool Search Tool for better discovery

工具搜索会依据名称和描述进行匹配,因此清晰、具有描述性的定义能提升发现的准确性。

Tool search matches against names and descriptions, so clear, descriptive definitions improve discovery accuracy.

``` // Good { "name": "search_customer_orders", "description": "Search for customer orders by date range, status, or total amount. Returns order details including items, shipping, and payment info." } // Bad { "name": "query_db_orders", "description": "Execute order query" } ```

``` // Good { "name": "search_customer_orders", "description": "Search for customer orders by date range, status, or total amount. Returns order details including items, shipping, and payment info." } // Bad { "name": "query_db_orders", "description": "Execute order query" } ```

添加系统提示词指引,让 Claude 知道有哪些可用工具:

Add system prompt guidance so Claude knows what's available:

``` You have access to tools for Slack messaging, Google Drive file management, Jira ticket tracking, and GitHub repository operations. Use the tool search to find specific capabilities. ```

``` You have access to tools for Slack messaging, Google Drive file management, Jira ticket tracking, and GitHub repository operations. Use the tool search to find specific capabilities. ```

将你最常用的三到五个工具始终保持加载,其余工具则延迟加载。这样既能为常见操作提供即时访问,又能对其余所有工具按需发现。

Keep your three to five most-used tools always loaded, and defer the rest. This balances immediate access for common operations with on-demand discovery for everything else.

为正确执行设置程序化工具调用 Set up Programmatic Tool Calling for correct execution

由于 Claude 会编写代码来解析工具输出,因此应清晰地记录返回格式。这有助于 Claude 编写正确的解析逻辑:

Since Claude writes code to parse tool outputs, document return formats clearly. This helps Claude write correct parsing logic:

``` { "name": "get_orders", "description": "Retrieve orders for a customer. Returns: List of order objects, each containing: - id (str): Order identifier - total (float): Order total in USD - status (str): One of 'pending', 'shipped', 'delivered' - items (list): Array of {sku, quantity, price} - created_at (str): ISO 8601 timestamp" } ```

``` { "name": "get_orders", "description": "Retrieve orders for a customer. Returns: List of order objects, each containing: - id (str): Order identifier - total (float): Order total in USD - status (str): One of 'pending', 'shipped', 'delivered' - items (list): Array of {sku, quantity, price} - created_at (str): ISO 8601 timestamp" } ```

以下是可以受益于程序化编排的可选工具:

See below for opt-in tools that benefit from programmatic orchestration:

* 可并行运行的工具(独立操作)

* Tools that can run in parallel (independent operations)

* 可安全重试的操作(幂等)

* Operations safe to retry (idempotent)

为参数准确性设置工具使用示例 Set up Tool Use Examples for parameter accuracy

* 使用真实数据(真实城市名、合理价格,而非 “string”或 “value”)

* Use realistic data (real city names, plausible prices, not "string" or "value")

* 通过最小、部分和完整规格模式展示多样性

* Show variety with minimal, partial, and full specification patterns

* 保持简洁:每个工具 1-5 个示例

* Keep it concise: 1-5 examples per tool

* 聚焦歧义(仅在正确用法无法从 schema 中明显看出时添加示例)

* Focus on ambiguity (only add examples where correct usage isn't obvious from schema)

入门 Getting started

这些功能目前处于 beta 阶段。要启用它们,请添加 beta 请求头并包含你需要的工具:

These features are available in beta. To enable them, add the beta header and include the tools you need:

``` client.beta.messages.create( betas=["advanced-tool-use-2025-11-20"], model="claude-sonnet-4-5-20250929", max_tokens=4096, tools=[ {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"}, {"type": "code_execution_20250825", "name": "code_execution"}, # Your tools with defer_loading, allowed_callers, and input_examples ] ) ```

``` client.beta.messages.create( betas=["advanced-tool-use-2025-11-20"], model="claude-sonnet-4-5-20250929", max_tokens=4096, tools=[ {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"}, {"type": "code_execution_20250825", "name": "code_execution"}, # Your tools with defer_loading, allowed_callers, and input_examples ] ) ```

有关详细的 API 文档和 SDK 示例,请参阅我们的:

For detailed API documentation and SDK examples, see our:

* Tool Search Tool 的文档与 cookbook

* Documentation and cookbook for Tool Search Tool

* Programmatic Tool Calling 的文档与 cookbook

* Documentation and cookbook for Programmatic Tool Calling

这些功能将工具使用从简单的函数调用推向智能编排。随着智能体处理跨越数十个工具和大型数据集的更复杂工作流,动态发现、高效执行和可靠调用变得至关重要。

These features move tool use from simple function calling toward intelligent orchestration. As agents tackle more complex workflows spanning dozens of tools and large datasets, dynamic discovery, efficient execution, and reliable invocation become foundational.

互动版:针对本篇提问 →

接着读 · Read next

目录