[ PROMPT_NODE_23840 ]
tool-use
[ SKILL_DOCUMENTATION ]
# Tool Use — Python
有关概念概述(工具定义、工具选择、提示),请参阅 [shared/tool-use-concepts.md](../../shared/tool-use-concepts.md)。
## 工具运行器 (推荐)
**Beta:** 工具运行器在 Python SDK 中处于 Beta 阶段。
使用 `@beta_tool` 装饰器将工具定义为类型化函数,然后将其传递给 `client.beta.messages.tool_runner()`:
python
import anthropic
from anthropic import beta_tool
client = anthropic.Anthropic()
@beta_tool
def get_weather(location: str, unit: str = "celsius") -> str:
"""获取指定地点的当前天气。
Args:
location: 城市和州,例如 San Francisco, CA。
unit: 温度单位,"celsius" 或 "fahrenheit"。
"""
# 在此实现逻辑
return f"72°F and sunny in {location}"
# 工具运行器自动处理智能体循环
runner = client.beta.messages.tool_runner(
model="claude-opus-4-7",
max_tokens=16000,
tools=[get_weather],
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
)
# 每次迭代产生一个 BetaMessage;当 Claude 完成时迭代停止
for message in runner:
print(message)
对于异步使用,请将 `@beta_async_tool` 与 `async def` 函数配合使用。
**工具运行器的主要优势:**
- 无需手动循环 — SDK 自动处理调用工具并将结果反馈回模型
- 通过装饰器实现类型安全的工具输入
- 工具 Schema 从函数签名自动生成
- 当 Claude 没有更多工具调用时,迭代自动停止
---
## MCP 工具转换助手
**Beta。** 将 [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) 工具、提示词和资源转换为 Anthropic API 类型,以便与工具运行器一起使用。需要 `pip install anthropic[mcp]` (Python 3.10+)。
> **注意:** Claude API 还支持 `mcp_servers` 参数,允许 Claude 直接连接到远程 MCP 服务器。当您需要本地 MCP 服务器、提示词、资源或对 MCP 连接有更多控制权时,请使用这些助手。
### 结合工具运行器的 MCP 工具
python
from anthropic import AsyncAnthropic
from anthropic.lib.tools.mcp import async_mcp_tool
from mcp import ClientSession
from mcp.client.stdio import stdio_client, StdioServerParameters
client = AsyncAnthropic()
async with stdio_client(StdioServerParameters(command="mcp-server")) as (read, write):
async with ClientSession(read, write) as mcp_client:
await mcp_client.initialize()
tools_result = await mcp_c