SPB Git

Repository Public

strict-tool-use.md 39.3 KB 1,145 lines markdown

1---2title: Strict tool use3url: https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use4description: Enforce JSON Schema compliance on Claude's tool inputs with grammar-constrained sampling.5---67Setting `strict: true` on a tool definition guarantees Claude's tool inputs match your JSON Schema by constraining the model's token sampling to schema-valid outputs (a technique called grammar-constrained sampling). This page covers why strict mode matters for agents, how to enable it, and common use cases. For the supported JSON Schema subset, see [JSON Schema limitations](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations). For non-strict schema guidance, see [Define tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools).89Strict tool use validates tool parameters, ensuring Claude calls your functions with correctly-typed arguments. Use strict tool use when you need to:1011* Validate tool parameters12* Build agentic workflows13* Ensure type-safe function calls14* Handle complex tools with nested properties1516## Why strict tool use matters for agents1718Building reliable agentic systems requires guaranteed schema conformance. Without strict mode, Claude might return incompatible types (`"2"` instead of `2`) or omit required fields, breaking your functions and causing runtime errors.1920Strict tool use guarantees type-safe parameters:2122* Functions receive correctly-typed arguments every time23* No need to validate and retry tool calls24* Production-ready agents that work consistently at scale2526For example, suppose a booking system needs `passengers: int`. Without strict mode, Claude might provide `passengers: "two"` or `passengers: "2"`. With `strict: true`, the response always contains `passengers: 2`.2728## Quick start2930<CodeGroup>31  ```bash cURL32  curl https://api.anthropic.com/v1/messages \33    -H "content-type: application/json" \34    -H "x-api-key: $ANTHROPIC_API_KEY" \35    -H "anthropic-version: 2023-06-01" \36    -d '{37      "model": "claude-opus-5",38      "max_tokens": 1024,39      "messages": [40        {"role": "user", "content": "What is the weather in San Francisco?"}41      ],42      "tools": [{43        "name": "get_weather",44        "description": "Get the current weather in a given location",45        "strict": true,46        "input_schema": {47          "type": "object",48          "properties": {49            "location": {50              "type": "string",51              "description": "The city and state, e.g. San Francisco, CA"52            },53            "unit": {54              "type": "string",55              "enum": ["celsius", "fahrenheit"]56            }57          },58          "required": ["location"],59          "additionalProperties": false60        }61      }]62    }'63  ```6465  ```bash CLI66  ant messages create --transform content <<'YAML'67  model: claude-opus-568  max_tokens: 102469  messages:70    - role: user71      content: What is the weather in San Francisco?72  tools:73    - name: get_weather74      description: Get the current weather in a given location75      strict: true76      input_schema:77        type: object78        properties:79          location:80            type: string81            description: The city and state, e.g. San Francisco, CA82          unit:83            type: string84            enum: [celsius, fahrenheit]85        required: [location]86        additionalProperties: false87  YAML88  ```8990  ```python Python91  client = anthropic.Anthropic()9293  response = client.messages.create(94      model="claude-opus-5",95      max_tokens=1024,96      messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],97      tools=[98          {99              "name": "get_weather",100              "description": "Get the current weather in a given location",101              "strict": True,  # Enable strict mode102              "input_schema": {103                  "type": "object",104                  "properties": {105                      "location": {106                          "type": "string",107                          "description": "The city and state, e.g. San Francisco, CA",108                      },109                      "unit": {110                          "type": "string",111                          "enum": ["celsius", "fahrenheit"],112                          "description": "The unit of temperature, either 'celsius' or 'fahrenheit'",113                      },114                  },115                  "required": ["location"],116                  "additionalProperties": False,117              },118          }119      ],120  )121  print(response.content)122  ```123124  ```typescript TypeScript125  const client = new Anthropic({126    apiKey: process.env.ANTHROPIC_API_KEY127  });128129  const response = await client.messages.create({130    model: "claude-opus-5",131    max_tokens: 1024,132    messages: [133      {134        role: "user",135        content: "What's the weather like in San Francisco?"136      }137    ],138    tools: [139      {140        name: "get_weather",141        description: "Get the current weather in a given location",142        strict: true, // Enable strict mode143        input_schema: {144          type: "object",145          properties: {146            location: {147              type: "string",148              description: "The city and state, e.g. San Francisco, CA"149            },150            unit: {151              type: "string",152              enum: ["celsius", "fahrenheit"]153            }154          },155          required: ["location"],156          additionalProperties: false157        }158      }159    ]160  });161  console.log(response.content);162  ```163164  ```csharp C#165  using System.Text.Json;166  using Anthropic;167  using Anthropic.Models.Messages;168169  AnthropicClient client = new();170171  var parameters = new MessageCreateParams172  {173      Model = Model.ClaudeOpus5,174      MaxTokens = 1024,175      Messages = [new() { Role = Role.User, Content = "What's the weather like in San Francisco?" }],176      Tools = [177          new ToolUnion(new Tool()178          {179              Name = "get_weather",180              Description = "Get the current weather in a given location",181              Strict = true,182              InputSchema = new InputSchema(new Dictionary<string, JsonElement>183              {184                  ["properties"] = JsonSerializer.SerializeToElement(new Dictionary<string, object>185                  {186                      ["location"] = new { type = "string", description = "The city and state, e.g. San Francisco, CA" },187                      ["unit"] = new { type = "string", @enum = new[] { "celsius", "fahrenheit" } },188                  }),189                  ["required"] = JsonSerializer.SerializeToElement(new[] { "location" }),190                  ["additionalProperties"] = JsonSerializer.SerializeToElement(false),191              }),192          }),193      ]194  };195196  var message = await client.Messages.Create(parameters);197  Console.WriteLine(message);198  ```199200  ```go Go201  client := anthropic.NewClient()202203  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{204  	Model:     anthropic.ModelClaudeOpus5,205  	MaxTokens: 1024,206  	Messages: []anthropic.MessageParam{207  		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather like in San Francisco?")),208  	},209  	Tools: []anthropic.ToolUnionParam{210  		{OfTool: &anthropic.ToolParam{211  			Name:        "get_weather",212  			Description: anthropic.String("Get the current weather in a given location"),213  			Strict:      anthropic.Bool(true),214  			InputSchema: anthropic.ToolInputSchemaParam{215  				Properties: map[string]any{216  					"location": map[string]any{217  						"type":        "string",218  						"description": "The city and state, e.g. San Francisco, CA",219  					},220  					"unit": map[string]any{221  						"type": "string",222  						"enum": []string{"celsius", "fahrenheit"},223  					},224  				},225  				Required: []string{"location"},226  				ExtraFields: map[string]any{227  					"additionalProperties": false,228  				},229  			}}},230  	},231  })232  if err != nil {233  	log.Fatal(err)234  }235  fmt.Println(response.Content)236  ```237238  ```java Java239  AnthropicClient client = AnthropicOkHttpClient.fromEnv();240241  InputSchema schema = InputSchema.builder()242      .properties(243          JsonValue.from(244              Map.of(245                  "location", Map.of(246                      "type", "string",247                      "description", "The city and state, e.g. San Francisco, CA"248                  ),249                  "unit", Map.of(250                      "type", "string",251                      "enum", List.of("celsius", "fahrenheit")252                  )253              )254          )255      )256      .putAdditionalProperty("required", JsonValue.from(List.of("location")))257      .putAdditionalProperty("additionalProperties", JsonValue.from(false))258      .build();259260  MessageCreateParams params = MessageCreateParams.builder()261      .model(Model.CLAUDE_OPUS_5)262      .maxTokens(1024L)263      .addUserMessage("What's the weather like in San Francisco?")264      .addTool(265          Tool.builder()266              .name("get_weather")267              .description("Get the current weather in a given location")268              .strict(true)269              .inputSchema(schema)270              .build()271      )272      .build();273274  Message response = client.messages().create(params);275  IO.println(response.content());276  ```277278  ```php PHP279  $client = new Client();280281  $message = $client->messages->create(282      maxTokens: 1024,283      messages: [284          ['role' => 'user', 'content' => "What's the weather like in San Francisco?"]285      ],286      model: 'claude-opus-5',287      tools: [288          [289              'name' => 'get_weather',290              'description' => 'Get the current weather in a given location',291              'strict' => true,292              'input_schema' => [293                  'type' => 'object',294                  'properties' => [295                      'location' => [296                          'type' => 'string',297                          'description' => 'The city and state, e.g. San Francisco, CA'298                      ],299                      'unit' => [300                          'type' => 'string',301                          'enum' => ['celsius', 'fahrenheit']302                      ]303                  ],304                  'required' => ['location'],305                  'additionalProperties' => false306              ]307          ]308      ],309  );310311  echo $message;312  ```313314  ```ruby Ruby315  client = Anthropic::Client.new316317  message = client.messages.create(318    model: "claude-opus-5",319    max_tokens: 1024,320    messages: [321      { role: "user", content: "What's the weather like in San Francisco?" }322    ],323    tools: [324      {325        name: "get_weather",326        description: "Get the current weather in a given location",327        strict: true,328        input_schema: {329          type: "object",330          properties: {331            location: {332              type: "string",333              description: "The city and state, e.g. San Francisco, CA"334            },335            unit: {336              type: "string",337              enum: ["celsius", "fahrenheit"]338            }339          },340          required: ["location"],341          additionalProperties: false342        }343      }344    ]345  )346  puts message.content347  ```348</CodeGroup>349350**Response format:** Tool use blocks with validated inputs in `response.content[x].input`351352```json Output353{354  "type": "tool_use",355  "name": "get_weather",356  "input": {357    "location": "San Francisco, CA"358  }359}360```361362**Guarantees:**363364* Tool `input` strictly follows the `input_schema`365* Tool `name` is always valid (from provided tools or server tools)366367## How it works368369<Steps>370  <Step title="Define your tool schema">371    Create a JSON schema for your tool's `input_schema`. The schema uses standard JSON Schema format with some limitations (see [JSON Schema limitations](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations)).372  </Step>373374  <Step title="Add strict: true">375    Set `"strict": true` as a top-level property in your tool definition, alongside `name`, `description`, and `input_schema`.376  </Step>377378  <Step title="Handle tool calls">379    When Claude uses the tool, the `input` field in the `tool_use` block strictly follows your `input_schema`, and the `name` is always valid.380  </Step>381</Steps>382383The [computer use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool) and [browser use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool) toolset entries (`computer_toolset_20260801` and `browser_toolset_20260801`) don't accept `strict: true`; a request that sets it on either entry is rejected.384385## Common use cases386387<AccordionGroup>388  <Accordion title="Validated tool inputs">389    Ensure tool parameters exactly match your schema:390391    <CodeGroup>392      ```bash cURL393      curl https://api.anthropic.com/v1/messages \394        -H "content-type: application/json" \395        -H "x-api-key: $ANTHROPIC_API_KEY" \396        -H "anthropic-version: 2023-06-01" \397        -d '{398          "model": "claude-opus-5",399          "max_tokens": 1024,400          "messages": [401            {"role": "user", "content": "Search for flights to Tokyo departing June 1, 2026"}402          ],403          "tools": [{404            "name": "search_flights",405            "strict": true,406            "input_schema": {407              "type": "object",408              "properties": {409                "destination": {"type": "string"},410                "departure_date": {"type": "string", "format": "date"},411                "passengers": {"type": "integer", "enum": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}412              },413              "required": ["destination", "departure_date"],414              "additionalProperties": false415            }416          }]417        }'418      ```419420      ```bash CLI421      ant messages create <<'YAML'422      model: claude-opus-5423      max_tokens: 1024424      messages:425        - role: user426          content: Search for flights to Tokyo departing June 1, 2026427      tools:428        - name: search_flights429          strict: true430          input_schema:431            type: object432            properties:433              destination:434                type: string435              departure_date:436                type: string437                format: date438              passengers:439                type: integer440                enum: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]441            required: [destination, departure_date]442            additionalProperties: false443      YAML444      ```445446      ```python Python447      client = Anthropic()448      response = client.messages.create(449          model="claude-opus-5",450          max_tokens=1024,451          messages=[452              {453                  "role": "user",454                  "content": "Search for flights to Tokyo departing June 1, 2026",455              }456          ],457          tools=[458              {459                  "name": "search_flights",460                  "strict": True,461                  "input_schema": {462                      "type": "object",463                      "properties": {464                          "destination": {"type": "string"},465                          "departure_date": {"type": "string", "format": "date"},466                          "passengers": {467                              "type": "integer",468                              "enum": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],469                          },470                      },471                      "required": ["destination", "departure_date"],472                      "additionalProperties": False,473                  },474              }475          ],476      )477478      print(response)479      ```480481      ```typescript TypeScript482      const client = new Anthropic();483484      const searchFlightsTool: Anthropic.Tool = {485        name: "search_flights",486        strict: true,487        input_schema: {488          type: "object",489          properties: {490            destination: { type: "string" },491            departure_date: { type: "string", format: "date" },492            passengers: { type: "integer", enum: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }493          },494          required: ["destination", "departure_date"],495          additionalProperties: false496        }497      };498499      const response = await client.messages.create({500        model: "claude-opus-5",501        max_tokens: 1024,502        messages: [{ role: "user", content: "Search for flights to Tokyo departing June 1, 2026" }],503        tools: [searchFlightsTool]504      });505506      console.log(response);507      ```508509      ```csharp C#510      using System.Text.Json;511      using Anthropic;512      using Anthropic.Models.Messages;513514      AnthropicClient client = new();515516      var parameters = new MessageCreateParams517      {518          Model = Model.ClaudeOpus5,519          MaxTokens = 1024,520          Messages = [new() { Role = Role.User, Content = "Search for flights to Tokyo departing June 1, 2026" }],521          Tools = [522              new ToolUnion(new Tool()523              {524                  Name = "search_flights",525                  Strict = true,526                  InputSchema = new InputSchema(new Dictionary<string, JsonElement>527                  {528                      ["properties"] = JsonSerializer.SerializeToElement(new Dictionary<string, object>529                      {530                          ["destination"] = new { type = "string" },531                          ["departure_date"] = new { type = "string", format = "date" },532                          ["passengers"] = new { type = "integer", @enum = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } },533                      }),534                      ["required"] = JsonSerializer.SerializeToElement(new[] { "destination", "departure_date" }),535                      ["additionalProperties"] = JsonSerializer.SerializeToElement(false),536                  }),537              }),538          ]539      };540541      var message = await client.Messages.Create(parameters);542      Console.WriteLine(message);543      ```544545      ```go Go546      client := anthropic.NewClient()547548      response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{549      	Model:     anthropic.ModelClaudeOpus5,550      	MaxTokens: 1024,551      	Messages: []anthropic.MessageParam{552      		anthropic.NewUserMessage(anthropic.NewTextBlock("Search for flights to Tokyo departing June 1, 2026")),553      	},554      	Tools: []anthropic.ToolUnionParam{555      		{OfTool: &anthropic.ToolParam{556      			Name:   "search_flights",557      			Strict: anthropic.Bool(true),558      			InputSchema: anthropic.ToolInputSchemaParam{559      				Properties: map[string]any{560      					"destination": map[string]any{561      						"type": "string",562      					},563      					"departure_date": map[string]any{564      						"type":   "string",565      						"format": "date",566      					},567      					"passengers": map[string]any{568      						"type": "integer",569      						"enum": []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},570      					},571      				},572      				Required: []string{"destination", "departure_date"},573      				ExtraFields: map[string]any{574      					"additionalProperties": false,575      				},576      			}}},577      	},578      })579      if err != nil {580      	log.Fatal(err)581      }582      fmt.Println(response.RawJSON())583      ```584585      ```java Java586      AnthropicClient client = AnthropicOkHttpClient.fromEnv();587588      InputSchema schema = InputSchema.builder()589          .properties(590              JsonValue.from(591                  Map.of(592                      "destination", Map.of("type", "string"),593                      "departure_date", Map.of("type", "string", "format", "date"),594                      "passengers", Map.of(595                          "type", "integer",596                          "enum", List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)597                      )598                  )599              )600          )601          .putAdditionalProperty("required", JsonValue.from(List.of("destination", "departure_date")))602          .putAdditionalProperty("additionalProperties", JsonValue.from(false))603          .build();604605      MessageCreateParams params = MessageCreateParams.builder()606          .model(Model.CLAUDE_OPUS_5)607          .maxTokens(1024L)608          .addUserMessage("Search for flights to Tokyo departing June 1, 2026")609          .addTool(610              Tool.builder()611                  .name("search_flights")612                  .strict(true)613                  .inputSchema(schema)614                  .build()615          )616          .build();617618      Message response = client.messages().create(params);619      IO.println(response);620      ```621622      ```php PHP623      $client = new Client();624625      $message = $client->messages->create(626          maxTokens: 1024,627          messages: [628              ['role' => 'user', 'content' => 'Search for flights to Tokyo departing June 1, 2026']629          ],630          model: 'claude-opus-5',631          tools: [632              [633                  'name' => 'search_flights',634                  'strict' => true,635                  'input_schema' => [636                      'type' => 'object',637                      'properties' => [638                          'destination' => ['type' => 'string'],639                          'departure_date' => ['type' => 'string', 'format' => 'date'],640                          'passengers' => [641                              'type' => 'integer',642                              'enum' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]643                          ]644                      ],645                      'required' => ['destination', 'departure_date'],646                      'additionalProperties' => false647                  ]648              ]649          ],650      );651652      echo $message;653      ```654655      ```ruby Ruby656      client = Anthropic::Client.new657658      message = client.messages.create(659        model: "claude-opus-5",660        max_tokens: 1024,661        messages: [662          { role: "user", content: "Search for flights to Tokyo departing June 1, 2026" }663        ],664        tools: [665          {666            name: "search_flights",667            strict: true,668            input_schema: {669              type: "object",670              properties: {671                destination: { type: "string" },672                departure_date: { type: "string", format: "date" },673                passengers: {674                  type: "integer",675                  enum: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]676                }677              },678              required: ["destination", "departure_date"],679              additionalProperties: false680            }681          }682        ]683      )684      puts message685      ```686    </CodeGroup>687  </Accordion>688689  <Accordion title="Agentic workflow with multiple validated tools">690    Build reliable multistep agents with guaranteed tool parameters:691692    <CodeGroup>693      ```bash cURL694      curl https://api.anthropic.com/v1/messages \695        -H "content-type: application/json" \696        -H "x-api-key: $ANTHROPIC_API_KEY" \697        -H "anthropic-version: 2023-06-01" \698        -d '{699          "model": "claude-opus-5",700          "max_tokens": 1024,701          "messages": [702            {"role": "user", "content": "Help me plan a trip from New York to Paris for 2 people, departing June 1, 2026"}703          ],704          "tools": [705            {706              "name": "search_flights",707              "strict": true,708              "input_schema": {709                "type": "object",710                "properties": {711                  "origin": {"type": "string"},712                  "destination": {"type": "string"},713                  "departure_date": {"type": "string", "format": "date"},714                  "travelers": {"type": "integer", "enum": [1, 2, 3, 4, 5, 6]}715                },716                "required": ["origin", "destination", "departure_date"],717                "additionalProperties": false718              }719            },720            {721              "name": "search_hotels",722              "strict": true,723              "input_schema": {724                "type": "object",725                "properties": {726                  "city": {"type": "string"},727                  "check_in": {"type": "string", "format": "date"},728                  "guests": {"type": "integer", "enum": [1, 2, 3, 4]}729                },730                "required": ["city", "check_in"],731                "additionalProperties": false732              }733            }734          ]735        }'736      ```737738      ```bash CLI739      ant messages create <<'YAML'740      model: claude-opus-5741      max_tokens: 1024742      messages:743        - role: user744          content: >-745            Help me plan a trip from New York to Paris for 2 people,746            departing June 1, 2026747      tools:748        - name: search_flights749          strict: true750          input_schema:751            type: object752            properties:753              origin: {type: string}754              destination: {type: string}755              departure_date: {type: string, format: date}756              travelers: {type: integer, enum: [1, 2, 3, 4, 5, 6]}757            required: [origin, destination, departure_date]758            additionalProperties: false759        - name: search_hotels760          strict: true761          input_schema:762            type: object763            properties:764              city: {type: string}765              check_in: {type: string, format: date}766              guests: {type: integer, enum: [1, 2, 3, 4]}767            required: [city, check_in]768            additionalProperties: false769      YAML770      ```771772      ```python Python773      client = Anthropic()774      response = client.messages.create(775          model="claude-opus-5",776          max_tokens=1024,777          messages=[778              {779                  "role": "user",780                  "content": "Help me plan a trip from New York to Paris for 2 people, departing June 1, 2026",781              }782          ],783          tools=[784              {785                  "name": "search_flights",786                  "strict": True,787                  "input_schema": {788                      "type": "object",789                      "properties": {790                          "origin": {"type": "string"},791                          "destination": {"type": "string"},792                          "departure_date": {"type": "string", "format": "date"},793                          "travelers": {"type": "integer", "enum": [1, 2, 3, 4, 5, 6]},794                      },795                      "required": ["origin", "destination", "departure_date"],796                      "additionalProperties": False,797                  },798              },799              {800                  "name": "search_hotels",801                  "strict": True,802                  "input_schema": {803                      "type": "object",804                      "properties": {805                          "city": {"type": "string"},806                          "check_in": {"type": "string", "format": "date"},807                          "guests": {"type": "integer", "enum": [1, 2, 3, 4]},808                      },809                      "required": ["city", "check_in"],810                      "additionalProperties": False,811                  },812              },813          ],814      )815816      print(response)817      ```818819      ```typescript TypeScript820      const client = new Anthropic();821822      const tools: Anthropic.Tool[] = [823        {824          name: "search_flights",825          strict: true,826          input_schema: {827            type: "object",828            properties: {829              origin: { type: "string" },830              destination: { type: "string" },831              departure_date: { type: "string", format: "date" },832              travelers: { type: "integer", enum: [1, 2, 3, 4, 5, 6] }833            },834            required: ["origin", "destination", "departure_date"],835            additionalProperties: false836          }837        },838        {839          name: "search_hotels",840          strict: true,841          input_schema: {842            type: "object",843            properties: {844              city: { type: "string" },845              check_in: { type: "string", format: "date" },846              guests: { type: "integer", enum: [1, 2, 3, 4] }847            },848            required: ["city", "check_in"],849            additionalProperties: false850          }851        }852      ];853854      const response = await client.messages.create({855        model: "claude-opus-5",856        max_tokens: 1024,857        messages: [858          {859            role: "user",860            content:861              "Help me plan a trip from New York to Paris for 2 people, departing June 1, 2026"862          }863        ],864        tools: tools865      });866867      console.log(response);868      ```869870      ```csharp C#871      using System.Text.Json;872      using Anthropic;873      using Anthropic.Models.Messages;874875      AnthropicClient client = new();876877      var parameters = new MessageCreateParams878      {879          Model = Model.ClaudeOpus5,880          MaxTokens = 1024,881          Messages = [new() { Role = Role.User, Content = "Help me plan a trip from New York to Paris for 2 people, departing June 1, 2026" }],882          Tools = [883              new ToolUnion(new Tool()884              {885                  Name = "search_flights",886                  Strict = true,887                  InputSchema = new InputSchema(new Dictionary<string, JsonElement>888                  {889                      ["properties"] = JsonSerializer.SerializeToElement(new Dictionary<string, object>890                      {891                          ["origin"] = new { type = "string" },892                          ["destination"] = new { type = "string" },893                          ["departure_date"] = new { type = "string", format = "date" },894                          ["travelers"] = new { type = "integer", @enum = new[] { 1, 2, 3, 4, 5, 6 } },895                      }),896                      ["required"] = JsonSerializer.SerializeToElement(new[] { "origin", "destination", "departure_date" }),897                      ["additionalProperties"] = JsonSerializer.SerializeToElement(false),898                  }),899              }),900              new ToolUnion(new Tool()901              {902                  Name = "search_hotels",903                  Strict = true,904                  InputSchema = new InputSchema(new Dictionary<string, JsonElement>905                  {906                      ["properties"] = JsonSerializer.SerializeToElement(new Dictionary<string, object>907                      {908                          ["city"] = new { type = "string" },909                          ["check_in"] = new { type = "string", format = "date" },910                          ["guests"] = new { type = "integer", @enum = new[] { 1, 2, 3, 4 } },911                      }),912                      ["required"] = JsonSerializer.SerializeToElement(new[] { "city", "check_in" }),913                      ["additionalProperties"] = JsonSerializer.SerializeToElement(false),914                  }),915              }),916          ]917      };918919      var message = await client.Messages.Create(parameters);920      Console.WriteLine(message);921      ```922923      ```go Go924      client := anthropic.NewClient()925926      response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{927      	Model:     anthropic.ModelClaudeOpus5,928      	MaxTokens: 1024,929      	Messages: []anthropic.MessageParam{930      		anthropic.NewUserMessage(anthropic.NewTextBlock("Help me plan a trip from New York to Paris for 2 people, departing June 1, 2026")),931      	},932      	Tools: []anthropic.ToolUnionParam{933      		{OfTool: &anthropic.ToolParam{934      			Name:   "search_flights",935      			Strict: anthropic.Bool(true),936      			InputSchema: anthropic.ToolInputSchemaParam{937      				Properties: map[string]any{938      					"origin":         map[string]any{"type": "string"},939      					"destination":    map[string]any{"type": "string"},940      					"departure_date": map[string]any{"type": "string", "format": "date"},941      					"travelers":      map[string]any{"type": "integer", "enum": []int{1, 2, 3, 4, 5, 6}},942      				},943      				Required: []string{"origin", "destination", "departure_date"},944      				ExtraFields: map[string]any{945      					"additionalProperties": false,946      				},947      			}}},948      		{OfTool: &anthropic.ToolParam{949      			Name:   "search_hotels",950      			Strict: anthropic.Bool(true),951      			InputSchema: anthropic.ToolInputSchemaParam{952      				Properties: map[string]any{953      					"city":     map[string]any{"type": "string"},954      					"check_in": map[string]any{"type": "string", "format": "date"},955      					"guests":   map[string]any{"type": "integer", "enum": []int{1, 2, 3, 4}},956      				},957      				Required: []string{"city", "check_in"},958      				ExtraFields: map[string]any{959      					"additionalProperties": false,960      				},961      			}}},962      	},963      })964      if err != nil {965      	log.Fatal(err)966      }967      fmt.Println(response.RawJSON())968      ```969970      ```java Java971      AnthropicClient client = AnthropicOkHttpClient.fromEnv();972973      InputSchema flightsSchema = InputSchema.builder()974          .properties(975              JsonValue.from(976                  Map.of(977                      "origin", Map.of("type", "string"),978                      "destination", Map.of("type", "string"),979                      "departure_date", Map.of("type", "string", "format", "date"),980                      "travelers", Map.of("type", "integer", "enum", List.of(1, 2, 3, 4, 5, 6))981                  )982              )983          )984          .putAdditionalProperty("required", JsonValue.from(List.of("origin", "destination", "departure_date")))985          .putAdditionalProperty("additionalProperties", JsonValue.from(false))986          .build();987988      InputSchema hotelsSchema = InputSchema.builder()989          .properties(990              JsonValue.from(991                  Map.of(992                      "city", Map.of("type", "string"),993                      "check_in", Map.of("type", "string", "format", "date"),994                      "guests", Map.of("type", "integer", "enum", List.of(1, 2, 3, 4))995                  )996              )997          )998          .putAdditionalProperty("required", JsonValue.from(List.of("city", "check_in")))999          .putAdditionalProperty("additionalProperties", JsonValue.from(false))1000          .build();10011002      MessageCreateParams params = MessageCreateParams.builder()1003          .model(Model.CLAUDE_OPUS_5)1004          .maxTokens(1024L)1005          .addUserMessage("Help me plan a trip from New York to Paris for 2 people, departing June 1, 2026")1006          .addTool(1007              Tool.builder()1008                  .name("search_flights")1009                  .strict(true)1010                  .inputSchema(flightsSchema)1011                  .build()1012          )1013          .addTool(1014              Tool.builder()1015                  .name("search_hotels")1016                  .strict(true)1017                  .inputSchema(hotelsSchema)1018                  .build()1019          )1020          .build();10211022      Message response = client.messages().create(params);1023      IO.println(response);1024      ```10251026      ```php PHP1027      $client = new Client();10281029      $message = $client->messages->create(1030          maxTokens: 1024,1031          messages: [1032              ['role' => 'user', 'content' => 'Help me plan a trip from New York to Paris for 2 people, departing June 1, 2026']1033          ],1034          model: 'claude-opus-5',1035          tools: [1036              [1037                  'name' => 'search_flights',1038                  'strict' => true,1039                  'input_schema' => [1040                      'type' => 'object',1041                      'properties' => [1042                          'origin' => ['type' => 'string'],1043                          'destination' => ['type' => 'string'],1044                          'departure_date' => ['type' => 'string', 'format' => 'date'],1045                          'travelers' => ['type' => 'integer', 'enum' => [1, 2, 3, 4, 5, 6]]1046                      ],1047                      'required' => ['origin', 'destination', 'departure_date'],1048                      'additionalProperties' => false1049                  ]1050              ],1051              [1052                  'name' => 'search_hotels',1053                  'strict' => true,1054                  'input_schema' => [1055                      'type' => 'object',1056                      'properties' => [1057                          'city' => ['type' => 'string'],1058                          'check_in' => ['type' => 'string', 'format' => 'date'],1059                          'guests' => ['type' => 'integer', 'enum' => [1, 2, 3, 4]]1060                      ],1061                      'required' => ['city', 'check_in'],1062                      'additionalProperties' => false1063                  ]1064              ]1065          ],1066      );10671068      echo $message;1069      ```10701071      ```ruby Ruby1072      client = Anthropic::Client.new10731074      message = client.messages.create(1075        model: "claude-opus-5",1076        max_tokens: 1024,1077        messages: [1078          { role: "user", content: "Help me plan a trip from New York to Paris for 2 people, departing June 1, 2026" }1079        ],1080        tools: [1081          {1082            name: "search_flights",1083            strict: true,1084            input_schema: {1085              type: "object",1086              properties: {1087                origin: { type: "string" },1088                destination: { type: "string" },1089                departure_date: { type: "string", format: "date" },1090                travelers: { type: "integer", enum: [1, 2, 3, 4, 5, 6] }1091              },1092              required: ["origin", "destination", "departure_date"],1093              additionalProperties: false1094            }1095          },1096          {1097            name: "search_hotels",1098            strict: true,1099            input_schema: {1100              type: "object",1101              properties: {1102                city: { type: "string" },1103                check_in: { type: "string", format: "date" },1104                guests: { type: "integer", enum: [1, 2, 3, 4] }1105              },1106              required: ["city", "check_in"],1107              additionalProperties: false1108            }1109          }1110        ]1111      )1112      puts message1113      ```1114    </CodeGroup>1115  </Accordion>1116</AccordionGroup>11171118## Data retention11191120Strict tool use compiles tool `input_schema` definitions into grammars using the same pipeline as [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs). Tool schemas are temporarily cached for up to 24 hours since last use. Prompts and responses are not retained beyond the API response.11211122Strict tool use is HIPAA eligible, but **protected health information (PHI) must not be included in tool schema definitions**. The API caches compiled schemas separately from message content, and these cached schemas do not receive the same PHI protections as prompts and responses. Do not include PHI in `input_schema` property names, `enum` values, `const` values, or `pattern` regular expressions. PHI should only appear in message content (prompts and responses), where it is protected under HIPAA safeguards.11231124For ZDR and HIPAA eligibility across all features, see [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention).11251126## Next steps11271128<CardGroup cols={2}>1129  <Card title="Web fetch tool" icon="link" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool">1130    Fetch and read content from specific URLs to bring live web content into Claude's context.1131  </Card>11321133  <Card title="Tool use with prompt caching" icon="database" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-use-with-prompt-caching">1134    Cache tool definitions across turns to reduce cost and latency.1135  </Card>11361137  <Card title="Structured outputs" icon="code-brackets" href="https://platform.claude.com/docs/en/build-with-claude/structured-outputs">1138    Get validated JSON responses using the same grammar-constrained sampling.1139  </Card>11401141  <Card title="Define tools" icon="hammer" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools">1142    Specify tool schemas, write effective descriptions, and control when Claude calls your tools.1143  </Card>1144</CardGroup>1145
Files main
Menu

Theme