Loading...
    • 开发者指南
    • API 参考
    • MCP
    • 资源
    • 更新日志
    Search...
    ⌘K
    入门
    Claude 简介快速开始
    模型与定价
    模型概览选择模型Claude 4.6 新特性迁移指南模型弃用定价
    使用 Claude 构建
    功能概览使用 Messages API处理停止原因提示词最佳实践
    上下文管理
    上下文窗口压缩上下文编辑
    能力
    提示缓存扩展思考自适应思考推理力度流式消息批量处理引用多语言支持Token 计数嵌入视觉PDF 支持Files API搜索结果结构化输出
    工具
    概览如何实现工具使用细粒度工具流式传输Bash 工具代码执行工具程序化工具调用计算机使用工具文本编辑器工具网页抓取工具网页搜索工具记忆工具工具搜索工具
    Agent Skills
    概览快速开始最佳实践企业级 Skills通过 API 使用 Skills
    Agent SDK
    概览快速开始TypeScript SDKTypeScript V2(预览版)Python SDK迁移指南
    API 中的 MCP
    MCP 连接器远程 MCP 服务器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示工程
    概览提示词生成器使用提示词模板提示词优化器清晰直接使用示例(多样本提示)让 Claude 思考(思维链)使用 XML 标签赋予 Claude 角色(系统提示词)链式复杂提示长上下文技巧扩展思考技巧
    测试与评估
    定义成功标准开发测试用例使用评估工具降低延迟
    加强安全护栏
    减少幻觉提高输出一致性防范越狱攻击流式拒绝减少提示词泄露保持 Claude 角色设定
    管理与监控
    Admin API 概览数据驻留工作空间用量与成本 APIClaude Code Analytics API零数据留存
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    工具

    Claude 的工具使用

    Claude 能够与工具和函数进行交互,使您可以扩展 Claude 的能力来执行更广泛的任务。

    通过我们全新的课程学习掌握 Claude 工具使用所需的一切知识!请继续使用此表单分享您的想法和建议。

    通过严格工具使用保证模式一致性

    结构化输出为工具输入提供有保证的模式验证。在您的工具定义中添加 strict: true,以确保 Claude 的工具调用始终与您的模式完全匹配——不再有类型不匹配或缺失字段的问题。

    非常适合无效工具参数会导致故障的生产环境代理。了解何时使用严格工具使用 →

    以下是如何使用 Messages API 向 Claude 提供工具的示例:

    curl https://api.anthropic.com/v1/messages \
      -H "content-type: application/json" \
      -H "x-api-key: $ANTHROPIC_API_KEY" \
      -H "anthropic-version: 2023-06-01" \
      -d '{
        "model": "claude-opus-4-6",
        "max_tokens": 1024,
        "tools": [
          {
            "name": "get_weather",
            "description": "Get the current weather in a given location",
            "input_schema": {
              "type": "object",
              "properties": {
                "location": {
                  "type": "string",
                  "description": "The city and state, e.g. San Francisco, CA"
                }
              },
              "required": ["location"]
            }
          }
        ],
        "messages": [
          {
            "role": "user",
            "content": "What is the weather like in San Francisco?"
          }
        ]
      }'

    工具使用的工作原理

    Claude 支持两种类型的工具:

    1. 客户端工具:在您的系统上执行的工具,包括:

      • 您创建和实现的用户自定义工具
      • Anthropic 定义的工具,如计算机使用和文本编辑器,需要客户端实现
    2. 服务端工具:在 Anthropic 服务器上执行的工具,如网页搜索和网页获取工具。这些工具必须在 API 请求中指定,但不需要您进行实现。

    Anthropic 定义的工具使用版本化类型(例如 web_search_20250305、text_editor_20250124)以确保跨模型版本的兼容性。

    客户端工具

    通过以下步骤将客户端工具与 Claude 集成:

    1. 1

      向 Claude 提供工具和用户提示

      • 在 API 请求中定义客户端工具,包括名称、描述和输入模式。
      • 包含可能需要这些工具的用户提示,例如"旧金山的天气怎么样?"
    2. 2

      Claude 决定使用工具

      • Claude 评估是否有工具可以帮助处理用户的查询。
      • 如果有,Claude 会构建一个格式正确的工具使用请求。
      • 对于客户端工具,API 响应的 stop_reason 为 tool_use,表示 Claude 的意图。
    3. 3

      执行工具并返回结果

      • 从 Claude 的请求中提取工具名称和输入
      • 在您的系统上执行工具代码
      • 在包含 tool_result 内容块的新 user 消息中返回结果
    4. 4

      Claude 使用工具结果生成响应

      • Claude 分析工具结果,为原始用户提示生成最终响应。

    注意:步骤 3 和 4 是可选的。对于某些工作流程,Claude 的工具使用请求(步骤 2)可能就是您所需要的全部,无需将结果发送回 Claude。

    服务端工具

    服务端工具遵循不同的工作流程:

    1. 1

      向 Claude 提供工具和用户提示

      • 服务端工具,如网页搜索和网页获取,有各自的参数。
      • 包含可能需要这些工具的用户提示,例如"搜索关于 AI 的最新新闻"或"分析此 URL 的内容。"
    2. 2

      Claude 执行服务端工具

      • Claude 评估服务端工具是否可以帮助处理用户的查询。
      • 如果可以,Claude 执行该工具,结果会自动整合到 Claude 的响应中。
    3. 3

      Claude 使用服务端工具结果生成响应

      • Claude 分析服务端工具结果,为原始用户提示生成最终响应。
      • 服务端工具执行不需要额外的用户交互。

    在 Claude 中使用 MCP 工具

    如果您正在构建使用模型上下文协议 (MCP) 的应用程序,您可以直接在 Claude 的 Messages API 中使用来自 MCP 服务器的工具。MCP 工具定义使用与 Claude 工具格式类似的模式格式。您只需要将 inputSchema 重命名为 input_schema。

    不想自己构建 MCP 客户端? 使用 MCP 连接器直接从 Messages API 连接到远程 MCP 服务器,无需实现客户端。

    将 MCP 工具转换为 Claude 格式

    当您构建 MCP 客户端并在 MCP 服务器上调用 list_tools() 时,您将收到带有 inputSchema 字段的工具定义。要在 Claude 中使用这些工具,请将它们转换为 Claude 的格式:

    from mcp import ClientSession
    
    async def get_claude_tools(mcp_session: ClientSession):
        """Convert MCP tools to Claude's tool format."""
        mcp_tools = await mcp_session.list_tools()
    
        claude_tools = []
        for tool in mcp_tools.tools:
            claude_tools.append({
                "name": tool.name,
                "description": tool.description or "",
                "input_schema": tool.inputSchema  # Rename inputSchema to input_schema
            })
    
        return claude_tools

    然后将这些转换后的工具传递给 Claude:

    import anthropic
    
    client = anthropic.Anthropic()
    claude_tools = await get_claude_tools(mcp_session)
    
    response = client.messages.create(
        model="claude-opus-4-6",
        max_tokens=1024,
        tools=claude_tools,
        messages=[{"role": "user", "content": "What tools do you have available?"}]
    )

    当 Claude 响应 tool_use 块时,使用 call_tool() 在您的 MCP 服务器上执行该工具,并在 tool_result 块中将结果返回给 Claude。

    有关构建 MCP 客户端的完整指南,请参阅构建 MCP 客户端。


    工具使用示例

    以下是一些演示各种工具使用模式和技术的代码示例。为简洁起见,这些工具都是简单工具,工具描述也比确保最佳性能所需的理想长度要短。


    定价

    Tool use requests are priced based on:

    1. The total number of input tokens sent to the model (including in the tools parameter)
    2. The number of output tokens generated
    3. For server-side tools, additional usage-based pricing (e.g., web search charges per search performed)

    Client-side tools are priced the same as any other Claude API request, while server-side tools may incur additional charges based on their specific usage.

    The additional tokens from tool use come from:

    • The tools parameter in API requests (tool names, descriptions, and schemas)
    • tool_use content blocks in API requests and responses
    • tool_result content blocks in API requests

    When you use tools, we also automatically include a special system prompt for the model which enables tool use. The number of tool use tokens required for each model are listed below (excluding the additional tokens listed above). Note that the table assumes at least 1 tool is provided. If no tools are provided, then a tool choice of none uses 0 additional system prompt tokens.

    ModelTool choiceTool use system prompt token count
    Claude Opus 4.6auto, none
    any, tool
    346 tokens
    313 tokens
    Claude Opus 4.5auto, none
    any, tool
    346 tokens
    313 tokens
    Claude Opus 4.1auto, none
    any, tool
    346 tokens
    313 tokens
    Claude Opus 4auto, none
    any, tool
    346 tokens
    313 tokens
    Claude Sonnet 4.5auto, none
    any, tool
    346 tokens
    313 tokens
    Claude Sonnet 4auto, none
    any, tool
    346 tokens
    313 tokens
    Claude Sonnet 3.7 (deprecated)auto, none
    any, tool
    346 tokens
    313 tokens
    Claude Haiku 4.5auto, none
    any, tool
    346 tokens
    313 tokens
    Claude Haiku 3.5auto, none
    any, tool
    264 tokens
    340 tokens
    Claude Opus 3 (deprecated)auto, none
    any, tool
    530 tokens
    281 tokens
    Claude Sonnet 3auto, none
    any, tool
    159 tokens
    235 tokens
    Claude Haiku 3auto, none
    any, tool
    264 tokens
    340 tokens

    These token counts are added to your normal input and output tokens to calculate the total cost of a request.

    请参阅我们的模型概览表了解当前各模型的价格。

    当您发送工具使用提示时,与任何其他 API 请求一样,响应将在报告的 usage 指标中输出输入和输出的 token 计数。


    后续步骤

    在我们的 cookbook 中探索可直接实现的工具使用代码示例:

    计算器工具

    了解如何将简单的计算器工具与 Claude 集成,以实现精确的数值计算。

    客户服务代理

    构建一个响应式客户服务机器人,利用客户端工具来增强支持服务。

    JSON 提取器

    了解 Claude 和工具使用如何从非结构化文本中提取结构化数据。

    Was this page helpful?

    • 在 Claude 中使用 MCP 工具
    • 将 MCP 工具转换为 Claude 格式