SPB Git

Repository Public

overview.md 37.3 KB 906 lines markdown

1---2title: Tool use with Claude3url: https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview4description: Connect Claude to external tools and APIs. See where tools execute, when Claude calls them, and which tool fits your task.5---67Tool use (also called function calling) lets Claude call functions that you define or that Anthropic provides. Claude determines when to call a tool based on the user's request and the tool's description. It then returns a structured call that your application executes (client tools) or that Anthropic executes (server tools).89Here's a minimal example using a server tool, the [Web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool), which Anthropic executes for you:1011<CodeGroup>12  ```bash cURL13  curl https://api.anthropic.com/v1/messages \14    -H "x-api-key: $ANTHROPIC_API_KEY" \15    -H "anthropic-version: 2023-06-01" \16    -H "content-type: application/json" \17    -d '{18      "model": "claude-opus-5",19      "max_tokens": 1024,20      "tools": [{"type": "web_search_20260209", "name": "web_search"}],21      "messages": [{"role": "user", "content": "What'\''s the latest on the Mars rover?"}]22    }'23  ```2425  ```bash CLI26  ant messages create --transform content --format yaml \27    --model claude-opus-5 \28    --max-tokens 1024 \29    --tool '{type: web_search_20260209, name: web_search}' \30    --message '{role: user, content: "What is the latest on the Mars rover?"}'31  ```3233  ```python Python34  client = anthropic.Anthropic()35  response = client.messages.create(36      model="claude-opus-5",37      max_tokens=1024,38      tools=[{"type": "web_search_20260209", "name": "web_search"}],39      messages=[{"role": "user", "content": "What's the latest on the Mars rover?"}],40  )41  print(response.content)42  ```4344  ```typescript TypeScript45  const client = new Anthropic();46  const response = await client.messages.create({47    model: "claude-opus-5",48    max_tokens: 1024,49    tools: [{ type: "web_search_20260209", name: "web_search" }],50    messages: [{ role: "user", content: "What's the latest on the Mars rover?" }]51  });52  console.log(response.content);53  ```5455  ```csharp C#56  AnthropicClient client = new();5758  var parameters = new MessageCreateParams59  {60      Model = Model.ClaudeOpus5,61      MaxTokens = 1024,62      Tools = [new ToolUnion(new WebSearchTool20260209())],63      Messages = [new() { Role = Role.User, Content = "What's the latest on the Mars rover?" }]64  };6566  var message = await client.Messages.Create(parameters);67  Console.WriteLine(message.Content);68  ```6970  ```go Go71  client := anthropic.NewClient()7273  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{74  	Model:     anthropic.ModelClaudeOpus5,75  	MaxTokens: 1024,76  	Tools: []anthropic.ToolUnionParam{77  		{OfWebSearchTool20260209: &anthropic.WebSearchTool20260209Param{}},78  	},79  	Messages: []anthropic.MessageParam{80  		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the latest on the Mars rover?")),81  	},82  })83  if err != nil {84  	log.Fatal(err)85  }86  fmt.Println(response.Content)87  ```8889  ```java Java90  import com.anthropic.models.messages.WebSearchTool20260209;9192  void main() {93      AnthropicClient client = AnthropicOkHttpClient.fromEnv();9495      MessageCreateParams params = MessageCreateParams.builder()96          .model(Model.CLAUDE_OPUS_5)97          .maxTokens(1024L)98          .addTool(WebSearchTool20260209.builder().build())99          .addUserMessage("What's the latest on the Mars rover?")100          .build();101102      Message response = client.messages().create(params);103      IO.println(response.content());104  }105  ```106107  ```php PHP108  $client = new Client();109110  $message = $client->messages->create(111      model: 'claude-opus-5',112      maxTokens: 1024,113      tools: [114          ['type' => 'web_search_20260209', 'name' => 'web_search'],115      ],116      messages: [117          ['role' => 'user', 'content' => "What's the latest on the Mars rover?"],118      ],119  );120121  echo $message;122  ```123124  ```ruby Ruby125  client = Anthropic::Client.new126127  message = client.messages.create(128    model: "claude-opus-5",129    max_tokens: 1024,130    tools: [{ type: "web_search_20260209", name: "web_search" }],131    messages: [{ role: "user", content: "What's the latest on the Mars rover?" }]132  )133  puts message.content134  ```135</CodeGroup>136137Claude runs the search on Anthropic's infrastructure and returns the cited results in the same response. To have Claude call a function that you define, pass a tool with an `input_schema`, then execute the call when Claude returns a `tool_use` block. [How tool use works](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview#how-tool-use-works) shows that round trip end to end. Learn more about [defining tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools) and [handling tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls).138139## How tool use works140141Tools differ primarily by where the code executes. **Client tools** (including user-defined tools and tools with Anthropic-defined schemas, such as `bash` and `text_editor`) run in your application. Claude responds with `stop_reason: "tool_use"` and one or more `tool_use` blocks. Your code executes the operation and sends back a `tool_result`. **Server tools** (such as `web_search`, `web_fetch`, `code_execution`, and `tool_search`) run on Anthropic's infrastructure: you see the results directly without handling execution, unless Claude calls the tool in the same group of parallel tool calls as one of your client tools (see [Stop reasons and fallback](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#tool-use)).142143Here's that round trip in full for a client tool. The first request defines a `get_weather` tool, and Claude answers the question by calling it: the response carries a `tool_use` block, your code runs the lookup, and a second request sends the result back in a `tool_result` block so Claude can reply with the answer.144145<CodeGroup>146  ```bash cURL147  # Claude replies with a tool_use block naming the tool and its arguments.148  TOOLS='[149    {150      "name": "get_weather",151      "description": "Get the current weather for a given location.",152      "input_schema": {153        "type": "object",154        "properties": {155          "location": {"type": "string", "description": "City and state, e.g. San Francisco, CA"}156        },157        "required": ["location"]158      }159    }160  ]'161  USER_MSG="What's the weather in San Francisco?"162  RESPONSE=$(curl -s https://api.anthropic.com/v1/messages \163    -H "x-api-key: $ANTHROPIC_API_KEY" \164    -H "anthropic-version: 2023-06-01" \165    -H "content-type: application/json" \166    -d "$(jq -n --argjson tools "$TOOLS" --arg msg "$USER_MSG" '{167      model: "claude-opus-5",168      max_tokens: 1024,169      tools: $tools,170      # Ask for at most one tool call per turn.171      tool_choice: {type: "auto", disable_parallel_tool_use: true},172      messages: [{role: "user", content: $msg}]173    }')")174  TOOL_USE=$(echo "$RESPONSE" | jq '.content[] | select(.type == "tool_use")')175  echo "Claude called $(echo "$TOOL_USE" | jq -r '.name') with $(echo "$TOOL_USE" | jq -c '.input')"176177  # Run the tool, then send the result back in a tool_result block.178  # Claude uses the result to answer the original question.179  WEATHER="15 degrees Celsius, partly cloudy"180  curl -s https://api.anthropic.com/v1/messages \181    -H "x-api-key: $ANTHROPIC_API_KEY" \182    -H "anthropic-version: 2023-06-01" \183    -H "content-type: application/json" \184    -d "$(jq -n \185      --argjson tools "$TOOLS" \186      --arg msg "$USER_MSG" \187      --argjson assistant "$(echo "$RESPONSE" | jq '.content')" \188      --arg tool_use_id "$(echo "$TOOL_USE" | jq -r '.id')" \189      --arg weather "$WEATHER" \190      '{191        model: "claude-opus-5",192        max_tokens: 1024,193        tools: $tools,194        tool_choice: {type: "auto", disable_parallel_tool_use: true},195        messages: [196          {role: "user", content: $msg},197          {role: "assistant", content: $assistant},198          {role: "user", content: [199            {type: "tool_result", tool_use_id: $tool_use_id, content: $weather}200          ]}201        ]202      }')"203  ```204205  ```bash CLI206  # ant reads the request body as YAML on stdin; jq carries the conversation207  # state into the second request.208  USER_MSG="What's the weather in San Francisco?"209  MESSAGES=$(jq -n --arg msg "$USER_MSG" '[{role: "user", content: $msg}]')210  call_api() {211    {212      cat <<'YAML'213  model: claude-opus-5214  max_tokens: 1024215  # Ask for at most one tool call per turn.216  tool_choice: {type: auto, disable_parallel_tool_use: true}217  tools:218    - name: get_weather219      description: Get the current weather for a given location.220      input_schema:221        type: object222        properties:223          location: {type: string, description: "City and state, e.g. San Francisco, CA"}224        required: [location]225  YAML226      printf 'messages: %s\n' "$MESSAGES"227    } | ant messages create --format json228  }229230  # Claude replies with a tool_use block naming the tool and its arguments.231  RESPONSE=$(call_api)232  TOOL_USE=$(jq '.content[] | select(.type == "tool_use")' <<<"$RESPONSE")233  echo "Claude called $(jq -r '.name' <<<"$TOOL_USE") with $(jq -c '.input' <<<"$TOOL_USE")"234235  # Run the tool, then send the result back in a tool_result block.236  WEATHER="15 degrees Celsius, partly cloudy"237  MESSAGES=$(jq \238    --argjson assistant "$(jq '.content' <<<"$RESPONSE")" \239    --arg tool_use_id "$(jq -r '.id' <<<"$TOOL_USE")" \240    --arg weather "$WEATHER" \241    '. + [242      {role: "assistant", content: $assistant},243      {role: "user", content: [244        {type: "tool_result", tool_use_id: $tool_use_id, content: $weather}245      ]}246    ]' <<<"$MESSAGES")247248  # Claude uses the result to answer the original question.249  call_api250  ```251252  ```python Python253  client = anthropic.Anthropic()254255  tools = [256      {257          "name": "get_weather",258          "description": "Get the current weather for a given location.",259          "input_schema": {260              "type": "object",261              "properties": {262                  "location": {263                      "type": "string",264                      "description": "City and state, e.g. San Francisco, CA",265                  }266              },267              "required": ["location"],268          },269      }270  ]271  messages = [{"role": "user", "content": "What's the weather in San Francisco?"}]272273  # Claude replies with a tool_use block naming the tool and its arguments.274  response = client.messages.create(275      model="claude-opus-5",276      max_tokens=1024,277      tools=tools,278      # Ask for at most one tool call per turn.279      tool_choice={"type": "auto", "disable_parallel_tool_use": True},280      messages=messages,281  )282  tool_use = next(block for block in response.content if block.type == "tool_use")283  print(f"Claude called {tool_use.name} with {json.dumps(tool_use.input)}")284285  # Run the tool, then send the result back in a tool_result block.286  weather = "15 degrees Celsius, partly cloudy"  # your weather lookup goes here287  messages += [288      {"role": "assistant", "content": response.content},289      {290          "role": "user",291          "content": [292              {"type": "tool_result", "tool_use_id": tool_use.id, "content": weather}293          ],294      },295  ]296  followup = client.messages.create(297      model="claude-opus-5",298      max_tokens=1024,299      tools=tools,300      tool_choice={"type": "auto", "disable_parallel_tool_use": True},301      messages=messages,302  )303304  # Claude uses the result to answer the original question.305  final_text = next(block for block in followup.content if block.type == "text")306  print(final_text.text)307  ```308309  ```typescript TypeScript310  const client = new Anthropic();311312  const tools: Anthropic.Tool[] = [313    {314      name: "get_weather",315      description: "Get the current weather for a given location.",316      input_schema: {317        type: "object",318        properties: {319          location: { type: "string", description: "City and state, e.g. San Francisco, CA" }320        },321        required: ["location"]322      }323    }324  ];325  const messages: Anthropic.MessageParam[] = [326    { role: "user", content: "What's the weather in San Francisco?" }327  ];328329  // Claude replies with a tool_use block naming the tool and its arguments.330  const response = await client.messages.create({331    model: "claude-opus-5",332    max_tokens: 1024,333    tools,334    // Ask for at most one tool call per turn.335    tool_choice: { type: "auto", disable_parallel_tool_use: true },336    messages337  });338  const toolUse = response.content.find(339    (block): block is Anthropic.ToolUseBlock => block.type === "tool_use"340  )!;341  console.log(`Claude called ${toolUse.name} with ${JSON.stringify(toolUse.input)}`);342343  // Run the tool, then send the result back in a tool_result block.344  const weather = "15 degrees Celsius, partly cloudy"; // your weather lookup goes here345  messages.push(346    { role: "assistant", content: response.content },347    {348      role: "user",349      content: [{ type: "tool_result", tool_use_id: toolUse.id, content: weather }]350    }351  );352  const followup = await client.messages.create({353    model: "claude-opus-5",354    max_tokens: 1024,355    tools,356    tool_choice: { type: "auto", disable_parallel_tool_use: true },357    messages358  });359360  // Claude uses the result to answer the original question.361  const finalText = followup.content.find(362    (block): block is Anthropic.TextBlock => block.type === "text"363  )!;364  console.log(finalText.text);365  ```366367  ```csharp C#368  AnthropicClient client = new();369370  List<ToolUnion> tools =371  [372      new ToolUnion(new Tool()373      {374          Name = "get_weather",375          Description = "Get the current weather for a given location.",376          InputSchema = new InputSchema()377          {378              Properties = new Dictionary<string, JsonElement>379              {380                  ["location"] = JsonSerializer.SerializeToElement(new381                  {382                      type = "string",383                      description = "City and state, e.g. San Francisco, CA",384                  }),385              },386              Required = ["location"],387          },388      }),389  ];390391  // Ask for at most one tool call per turn.392  var toolChoice = new ToolChoice(new ToolChoiceAuto { DisableParallelToolUse = true });393394  const string userPrompt = "What's the weather in San Francisco?";395396  // Claude replies with a tool_use block naming the tool and its arguments.397  var response = await client.Messages.Create(new MessageCreateParams398  {399      Model = Model.ClaudeOpus5,400      MaxTokens = 1024,401      Tools = tools,402      ToolChoice = toolChoice,403      Messages = [new() { Role = Role.User, Content = userPrompt }],404  });405  ToolUseBlock? toolUse = null;406  foreach (var block in response.Content)407  {408      if (block.TryPickToolUse(out var picked))409      {410          toolUse = picked;411          break;412      }413  }414  Console.WriteLine($"Claude called {toolUse!.Name} with {JsonSerializer.Serialize(toolUse.Input)}");415416  // Run the tool, then send the result back in a tool_result block.417  var weather = "15 degrees Celsius, partly cloudy";418  List<ContentBlockParam> toolResults =419  [420      new ContentBlockParam(new ToolResultBlockParam()421      {422          ToolUseID = toolUse.ID,423          Content = weather,424      }),425  ];426  var followup = await client.Messages.Create(new MessageCreateParams427  {428      Model = Model.ClaudeOpus5,429      MaxTokens = 1024,430      Tools = tools,431      ToolChoice = toolChoice,432      Messages =433      [434          new() { Role = Role.User, Content = userPrompt },435          new() { Role = Role.Assistant, Content = response.Content.Select(block => new ContentBlockParam(block.Json)).ToList() },436          new() { Role = Role.User, Content = new MessageParamContent(toolResults) },437      ],438  });439440  // Claude uses the result to answer the original question.441  foreach (var block in followup.Content)442  {443      if (block.TryPickText(out var text))444      {445          Console.WriteLine(text.Text);446      }447  }448  ```449450  ```go Go451  client := anthropic.NewClient()452  ctx := context.Background()453454  tools := []anthropic.ToolUnionParam{455  	{OfTool: &anthropic.ToolParam{456  		Name:        "get_weather",457  		Description: anthropic.String("Get the current weather for a given location."),458  		InputSchema: anthropic.ToolInputSchemaParam{459  			Properties: map[string]any{460  				"location": map[string]any{461  					"type":        "string",462  					"description": "City and state, e.g. San Francisco, CA",463  				},464  			},465  			Required: []string{"location"},466  		},467  	}},468  }469  // Ask for at most one tool call per turn.470  toolChoice := anthropic.ToolChoiceUnionParam{471  	OfAuto: &anthropic.ToolChoiceAutoParam{DisableParallelToolUse: anthropic.Bool(true)},472  }473  messages := []anthropic.MessageParam{474  	anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather in San Francisco?")),475  }476477  // Claude replies with a tool_use block naming the tool and its arguments.478  response, err := client.Messages.New(ctx, anthropic.MessageNewParams{479  	Model:      anthropic.ModelClaudeOpus5,480  	MaxTokens:  1024,481  	Tools:      tools,482  	ToolChoice: toolChoice,483  	Messages:   messages,484  })485  if err != nil {486  	log.Fatal(err)487  }488  var toolUse anthropic.ContentBlockUnion489  for _, block := range response.Content {490  	if block.Type == "tool_use" {491  		toolUse = block492  		break493  	}494  }495  fmt.Printf("Claude called %s with %s\n", toolUse.Name, string(toolUse.Input))496497  // Run the tool, then send the result back in a tool_result block.498  weather := "15 degrees Celsius, partly cloudy"499  var assistantContent []anthropic.ContentBlockParamUnion500  for _, block := range response.Content {501  	assistantContent = append(assistantContent, block.ToParam())502  }503  messages = append(messages,504  	anthropic.NewAssistantMessage(assistantContent...),505  	anthropic.NewUserMessage(anthropic.NewToolResultBlock(toolUse.ID, weather, false)),506  )507  followup, err := client.Messages.New(ctx, anthropic.MessageNewParams{508  	Model:      anthropic.ModelClaudeOpus5,509  	MaxTokens:  1024,510  	Tools:      tools,511  	ToolChoice: toolChoice,512  	Messages:   messages,513  })514  if err != nil {515  	log.Fatal(err)516  }517518  // Claude uses the result to answer the original question.519  for _, block := range followup.Content {520  	if block.Type == "text" {521  		fmt.Println(block.Text)522  	}523  }524  ```525526  ```java Java527  import com.anthropic.core.JsonValue;528  import com.anthropic.models.messages.ContentBlockParam;529  // ...530  import com.anthropic.models.messages.Tool;531  import com.anthropic.models.messages.Tool.InputSchema;532  import com.anthropic.models.messages.ToolChoiceAuto;533  import com.anthropic.models.messages.ToolResultBlockParam;534  import com.anthropic.models.messages.ToolUseBlock;535  // ...536537  void main() {538      AnthropicClient client = AnthropicOkHttpClient.fromEnv();539540      Tool weatherTool = Tool.builder()541          .name("get_weather")542          .description("Get the current weather for a given location.")543          .inputSchema(InputSchema.builder()544              .properties(JsonValue.from(Map.of(545                  "location", Map.of(546                      "type", "string",547                      "description", "City and state, e.g. San Francisco, CA"548                  )549              )))550              .required(List.of("location"))551              .build())552          .build();553554      // Ask for at most one tool call per turn.555      ToolChoiceAuto toolChoice = ToolChoiceAuto.builder()556          .disableParallelToolUse(true)557          .build();558559      String userPrompt = "What's the weather in San Francisco?";560561      // Claude replies with a tool_use block naming the tool and its arguments.562      Message response = client.messages().create(MessageCreateParams.builder()563          .model(Model.CLAUDE_OPUS_5)564          .maxTokens(1024L)565          .addTool(weatherTool)566          .toolChoice(toolChoice)567          .addUserMessage(userPrompt)568          .build());569      ToolUseBlock toolUse = response.content().stream()570          .flatMap(block -> block.toolUse().stream())571          .findFirst()572          .orElseThrow();573      IO.println("Claude called " + toolUse.name() + " with " + toolUse._input());574575      // Run the tool, then send the result back in a tool_result block.576      String weather = "15 degrees Celsius, partly cloudy";577      Message followup = client.messages().create(MessageCreateParams.builder()578          .model(Model.CLAUDE_OPUS_5)579          .maxTokens(1024L)580          .addTool(weatherTool)581          .toolChoice(toolChoice)582          .addUserMessage(userPrompt)583          .addMessage(response)584          .addUserMessageOfBlockParams(List.of(ContentBlockParam.ofToolResult(585              ToolResultBlockParam.builder()586                  .toolUseId(toolUse.id())587                  .content(weather)588                  .build())))589          .build());590591      // Claude uses the result to answer the original question.592      followup.content().stream()593          .flatMap(block -> block.text().stream())594          .forEach(textBlock -> IO.println(textBlock.text()));595  }596  ```597598  ```php PHP599  use Anthropic\Messages\ToolChoiceAuto;600601  $client = new Client();602603  $tools = [604      [605          'name' => 'get_weather',606          'description' => 'Get the current weather for a given location.',607          'input_schema' => [608              'type' => 'object',609              'properties' => [610                  'location' => [611                      'type' => 'string',612                      'description' => 'City and state, e.g. San Francisco, CA',613                  ],614              ],615              'required' => ['location'],616          ],617      ],618  ];619  $userMessage = ['role' => 'user', 'content' => "What's the weather in San Francisco?"];620621  // Ask for at most one tool call per turn.622  $toolChoice = ToolChoiceAuto::with(disableParallelToolUse: true);623624  // Claude replies with a tool_use block naming the tool and its arguments.625  $response = $client->messages->create(626      model: 'claude-opus-5',627      maxTokens: 1024,628      tools: $tools,629      toolChoice: $toolChoice,630      messages: [$userMessage],631  );632  $toolUse = null;633  foreach ($response->content as $block) {634      if ($block->type === 'tool_use') {635          $toolUse = $block;636          break;637      }638  }639  printf("Claude called %s with %s\n", $toolUse->name, json_encode($toolUse->input));640641  // Run the tool, then send the result back in a tool_result block.642  $weather = '15 degrees Celsius, partly cloudy';643  $followup = $client->messages->create(644      model: 'claude-opus-5',645      maxTokens: 1024,646      tools: $tools,647      toolChoice: $toolChoice,648      messages: [649          $userMessage,650          ['role' => 'assistant', 'content' => $response->content],651          [652              'role' => 'user',653              'content' => [654                  [655                      'type' => 'tool_result',656                      'tool_use_id' => $toolUse->id,657                      'content' => $weather,658                  ],659              ],660          ],661      ],662  );663664  // Claude uses the result to answer the original question.665  foreach ($followup->content as $block) {666      if ($block->type === 'text') {667          echo $block->text, "\n";668      }669  }670  ```671672  ```ruby Ruby673  client = Anthropic::Client.new674675  tools = [676    {677      name: "get_weather",678      description: "Get the current weather for a given location.",679      input_schema: {680        type: "object",681        properties: {682          location: {type: "string", description: "City and state, e.g. San Francisco, CA"}683        },684        required: ["location"]685      }686    }687  ]688  messages = [{role: "user", content: "What's the weather in San Francisco?"}]689690  # Claude replies with a tool_use block naming the tool and its arguments.691  response = client.messages.create(692    model: "claude-opus-5",693    max_tokens: 1024,694    tools: tools,695    # Ask for at most one tool call per turn.696    tool_choice: {type: "auto", disable_parallel_tool_use: true},697    messages: messages698  )699  tool_use = response.content.find { |block| block.type == :tool_use }700  puts "Claude called #{tool_use.name} with #{JSON.generate(tool_use.input)}"701702  # Run the tool, then send the result back in a tool_result block.703  weather = "15 degrees Celsius, partly cloudy"704  messages += [705    {role: "assistant", content: response.content},706    {707      role: "user",708      content: [709        {type: "tool_result", tool_use_id: tool_use.id, content: weather}710      ]711    }712  ]713  followup = client.messages.create(714    model: "claude-opus-5",715    max_tokens: 1024,716    tools: tools,717    tool_choice: {type: "auto", disable_parallel_tool_use: true},718    messages: messages719  )720721  # Claude uses the result to answer the original question.722  final_text = followup.content.find { |block| block.type == :text }723  puts final_text.text724  ```725</CodeGroup>726727```text Output wrap728Claude called get_weather with {"location": "San Francisco, CA"}729The current weather in San Francisco is 15 degrees Celsius with partly cloudy skies.730```731732[Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) covers each step in detail, including result formatting and error signaling; [Parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use) covers responses that call several tools at once. To skip writing this round trip yourself, use [Tool Runner](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner): the SDKs execute your tools and send the results back automatically.733734For the full conceptual model including the agentic loop and when to choose each approach, see [How tool use works](https://platform.claude.com/docs/en/agents-and-tools/tool-use/how-tool-use-works).735736To connect to Model Context Protocol (MCP) servers, see the [MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector). To build your own MCP client, see the Model Context Protocol guide to [building an MCP client](https://modelcontextprotocol.io/docs/develop/build-client).737738## When Claude uses tools739740With the default `tool_choice` of `{"type": "auto"}`, Claude determines on each turn whether to call a tool or respond directly. It calls a tool when the request maps to that tool's described capability and the answer isn't already in context. It responds directly for stable knowledge, creative tasks, and conversational turns.741742This boundary is steerable through your system prompt. If Claude isn't calling tools when you expect, a light instruction such as `"Use the tools to investigate before responding."` increases tool use. A stronger form such as `"Always call a tool first before responding."` pushes further. Conversely, `"Use your judgment about whether to call a tool or respond directly."` keeps triggering behavior conservative.743744To require a tool call rather than rely on prompting, set [`tool_choice`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools#forcing-tool-use).745746<Tip>747  **Guarantee schema conformance with strict tool use**748749  Add `strict: true` to your custom tool definitions to ensure Claude's tool calls always match your schema exactly. See [Strict tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use).750</Tip>751752Each server tool's page describes its own trigger boundary in more detail.753754<Accordion title="When required parameters are missing">755  If the user's prompt doesn't include enough information to fill all the required parameters for a tool, Claude Opus is much more likely to recognize that a parameter is missing and ask for it. Claude Sonnet might ask, especially when prompted to think before outputting a tool request. But it might also infer a reasonable value.756757  For example, given a `get_weather` tool that requires a `location` parameter, if you ask Claude "What's the weather?" without specifying a location, Claude (particularly Claude Sonnet) might guess values you didn't supply:758759  ```json JSON760  {761    "type": "tool_use",762    "id": "toolu_01A09q90qw90lq917835lq9",763    "name": "get_weather",764    "input": { "location": "New York, NY", "unit": "fahrenheit" }765  }766  ```767768  This behavior is not guaranteed, especially for more ambiguous prompts and for less capable models.769</Accordion>770771## Choose a tool772773For `type` strings, versions, and beta headers, see [Tool reference](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference).774775### Your own tools776777For tools you define, you write the schema and your application executes each call.778779<CardGroup cols={2}>780  <Card title="Define tools" icon="hammer" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools">781    Specify tool schemas, write descriptions, and control when Claude calls your tools.782  </Card>783784  <Card title="Handle tool calls" icon="arrows-left-right" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls">785    Parse `tool_use` blocks, format `tool_result` responses, and handle errors.786  </Card>787</CardGroup>788789### Anthropic-schema client tools790791Anthropic publishes the schema and trains Claude on it. Your application still executes each call and returns the `tool_result`.792793<CardGroup cols={2}>794  <Card title="Memory tool" icon="brain" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool">795    Store and retrieve information across conversations in files you control.796  </Card>797798  <Card title="Bash tool" icon="terminal" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool">799    Run shell commands in a persistent session that maintains state.800  </Card>801802  <Card title="Text editor tool" icon="edit" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool">803    View and modify text files to debug, fix, and improve code.804  </Card>805806  <Card title="Computer use tool" icon="computer" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool">807    Take screenshots and control the mouse and keyboard in a desktop environment.808  </Card>809810  <Card title="Browser use tool" icon="browser" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool">811    Navigate, read, and interact with webpages in your own browser environment.812  </Card>813</CardGroup>814815### Server tools816817Server tools run on Anthropic's infrastructure, with no handler code in your application. See [Server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools) for the mechanics they share.818819<CardGroup cols={2}>820  <Card title="Web search tool" icon="magnifying-glass" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool">821    Search the web for information beyond the knowledge cutoff, with cited sources.822  </Card>823824  <Card title="Web fetch tool" icon="download" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool">825    Retrieve the full content of specified web pages and PDF documents.826  </Card>827828  <Card title="Code execution tool" icon="code" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool">829    Run Python and bash code in a sandboxed container to analyze data and generate files.830  </Card>831832  <Card title="Advisor tool" icon="lightbulb" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool">833    Let a faster executor model consult a higher-intelligence advisor model mid-generation.834  </Card>835836  <Card title="Tool search tool" icon="library" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool">837    Work with thousands of tools by discovering and loading them on demand.838  </Card>839840  <Card title="MCP connector" icon="link" href="https://platform.claude.com/docs/en/agents-and-tools/mcp-connector">841    Connect to remote MCP servers from the Messages API without a separate MCP client.842  </Card>843</CardGroup>844845<Note>846  [Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) provides a built-in toolset that Claude uses autonomously within a session. For that toolset and the Managed Agents way to add custom tools, see its [Tools](https://platform.claude.com/docs/en/managed-agents/tools) page.847</Note>848849## Pricing850851Tool use requests are priced based on:8528531. The total number of input tokens sent to the model (including in the `tools` parameter)8542. The number of output tokens generated8553. For server-side tools, additional usage-based pricing (for example, web search charges per search performed)856857Client-side tools are priced the same as any other Claude API request, although server-side tools can incur additional charges based on their specific usage.858859The additional tokens from tool use come from:860861* The `tools` parameter in API requests (tool names, descriptions, and schemas)862* `tool_use` content blocks in API requests and responses863* `tool_result` content blocks in API requests864865When you use `tools`, the API also automatically includes a special system prompt for the model that enables tool use. The number of tool use tokens required for each model is listed in the following table (excluding the additional tokens listed earlier). 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.866867| Model                                                                                                                                 | Tool choice                    | Tool use system prompt token count |868| ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | ---------------------------------- |869| Claude Opus 5                                                                                                                         | `auto`, `none`***`any`, `tool` | 286 tokens***406 tokens            |870| Claude Opus 4.8                                                                                                                       | `auto`, `none`***`any`, `tool` | 290 tokens***410 tokens            |871| Claude Opus 4.7                                                                                                                       | `auto`, `none`***`any`, `tool` | 675 tokens***804 tokens            |872| Claude Opus 4.6                                                                                                                       | `auto`, `none`***`any`, `tool` | 497 tokens***589 tokens            |873| Claude Opus 4.5                                                                                                                       | `auto`, `none`***`any`, `tool` | 496 tokens***588 tokens            |874| Claude Opus 4.1 ([retired, except on Bedrock and Google Cloud](https://platform.claude.com/docs/en/about-claude/model-deprecations))  | `auto`, `none`***`any`, `tool` | 313 tokens***315 tokens            |875| Claude Opus 4 ([retired, except on Google Cloud](https://platform.claude.com/docs/en/about-claude/model-deprecations))                | `auto`, `none`***`any`, `tool` | 313 tokens***315 tokens            |876| Claude Sonnet 5                                                                                                                       | `auto`, `none`***`any`, `tool` | 354 tokens***474 tokens            |877| Claude Sonnet 4.6                                                                                                                     | `auto`, `none`***`any`, `tool` | 497 tokens***589 tokens            |878| Claude Sonnet 4.5                                                                                                                     | `auto`, `none`***`any`, `tool` | 496 tokens***588 tokens            |879| Claude Sonnet 4 ([retired, except on Bedrock and Google Cloud](https://platform.claude.com/docs/en/about-claude/model-deprecations))  | `auto`, `none`***`any`, `tool` | 313 tokens***315 tokens            |880| Claude Haiku 4.5                                                                                                                      | `auto`, `none`***`any`, `tool` | 496 tokens***588 tokens            |881| Claude Haiku 3.5 ([retired, except on Bedrock and Google Cloud](https://platform.claude.com/docs/en/about-claude/model-deprecations)) | `auto`, `none`***`any`, `tool` | 264 tokens***355 tokens            |882883These token counts are added to your normal input and output tokens to calculate the total cost of a request.884885See the [Models overview](https://platform.claude.com/docs/en/models/overview#latest-models-comparison) table for current per-model prices.886887When you send a tool use prompt, like any other API request, the response includes both input and output token counts in the reported `usage` metrics.888889Some server tools add usage-based charges on top of tokens: see [Web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#usage-and-pricing) and [Code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#usage-and-pricing) for their rates.890891## Next steps892893<CardGroup cols={3}>894  <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/how-tool-use-works" title="How tool use works" icon="compass">895    Understand the tool use loop, where tools execute, and when to use tools instead of prose.896  </Card>897898  <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/build-a-tool-using-agent" title="Tutorial: Build a tool-using agent" icon="graduation-cap">899    A guided walkthrough from a single tool call to a production-ready agentic loop.900  </Card>901902  <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference" title="Tool reference" icon="book">903    Directory of Anthropic-provided tools and reference for optional tool definition properties.904  </Card>905</CardGroup>906
Files main
Menu

Theme