---
title: Uso degli strumenti con Claude
url: https://platform.claude.com/docs/it/agents-and-tools/tool-use/overview
description: Collega Claude a strumenti e API esterni. Scopri dove vengono eseguiti gli strumenti, quando Claude li chiama e quale strumento è adatto al tuo compito.
---

Il "tool use" (uso degli strumenti), chiamato anche function calling, consente a Claude di chiamare funzioni definite da te o fornite da Anthropic. Claude determina quando chiamare uno strumento in base alla richiesta dell'utente e alla descrizione dello strumento. Restituisce quindi una chiamata strutturata che la tua applicazione esegue (strumenti client) o che Anthropic esegue (strumenti server).

Ecco un esempio minimo che utilizza uno strumento server, lo [strumento Web search](https://platform.claude.com/docs/it/agents-and-tools/tool-use/web-search-tool), che Anthropic esegue per te:

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "tools": [{"type": "web_search_20260209", "name": "web_search"}],
      "messages": [{"role": "user", "content": "What'\''s the latest on the Mars rover?"}]
    }'
  ```

  ```bash CLI
  ant messages create --transform content --format yaml \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --tool '{type: web_search_20260209, name: web_search}' \
    --message '{role: user, content: "What is the latest on the Mars rover?"}'
  ```

  ```python Python
  client = anthropic.Anthropic()
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      tools=[{"type": "web_search_20260209", "name": "web_search"}],
      messages=[{"role": "user", "content": "What's the latest on the Mars rover?"}],
  )
  print(response.content)
  ```

  ```typescript TypeScript
  const client = new Anthropic();
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: [{ type: "web_search_20260209", name: "web_search" }],
    messages: [{ role: "user", content: "What's the latest on the Mars rover?" }]
  });
  console.log(response.content);
  ```

  ```csharp C#
  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Tools = [new ToolUnion(new WebSearchTool20260209())],
      Messages = [new() { Role = Role.User, Content = "What's the latest on the Mars rover?" }]
  };

  var message = await client.Messages.Create(parameters);
  Console.WriteLine(message.Content);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Tools: []anthropic.ToolUnionParam{
  		{OfWebSearchTool20260209: &anthropic.WebSearchTool20260209Param{}},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the latest on the Mars rover?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.Content)
  ```

  ```java Java
  import com.anthropic.models.messages.WebSearchTool20260209;

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addTool(WebSearchTool20260209.builder().build())
          .addUserMessage("What's the latest on the Mars rover?")
          .build();

      Message response = client.messages().create(params);
      IO.println(response.content());
  }
  ```

  ```php PHP
  $client = new Client();

  $message = $client->messages->create(
      model: 'claude-opus-5-5',
      maxTokens: 1024,
      tools: [
          ['type' => 'web_search_20260209', 'name' => 'web_search'],
      ],
      messages: [
          ['role' => 'user', 'content' => "What's the latest on the Mars rover?"],
      ],
  );

  echo $message;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: [{ type: "web_search_20260209", name: "web_search" }],
    messages: [{ role: "user", content: "What's the latest on the Mars rover?" }]
  )
  puts message.content
  ```
</CodeGroup>

Claude esegue la ricerca sull'infrastruttura di Anthropic e restituisce i risultati citati nella stessa risposta. Per fare in modo che Claude chiami una funzione definita da te, passa uno strumento con un `input_schema`, quindi esegui la chiamata quando Claude restituisce un blocco `tool_use`. [Come funziona l'uso degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/overview#how-tool-use-works) mostra questo ciclo completo dall'inizio alla fine. Scopri di più su come [definire gli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/define-tools) e [gestire le chiamate agli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/handle-tool-calls).

## Come funziona l'uso degli strumenti

Gli strumenti differiscono principalmente per il luogo in cui viene eseguito il codice. Gli **strumenti client** (inclusi gli strumenti definiti dall'utente e gli strumenti con schemi definiti da Anthropic, come `bash` e `text_editor`) vengono eseguiti nella tua applicazione. Claude risponde con `stop_reason: "tool_use"` e uno o più blocchi `tool_use`. Il tuo codice esegue l'operazione e restituisce un `tool_result`. Gli **strumenti server** (come `web_search`, `web_fetch`, `code_execution` e `tool_search`) vengono eseguiti sull'infrastruttura di Anthropic: vedi i risultati direttamente senza gestire l'esecuzione, a meno che Claude non chiami lo strumento nello stesso gruppo di chiamate parallele agli strumenti insieme a uno dei tuoi strumenti client (vedi [Motivi di arresto e fallback](https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons#tool-use)).

Ecco il ciclo completo per uno strumento client. La prima richiesta definisce uno strumento `get_weather` e Claude risponde alla domanda chiamandolo: la risposta contiene un blocco `tool_use`, il tuo codice esegue la ricerca e una seconda richiesta restituisce il risultato in un blocco `tool_result` in modo che Claude possa rispondere con la risposta.

<CodeGroup>
  ```bash cURL
  # Claude risponde con un blocco tool_use che indica lo strumento e i suoi argomenti.
  TOOLS='[
    {
      "name": "get_weather",
      "description": "Get the current weather for a given location.",
      "input_schema": {
        "type": "object",
        "properties": {
          "location": {"type": "string", "description": "City and state, e.g. San Francisco, CA"}
        },
        "required": ["location"]
      }
    }
  ]'
  USER_MSG="What's the weather in San Francisco?"
  RESPONSE=$(curl -s https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d "$(jq -n --argjson tools "$TOOLS" --arg msg "$USER_MSG" '{
      model: "claude-opus-5-5",
      max_tokens: 1024,
      tools: $tools,
      # Richiedi al massimo una chiamata a uno strumento per turno.
      tool_choice: {type: "auto", disable_parallel_tool_use: true},
      messages: [{role: "user", content: $msg}]
    }')")
  TOOL_USE=$(echo "$RESPONSE" | jq '.content[] | select(.type == "tool_use")')
  echo "Claude called $(echo "$TOOL_USE" | jq -r '.name') with $(echo "$TOOL_USE" | jq -c '.input')"

  # Esegui lo strumento, poi invia il risultato in un blocco tool_result.
  # Claude usa il risultato per rispondere alla domanda originale.
  WEATHER="15 degrees Celsius, partly cloudy"
  curl -s https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d "$(jq -n \
      --argjson tools "$TOOLS" \
      --arg msg "$USER_MSG" \
      --argjson assistant "$(echo "$RESPONSE" | jq '.content')" \
      --arg tool_use_id "$(echo "$TOOL_USE" | jq -r '.id')" \
      --arg weather "$WEATHER" \
      '{
        model: "claude-opus-5-5",
        max_tokens: 1024,
        tools: $tools,
        tool_choice: {type: "auto", disable_parallel_tool_use: true},
        messages: [
          {role: "user", content: $msg},
          {role: "assistant", content: $assistant},
          {role: "user", content: [
            {type: "tool_result", tool_use_id: $tool_use_id, content: $weather}
          ]}
        ]
      }')"
  ```

  ```bash CLI
  # ant legge il corpo della richiesta come YAML da stdin; jq trasferisce lo stato
  # della conversazione nella seconda richiesta.
  USER_MSG="What's the weather in San Francisco?"
  MESSAGES=$(jq -n --arg msg "$USER_MSG" '[{role: "user", content: $msg}]')
  call_api() {
    {
      cat <<'YAML'
  model: claude-opus-5-5
  max_tokens: 1024
  # Richiedi al massimo una chiamata a uno strumento per turno.
  tool_choice: {type: auto, disable_parallel_tool_use: true}
  tools:
    - name: get_weather
      description: Get the current weather for a given location.
      input_schema:
        type: object
        properties:
          location: {type: string, description: "City and state, e.g. San Francisco, CA"}
        required: [location]
  YAML
      printf 'messages: %s\n' "$MESSAGES"
    } | ant messages create --format json
  }

  # Claude risponde con un blocco tool_use che indica lo strumento e i suoi argomenti.
  RESPONSE=$(call_api)
  TOOL_USE=$(jq '.content[] | select(.type == "tool_use")' <<<"$RESPONSE")
  echo "Claude called $(jq -r '.name' <<<"$TOOL_USE") with $(jq -c '.input' <<<"$TOOL_USE")"

  # Esegui lo strumento, poi rimanda il risultato in un blocco tool_result.
  WEATHER="15 degrees Celsius, partly cloudy"
  MESSAGES=$(jq \
    --argjson assistant "$(jq '.content' <<<"$RESPONSE")" \
    --arg tool_use_id "$(jq -r '.id' <<<"$TOOL_USE")" \
    --arg weather "$WEATHER" \
    '. + [
      {role: "assistant", content: $assistant},
      {role: "user", content: [
        {type: "tool_result", tool_use_id: $tool_use_id, content: $weather}
      ]}
    ]' <<<"$MESSAGES")

  # Claude usa il risultato per rispondere alla domanda originale.
  call_api
  ```

  ```python Python
  client = anthropic.Anthropic()

  tools = [
      {
          "name": "get_weather",
          "description": "Get the current weather for a given location.",
          "input_schema": {
              "type": "object",
              "properties": {
                  "location": {
                      "type": "string",
                      "description": "City and state, e.g. San Francisco, CA",
                  }
              },
              "required": ["location"],
          },
      }
  ]
  messages = [{"role": "user", "content": "What's the weather in San Francisco?"}]

  # Claude risponde con un blocco tool_use che indica lo strumento e i suoi argomenti.
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      tools=tools,
      # Richiedi al massimo una chiamata a uno strumento per turno.
      tool_choice={"type": "auto", "disable_parallel_tool_use": True},
      messages=messages,
  )
  tool_use = next(block for block in response.content if block.type == "tool_use")
  print(f"Claude called {tool_use.name} with {json.dumps(tool_use.input)}")

  # Esegui lo strumento, poi rinvia il risultato in un blocco tool_result.
  weather = "15 degrees Celsius, partly cloudy"  # your weather lookup goes here
  messages += [
      {"role": "assistant", "content": response.content},
      {
          "role": "user",
          "content": [
              {"type": "tool_result", "tool_use_id": tool_use.id, "content": weather}
          ],
      },
  ]
  followup = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      tools=tools,
      tool_choice={"type": "auto", "disable_parallel_tool_use": True},
      messages=messages,
  )

  # Claude usa il risultato per rispondere alla domanda originale.
  final_text = next(block for block in followup.content if block.type == "text")
  print(final_text.text)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const tools: Anthropic.Tool[] = [
    {
      name: "get_weather",
      description: "Get the current weather for a given location.",
      input_schema: {
        type: "object",
        properties: {
          location: { type: "string", description: "City and state, e.g. San Francisco, CA" }
        },
        required: ["location"]
      }
    }
  ];
  const messages: Anthropic.MessageParam[] = [
    { role: "user", content: "What's the weather in San Francisco?" }
  ];

  // Claude risponde con un blocco tool_use che indica lo strumento e i suoi argomenti.
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools,
    // Richiedi al massimo una chiamata a uno strumento per turno.
    tool_choice: { type: "auto", disable_parallel_tool_use: true },
    messages
  });
  const toolUse = response.content.find(
    (block): block is Anthropic.ToolUseBlock => block.type === "tool_use"
  )!;
  console.log(`Claude called ${toolUse.name} with ${JSON.stringify(toolUse.input)}`);

  // Esegui lo strumento, poi invia il risultato in un blocco tool_result.
  const weather = "15 degrees Celsius, partly cloudy"; // your weather lookup goes here
  messages.push(
    { role: "assistant", content: response.content },
    {
      role: "user",
      content: [{ type: "tool_result", tool_use_id: toolUse.id, content: weather }]
    }
  );
  const followup = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools,
    tool_choice: { type: "auto", disable_parallel_tool_use: true },
    messages
  });

  // Claude usa il risultato per rispondere alla domanda originale.
  const finalText = followup.content.find(
    (block): block is Anthropic.TextBlock => block.type === "text"
  )!;
  console.log(finalText.text);
  ```

  ```csharp C#
  AnthropicClient client = new();

  List<ToolUnion> tools =
  [
      new ToolUnion(new Tool()
      {
          Name = "get_weather",
          Description = "Get the current weather for a given location.",
          InputSchema = new InputSchema()
          {
              Properties = new Dictionary<string, JsonElement>
              {
                  ["location"] = JsonSerializer.SerializeToElement(new
                  {
                      type = "string",
                      description = "City and state, e.g. San Francisco, CA",
                  }),
              },
              Required = ["location"],
          },
      }),
  ];

  // Richiedi al massimo una chiamata a uno strumento per turno.
  var toolChoice = new ToolChoice(new ToolChoiceAuto { DisableParallelToolUse = true });

  const string userPrompt = "What's the weather in San Francisco?";

  // Claude risponde con un blocco tool_use che indica lo strumento e i suoi argomenti.
  var response = await client.Messages.Create(new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Tools = tools,
      ToolChoice = toolChoice,
      Messages = [new() { Role = Role.User, Content = userPrompt }],
  });
  ToolUseBlock? toolUse = null;
  foreach (var block in response.Content)
  {
      if (block.TryPickToolUse(out var picked))
      {
          toolUse = picked;
          break;
      }
  }
  Console.WriteLine($"Claude called {toolUse!.Name} with {JsonSerializer.Serialize(toolUse.Input)}");

  // Esegui lo strumento, poi rinvia il risultato in un blocco tool_result.
  var weather = "15 degrees Celsius, partly cloudy";
  List<ContentBlockParam> toolResults =
  [
      new ContentBlockParam(new ToolResultBlockParam()
      {
          ToolUseID = toolUse.ID,
          Content = weather,
      }),
  ];
  var followup = await client.Messages.Create(new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Tools = tools,
      ToolChoice = toolChoice,
      Messages =
      [
          new() { Role = Role.User, Content = userPrompt },
          new() { Role = Role.Assistant, Content = response.Content.Select(block => new ContentBlockParam(block.Json)).ToList() },
          new() { Role = Role.User, Content = new MessageParamContent(toolResults) },
      ],
  });

  // Claude usa il risultato per rispondere alla domanda originale.
  foreach (var block in followup.Content)
  {
      if (block.TryPickText(out var text))
      {
          Console.WriteLine(text.Text);
      }
  }
  ```

  ```go Go
  client := anthropic.NewClient()
  ctx := context.Background()

  tools := []anthropic.ToolUnionParam{
  	{OfTool: &anthropic.ToolParam{
  		Name:        "get_weather",
  		Description: anthropic.String("Get the current weather for a given location."),
  		InputSchema: anthropic.ToolInputSchemaParam{
  			Properties: map[string]any{
  				"location": map[string]any{
  					"type":        "string",
  					"description": "City and state, e.g. San Francisco, CA",
  				},
  			},
  			Required: []string{"location"},
  		},
  	}},
  }
  // Richiedi al massimo una chiamata a strumento per turno.
  toolChoice := anthropic.ToolChoiceUnionParam{
  	OfAuto: &anthropic.ToolChoiceAutoParam{DisableParallelToolUse: anthropic.Bool(true)},
  }
  messages := []anthropic.MessageParam{
  	anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather in San Francisco?")),
  }

  // Claude risponde con un blocco tool_use che indica lo strumento e i suoi argomenti.
  response, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  	Model:      anthropic.ModelClaudeOpus5_5,
  	MaxTokens:  1024,
  	Tools:      tools,
  	ToolChoice: toolChoice,
  	Messages:   messages,
  })
  if err != nil {
  	log.Fatal(err)
  }
  var toolUse anthropic.ContentBlockUnion
  for _, block := range response.Content {
  	if block.Type == "tool_use" {
  		toolUse = block
  		break
  	}
  }
  fmt.Printf("Claude called %s with %s\n", toolUse.Name, string(toolUse.Input))

  // Esegui lo strumento, poi rimanda il risultato in un blocco tool_result.
  weather := "15 degrees Celsius, partly cloudy"
  var assistantContent []anthropic.ContentBlockParamUnion
  for _, block := range response.Content {
  	assistantContent = append(assistantContent, block.ToParam())
  }
  messages = append(messages,
  	anthropic.NewAssistantMessage(assistantContent...),
  	anthropic.NewUserMessage(anthropic.NewToolResultBlock(toolUse.ID, weather, false)),
  )
  followup, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  	Model:      anthropic.ModelClaudeOpus5_5,
  	MaxTokens:  1024,
  	Tools:      tools,
  	ToolChoice: toolChoice,
  	Messages:   messages,
  })
  if err != nil {
  	log.Fatal(err)
  }

  // Claude usa il risultato per rispondere alla domanda originale.
  for _, block := range followup.Content {
  	if block.Type == "text" {
  		fmt.Println(block.Text)
  	}
  }
  ```

  ```java Java
  import com.anthropic.core.JsonValue;
  import com.anthropic.models.messages.ContentBlockParam;
  // ...
  import com.anthropic.models.messages.Tool;
  import com.anthropic.models.messages.Tool.InputSchema;
  import com.anthropic.models.messages.ToolChoiceAuto;
  import com.anthropic.models.messages.ToolResultBlockParam;
  import com.anthropic.models.messages.ToolUseBlock;
  // ...

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      Tool weatherTool = Tool.builder()
          .name("get_weather")
          .description("Get the current weather for a given location.")
          .inputSchema(InputSchema.builder()
              .properties(JsonValue.from(Map.of(
                  "location", Map.of(
                      "type", "string",
                      "description", "City and state, e.g. San Francisco, CA"
                  )
              )))
              .required(List.of("location"))
              .build())
          .build();

      // Richiedi al massimo una chiamata a strumento per turno.
      ToolChoiceAuto toolChoice = ToolChoiceAuto.builder()
          .disableParallelToolUse(true)
          .build();

      String userPrompt = "What's the weather in San Francisco?";

      // Claude risponde con un blocco tool_use che indica lo strumento e i suoi argomenti.
      Message response = client.messages().create(MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addTool(weatherTool)
          .toolChoice(toolChoice)
          .addUserMessage(userPrompt)
          .build());
      ToolUseBlock toolUse = response.content().stream()
          .flatMap(block -> block.toolUse().stream())
          .findFirst()
          .orElseThrow();
      IO.println("Claude called " + toolUse.name() + " with " + toolUse._input());

      // Esegui lo strumento, poi rinvia il risultato in un blocco tool_result.
      String weather = "15 degrees Celsius, partly cloudy";
      Message followup = client.messages().create(MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addTool(weatherTool)
          .toolChoice(toolChoice)
          .addUserMessage(userPrompt)
          .addMessage(response)
          .addUserMessageOfBlockParams(List.of(ContentBlockParam.ofToolResult(
              ToolResultBlockParam.builder()
                  .toolUseId(toolUse.id())
                  .content(weather)
                  .build())))
          .build());

      // Claude usa il risultato per rispondere alla domanda originale.
      followup.content().stream()
          .flatMap(block -> block.text().stream())
          .forEach(textBlock -> IO.println(textBlock.text()));
  }
  ```

  ```php PHP
  use Anthropic\Messages\ToolChoiceAuto;

  $client = new Client();

  $tools = [
      [
          'name' => 'get_weather',
          'description' => 'Get the current weather for a given location.',
          'input_schema' => [
              'type' => 'object',
              'properties' => [
                  'location' => [
                      'type' => 'string',
                      'description' => 'City and state, e.g. San Francisco, CA',
                  ],
              ],
              'required' => ['location'],
          ],
      ],
  ];
  $userMessage = ['role' => 'user', 'content' => "What's the weather in San Francisco?"];

  // Richiedi al massimo una chiamata a uno strumento per turno.
  $toolChoice = ToolChoiceAuto::with(disableParallelToolUse: true);

  // Claude risponde con un blocco tool_use che indica lo strumento e i suoi argomenti.
  $response = $client->messages->create(
      model: 'claude-opus-5-5',
      maxTokens: 1024,
      tools: $tools,
      toolChoice: $toolChoice,
      messages: [$userMessage],
  );
  $toolUse = null;
  foreach ($response->content as $block) {
      if ($block->type === 'tool_use') {
          $toolUse = $block;
          break;
      }
  }
  printf("Claude called %s with %s\n", $toolUse->name, json_encode($toolUse->input));

  // Esegui lo strumento, poi rinvia il risultato in un blocco tool_result.
  $weather = '15 degrees Celsius, partly cloudy';
  $followup = $client->messages->create(
      model: 'claude-opus-5-5',
      maxTokens: 1024,
      tools: $tools,
      toolChoice: $toolChoice,
      messages: [
          $userMessage,
          ['role' => 'assistant', 'content' => $response->content],
          [
              'role' => 'user',
              'content' => [
                  [
                      'type' => 'tool_result',
                      'tool_use_id' => $toolUse->id,
                      'content' => $weather,
                  ],
              ],
          ],
      ],
  );

  // Claude usa il risultato per rispondere alla domanda originale.
  foreach ($followup->content as $block) {
      if ($block->type === 'text') {
          echo $block->text, "\n";
      }
  }
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  tools = [
    {
      name: "get_weather",
      description: "Get the current weather for a given location.",
      input_schema: {
        type: "object",
        properties: {
          location: {type: "string", description: "City and state, e.g. San Francisco, CA"}
        },
        required: ["location"]
      }
    }
  ]
  messages = [{role: "user", content: "What's the weather in San Francisco?"}]

  # Claude risponde con un blocco tool_use che indica lo strumento e i suoi argomenti.
  response = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: tools,
    # Richiedi al massimo una chiamata a uno strumento per turno.
    tool_choice: {type: "auto", disable_parallel_tool_use: true},
    messages: messages
  )
  tool_use = response.content.find { |block| block.type == :tool_use }
  puts "Claude called #{tool_use.name} with #{JSON.generate(tool_use.input)}"

  # Esegui lo strumento, poi invia il risultato in un blocco tool_result.
  weather = "15 degrees Celsius, partly cloudy"
  messages += [
    {role: "assistant", content: response.content},
    {
      role: "user",
      content: [
        {type: "tool_result", tool_use_id: tool_use.id, content: weather}
      ]
    }
  ]
  followup = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: tools,
    tool_choice: {type: "auto", disable_parallel_tool_use: true},
    messages: messages
  )

  # Claude usa il risultato per rispondere alla domanda originale.
  final_text = followup.content.find { |block| block.type == :text }
  puts final_text.text
  ```
</CodeGroup>

```text Output wrap
Claude called get_weather with {"location": "San Francisco, CA"}
The current weather in San Francisco is 15 degrees Celsius with partly cloudy skies.
```

[Gestire le chiamate agli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/handle-tool-calls) tratta ogni passaggio in dettaglio, inclusa la formattazione dei risultati e la segnalazione degli errori; [Uso parallelo degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/parallel-tool-use) tratta le risposte che chiamano più strumenti contemporaneamente. Per evitare di scrivere tu stesso questo ciclo, usa [Tool Runner](https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-runner): l'SDK esegue i tuoi strumenti e restituisce automaticamente i risultati.

Per il modello concettuale completo, incluso il ciclo agentico e quando scegliere ciascun approccio, consulta [Come funziona l'uso degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/how-tool-use-works).

Per connetterti ai server Model Context Protocol (MCP), consulta il [connettore MCP](https://platform.claude.com/docs/it/agents-and-tools/mcp-connector). Per creare il tuo client MCP, consulta la guida del Model Context Protocol su come [creare un client MCP](https://modelcontextprotocol.io/docs/develop/build-client).

## Quando Claude usa gli strumenti

Con il valore predefinito di `tool_choice` pari a `{"type": "auto"}`, Claude determina a ogni turno se chiamare uno strumento o rispondere direttamente. Chiama uno strumento quando la richiesta corrisponde alla capacità descritta di quello strumento e la risposta non è già presente nel contesto. Risponde direttamente per conoscenze stabili, compiti creativi e turni conversazionali.

Questo confine è orientabile tramite il tuo prompt di sistema. Se Claude non chiama gli strumenti quando te lo aspetti, un'istruzione leggera come `"Use the tools to investigate before responding."` aumenta l'uso degli strumenti. Una forma più forte come `"Always call a tool first before responding."` spinge ulteriormente. Al contrario, `"Use your judgment about whether to call a tool or respond directly."` mantiene conservativo il comportamento di attivazione.

Per richiedere una chiamata a uno strumento anziché affidarti al prompting, imposta [`tool_choice`](https://platform.claude.com/docs/it/agents-and-tools/tool-use/define-tools#forcing-tool-use).

<Tip>
  **Garantisci la conformità allo schema con l'uso rigoroso degli strumenti**

  Aggiungi `strict: true` alle definizioni dei tuoi strumenti personalizzati per garantire che le chiamate agli strumenti di Claude corrispondano sempre esattamente al tuo schema. Consulta [Uso rigoroso degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/strict-tool-use).
</Tip>

La pagina di ciascuno strumento server descrive in maggiore dettaglio il proprio confine di attivazione.

<Accordion title="Quando mancano parametri obbligatori">
  Se il prompt dell'utente non include informazioni sufficienti per compilare tutti i parametri obbligatori di uno strumento, Claude Opus è molto più propenso a riconoscere che manca un parametro e a richiederlo. Claude Sonnet potrebbe chiederlo, specialmente quando gli viene richiesto di riflettere prima di produrre una richiesta di strumento. Ma potrebbe anche dedurre un valore ragionevole.

  Ad esempio, dato uno strumento `get_weather` che richiede un parametro `location`, se chiedi a Claude "Che tempo fa?" senza specificare una località, Claude (in particolare Claude Sonnet) potrebbe indovinare valori che non hai fornito:

  ```json JSON
  {
    "type": "tool_use",
    "id": "toolu_01A09q90qw90lq917835lq9",
    "name": "get_weather",
    "input": { "location": "New York, NY", "unit": "fahrenheit" }
  }
  ```

  Questo comportamento non è garantito, specialmente per prompt più ambigui e per modelli meno capaci.
</Accordion>

## Scegli uno strumento

Per le stringhe `type`, le versioni e gli header beta, consulta il [Riferimento degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-reference).

### I tuoi strumenti

Per gli strumenti che definisci tu, scrivi lo schema e la tua applicazione esegue ogni chiamata.

<CardGroup cols={2}>
  <Card title="Definire gli strumenti" icon="hammer" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/define-tools">
    Specifica gli schemi degli strumenti, scrivi le descrizioni e controlla quando Claude chiama i tuoi strumenti.
  </Card>

  <Card title="Gestire le chiamate agli strumenti" icon="arrows-left-right" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/handle-tool-calls">
    Analizza i blocchi `tool_use`, formatta le risposte `tool_result` e gestisci gli errori.
  </Card>
</CardGroup>

### Strumenti client con schema Anthropic

Anthropic pubblica lo schema e addestra Claude su di esso. La tua applicazione esegue comunque ogni chiamata e restituisce il `tool_result`.

<CardGroup cols={2}>
  <Card title="Strumento Memory" icon="brain" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/memory-tool">
    Memorizza e recupera informazioni tra le conversazioni in file che controlli tu.
  </Card>

  <Card title="Strumento Bash" icon="terminal" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/bash-tool">
    Esegui comandi shell in una sessione persistente che mantiene lo stato.
  </Card>

  <Card title="Strumento Text editor" icon="edit" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/text-editor-tool">
    Visualizza e modifica file di testo per eseguire il debug, correggere e migliorare il codice.
  </Card>

  <Card title="Strumento Computer use" icon="computer" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/computer-use-tool">
    Acquisisci screenshot e controlla mouse e tastiera in un ambiente desktop.
  </Card>

  <Card title="Strumento Browser use" icon="browser" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/browser-use-tool">
    Naviga, leggi e interagisci con le pagine web nel tuo ambiente browser.
  </Card>
</CardGroup>

### Strumenti server

Gli strumenti server vengono eseguiti sull'infrastruttura di Anthropic, senza codice di gestione nella tua applicazione. Consulta [Strumenti server](https://platform.claude.com/docs/it/agents-and-tools/tool-use/server-tools) per i meccanismi che condividono.

<CardGroup cols={2}>
  <Card title="Strumento Web search" icon="magnifying-glass" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/web-search-tool">
    Cerca sul web informazioni oltre la data limite delle conoscenze, con fonti citate.
  </Card>

  <Card title="Strumento Web fetch" icon="download" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/web-fetch-tool">
    Recupera il contenuto completo di pagine web e documenti PDF specificati.
  </Card>

  <Card title="Strumento Code execution" icon="code" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/code-execution-tool">
    Esegui codice Python e bash in un container sandbox per analizzare dati e generare file.
  </Card>

  <Card title="Strumento Advisor" icon="lightbulb" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/advisor-tool">
    Consenti a un modello esecutore più veloce di consultare un modello consulente più intelligente durante la generazione.
  </Card>

  <Card title="Strumento Tool search" icon="library" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-search-tool">
    Lavora con migliaia di strumenti scoprendoli e caricandoli su richiesta.
  </Card>

  <Card title="Connettore MCP" icon="link" href="https://platform.claude.com/docs/it/agents-and-tools/mcp-connector">
    Connettiti a server MCP remoti dalla Messages API senza un client MCP separato.
  </Card>
</CardGroup>

<Note>
  [Claude Managed Agents](https://platform.claude.com/docs/it/managed-agents/overview) fornisce un set di strumenti integrato che Claude usa autonomamente all'interno di una sessione. Per quel set di strumenti e per il modo in cui Managed Agents consente di aggiungere strumenti personalizzati, consulta la relativa pagina [Strumenti](https://platform.claude.com/docs/it/managed-agents/tools).
</Note>

## Prezzi

Le richieste di "tool use" (uso degli strumenti) hanno un prezzo basato su:

1. Il numero totale di token di input inviati al modello (inclusi quelli nel parametro `tools`)
2. Il numero di token di output generati
3. Per gli strumenti lato server, prezzi aggiuntivi basati sull'utilizzo (ad esempio, la ricerca web addebita un costo per ogni ricerca eseguita)

Gli strumenti lato client hanno lo stesso prezzo di qualsiasi altra richiesta alla Claude API, mentre gli strumenti lato server possono comportare costi aggiuntivi in base al loro utilizzo specifico.

I token aggiuntivi derivanti dall'uso degli strumenti provengono da:

* Il parametro `tools` nelle richieste API (nomi, descrizioni e schemi degli strumenti)
* I blocchi di contenuto `tool_use` nelle richieste e nelle risposte API
* I blocchi di contenuto `tool_result` nelle richieste API

Quando usi `tools`, l'API include automaticamente anche uno speciale "system prompt" (prompt di sistema) per il modello che abilita l'uso degli strumenti. Il numero di token per l'uso degli strumenti richiesto per ciascun modello è elencato nella tabella seguente (esclusi i token aggiuntivi elencati in precedenza). Nota che la tabella presuppone che venga fornito almeno 1 strumento. Se non viene fornito alcun `tools`, una scelta dello strumento pari a `none` utilizza 0 token aggiuntivi del prompt di sistema.

| Model                                                                                                                                | Tool use system prompt tokens: auto, none | Tool use system prompt tokens: any, tool |
| :----------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------- | :--------------------------------------- |
| Claude Opus 5.5                                                                                                                      | 286 tokens                                |                                          |
| Claude Opus 5                                                                                                                        | 286 tokens                                | 406 tokens                               |
| Claude Opus 4.8                                                                                                                      | 290 tokens                                | 410 tokens                               |
| Claude Opus 4.7                                                                                                                      | 675 tokens                                | 804 tokens                               |
| Claude Opus 4.6                                                                                                                      | 497 tokens                                | 589 tokens                               |
| Claude Opus 4.5                                                                                                                      | 496 tokens                                | 588 tokens                               |
| Claude Opus 4.1 ([retired, except on Bedrock and Google Cloud](https://platform.claude.com/docs/it/about-claude/model-deprecations)) | 313 tokens                                | 315 tokens                               |
| Claude Opus 4 ([retired, except on Google Cloud](https://platform.claude.com/docs/it/about-claude/model-deprecations))               | 313 tokens                                | 315 tokens                               |
| Claude Sonnet 5.5                                                                                                                    | 286 tokens                                |                                          |
| Claude Sonnet 5                                                                                                                      | 354 tokens                                | 474 tokens                               |
| Claude Sonnet 4.6                                                                                                                    | 497 tokens                                | 589 tokens                               |
| Claude Sonnet 4.5                                                                                                                    | 496 tokens                                | 588 tokens                               |
| Claude Sonnet 4 ([retired, except on Bedrock and Google Cloud](https://platform.claude.com/docs/it/about-claude/model-deprecations)) | 313 tokens                                | 315 tokens                               |
| Claude Haiku 5.5                                                                                                                     | 286 tokens                                | 406 tokens                               |
| Claude Haiku 4.5                                                                                                                     | 496 tokens                                | 588 tokens                               |
| Claude Haiku 3.5 ([retired, except on Google Cloud](https://platform.claude.com/docs/it/about-claude/model-deprecations))            | 264 tokens                                | 355 tokens                               |

* **auto, none:** The count when tool\_choice is auto or none.
* **any, tool:** The count when tool\_choice is any or tool.
* **Retired:** May still be available on other cloud platforms. See [Model deprecations](https://platform.claude.com/docs/it/about-claude/model-deprecations) for more.

Questi conteggi di token vengono aggiunti ai tuoi normali token di input e di output per calcolare il costo totale di una richiesta.

Consulta la tabella [Panoramica dei modelli](https://platform.claude.com/docs/it/models/overview#latest-models-comparison) per i prezzi attuali per modello.

Quando invii un prompt con uso degli strumenti, come per qualsiasi altra richiesta API, la risposta include sia il conteggio dei token di input sia quello dei token di output nelle metriche `usage` riportate.

Alcuni strumenti server aggiungono costi basati sull'utilizzo oltre ai token: consulta [Strumento Web search](https://platform.claude.com/docs/it/agents-and-tools/tool-use/web-search-tool#usage-and-pricing) e [Strumento Code execution](https://platform.claude.com/docs/it/agents-and-tools/tool-use/code-execution-tool#usage-and-pricing) per le relative tariffe.

## Passaggi successivi

<CardGroup cols={3}>
  <Card href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/how-tool-use-works" title="Come funziona l'uso degli strumenti" icon="compass">
    Comprendi il ciclo dell'uso degli strumenti, dove vengono eseguiti gli strumenti e quando usare gli strumenti invece della prosa.
  </Card>

  <Card href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/build-a-tool-using-agent" title="Tutorial: crea un agente che usa strumenti" icon="graduation-cap">
    Una guida passo passo da una singola chiamata a uno strumento fino a un ciclo agentico pronto per la produzione.
  </Card>

  <Card href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-reference" title="Riferimento degli strumenti" icon="book">
    Elenco degli strumenti forniti da Anthropic e riferimento per le proprietà opzionali di definizione degli strumenti.
  </Card>
</CardGroup>
