服务端工具
24 篇讲的工具都由你自己执行:Claude 返回 tool_use,你的代码跑函数,把 tool_result 送回去。还有一类工具不用你执行——在 tools 里声明一下,Anthropic 的服务器就替你跑完:搜网页、抓网页、在沙箱里跑代码、按需搜索工具定义、连接远程 MCP server、请一个更强的模型出主意。这一篇把这些服务端工具和与它们相关的几个机制(Agent Skills、程序化工具调用、computer use、pause_turn)讲清楚。
一句话先记住:服务端工具把"循环"搬到了 Anthropic 那边。一次请求里,服务端可能已经搜了五次网、跑了三段代码,你拿到的是一个已经带着结果的回答。好处是代码少、延迟低;代价是你要学会读新的结果块、处理
pause_turn,并且清楚每个工具在哪个平台上可用。
一、三类工具
| 类别 | 谁定义 schema | 谁执行 | 例子 |
|---|---|---|---|
| 自定义工具 | 你 | 你 | get_weather、query_db(24 篇) |
| Anthropic 定义、客户端执行 | Anthropic | 你 | bash、text editor、memory、computer use |
| 服务端工具 | Anthropic | Anthropic | 网页搜索、网页抓取、代码执行、工具搜索、advisor、MCP connector |
第二类的意思是:模型对这些工具训练得很熟,你只需要声明 type,不用写 schema;但它们操作的是你的环境(你的文件系统、你的屏幕),所以执行还得你来。第三类连执行都不用管。
服务端工具的结果以内容块的形式出现在同一个响应里:
for block in response.content:
if block.type == "text":
print(block.text)
elif block.type == "server_tool_use":
print(f"[服务端调用] {block.name}: {block.input}")
elif block.type == "web_search_tool_result":
...
elif block.type == "bash_code_execution_tool_result":
...选最新的版本号:服务端工具的 type 带日期后缀,新模型往往需要新版本。下面每节给的都是 2026-10 时的当前版本。
二、网页搜索与抓取
2.1 声明
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
tools=[
{"type": "web_search_20260209", "name": "web_search", "max_uses": 5},
{"type": "web_fetch_20260209", "name": "web_fetch"},
],
messages=[{"role": "user", "content": "Python 3.14 的自由线程模式现在是什么状态?"}],
)| 工具 | 常用参数 | 结果块 |
|---|---|---|
web_search | max_uses、allowed_domains / blocked_domains、user_location | web_search_tool_result,content 是一组 web_search_result |
web_fetch | max_uses、allowed_domains / blocked_domains、citations、max_content_tokens | web_fetch_tool_result,content 里是一个文档块 |
2.2 动态过滤
_20260209 这两个版本自带动态过滤:Claude 先写代码把搜索结果、网页内容过滤一遍,只把有用的部分放进上下文。网页里大量的导航栏、广告、页脚不再占 token,答案也更准。
- 支持的模型:Opus 5.5 / 5 / 4.8 / 4.7 / 4.6、Sonnet 5.5 / 5 / 4.6
- 更早的模型用基础版:
web_search_20250305、web_fetch_20250910 - 用了
_20260209就不要再单独声明code_execution——动态过滤本身就在后台跑代码,再加一个执行环境会让模型困惑。只有你的应用自己需要算数据、处理文件时才另外声明
2.3 两个要知道的行为
- 网页抓取只抓对话里已经出现过的 URL(用户给的,或者搜索结果里的)。模型不能凭空编一个 URL 去访问,这是防止数据被带出去的安全设计
- 搜索结果自动带出处:回答里引用搜索结果的
text块会带citations,和 27 篇的文档引用是同一套结构,可以直接渲染成脚注
2.4 用域名限制收窄范围
{"type": "web_search_20260209", "name": "web_search",
"allowed_domains": ["docs.python.org", "peps.python.org"]}内部知识库助手、只信任官方文档的场景,用 allowed_domains 比在提示词里写"只看官方文档"可靠。
三、代码执行
3.1 声明和读取结果
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
tools=[{"type": "code_execution_20260521", "name": "code_execution"}],
messages=[{"role": "user", "content": "算一下 1 到 100 万里有多少个素数"}],
)
for block in response.content:
if block.type == "bash_code_execution_tool_result":
r = block.content
if r.type == "bash_code_execution_result":
print(r.stdout if r.return_code == 0 else r.stderr)
else:
print("工具出错:", r.error_code)不需要 schema。声明之后 Claude 自动获得两个子能力:bash_code_execution(跑 shell 命令)和 text_editor_code_execution(建、看、改文件),结果分别是 bash_code_execution_tool_result 和 text_editor_code_execution_tool_result。
版本:code_execution_20260521 是当前版本;code_execution_20260120 是支持 REPL 状态保持和程序化工具调用(第五节)的版本,用于 Opus 4.5+ / Sonnet 4.5+。
3.2 沙箱环境
| 项 | 值 |
|---|---|
| 资源 | 1 CPU、5GiB 内存、5GiB 磁盘 |
| 网络 | 没有,完全隔离 |
| 语言 | Python 3.11 |
| 预装库 | pandas、numpy、scipy、scikit-learn、statsmodels、matplotlib、seaborn、openpyxl、xlsxwriter、pillow、pypdf、pdfplumber、python-docx、python-pptx、sympy 等;运行时可以 pip install |
| 容器保留 | 30 天,可以跨请求复用 |
| 计费 | 和网页搜索 / 抓取一起用时免费;否则每个组织每月 1550 小时免费,之后 $0.05 / 小时 |
3.3 把文件交进去、把结果拿出来
from pathlib import Path
uploaded = client.files.upload(file=Path("sales.csv"))
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
tools=[{"type": "code_execution_20260521", "name": "code_execution"}],
messages=[{"role": "user", "content": [
{"type": "text", "text": "分析销售趋势,画一张按月汇总的折线图"},
{"type": "container_upload", "file_id": uploaded.id}, # 文件放进容器
]}],
)代码生成的文件(图表、Excel、PPT)会在结果块里给出 file_id,用 Files API 下载——这就是 27 篇说的"只能下载代码执行或 skills 生成的文件"。
import os
for block in response.content:
if block.type == "bash_code_execution_tool_result" and block.content.type == "bash_code_execution_result":
for ref in block.content.content or []:
if ref.type == "bash_code_execution_output":
meta = client.files.retrieve_metadata(ref.file_id)
safe_name = os.path.basename(meta.filename) # 防路径穿越
if safe_name and safe_name not in (".", ".."):
client.files.download(ref.file_id).write_to_file(os.path.join("outputs", safe_name))文件名一定要过 basename:文件名是模型生成的,../../.bashrc 这种名字直接拼路径就是路径穿越。
3.4 复用容器
r1 = client.messages.create(..., messages=[{"role": "user", "content": "装上 tabulate,生成 data.json"}])
r2 = client.messages.create(container=r1.container.id, ...) # 同一个容器,文件和装好的包都还在四、Agent Skills
10 篇讲过 Claude Code 里的 skills。同样的机制在 API 里也能用:skill 是一个打包好的指令 + 脚本文件夹,在代码执行容器里按需加载。Anthropic 预置了处理 Office 文档和 PDF 的 skills(pptx、xlsx、docx、pdf),你也可以上传自己的。
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
betas=["code-execution-2025-08-25"],
container={"skills": [{"type": "anthropic", "skill_id": "pptx", "version": "latest"}]},
tools=[{"type": "code_execution_20260521", "name": "code_execution"}],
messages=[{"role": "user", "content": "做一份 3 页的季度复盘 PPT"}],
)三个要点:
container.skills决定容器里有哪些 skill 可用- 必须同时声明代码执行工具——skill 是在容器里跑的
- 生成的文件拿
file_id从 Files API 下载
自定义 skill 用 Skills API 管理,它也已经转正:用 client.skills,不需要 beta 头(旧的 client.beta.skills + skills-2025-10-02 是过时写法)。
什么时候用 skill 而不是写进 system prompt:一份很长的操作规范(公司 PPT 模板的用法、报表格式要求)只有一部分请求会用到。写进 system 每次都占 token;做成 skill,模型只在需要时读取。
五、程序化工具调用
5.1 解决什么问题
普通的工具调用,每次调用都是一个来回:Claude 调用 → 结果进入上下文 → Claude 推理 → 调下一个。要查 50 个订单、比较它们的状态,50 份 JSON 全部进入上下文,大部分其实不需要 Claude 看。
程序化工具调用让 Claude 写一段脚本来编排这些调用。脚本在代码执行容器里跑,调用你的工具时容器暂停,你执行完把结果交回,结果回到脚本里而不是 Claude 的上下文里。最后只有脚本过滤、汇总后的输出进入上下文。官方文档给出的数据是:在 agentic 搜索基准上输入 token 少了 24%,得分还更高。
5.2 写法
tools = [
{"type": "code_execution_20260120", "name": "code_execution"},
{
"name": "get_order",
"description": "按订单号查询订单。返回 JSON:{id, status, amount, updated_at}",
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
"allowed_callers": ["code_execution_20260120"], # 允许从代码里调用
},
]- 工具的
description要写清返回格式:Claude 是在写代码处理返回值,不知道结构就没法写解析逻辑 - 回应一个来自代码的工具调用时,user 消息里只能有
tool_result块,不能夹带文字 - 继续请求时带上响应里的
containerid,让暂停的脚本接着跑
5.3 不能一起用的
strict: true、disable_parallel_tool_use、强制 tool_choice、MCP 工具。
六、工具搜索
工具一多(接了几个 MCP server 很容易就有上百个),光工具定义就能占掉几万 token。工具搜索让 Claude 先搜、再加载:
tools = [
{"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"},
{"name": "get_weather", "description": "...", "input_schema": {...}}, # 常用的,直接加载
{"name": "get_tide_table", "description": "...", "input_schema": {...},
"defer_loading": True}, # 不常用的,延迟加载
# ……另外几十个 defer_loading 的工具
]- 两种搜索方式:
tool_search_tool_regex_20251119(正则)和tool_search_tool_bm25_20251119(BM25 相关度) defer_loading: True的工具在被搜到之前不进入模型上下文- 最常用的几个工具不要延迟,否则每个请求都要先多一轮搜索
- 工具定义总量在 1 万 token 以下时不值得用,搜索那一步本身就是开销
12 篇讲过 Claude Code 的 MCP 工具搜索,原理相同。25 篇提到的"对话中途用 tool_addition 加工具",也要求那个工具一开始就以 defer_loading 声明在 tools 里。
七、MCP Connector
12 篇讲 Claude Code 怎么接 MCP server。如果你在自己的应用里调 API,也可以让 Anthropic 的服务器替你连接远程 MCP server,不用自己写 MCP 客户端:
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
betas=["mcp-client-2025-11-20"],
mcp_servers=[{
"type": "url",
"url": "https://mcp.example.com/mcp",
"name": "crm",
"authorization_token": os.environ["CRM_MCP_TOKEN"],
}],
tools=[{
"type": "mcp_toolset",
"mcp_server_name": "crm",
"default_config": {"enabled": False}, # 默认全部关闭
"configs": {"search_customers": {"enabled": True}}, # 只开需要的
}],
messages=[{"role": "user", "content": "找出上周新签的客户"}],
)mcp_servers和tools里的mcp_toolset必须成对出现,mcp_server_name对应name;只写mcp_servers不写 toolset 会被拒绝- 只支持远程(URL)server,本地 stdio server 连不了——Anthropic 的服务器访问不到你的本机
default_config: {"enabled": False}+configs是白名单模式,只暴露需要的工具,既省 token 又缩小攻击面- 不想把 MCP 交给服务端时,也可以在客户端用 SDK 的 MCP 转换工具把 MCP 工具变成普通工具,交给 Tool Runner 执行
八、Advisor:请一个更强的模型出主意
Advisor 工具把两个模型配成一对:执行者(请求的 model)负责大部分生成,遇到需要规划的地方咨询顾问(工具里的 model)。执行者用便宜快速的模型,关键决策借用强模型的判断。
response = client.beta.messages.create(
model="claude-sonnet-5-5", # 执行者
max_tokens=16000,
betas=["advisor-tool-2026-03-01"],
tools=[{
"type": "advisor_20260301",
"name": "advisor",
"model": "claude-opus-5-5", # 顾问
"max_uses": 3,
"caching": {"type": "ephemeral", "ttl": "5m"},
}],
messages=[...],
)| 规则 | 说明 |
|---|---|
| 顾问至少和执行者一样强 | 配对不合法返回 400。比如 Sonnet 5.5 做执行者时,顾问只能是 Fable 5.1 / Fable 5 / Opus 5.5 / Opus 5 / Sonnet 5.5 等新模型 |
| 新模型的建议是加密的 | Opus 5.5、Sonnet 5.5 等新模型做顾问时,结果是 advisor_redacted_result,只有 encrypted_content,你读不到,只能原样传回 |
按 content 的类型分支 | 结果块总是 advisor_tool_result,要看它的 content 是 advisor_result(明文)、advisor_redacted_result(加密)还是 advisor_tool_result_error |
| 不能强制调用 | 新模型不接受强制 tool_choice,想让它咨询顾问就在提示词里引导 |
| 多轮对话 | 把包括 advisor_tool_result 在内的完整 response.content 传回 |
| 可用性 | Beta,只在 Claude API 和 Claude Platform on AWS 上 |
适合的场景:长任务里大部分是机械执行,偶尔有一两个关键决策点(选方案、定架构)。如果每一步都需要强推理,直接用强模型更简单。
九、Computer Use
21 篇讲过 Claude Code 里的 computer use。在 API 里,computer use 是 Anthropic 定义、客户端执行的工具:你提供桌面环境(虚拟机、容器),截图发给 Claude,执行它要求的点击和键盘操作。
新模型上只能用 computer toolset:
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
tools=[{"type": "computer_toolset_20260801"}], # 没有 name,没有屏幕尺寸,不需要 beta 头
messages=[...],
)和旧的 computer_20251124 相比,agent 循环要改三处:
- 动作是
tool_use块的name(screenshot、left_click、type、zoom等 17 个成员),不再是input.action - 一轮可能有多个调用(批量动作),每个调用回一个
tool_result - 每个
tool_result都要带上"toolset_name": "computer";只有screenshot和zoom需要回图片,其余回OK即可
平台差异:Opus 5.5 在 Claude API 和 Google Cloud 上只接受 toolset,传 computer_20251124 返回 400;Sonnet 5.5 同样如此,但 Amazon Bedrock 上仍接受旧版本。Bedrock、Claude Platform on AWS、Foundry 目前只提供旧的 beta 版本。浏览器场景还有一个对应的 browser_toolset_20260801。
安全:computer use 让模型看到屏幕上的一切、点击任何地方。用专门的虚拟机,不要登录敏感账号,网页内容里可能有针对模型的提示注入。
十、pause_turn 与错误处理
10.1 pause_turn
服务端工具在服务端跑一个采样循环,默认最多 10 次迭代。到了上限,响应的 stop_reason 是 pause_turn,意思是"还没做完,可以接着来":
messages = [{"role": "user", "content": user_query}]
for _ in range(5): # 给续接次数设上限
response = client.messages.create(
model="claude-opus-5-5", max_tokens=16000, tools=tools, messages=messages,
)
if response.stop_reason != "pause_turn":
break
messages = [
{"role": "user", "content": user_query},
{"role": "assistant", "content": response.content}, # 原样传回,服务端从这里继续
]- 不要追加一条"请继续"的 user 消息,把暂停的 assistant 回合原样传回就行
- SDK 的 Tool Runner 不会自动续接
pause_turn:暂停的回合会作为最终消息返回,不报错。Python 里要在外面包一层循环,用保存的历史重新启动 runner
10.2 错误不走 HTTP 状态码
服务端工具出错(搜索超限、代码超时、抓取失败)时,HTTP 状态码仍然是 200,错误以结果块里的错误对象出现,比如 bash_code_execution_tool_result 的 content.type 不是 bash_code_execution_result 而是一个带 error_code 的错误。只检查 HTTP 状态的代码会把这些失败当成功。
十一、平台可用性
| 工具 | Claude API | Bedrock | Vertex AI | 备注 |
|---|---|---|---|---|
| 网页搜索 | ✓ | ✗ | 仅基础版 | Vertex 只有 web_search_20250305,没有动态过滤 |
| 网页抓取 | ✓ | ✗ | ✗ | |
| 代码执行 | ✓ | ✗ | ✗ | |
| Agent Skills | ✓ | ✗ | ✗ | |
| 程序化工具调用 | ✓ | ✗ | ✗ | |
| 工具搜索 | ✓ | ✓ | ✓ | Bedrock 仅 InvokeModel,不支持 Converse |
| MCP connector | beta | ✗ | ✗ | |
| Advisor | beta | ✗ | ✗ | |
| bash / text editor / memory | ✓ | ✓ | ✓ | 客户端执行 |
| Computer use | toolset GA | 旧版 beta | toolset GA |
Claude Platform on AWS 与 Claude API 同步;Microsoft Foundry 上大部分服务端工具只在 "Hosted on Anthropic" 部署里可用。要上第三方云,先查这张表——很多架构是在 Claude API 上原型做完、迁到 Bedrock 时才发现代码执行用不了。
十二、踩坑
- 新模型还用
web_search_20250305——拿不到动态过滤,token 更多、结果更杂 _20260209的搜索又单独声明了code_execution——两个执行环境,模型会困惑- 以为网页抓取能访问任意 URL——只能抓对话里出现过的 URL
- 生成的文件名直接拼路径——路径穿越,先
os.path.basename - 在 Bedrock 上用代码执行、网页抓取、skills——不可用,先查平台表
- 程序化调用的工具 description 没写返回格式——Claude 写不出正确的解析代码
- 回应程序化工具调用时夹带文字——user 消息里只能有
tool_result - 所有工具都
defer_loading——每次请求都要先搜,常用的几个直接加载 - 读 advisor 结果时直接取
.text——新模型的建议是加密的,要按content.type分支 - 用 Tool Runner 跑服务端工具却不处理
pause_turn——任务半途结束且不报错,包一层续接循环
下一篇:29-长对话-Compaction与Context-Editing.md,讲 agent 跑得越久上下文越长时的几种处理:服务端 compaction、context editing 清理旧工具结果、memory 工具跨会话记忆,以及它们和缓存、preserved thinking 的关系。