你可以构建自己的自定义工具,但有些功能足够常见,Anthropic 将它们预构建好。你不需要编写代码。你不需要托管沙箱。你只需声明工具,Anthropic 就会运行它。
Anthropic 提供在它们基础设施上运行的 服务器工具。你不执行这些——Anthropic 执行。这意味着你不需要为这些调用运行 agent 循环。Claude 自己调用工具,结果在同一个响应中返回。
主要的有:
让我们在一个文件中看看一些主要的:两个 messages.create 调用,一个使用网页搜索,一个使用代码执行。
import anthropic
client = anthropic.Anthropic()
# 调用 1:网页搜索——Anthropic 在服务器端运行搜索
search_response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
tools=[{"type": "web_search_20260209", "name": "web_search"}],
messages=[
{"role": "user", "content": "What is Anthropic's latest model release? Answer in one sentence."}
],
)
for block in search_response.content:
if block.type == "server_tool_use":
print(f"Tool call: {block.name} — {block.input}")
elif block.type == "text":
print(block.text)
# 调用 2:代码执行——Claude 在沙箱中编写和运行 Python
code_response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
tools=[{"type": "code_execution_20260120", "name": "code_execution"}],
messages=[
{"role": "user", "content": "Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"}
],
)
for block in code_response.content:
if block.type == "server_tool_use":
print(f"Tool call: {block.name} — {block.input}")
elif block.type == "bash_code_execution_tool_result":
print(f"stdout: {block.content.stdout}")
elif block.type == "text":
print(block.text)
要注意两件事:
stop_reason 上 switch。我们没有将工具结果推回。Anthropic 在服务器端运行工具,响应已经包含结果。server_tool_use 块,用于输出的代码执行工具结果块,加上常规的 text 块。对于网页搜索,你会看到 Claude 的工具调用被打印,然后是一句关于最新模型发布的答案,搜索引用已包含在内。
对于代码执行,你会看到 Claude 编写的实际 Python、沙箱运行它的 stdout,以及最终的文本答案。
我们不需要启动搜索爬虫。我们没有运行 Python 沙箱。我们声明了两个工具并免费获得了两个。
登录 参与讨论
值得知道另一个类别的存在。客户端工具 在你的代码运行的地方运行。Anthropic 发布它们的模式并在其上训练 Claude,因此你不必自己定义模式。两个例子:
它们具有与自定义工具相同的形状,但 SDK 为你提供模式和合理的运行器。
在生产应用中,这是通往否则需要数周才能实现的功能的最短路径。网页搜索可以驱动一个事实检查端点,根据实时网络验证草稿中的每个数字和监管声明。
一个提醒:仅仅因为某些东西在网上被验证并不意味着它是真的。始终仔细检查 Claude 的工作。
tools 数组中声明。Anthropic 运行它们。server_tool_use 和工具结果块。