---
title: ツールを定義する
url: https://platform.claude.com/docs/ja/agents-and-tools/tool-use/define-tools
description: ツールスキーマを指定し、効果的な説明を記述し、Claudeがツールを呼び出すタイミングを制御します。
---

## 前提条件

* [ツール使用の概要](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/overview)を理解していること
* Claude APIキーと、動作するSDKまたはcURLのセットアップ

<Tip>
  Claudeでツール使用と思考を併用する場合は、詳細について[思考](https://platform.claude.com/docs/ja/build-with-claude/thinking)を参照してください。
</Tip>

## クライアントツールの指定

クライアントツールは、APIリクエストのトップレベルパラメータ `tools` で指定します。bashツールやテキストエディタツールなどのAnthropicスキーマのクライアントツールは、日付でバージョン管理された `type` によって宣言されます。各ツールが受け付けるフィールドについては、[ツールリファレンス](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/tool-reference)からリンクされている各ツールのページを参照してください。コンピュータ使用ツールとブラウザ使用ツールは[クライアントツールセット](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/tool-reference#client-toolsets)です。これは `name` を持たない単一のエントリで、固定されたメンバーツールのセットを宣言します。ユーザー定義のツール定義には以下が含まれます。

| パラメータ            | 説明                                                                                                                                                                         |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`           | ツールの名前。正規表現`^[a-zA-Z0-9_-]{1,128}$`に一致する必要があります。                                                                                                                           |
| `description`    | ツールの機能、使用すべき場面、動作を説明する詳細なプレーンテキスト。                                                                                                                                         |
| `input_schema`   | ツールが想定するパラメータを定義する[JSON Schema](https://json-schema.org/)オブジェクト。                                                                                                           |
| `input_examples` | （オプション）Claudeがツールの使い方を理解するための入力例オブジェクトの配列。[ツール使用の例を提供する](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/define-tools#providing-tool-use-examples)を参照してください。 |

`cache_control`、`strict`、`defer_loading`、`allowed_callers` など、単一のツール定義で利用可能なオプションプロパティの完全なセットについては、[ツールリファレンス](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/tool-reference#tool-definition-properties)を参照してください。クライアントツールセットのエントリは、エントリに対して `cache_control` と `allowed_callers` を受け付け、メンバーごとに `defer_loading` を設定します。[クライアントツールセット](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/tool-reference#client-toolsets)を参照してください。

<Accordion title="シンプルなツール定義の例">
  ```json JSON
  {
    "name": "get_weather",
    "description": "Get the current weather in a given location",
    "input_schema": {
      "type": "object",
      "properties": {
        "location": {
          "type": "string",
          "description": "The city and state, e.g. San Francisco, CA"
        },
        "unit": {
          "type": "string",
          "enum": ["celsius", "fahrenheit"],
          "description": "The unit of temperature, either 'celsius' or 'fahrenheit'"
        }
      },
      "required": ["location"]
    }
  }
  ```

  `get_weather` という名前のこのツールは、必須の `location` 文字列と、"celsius" または "fahrenheit" のいずれかでなければならないオプションの `unit` 文字列を持つ入力オブジェクトを期待します。
</Accordion>

### ツール使用のシステムプロンプト

`tools` パラメータを指定してClaude APIを呼び出すと、APIはツール定義、ツール設定、およびユーザーが指定した「system prompt」（システムプロンプト）から特別なシステムプロンプトを構築します。構築されたプロンプトは、指定されたツールを使用するようモデルに指示し、ツールが適切に動作するために必要なコンテキストを提供するように設計されています。

```text wrap
In this environment you have access to a set of tools you can use to answer the user's question.
{{ FORMATTING INSTRUCTIONS }}
String and scalar parameters should be specified as is, while lists and objects should use JSON format. Note that spaces for string values are not stripped. The output is not expected to be valid XML and is parsed with regular expressions.
Here are the functions available in JSONSchema format:
{{ TOOL DEFINITIONS IN JSON SCHEMA }}
{{ USER SYSTEM PROMPT }}
{{ TOOL CONFIGURATION }}
```

### ツール定義のベストプラクティス

ツールを使用する際にClaudeから最高のパフォーマンスを引き出すには、以下のガイドラインに従ってください。

* **非常に詳細な説明を提供する。** これはツールのパフォーマンスにおいて圧倒的に最も重要な要素です。説明では、ツールに関するあらゆる詳細を説明する必要があります。これには以下が含まれます。

  * ツールが何をするのか
  * いつ使用すべきか（そしていつ使用すべきでないか）
  * 各パラメータが何を意味し、ツールの動作にどのように影響するか
  * ツール名が不明瞭な場合にツールが返さない情報など、重要な注意事項や制限。ツールについてClaudeに提供できるコンテキストが多いほど、Claudeはツールをいつどのように使用するかをより適切に判断できます。各ツールの説明には少なくとも3〜4文を目指し、ツールが複雑な場合はさらに多く記述してください。

* **説明を優先しつつ、複雑なツールには `input_examples` の使用を検討する。** 明確な説明が最も重要ですが、複雑な入力、ネストされたオブジェクト、またはフォーマットに敏感なパラメータを持つツールの場合は、`input_examples` フィールドを使用してスキーマ検証済みの例を提供できます。詳細は[ツール使用例の提供](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/define-tools#providing-tool-use-examples)を参照してください。

* **関連する操作をより少ないツールに統合する。** すべてのアクションごとに個別のツール（`create_pr`、`review_pr`、`merge_pr`）を作成するのではなく、`action` パラメータを持つ単一のツールにまとめてください。より少なく、より高機能なツールにすることで、選択の曖昧さが減り、Claudeがツール群を把握しやすくなります。

* **ツール名に意味のある名前空間を使用する。** ツールが複数のサービスやリソースにまたがる場合は、名前の先頭にサービス名を付けてください（例：`github_list_prs`、`slack_send_message`）。これにより、ライブラリが大きくなってもツール選択が曖昧にならず、[ツール検索](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/tool-search-tool)を使用する場合に特に重要です。

* **ツールのレスポンスはシグナルの高い情報のみを返すように設計する。** 不透明な内部参照ではなく、意味のある安定した識別子（例：スラッグやUUID）を返し、Claudeが次のステップを推論するために必要なフィールドのみを含めてください。肥大化したレスポンスはコンテキストを浪費し、Claudeが重要な情報を抽出するのを難しくします。

* **推論ではなく説明を求める。** パラメータでClaudeに呼び出しを行う理由を尋ねる場合は、短い説明または裏付けとなる根拠を求めてください。モデルの思考や段階的な推論を求めるパラメータは、`reasoning_extraction`による拒否につながる可能性があります。[推論を思考ブロック内に保つ](https://platform.claude.com/docs/ja/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks)を参照してください。

<AccordionGroup>
  <Accordion title="良いツール説明の例">
    ```json JSON
    {
      "name": "get_stock_price",
      "description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
      "input_schema": {
        "type": "object",
        "properties": {
          "ticker": {
            "type": "string",
            "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
          }
        },
        "required": ["ticker"]
      }
    }
    ```
  </Accordion>

  <Accordion title="悪いツール説明の例">
    ```json JSON
    {
      "name": "get_stock_price",
      "description": "Gets the stock price for a ticker.",
      "input_schema": {
        "type": "object",
        "properties": {
          "ticker": {
            "type": "string"
          }
        },
        "required": ["ticker"]
      }
    }
    ```
  </Accordion>
</AccordionGroup>

良い説明は、ツールが何をするか、いつ使用するか、どのようなデータを返すか、そして `ticker` パラメータが何を意味するかを明確に説明しています。悪い説明は簡潔すぎて、ツールの動作や使い方についてClaudeに多くの疑問を残してしまいます。

<Tip>
  ツール設計（統合、命名、レスポンスの整形）に関するより深いガイダンスについては、[Writing tools for agents](https://www.anthropic.com/engineering/writing-tools-for-agents)を参照してください。
</Tip>

## ツール使用例の提供

有効なツール入力の具体例を提供することで、Claudeがツールをより効果的に使用する方法を理解するのに役立てることができます。これは、ネストされたオブジェクト、オプションのパラメータ、またはフォーマットに敏感な入力を持つ複雑なツールに特に有用です。

### 基本的な使い方

ツール定義にオプションの `input_examples` フィールドを追加し、入力オブジェクトの例の配列を指定します。各例はツールの `input_schema` に従って有効でなければなりません。

<CodeGroup>
  ```bash cURL
  curl -sS https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "tools": [
        {
          "name": "get_weather",
          "description": "Get the current weather in a given location",
          "input_schema": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, CA"
              },
              "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"],
                "description": "The unit of temperature"
              }
            },
            "required": ["location"]
          },
          "input_examples": [
            {"location": "San Francisco, CA", "unit": "fahrenheit"},
            {"location": "Tokyo, Japan", "unit": "celsius"},
            {"location": "New York, NY"}
          ]
        }
      ],
      "messages": [
        {"role": "user", "content": "What is the weather like in San Francisco?"}
      ]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 1024
  tools:
    - name: get_weather
      description: Get the current weather in a given location
      input_schema:
        type: object
        properties:
          location:
            type: string
            description: The city and state, e.g. San Francisco, CA
          unit:
            type: string
            enum: [celsius, fahrenheit]
            description: The unit of temperature
        required: [location]
      input_examples:
        - location: San Francisco, CA
          unit: fahrenheit
        - location: Tokyo, Japan
          unit: celsius
        - location: New York, NY  # 'unit' is optional
  messages:
    - role: user
      content: What's the weather like in San Francisco?
  YAML
  ```

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

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      tools=[
          {
              "name": "get_weather",
              "description": "Get the current weather in a given location",
              "input_schema": {
                  "type": "object",
                  "properties": {
                      "location": {
                          "type": "string",
                          "description": "The city and state, e.g. San Francisco, CA",
                      },
                      "unit": {
                          "type": "string",
                          "enum": ["celsius", "fahrenheit"],
                          "description": "The unit of temperature",
                      },
                  },
                  "required": ["location"],
              },
              "input_examples": [
                  {"location": "San Francisco, CA", "unit": "fahrenheit"},
                  {"location": "Tokyo, Japan", "unit": "celsius"},
                  {
                      "location": "New York, NY"  # 'unit' is optional
                  },
              ],
          }
      ],
      messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
  )

  print(response)
  ```

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

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: [
      {
        name: "get_weather",
        description: "Get the current weather in a given location",
        input_schema: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "The city and state, e.g. San Francisco, CA"
            },
            unit: {
              type: "string",
              enum: ["celsius", "fahrenheit"],
              description: "The unit of temperature"
            }
          },
          required: ["location"]
        },
        input_examples: [
          {
            location: "San Francisco, CA",
            unit: "fahrenheit"
          },
          {
            location: "Tokyo, Japan",
            unit: "celsius"
          },
          {
            location: "New York, NY"
            // 'unit' が省略可能であることを示します
          }
        ]
      }
    ],
    messages: [{ role: "user", content: "What's the weather like in San Francisco?" }]
  });

  console.log(response);
  ```

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

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Tools = [
          new ToolUnion(new Tool()
          {
              Name = "get_weather",
              Description = "Get the current weather in a given location",
              InputSchema = new InputSchema()
              {
                  Properties = new Dictionary<string, JsonElement>
                  {
                      ["location"] = JsonSerializer.SerializeToElement(new { type = "string", description = "The city and state, e.g. San Francisco, CA" }),
                      ["unit"] = JsonSerializer.SerializeToElement(new { type = "string", @enum = new[] { "celsius", "fahrenheit" }, description = "The unit of temperature" }),
                  },
                  Required = ["location"],
              },
              InputExamples =
              [
                  new Dictionary<string, JsonElement>()
                  {
                      { "location", JsonSerializer.SerializeToElement("San Francisco, CA") },
                      { "unit", JsonSerializer.SerializeToElement("fahrenheit") },
                  },
                  new Dictionary<string, JsonElement>()
                  {
                      { "location", JsonSerializer.SerializeToElement("Tokyo, Japan") },
                      { "unit", JsonSerializer.SerializeToElement("celsius") },
                  },
                  new Dictionary<string, JsonElement>()
                  {
                      { "location", JsonSerializer.SerializeToElement("New York, NY") },
                  },
              ],
          }),
      ],
      Messages = [
          new() { Role = Role.User, Content = "What's the weather like in San Francisco?" }
      ]
  };

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

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

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Tools: []anthropic.ToolUnionParam{
  		{OfTool: &anthropic.ToolParam{
  			Name:        "get_weather",
  			Description: anthropic.String("Get the current weather in a given location"),
  			InputSchema: anthropic.ToolInputSchemaParam{
  				Properties: map[string]any{
  					"location": map[string]any{
  						"type":        "string",
  						"description": "The city and state, e.g. San Francisco, CA",
  					},
  					"unit": map[string]any{
  						"type":        "string",
  						"enum":        []string{"celsius", "fahrenheit"},
  						"description": "The unit of temperature",
  					},
  				},
  				Required: []string{"location"},
  			},
  			InputExamples: []map[string]any{
  				{
  					"location": "San Francisco, CA",
  					"unit":     "fahrenheit",
  				},
  				{
  					"location": "Tokyo, Japan",
  					"unit":     "celsius",
  				},
  				{
  					"location": "New York, NY",
  					// 'unit' が省略可能であることを示します
  				},
  			},
  		}},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather like in San Francisco?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.Tool;
  import com.anthropic.models.messages.Tool.InputSchema;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addTool(Tool.builder()
              .name("get_weather")
              .description("Get the current weather in a given location")
              .inputSchema(InputSchema.builder()
                  .properties(JsonValue.from(Map.of(
                      "location", Map.of(
                          "type", "string",
                          "description", "The city and state, e.g. San Francisco, CA"
                      ),
                      "unit", Map.of(
                          "type", "string",
                          "enum", List.of("celsius", "fahrenheit"),
                          "description", "The unit of temperature"
                      )
                  )))
                  .required(List.of("location"))
                  .build())
              .putAdditionalProperty("input_examples", JsonValue.from(List.of(
                  Map.of(
                      "location", "San Francisco, CA",
                      "unit", "fahrenheit"
                  ),
                  Map.of(
                      "location", "Tokyo, Japan",
                      "unit", "celsius"
                  ),
                  Map.of(
                      "location", "New York, NY"
                  )
              )))
              .build())
          .addUserMessage("What's the weather like in San Francisco?")
          .build();

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

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

  $message = $client->messages->create(
      maxTokens: 1024,
      messages: [
          ['role' => 'user', 'content' => "What's the weather like in San Francisco?"]
      ],
      model: 'claude-opus-5-5',
      tools: [
          [
              'name' => 'get_weather',
              'description' => 'Get the current weather in a given location',
              'input_schema' => [
                  'type' => 'object',
                  'properties' => [
                      'location' => [
                          'type' => 'string',
                          'description' => 'The city and state, e.g. San Francisco, CA'
                      ],
                      'unit' => [
                          'type' => 'string',
                          'enum' => ['celsius', 'fahrenheit'],
                          'description' => 'The unit of temperature'
                      ]
                  ],
                  'required' => ['location']
              ],
              'input_examples' => [
                  [
                      'location' => 'San Francisco, CA',
                      'unit' => 'fahrenheit'
                  ],
                  [
                      'location' => 'Tokyo, Japan',
                      'unit' => 'celsius'
                  ],
                  [
                      'location' => 'New York, NY'
                  ]
              ]
          ]
      ],
  );
  ```

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

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: [
      {
        name: "get_weather",
        description: "Get the current weather in a given location",
        input_schema: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "The city and state, e.g. San Francisco, CA"
            },
            unit: {
              type: "string",
              enum: ["celsius", "fahrenheit"],
              description: "The unit of temperature"
            }
          },
          required: ["location"]
        },
        input_examples: [
          {
            location: "San Francisco, CA",
            unit: "fahrenheit"
          },
          {
            location: "Tokyo, Japan",
            unit: "celsius"
          },
          {
            location: "New York, NY"
          }
        ]
      }
    ],
    messages: [
      { role: "user", content: "What's the weather like in San Francisco?" }
    ]
  )
  puts message
  ```
</CodeGroup>

例はツールスキーマとともにプロンプトに含まれ、適切な形式のツール呼び出しの具体的なパターンをClaudeに示します。これにより、Claudeはオプションのパラメータをいつ含めるべきか、どのフォーマットを使用すべきか、複雑な入力をどのように構造化すべきかを理解しやすくなります。

### 要件と制限事項

* **スキーマ検証** - 各例はツールの `input_schema` に従って有効でなければなりません。無効な例は400エラーを返します
* **サーバーサイドツールおよびクライアントツールセットではサポートされない** - 入力例は、[コンピュータ使用](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/computer-use-tool)および[ブラウザ使用](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/browser-use-tool)ツールセットを除くユーザー定義およびAnthropicスキーマのクライアントツールで機能しますが、ウェブ検索やコード実行などのサーバーツールでは機能しません
* **トークンコスト** - 例はプロンプトのトークンを増加させます。シンプルな例で約20〜50トークン、複雑なネストされたオブジェクトで約100〜200トークンです

## Claudeの出力の制御

### ツール使用の強制

場合によっては、Claudeがツールを呼び出さずに直接回答するような場合でも、ユーザーの質問に答えるために特定のツールをClaudeに使用させたいことがあります。これは、リクエストの `tool_choice` フィールドでツールを指定することで実現できます。

すべてのモデルや設定が強制的なツール使用をサポートしているわけではありません。サポートされていない場合、`tool_choice: {"type": "any"}` と `tool_choice: {"type": "tool", "name": "..."}` は失敗しますが、`tool_choice: {"type": "auto"}`（デフォルト）と `tool_choice: {"type": "none"}` は引き続き機能します。

| モデルまたは設定                                                                                                                                  | 制限                                                                                                       | 代替手段                                                                                                                                                                                                                                                                                                 |
| ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 手動の[拡張思考](https://platform.claude.com/docs/ja/build-with-claude/extended-thinking)（`thinking: {type: "enabled"}`）                         | `any`と`tool`はサポートされておらず、エラーになります                                                                         | `auto`または`none`。[適応型思考](https://platform.claude.com/docs/ja/build-with-claude/thinking)自体は強制的なツール使用を妨げません（Claude Opus 5やClaude Haiku 5.5など、デフォルトで思考が有効なモデルはこれを受け付けますが、強制された呼び出しでは思考がスキップされます。レスポンスはツール呼び出しから始まり、`thinking`ブロックは含まれません）。次の行のモデルは、思考の設定に関係なく強制的なツール使用を拒否します                            |
| Claude Opus 5.5、Claude Sonnet 5.5、Claude Fable 5.1、および[Claude Mythos 5.1](https://platform.claude.com/docs/ja/models/mythos-5-1/overview) | `any`と`tool`は[400エラー](https://platform.claude.com/docs/ja/api/errors#forced-tool-use-not-supported)を返します | スキーマに準拠したツール入力を保証するには[厳密なツール使用](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/strict-tool-use)と組み合わせた`auto`を、固定されたJSON形式のレスポンスが必要な場合は[構造化出力](https://platform.claude.com/docs/ja/build-with-claude/structured-outputs)を使用してください。プロンプトは引き続き`auto`がどのツールを選択するかに影響します。`none`もサポートされています |

サポートしているモデルでは、ハイライトされた行が標準的なツール使用リクエストとの唯一の違いです。

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

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5
  max_tokens: 1024
  tools:
    - name: get_weather
      description: Get the current weather in a given location
      input_schema:
        type: object
        properties:
          location:
            type: string
            description: The city and state, e.g. San Francisco, CA
        required: [location]
  tool_choice:
    type: tool
    name: get_weather
  messages:
    - role: user
      content: What's the weather like in San Francisco?
  YAML
  ```

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

  tools = [
      {
          "name": "get_weather",
          "description": "Get the current weather in a given location",
          "input_schema": {
              "type": "object",
              "properties": {
                  "location": {
                      "type": "string",
                      "description": "The city and state, e.g. San Francisco, CA",
                  }
              },
              "required": ["location"],
          },
      }
  ]

  response = client.messages.create(
      model="claude-opus-5",
      max_tokens=1024,
      tools=tools,
      tool_choice={"type": "tool", "name": "get_weather"},
      messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
  )

  print(response)
  ```

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

  const response = await client.messages.create({
    model: "claude-opus-5",
    max_tokens: 1024,
    tools: [
      {
        name: "get_weather",
        description: "Get the current weather in a given location",
        input_schema: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "The city and state, e.g. San Francisco, CA"
            }
          },
          required: ["location"]
        }
      }
    ],
    tool_choice: { type: "tool", name: "get_weather" },
    messages: [{ role: "user", content: "What's the weather like in San Francisco?" }]
  });

  console.log(response);
  ```

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

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5,
      MaxTokens = 1024,
      Tools = [
          new ToolUnion(new Tool()
          {
              Name = "get_weather",
              Description = "Get the current weather in a given location",
              InputSchema = new InputSchema()
              {
                  Properties = new Dictionary<string, JsonElement>
                  {
                      ["location"] = JsonSerializer.SerializeToElement(new { type = "string", description = "The city and state, e.g. San Francisco, CA" }),
                  },
                  Required = ["location"],
              },
          }),
      ],
      ToolChoice = new ToolChoiceTool { Name = "get_weather" },
      Messages = [
          new() { Role = Role.User, Content = "What's the weather like in San Francisco?" }
      ]
  };

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

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

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5,
  	MaxTokens: 1024,
  	Tools: []anthropic.ToolUnionParam{
  		{OfTool: &anthropic.ToolParam{
  			Name:        "get_weather",
  			Description: anthropic.String("Get the current weather in a given location"),
  			InputSchema: anthropic.ToolInputSchemaParam{
  				Properties: map[string]any{
  					"location": map[string]any{
  						"type":        "string",
  						"description": "The city and state, e.g. San Francisco, CA",
  					},
  				},
  				Required: []string{"location"},
  			},
  		}},
  	},
  	ToolChoice: anthropic.ToolChoiceUnionParam{OfTool: &anthropic.ToolChoiceToolParam{Name: "get_weather"}},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather like in San Francisco?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.Tool;
  import com.anthropic.models.messages.Tool.InputSchema;
  import com.anthropic.models.messages.ToolChoice;
  import com.anthropic.models.messages.ToolChoiceTool;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5)
          .maxTokens(1024L)
          .addTool(Tool.builder()
              .name("get_weather")
              .description("Get the current weather in a given location")
              .inputSchema(InputSchema.builder()
                  .properties(JsonValue.from(Map.of(
                      "location", Map.of(
                          "type", "string",
                          "description", "The city and state, e.g. San Francisco, CA"
                      )
                  )))
                  .required(List.of("location"))
                  .build())
              .build())
          .toolChoice(ToolChoice.ofTool(ToolChoiceTool.builder()
              .name("get_weather")
              .build()))
          .addUserMessage("What's the weather like in San Francisco?")
          .build();

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

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

  $message = $client->messages->create(
      maxTokens: 1024,
      messages: [
          ['role' => 'user', 'content' => "What's the weather like in San Francisco?"]
      ],
      model: 'claude-opus-5',
      toolChoice: ['type' => 'tool', 'name' => 'get_weather'],
      tools: [
          [
              'name' => 'get_weather',
              'description' => 'Get the current weather in a given location',
              'input_schema' => [
                  'type' => 'object',
                  'properties' => [
                      'location' => [
                          'type' => 'string',
                          'description' => 'The city and state, e.g. San Francisco, CA'
                      ]
                  ],
                  'required' => ['location']
              ]
          ]
      ],
  );
  ```

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

  message = client.messages.create(
    model: "claude-opus-5",
    max_tokens: 1024,
    tools: [
      {
        name: "get_weather",
        description: "Get the current weather in a given location",
        input_schema: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "The city and state, e.g. San Francisco, CA"
            }
          },
          required: ["location"]
        }
      }
    ],
    tool_choice: { type: "tool", name: "get_weather" },
    messages: [
      { role: "user", content: "What's the weather like in San Francisco?" }
    ]
  )
  puts message
  ```
</CodeGroup>

`tool_choice` パラメータを使用する場合、4つの選択肢があります。

* `auto` は、提供されたツールを呼び出すかどうかをClaudeが判断できるようにします。これは `tools` が提供されている場合のデフォルト値です。
* `any` は、提供されたツールのいずれかを必ず使用するようClaudeに指示しますが、特定のツールを強制するものではありません。
* `tool` は、Claudeに常に特定のツールを使用させます。
* `none` は、Claudeがいかなるツールも使用しないようにします。これは `tools` が提供されていない場合のデフォルト値です。

<Note>
  [プロンプトキャッシング](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching#what-invalidates-the-cache)を使用している場合、`tool_choice` パラメータを変更するとキャッシュされたメッセージブロックが無効になります。ツール定義とシステムプロンプトはキャッシュされたままですが、メッセージの内容は再処理する必要があります。
</Note>

この図は各オプションがどのように機能するかを示しています。

<Frame>
  ![3つのtool\_choiceオプションの図：auto（ツールまたは通常の応答）、any（いずれかのツール）、tool（指定されたツール）](https://platform.claude.com/docs/images/tool_choice.svg)
</Frame>

`tool_choice` を `any` または `tool` に設定した場合、APIはツールの使用を強制するためにアシスタントメッセージをプリフィルすることに注意してください。これは、明示的に求められた場合でも、モデルが `tool_use` コンテンツブロックの前に自然言語による応答や説明を出力しないことを意味します。

テストでは、これによってパフォーマンスが低下することはないと示されています。モデルに特定のツールの使用を求めつつ、自然言語によるコンテキストや説明も提供させたい場合は、`tool_choice` に `{"type": "auto"}`（デフォルト）を使用し、`user` メッセージに明示的な指示を追加できます。例：`What's the weather like in London? Use the get_weather tool in your response.`

ツールを強制すると、強制的なツール使用を受け付けるすべてのモデルで思考もスキップされます。レスポンスは`tool_use`ブロックから始まり、`thinking`ブロックは含まれません。ツールを呼び出す前にモデルに思考させるには、同様に`auto`とプロンプトでの指示を組み合わせて使用してください。

<Tip>
  **厳密なツールによるツール呼び出しの保証**

  強制的なツール使用をサポートするモデルでは、`tool_choice: {"type": "any"}` と[厳密なツール使用](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/strict-tool-use)を組み合わせることで、ツールのいずれかが呼び出されることと、ツール入力がスキーマに厳密に従うことの両方を保証できます。スキーマ検証を有効にするには、ツール定義に `strict: true` を設定してください。
</Tip>

### ツールを使用したモデルの応答

ツールを使用する際、Claudeはツールを呼び出す前に、自分が何をしているかについてコメントしたり、ユーザーに自然に応答したりすることがよくあります。

例えば、「What's the weather like in San Francisco right now, and what time is it there?」というプロンプトに対して、Claudeは次のように応答するかもしれません。

```json JSON
{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll help you check the current weather and time in San Francisco."
    },
    {
      "type": "tool_use",
      "id": "toolu_01A09q90qw90lq917835lq9",
      "name": "get_weather",
      "input": { "location": "San Francisco, CA" }
    }
  ]
}
```

この自然な応答スタイルは、ユーザーがClaudeが何をしているかを理解するのに役立ち、より会話的なやり取りを生み出します。システムプロンプトやプロンプト内に `<examples>` を提供することで、これらの応答のスタイルや内容を誘導できます。

Claudeは自身の行動を説明する際にさまざまな言い回しやアプローチを使用する可能性があることに注意することが重要です。コードではこれらの応答を他のアシスタント生成テキストと同様に扱い、特定のフォーマット規則に依存しないようにしてください。

## 次のステップ

<CardGroup>
  <Card href="https://platform.claude.com/docs/ja/agents-and-tools/tool-use/handle-tool-calls" title="ツール呼び出しの処理">
    tool\_useブロックを解析し、tool\_resultレスポンスをフォーマットします。
  </Card>

  <Card href="https://platform.claude.com/docs/ja/agents-and-tools/tool-use/tool-runner" title="Tool Runner（SDK）">
    SDKにエージェントループを自動的に処理させます。
  </Card>

  <Card href="https://platform.claude.com/docs/ja/agents-and-tools/tool-use/tool-reference" title="ツールリファレンス">
    Anthropicが提供するツールとオプションプロパティの一覧。
  </Card>
</CardGroup>
