---
title: プログラマティックツール呼び出し
url: https://platform.claude.com/docs/ja/agents-and-tools/tool-use/programmatic-tool-calling
description: コード実行コンテナ内のコードからClaudeがツールを呼び出せるようにし、複数ツールを使うワークフローでのモデルとの往復回数とトークン使用量を削減します。
featureMetadata:
  status: ga
  zdr: not-eligible
  supportedModels:
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-opus-5-5
    - claude-opus-5
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-sonnet-4-6
    - claude-sonnet-4-5-20250929
    - claude-haiku-5-5
  supportedPlatforms:
    Claude API: ga
    Claude Platform on AWS: ga
    Microsoft Foundry:
      availability: ga
      note: "[Microsoft Foundry](https://platform.claude.com/docs/ja/build-with-claude/claude-in-microsoft-foundry)では、プログラマティックツール呼び出しには[Hosted on Anthropicデプロイメント](https://platform.claude.com/docs/ja/build-with-claude/claude-in-microsoft-foundry#additional-features-not-supported-when-hosted-on-azure)が必要です。"
  details:
    - プログラマティックツール呼び出しには、`code_execution_20260120`以降の[ツールバージョン](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#tool-versions)のコード実行ツールが必要です。
    - Claude Haiku 4.5は`code_execution_20260120`以降のツールバージョンを受け付けますが、プログラマティックツール呼び出しはサポートしていません。
---

「programmatic tool calling」（プログラマティックツール呼び出し）を使用すると、Claudeはツール呼び出しごとにモデルを経由するラウンドトリップを必要とせず、[コード実行](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool)コンテナ内でツールをプログラム的に呼び出すコードを記述できます。これにより、複数ツールのワークフローにおける「latency」（レイテンシ）が削減され、データがモデルの「context window」（コンテキストウィンドウ）に到達する前にClaudeがフィルタリングや処理を行えるため、トークン消費量も減少します。複数ステップのウェブリサーチや複雑な情報検索をテストする[BrowseComp](https://arxiv.org/abs/2504.12516)や[DeepSearchQA](https://github.com/google-deepmind/deepsearchqa)などのエージェント型検索ベンチマークでは、基本的な検索ツールにプログラマティックツール呼び出しを追加することで、入力トークンを24%削減しながらパフォーマンスが平均11%向上しました（[動的フィルタリングによるウェブ検索の改善](https://claude.com/blog/improved-web-search-with-dynamic-filtering)を参照）。

20人の従業員の予算遵守状況を確認する場合を考えてみましょう。従来のアプローチでは20回の個別のモデルラウンドトリップが必要で、その過程で数千件の経費明細がコンテキストに取り込まれます。プログラマティックツール呼び出しでは、1つのスクリプトが20件すべての検索を実行し、結果をフィルタリングして、上限を超えた従業員のみを返します。これにより、Claudeが推論する必要のある情報が数百キロバイトからわずか数行にまで縮小されます。

<Tip>
  プログラマティックツール呼び出しが対処する推論コストとコンテキストコストについて詳しくは、[高度なツール使用](https://www.anthropic.com/engineering/advanced-tool-use)を参照してください。
</Tip>

プログラマティックツール呼び出しには、ツールバージョン`code_execution_20260120`以降の[コード実行ツール](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool)が必要です。リクエストを送信する前にモデルがプログラマティックツール呼び出しをサポートしているかどうかを確認するには、Models APIからそのモデルの`capabilities.code_execution.supported`の値を読み取ってください。このフィールドについては[Models APIの使用](https://platform.claude.com/docs/ja/models/overview#using-the-models-api)で説明しています。

## クイックスタート

以下は、Claudeがデータベースをプログラム的に複数回クエリし、結果を集計する例です。ツール定義に`allowed_callers: ["code_execution_20260120"]`を追加することで、そのツールがコード実行内から呼び出し可能になります（[`allowed_callers`フィールド](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/programmatic-tool-calling#the-allowed-callers-field)を参照）。

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
      --header "x-api-key: $ANTHROPIC_API_KEY" \
      --header "anthropic-version: 2023-06-01" \
      --header "content-type: application/json" \
      --data '{
          "model": "claude-opus-5-5",
          "max_tokens": 4096,
          "messages": [
              {
                  "role": "user",
                  "content": "Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue"
              }
          ],
          "tools": [
              {
                  "type": "code_execution_20260120",
                  "name": "code_execution"
              },
              {
                  "name": "query_database",
                  "description": "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
                  "input_schema": {
                      "type": "object",
                      "properties": {
                          "sql": {
                              "type": "string",
                              "description": "SQL query to execute"
                          }
                      },
                      "required": ["sql"]
                  },
                  "allowed_callers": ["code_execution_20260120"]
              }
          ]
      }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 4096
  messages:
    - role: user
      content: >-
        Query sales data for the West, East, and Central regions, then
        tell me which region had the highest revenue
  tools:
    - type: code_execution_20260120
      name: code_execution
    - name: query_database
      description: >-
        Execute a SQL query against the sales database. Returns a list
        of rows as JSON objects.
      input_schema:
        type: object
        properties:
          sql:
            type: string
            description: SQL query to execute
        required:
          - sql
      allowed_callers:
        - code_execution_20260120
  YAML
  ```

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

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[
          {
              "role": "user",
              "content": "Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue",
          }
      ],
      tools=[
          {"type": "code_execution_20260120", "name": "code_execution"},
          {
              "name": "query_database",
              "description": "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
              "input_schema": {
                  "type": "object",
                  "properties": {
                      "sql": {"type": "string", "description": "SQL query to execute"}
                  },
                  "required": ["sql"],
              },
              "allowed_callers": ["code_execution_20260120"],
          },
      ],
  )

  print(response)
  ```

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

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content:
          "Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue"
      }
    ],
    tools: [
      {
        type: "code_execution_20260120",
        name: "code_execution"
      },
      {
        name: "query_database",
        description:
          "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
        input_schema: {
          type: "object" as const,
          properties: {
            sql: {
              type: "string",
              description: "SQL query to execute"
            }
          },
          required: ["sql"]
        },
        allowed_callers: ["code_execution_20260120"]
      }
    ]
  });

  console.log(response);
  ```

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

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [
          new() {
              Role = Role.User,
              Content = "Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue"
          }
      ],
      Tools = [
          new CodeExecutionTool20260120(),
          new ToolUnion(new Tool()
          {
              Name = "query_database",
              Description = "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
              InputSchema = new InputSchema()
              {
                  Properties = new Dictionary<string, JsonElement>
                  {
                      ["sql"] = JsonSerializer.SerializeToElement(new { type = "string", description = "SQL query to execute" }),
                  },
                  Required = ["sql"],
              },
              AllowedCallers = ["code_execution_20260120"]
          }),
      ]
  };

  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: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue")),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfCodeExecutionTool20260120: &anthropic.CodeExecutionTool20260120Param{}},
  		{OfTool: &anthropic.ToolParam{
  			Name:        "query_database",
  			Description: anthropic.String("Execute a SQL query against the sales database. Returns a list of rows as JSON objects."),
  			InputSchema: anthropic.ToolInputSchemaParam{
  				Properties: map[string]any{
  					"sql": map[string]any{
  						"type":        "string",
  						"description": "SQL query to execute",
  					},
  				},
  				Required: []string{"sql"},
  			},
  			AllowedCallers: []string{"code_execution_20260120"},
  		}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.CodeExecutionTool20260120;
  // ...

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

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessage("Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue")
          .addTool(CodeExecutionTool20260120.builder().build())
          .addTool(Tool.builder()
              .name("query_database")
              .description("Execute a SQL query against the sales database. Returns a list of rows as JSON objects.")
              .inputSchema(InputSchema.builder()
                  .properties(JsonValue.from(Map.of(
                      "sql", Map.of(
                          "type", "string",
                          "description", "SQL query to execute"
                      )
                  )))
                  .putAdditionalProperty("required", JsonValue.from(List.of("sql")))
                  .build())
              .allowedCallers(List.of(Tool.AllowedCaller.of("code_execution_20260120")))
              .build())
          .build();

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

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

  $message = $client->messages->create(
      maxTokens: 4096,
      messages: [
          ['role' => 'user', 'content' => 'Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue'],
      ],
      model: 'claude-opus-5-5',
      tools: [
          [
              'type' => 'code_execution_20260120',
              'name' => 'code_execution',
          ],
          [
              'name' => 'query_database',
              'description' => 'Execute a SQL query against the sales database. Returns a list of rows as JSON objects.',
              'input_schema' => [
                  'type' => 'object',
                  'properties' => [
                      'sql' => [
                          'type' => 'string',
                          'description' => 'SQL query to execute',
                      ],
                  ],
                  'required' => ['sql'],
              ],
              'allowed_callers' => ['code_execution_20260120'],
          ],
      ],
  );

  echo $message;
  ```

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

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue"
      }
    ],
    tools: [
      {
        type: "code_execution_20260120",
        name: "code_execution"
      },
      {
        name: "query_database",
        description: "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
        input_schema: {
          type: "object",
          properties: {
            sql: {
              type: "string",
              description: "SQL query to execute"
            }
          },
          required: ["sql"]
        },
        allowed_callers: ["code_execution_20260120"]
      }
    ]
  )

  puts message
  ```
</CodeGroup>

レスポンスは`stop_reason: "tool_use"`、`container` ID、および`query_database`の`tool_use`ブロックとともに停止します。このブロックの`caller`フィールドは、それを呼び出したコード実行の実行を識別します。コードが完了できるように、[ワークフロー例のステップ3](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/programmatic-tool-calling#step-3-provide-tool-result)に示すように結果を返してください。

## プログラマティックツール呼び出しの仕組み

ツールをコード実行から呼び出し可能に設定し、Claudeがそのツールが必要だと判断した場合：

1. Claudeはツールを関数として呼び出すPythonコードを記述します。複数のツール呼び出しや前処理・後処理ロジックを含む場合もあります
2. Claudeはコード実行を通じて、サンドボックス化されたコンテナ内でこのコードを実行します
3. ツール関数が呼び出されると、コード実行は一時停止し、APIは`tool_use`ブロックを返します
4. ツール結果を提供すると、コード実行が続行されます（中間結果はClaudeのコンテキストウィンドウに読み込まれません）
5. すべてのコード実行が完了すると、Claudeは最終出力を受け取り、タスクの作業を続行します

このアプローチは特に以下の場合に有用です：

* **大規模データ処理：** ツール結果がClaudeのコンテキストに到達する前にフィルタリングまたは集計する
* **複数ステップのワークフロー：** ツール呼び出しの間にClaudeをサンプリングすることなく、ツールを順次またはループで呼び出すことでトークンとレイテンシを節約する
* **条件付きロジック：** 中間のツール結果に基づいて判断を行う

<Note>
  コード実行の呼び出し元を許可するツールは、Claudeのコードに非同期Python関数として公開されるため、Claudeは`asyncio.gather`を使用してそれらを並列実行できます。各関数は引数の単一のdictを受け取り、文字列（送り返す`tool_result`のテキスト）を返します。Claudeのコードはトップレベルの`await`でこれらの関数を待機し、必要な結果を構造化データとして解析します。例：`rows = json.loads(await query_database({"sql": "<sql>"}))`。
</Note>

## コアコンセプト

### `allowed_callers`フィールド

`allowed_callers`フィールドは、どのコンテキストがツールを呼び出せるかを指定します：

```json
{
  "name": "query_database",
  "description": "Execute a SQL query against the database",
  "input_schema": {
    // ...
  },
  "allowed_callers": ["code_execution_20260120"]
}
```

**指定可能な値：**

* `["direct"]` - Claudeはこのツールを直接呼び出すよう誘導されます（省略時のデフォルト）
* `["code_execution_20260120"]` - Claudeはこのツールをコード実行内からのみ呼び出すよう誘導されます
* `["direct", "code_execution_20260120"]` - Claudeはこのツールを直接またはコード実行内から呼び出すことができます

`"code_execution_20260120"`と`"code_execution_20260521"`はどちらも`allowed_callers`で受け付けられ、相互に交換可能です。いずれかのコード実行ツールバージョンを使用するリクエストは、いずれかの呼び出し元をリストするツールの条件を満たします。レスポンスブロックは、リクエストがどのバージョンを宣言したかに関係なく、常に呼び出し元を`code_execution_20260120`としてタグ付けします。

<Tip>
  各ツールについて、両方を有効にするのではなく`["direct"]`または`["code_execution_20260120"]`のいずれかを選択してください。これにより、ツールの最適な使用方法についてClaudeにより明確なガイダンスが提供されます。
</Tip>

<Note>
  `allowed_callers`はツールがClaudeにどのように提示されるかを制御し、`tool_choice`に対して検証されますが、直接呼び出しに対するAPIレベルの厳格なブロックではありません。Claudeはこれを尊重するよう強く誘導されますが、クライアントは定義したすべてのツールについて直接の`tool_use`を処理できるよう準備しておく必要があります。`allowed_callers`をセキュリティ境界として依存しないでください。
</Note>

### レスポンス内の`caller`フィールド

すべてのツール使用ブロックには、どのように呼び出されたかを示す`caller`フィールドが含まれます：

**直接呼び出し（従来のツール使用）：**

```json
{
  "type": "tool_use",
  "id": "toolu_abc123",
  "name": "query_database",
  "input": { "sql": "<sql>" },
  "caller": { "type": "direct" }
}
```

**プログラマティック呼び出し：**

```json
{
  "type": "tool_use",
  "id": "toolu_xyz789",
  "name": "query_database",
  "input": { "sql": "<sql>" },
  "caller": {
    "type": "code_execution_20260120",
    "tool_id": "srvtoolu_abc123"
  }
}
```

`tool_id`は呼び出しを行ったコード実行の`server_tool_use`ブロックの`id`であるため、各プログラマティック`tool_use`をそれを生成したコード実行の実行と照合できます。

### コンテナのライフサイクル

プログラマティックツール呼び出しは、コード実行と同じコンテナを使用します：

* **コンテナの作成：** 既存のコンテナを再利用しない限り、リクエストごとに新しいコンテナが作成されます
* **コンテナID：** レスポンスの`container`フィールドに、`expires_at`タイムスタンプとともに返されます
* **再利用：** 状態を保持するには、次のリクエストでコンテナIDを渡します。プログラマティックツール呼び出しが結果を待機している間、そのリクエストではコンテナIDは任意ではなく必須です。APIはコンテナIDのないリクエストを拒否します。
* **有効期限：** `expires_at`はコンテナの残り時間を示します。アイドル状態のコンテナは現在約5分後に回収され、作成から30日を超えてコンテナを再利用することはできません。

<Warning>
  Claudeのコードがプログラマティックツール結果を待機している間、保留中の呼び出しは約4分後にタイムアウトし、コード内で`TimeoutError`が発生します。一時停止したレスポンスの`expires_at`タイムスタンプより十分前に各ツール結果を返してください。[ツール呼び出し中のコンテナの有効期限切れ](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/programmatic-tool-calling#container-expiration-during-tool-call)を参照してください。
</Warning>

## ワークフロー例

完全なプログラマティックツール呼び出しフローの仕組みは以下のとおりです：

### ステップ1：最初のリクエスト

コード実行と、プログラマティック呼び出しを許可するツールを含むリクエストを送信します。プログラマティック呼び出しを有効にするには、ツール定義に`allowed_callers`フィールドを追加します。

<Note>
  ツールの説明に、ツールの出力形式の詳細な説明を記載してください。ツールがJSONを返すと指定した場合、Claudeはコード内で結果をデシリアライズして処理しようとします。出力スキーマについて詳細を提供するほど、Claudeはレスポンスをプログラム的により適切に処理できます。
</Note>

リクエストの形式は[クイックスタート](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/programmatic-tool-calling#quick-start)の例と同一です。ツールリストに`code_execution`を含め、Claudeにコードから呼び出させたいツールに`allowed_callers: ["code_execution_20260120"]`を追加し、ユーザーメッセージを送信します。このワークフローの残りのステップでは、ユーザーメッセージ`"Query customer purchase history from the last quarter and identify our top 5 customers by revenue"`を使用します。

### ステップ2：ツール呼び出しを含むAPIレスポンス

Claudeはツールを呼び出すコードを記述します。APIは一時停止し、以下を返します：

```json Output
{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll query the purchase history and analyze the results."
    },
    {
      "type": "server_tool_use",
      "id": "srvtoolu_abc123",
      "name": "code_execution",
      "input": {
        "code": "import json\n\nrows = json.loads(await query_database({'sql': '<sql>'}))\ntop_customers = sorted(rows, key=lambda x: x['revenue'], reverse=True)[:5]\nprint(f'Top 5 customers: {top_customers}')"
      }
    },
    {
      "type": "tool_use",
      "id": "toolu_def456",
      "name": "query_database",
      "input": { "sql": "<sql>" },
      "caller": {
        "type": "code_execution_20260120",
        "tool_id": "srvtoolu_abc123"
      }
    }
  ],
  "container": {
    "id": "container_xyz789",
    "expires_at": "2026-01-20T14:30:00Z"
  },
  "stop_reason": "tool_use"
}
```

### ステップ3：ツール結果の提供

完全な会話履歴とツール結果を送信します。このリクエストでは3つの点が重要です：

* 結果を含むユーザーメッセージには`tool_result`ブロックのみを含めることができます。[メッセージ形式の制限](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/programmatic-tool-calling#message-formatting-restrictions)を参照してください。
* 一時停止したレスポンスの`container` IDを渡します。APIは、保留中のプログラマティックツール呼び出しがあるにもかかわらずコンテナIDのない継続リクエストを拒否します。
* 元のリクエストと同じ`tools`配列を送信します。一時停止したコードを再開するにはコード実行ツールが引き続き存在している必要があり、このリクエストで送信するツールは、ターンの残りの間Claudeと実行中のコードが使用できる定義となります。

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
      --header "x-api-key: $ANTHROPIC_API_KEY" \
      --header "anthropic-version: 2023-06-01" \
      --header "content-type: application/json" \
      --data '{
          "model": "claude-opus-5-5",
          "max_tokens": 4096,
          "container": "container_xyz789",
          "messages": [
              {
                  "role": "user",
                  "content": "Query customer purchase history from the last quarter and identify our top 5 customers by revenue"
              },
              {
                  "role": "assistant",
                  "content": [
                      {
                          "type": "text",
                          "text": "I'\''ll query the purchase history and analyze the results."
                      },
                      {
                          "type": "server_tool_use",
                          "id": "srvtoolu_abc123",
                          "name": "code_execution",
                          "input": {"code": "..."}
                      },
                      {
                          "type": "tool_use",
                          "id": "toolu_def456",
                          "name": "query_database",
                          "input": {"sql": "<sql>"},
                          "caller": {
                              "type": "code_execution_20260120",
                              "tool_id": "srvtoolu_abc123"
                          }
                      }
                  ]
              },
              {
                  "role": "user",
                  "content": [
                      {
                          "type": "tool_result",
                          "tool_use_id": "toolu_def456",
                          "content": "[{\"customer_id\": \"C1\", \"revenue\": 45000}, {\"customer_id\": \"C2\", \"revenue\": 38000}]"
                      }
                  ]
              }
          ],
          "tools": [
              {
                  "type": "code_execution_20260120",
                  "name": "code_execution"
              },
              {
                  "name": "query_database",
                  "description": "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
                  "input_schema": {
                      "type": "object",
                      "properties": {
                          "sql": {
                              "type": "string",
                              "description": "SQL query to execute"
                          }
                      },
                      "required": ["sql"]
                  },
                  "allowed_callers": ["code_execution_20260120"]
              }
          ]
      }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 4096
  container: container_xyz789
  messages:
    - role: user
      content: >-
        Query customer purchase history from the last quarter and identify our
        top 5 customers by revenue
    - role: assistant
      content:
        - type: text
          text: I'll query the purchase history and analyze the results.
        - type: server_tool_use
          id: srvtoolu_abc123
          name: code_execution
          input:
            code: "..."
        - type: tool_use
          id: toolu_def456
          name: query_database
          input:
            sql: "<sql>"
          caller:
            type: code_execution_20260120
            tool_id: srvtoolu_abc123
    - role: user
      content:
        - type: tool_result
          tool_use_id: toolu_def456
          content: >-
            [{"customer_id": "C1", "revenue": 45000}, {"customer_id": "C2",
            "revenue": 38000}, ...]
  # 元のリクエストと同じ tools 配列です
  tools:
    - type: code_execution_20260120
      name: code_execution
    - name: query_database
      description: >-
        Execute a SQL query against the sales database. Returns a list
        of rows as JSON objects.
      input_schema:
        type: object
        properties:
          sql:
            type: string
            description: SQL query to execute
        required:
          - sql
      allowed_callers:
        - code_execution_20260120
  YAML
  ```

  ```python Python
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      container="container_xyz789",  # Reuse the container
      messages=[
          {
              "role": "user",
              "content": "Query customer purchase history from the last quarter and identify our top 5 customers by revenue",
          },
          {
              "role": "assistant",
              "content": [
                  {
                      "type": "text",
                      "text": "I'll query the purchase history and analyze the results.",
                  },
                  {
                      "type": "server_tool_use",
                      "id": "srvtoolu_abc123",
                      "name": "code_execution",
                      "input": {"code": "..."},
                  },
                  {
                      "type": "tool_use",
                      "id": "toolu_def456",
                      "name": "query_database",
                      "input": {"sql": "<sql>"},
                      "caller": {
                          "type": "code_execution_20260120",
                          "tool_id": "srvtoolu_abc123",
                      },
                  },
              ],
          },
          {
              "role": "user",
              "content": [
                  {
                      "type": "tool_result",
                      "tool_use_id": "toolu_def456",
                      "content": '[{"customer_id": "C1", "revenue": 45000}, {"customer_id": "C2", "revenue": 38000}, ...]',
                  }
              ],
          },
      ],
      # 元のリクエストと同じ tools 配列です
      tools=[
          {"type": "code_execution_20260120", "name": "code_execution"},
          {
              "name": "query_database",
              "description": "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
              "input_schema": {
                  "type": "object",
                  "properties": {
                      "sql": {"type": "string", "description": "SQL query to execute"}
                  },
                  "required": ["sql"],
              },
              "allowed_callers": ["code_execution_20260120"],
          },
      ],
  )

  print(response)
  ```

  ```typescript TypeScript
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    container: "container_xyz789", // Reuse the container
    messages: [
      {
        role: "user",
        content:
          "Query customer purchase history from the last quarter and identify our top 5 customers by revenue"
      },
      {
        role: "assistant",
        content: [
          { type: "text", text: "I'll query the purchase history and analyze the results." },
          {
            type: "server_tool_use",
            id: "srvtoolu_abc123",
            name: "code_execution",
            input: { code: "..." }
          },
          {
            type: "tool_use",
            id: "toolu_def456",
            name: "query_database",
            input: { sql: "<sql>" },
            caller: {
              type: "code_execution_20260120",
              tool_id: "srvtoolu_abc123"
            }
          }
        ]
      },
      {
        role: "user",
        content: [
          {
            type: "tool_result",
            tool_use_id: "toolu_def456",
            content:
              '[{"customer_id": "C1", "revenue": 45000}, {"customer_id": "C2", "revenue": 38000}, ...]'
          }
        ]
      }
    ],
    // 元のリクエストと同じ tools 配列です
    tools: [
      {
        type: "code_execution_20260120",
        name: "code_execution"
      },
      {
        name: "query_database",
        description:
          "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
        input_schema: {
          type: "object" as const,
          properties: {
            sql: {
              type: "string",
              description: "SQL query to execute"
            }
          },
          required: ["sql"]
        },
        allowed_callers: ["code_execution_20260120"]
      }
    ]
  });

  console.log(response);
  ```

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

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Container = "container_xyz789",
      Messages =
      [
          new()
          {
              Role = Role.User,
              Content = "Query customer purchase history from the last quarter and identify our top 5 customers by revenue"
          },
          new()
          {
              Role = Role.Assistant,
              Content = new ContentBlock[]
              {
                  new TextBlock { Text = "I'll query the purchase history and analyze the results." },
                  new ServerToolUseBlock
                  {
                      Id = "srvtoolu_abc123",
                      Name = "code_execution",
                      Input = new { code = "..." }
                  },
                  new ToolUseBlock
                  {
                      Id = "toolu_def456",
                      Name = "query_database",
                      Input = new { sql = "<sql>" },
                      Caller = new ToolCaller
                      {
                          Type = "code_execution_20260120",
                          ToolId = "srvtoolu_abc123"
                      }
                  }
              }
          },
          new()
          {
              Role = Role.User,
              Content = new ContentBlockParam[]
              {
                  new ToolResultBlockParam
                  {
                      ToolUseID = "toolu_def456",
                      Content = "[{\"customer_id\": \"C1\", \"revenue\": 45000}, {\"customer_id\": \"C2\", \"revenue\": 38000}, ...]"
                  }
              }
          }
      ],
      // 元のリクエストと同じ tools 配列です
      Tools = [
          new CodeExecutionTool20260120(),
          new ToolUnion(new Tool()
          {
              Name = "query_database",
              Description = "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
              InputSchema = new InputSchema()
              {
                  Properties = new Dictionary<string, JsonElement>
                  {
                      ["sql"] = JsonSerializer.SerializeToElement(new { type = "string", description = "SQL query to execute" }),
                  },
                  Required = ["sql"],
              },
              AllowedCallers = ["code_execution_20260120"]
          }),
      ]
  };

  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: 4096,
  	Container: anthropic.MessageCreateParamsContainerUnion{
  		OfString: anthropic.String("container_xyz789"),
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Query customer purchase history from the last quarter and identify our top 5 customers by revenue")),
  		{
  			Role: anthropic.MessageParamRoleAssistant,
  			Content: []anthropic.ContentBlockParamUnion{
  				anthropic.NewTextBlock("I'll query the purchase history and analyze the results."),
  				{OfServerToolUse: &anthropic.ServerToolUseBlockParam{
  					ID:    "srvtoolu_abc123",
  					Name:  anthropic.ServerToolUseBlockParamNameCodeExecution,
  					Input: map[string]any{"code": "..."},
  				}},
  				{OfToolUse: &anthropic.ToolUseBlockParam{
  					ID:    "toolu_def456",
  					Name:  "query_database",
  					Input: map[string]any{"sql": "<sql>"},
  					Caller: anthropic.ServerToolUseBlockParamCallerUnion{
  						OfCodeExecution20260120: &anthropic.ServerToolCaller20260120Param{
  							ToolID: "srvtoolu_abc123",
  						},
  					},
  				}},
  			},
  		},
  		{
  			Role: anthropic.MessageParamRoleUser,
  			Content: []anthropic.ContentBlockParamUnion{
  				{OfToolResult: &anthropic.ToolResultBlockParam{
  					ToolUseID: "toolu_def456",
  					Content: []anthropic.ToolResultBlockParamContentUnion{
  						{OfText: &anthropic.TextBlockParam{
  							Text: `[{"customer_id": "C1", "revenue": 45000}, {"customer_id": "C2", "revenue": 38000}, ...]`,
  						}},
  					},
  				}},
  			},
  		},
  	},
  	// 元のリクエストと同じ tools 配列です
  	Tools: []anthropic.ToolUnionParam{
  		{OfCodeExecutionTool20260120: &anthropic.CodeExecutionTool20260120Param{}},
  		{OfTool: &anthropic.ToolParam{
  			Name:        "query_database",
  			Description: anthropic.String("Execute a SQL query against the sales database. Returns a list of rows as JSON objects."),
  			InputSchema: anthropic.ToolInputSchemaParam{
  				Properties: map[string]any{
  					"sql": map[string]any{
  						"type":        "string",
  						"description": "SQL query to execute",
  					},
  				},
  				Required: []string{"sql"},
  			},
  			AllowedCallers: []string{"code_execution_20260120"},
  		}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.CodeExecutionTool20260120;
  // ...

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

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .container("container_xyz789")
          .addUserMessage("Query customer purchase history from the last quarter and identify our top 5 customers by revenue")
          .addAssistantMessageOfBlockParams(List.of(
              ContentBlockParam.ofText(
                  TextBlockParam.builder()
                      .text("I'll query the purchase history and analyze the results.")
                      .build()),
              ContentBlockParam.ofServerToolUse(
                  ServerToolUseBlockParam.builder()
                      .id("srvtoolu_abc123")
                      .name("code_execution")
                      .input(JsonValue.from(Map.of("code", "...")))
                      .build()),
              ContentBlockParam.ofToolUse(
                  ToolUseBlockParam.builder()
                      .id("toolu_def456")
                      .name("query_database")
                      .input(JsonValue.from(Map.of("sql", "<sql>")))
                      .codeExecution20260120Caller("srvtoolu_abc123")
                      .build())
          ))
          .addUserMessageOfBlockParams(List.of(
              ContentBlockParam.ofToolResult(
                  ToolResultBlockParam.builder()
                      .toolUseId("toolu_def456")
                      .content("[{\"customer_id\": \"C1\", \"revenue\": 45000}, {\"customer_id\": \"C2\", \"revenue\": 38000}, ...]")
                      .build())
          ))
          // 元のリクエストと同じ tools 配列です
          .addTool(CodeExecutionTool20260120.builder().build())
          .addTool(Tool.builder()
              .name("query_database")
              .description("Execute a SQL query against the sales database. Returns a list of rows as JSON objects.")
              .inputSchema(InputSchema.builder()
                  .properties(JsonValue.from(Map.of(
                      "sql", Map.of(
                          "type", "string",
                          "description", "SQL query to execute"
                      )
                  )))
                  .putAdditionalProperty("required", JsonValue.from(List.of("sql")))
                  .build())
              .allowedCallers(List.of(Tool.AllowedCaller.of("code_execution_20260120")))
              .build())
          .build();

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

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

  $message = $client->messages->create(
      maxTokens: 4096,
      messages: [
          [
              'role' => 'user',
              'content' => 'Query customer purchase history from the last quarter and identify our top 5 customers by revenue',
          ],
          [
              'role' => 'assistant',
              'content' => [
                  [
                      'type' => 'text',
                      'text' => "I'll query the purchase history and analyze the results.",
                  ],
                  [
                      'type' => 'server_tool_use',
                      'id' => 'srvtoolu_abc123',
                      'name' => 'code_execution',
                      'input' => ['code' => '...'],
                  ],
                  [
                      'type' => 'tool_use',
                      'id' => 'toolu_def456',
                      'name' => 'query_database',
                      'input' => ['sql' => '<sql>'],
                      'caller' => [
                          'type' => 'code_execution_20260120',
                          'tool_id' => 'srvtoolu_abc123',
                      ],
                  ],
              ],
          ],
          [
              'role' => 'user',
              'content' => [
                  [
                      'type' => 'tool_result',
                      'tool_use_id' => 'toolu_def456',
                      'content' => '[{"customer_id": "C1", "revenue": 45000}, {"customer_id": "C2", "revenue": 38000}, ...]',
                  ],
              ],
          ],
      ],
      model: 'claude-opus-5-5',
      container: 'container_xyz789',
      // 元のリクエストと同じ tools 配列です
      tools: [
          [
              'type' => 'code_execution_20260120',
              'name' => 'code_execution',
          ],
          [
              'name' => 'query_database',
              'description' => 'Execute a SQL query against the sales database. Returns a list of rows as JSON objects.',
              'input_schema' => [
                  'type' => 'object',
                  'properties' => [
                      'sql' => [
                          'type' => 'string',
                          'description' => 'SQL query to execute',
                      ],
                  ],
                  'required' => ['sql'],
              ],
              'allowed_callers' => ['code_execution_20260120'],
          ],
      ],
  );

  echo $message;
  ```

  ```ruby Ruby
  require "anthropic"

  client = Anthropic::Client.new

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 4096,
    container: "container_xyz789",
    messages: [
      {
        role: "user",
        content: "Query customer purchase history from the last quarter and identify our top 5 customers by revenue"
      },
      {
        role: "assistant",
        content: [
          {
            type: "text",
            text: "I'll query the purchase history and analyze the results."
          },
          {
            type: "server_tool_use",
            id: "srvtoolu_abc123",
            name: "code_execution",
            input: { code: "..." }
          },
          {
            type: "tool_use",
            id: "toolu_def456",
            name: "query_database",
            input: { sql: "<sql>" },
            caller: {
              type: "code_execution_20260120",
              tool_id: "srvtoolu_abc123"
            }
          }
        ]
      },
      {
        role: "user",
        content: [
          {
            type: "tool_result",
            tool_use_id: "toolu_def456",
            content: '[{"customer_id": "C1", "revenue": 45000}, {"customer_id": "C2", "revenue": 38000}, ...]'
          }
        ]
      }
    ],
    # 元のリクエストと同じ tools 配列です
    tools: [
      {
        type: "code_execution_20260120",
        name: "code_execution"
      },
      {
        name: "query_database",
        description: "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
        input_schema: {
          type: "object",
          properties: {
            sql: {
              type: "string",
              description: "SQL query to execute"
            }
          },
          required: ["sql"]
        },
        allowed_callers: ["code_execution_20260120"]
      }
    ]
  )

  puts message
  ```
</CodeGroup>

### ステップ4：次のツール呼び出しまたは完了

コードは一時停止した箇所から再開し、結果を処理します。各継続レスポンスは、さらにプログラマティック`tool_use`ブロックを伴って再び一時停止するか、コード実行を完了してClaudeにターンを続行させます（ステップ5）。この2つを区別するには、`stop_reason`と各`tool_use`ブロックの`caller`を確認します。あなたのために一時停止するレスポンスには`stop_reason: "tool_use"`と、`caller`がコード実行バージョンを指す`tool_use`ブロックがあり、その場合は保留中のすべてのプログラマティック呼び出しに対する`tool_result`を1つのユーザーメッセージにまとめてステップ3を繰り返します。

### ステップ5：最終レスポンス

コード実行が完了すると、Claudeは最終レスポンスを提供します：

```json Output
{
  "content": [
    {
      "type": "code_execution_tool_result",
      "tool_use_id": "srvtoolu_abc123",
      "content": {
        "type": "code_execution_result",
        "stdout": "Top 5 customers: [{'customer_id': 'C1', 'revenue': 45000}, {'customer_id': 'C2', 'revenue': 38000}, {'customer_id': 'C5', 'revenue': 32000}, {'customer_id': 'C8', 'revenue': 28500}, {'customer_id': 'C3', 'revenue': 24000}]",
        "stderr": "",
        "return_code": 0,
        "content": []
      }
    },
    {
      "type": "text",
      "text": "I've analyzed the purchase history from last quarter. Your top 5 customers generated $167,500 in total revenue, with Customer C1 leading at $45,000."
    }
  ],
  "stop_reason": "end_turn"
}
```

## 高度なパターン

### ループによるバッチ処理

Claudeは複数の項目を効率的に処理するコードを記述できます：

```python
regions = ["West", "East", "Central", "North", "South"]
results = {}
for region in regions:
    rows = json.loads(await query_database({"sql": f"<sql for {region}>"}))
    results[region] = sum(row["revenue"] for row in rows)

# 結果をプログラムで処理する
top_region = max(results.items(), key=lambda x: x[1])
print(f"Top region: {top_region[0]} with ${top_region[1]:,} in revenue")
```

このパターンは：

* モデルのラウンドトリップをN回（リージョンごとに1回）から1回に削減します
* Claudeに返す前に大規模な結果セットをプログラム的に処理します
* 生データではなく集計された結論のみを返すことでトークンを節約します

### 早期終了

Claudeは成功基準が満たされた時点で処理を停止できます：

```python
endpoints = ["us-east", "eu-west", "apac"]
for endpoint in endpoints:
    status = await check_health({"endpoint": endpoint})
    if status == "healthy":
        print(f"Found healthy endpoint: {endpoint}")
        break  # Stop early, don't check remaining
```

### 条件付きツール選択

```python
path = "/tmp/example.txt"
file_info = json.loads(await get_file_info({"path": path}))
if file_info["size"] < 10000:
    content = await read_full_file({"path": path})
else:
    content = await read_file_summary({"path": path})
print(content)
```

### データフィルタリング

```python
server_id = "srv-01"
log_text = await fetch_logs({"server_id": server_id})
errors = [line for line in log_text.splitlines() if "ERROR" in line]
print(f"Found {len(errors)} errors")
for error in errors[-10:]:  # Only return last 10 errors
    print(error)
```

## レスポンス形式

### プログラマティックツール呼び出し

コード実行がツールを呼び出す場合：

```json
{
  "type": "tool_use",
  "id": "toolu_abc123",
  "name": "query_database",
  "input": { "sql": "<sql>" },
  "caller": {
    "type": "code_execution_20260120",
    "tool_id": "srvtoolu_xyz789"
  }
}
```

### ツール結果の処理

ツール結果は実行中のコードに渡されます：

```json
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_abc123",
      "content": "[{\"customer_id\": \"C1\", \"revenue\": 45000, \"orders\": 23}, {\"customer_id\": \"C2\", \"revenue\": 38000, \"orders\": 18}, ...]"
    }
  ]
}
```

### コード実行の完了

すべてのツール呼び出しが満たされ、コードが完了した場合：

```json
{
  "type": "code_execution_tool_result",
  "tool_use_id": "srvtoolu_xyz789",
  "content": {
    "type": "code_execution_result",
    "stdout": "Analysis complete. Top 5 customers identified from 847 total records.",
    "stderr": "",
    "return_code": 0,
    "content": []
  }
}
```

## エラー処理

### 一般的なエラー

| エラー                                        | 発生箇所                                                    | 説明                                                          | 解決策                                                                                                               |
| ------------------------------------------ | ------------------------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `invalid_tool_input`                       | レスポンス内の`code_execution_tool_result`エラーブロックの`error_code` | コード実行ツールに無効なパラメータが渡されました                                    | [コード実行ツールのエラー](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#errors)を参照してください |
| `invalid_request_error`（`tool_choice`に関して） | HTTP 400エラーレスポンス                                        | `tool_choice`が、`allowed_callers`に`"direct"`を含まないツールを指定しています | そのツールの`allowed_callers`に`"direct"`を追加するか、`tool_choice`からそのツールを削除してClaudeにコードから呼び出させてください                          |

### ツール呼び出し中のコンテナの有効期限切れ

ツール結果が約4分以内に届かない場合、保留中の呼び出しはClaudeの実行中のコード内で`TimeoutError`を発生させます。Claudeは`stderr`でエラーを確認し、通常は呼び出しを再試行します：

```json
{
  "type": "code_execution_tool_result",
  "tool_use_id": "srvtoolu_abc123",
  "content": {
    "type": "code_execution_result",
    "stdout": "",
    "stderr": "TimeoutError: Calling tool ['query_database'] timed out (no response after 270s).",
    "return_code": 0,
    "content": []
  }
}
```

タイムアウトを防ぐには：

* レスポンスの`expires_at`フィールドを監視する
* ツール実行にタイムアウトを実装する
* 長時間の操作をより小さなチャンクに分割することを検討する

### ツール実行エラー

ツールがエラーを返す場合：

```json
{
  "type": "tool_result",
  "tool_use_id": "toolu_abc123",
  "content": "Error: Query timeout - table lock exceeded 30 seconds"
}
```

Claudeのコードはこのエラーを受け取り、適切に処理できます。

## 制約と制限

### 機能の非互換性

* **構造化出力：** `strict: true`を持つツールはプログラマティック呼び出しではサポートされません
* **ツール選択：** `tool_choice`を通じて特定のツールのプログラマティック呼び出しを強制することはできません
* **並列ツール使用：** `disable_parallel_tool_use: true`はプログラマティック呼び出しではサポートされません

### 入力スキーマの制限

`input_schema`に再帰的な`$ref`（自身を参照するスキーマなどの参照サイクル）を含むカスタムツールは、プログラマティック呼び出しを有効にできません。そのようなツールの`allowed_callers`にコード実行ツールバージョンを含めると、リクエストは`400 invalid_request_error`で失敗し、そのメッセージには`Circular $ref detected`が含まれます。同じスキーマは直接ツール呼び出しでは受け付けられます。

これを回避するには、以下のいずれかを行ってください：

* `allowed_callers`を省略する（または`["direct"]`に設定する）ことで、ツールを直接呼び出し専用にします。同じリクエスト内の他のツールは引き続きプログラマティック呼び出しを使用できます。
* スキーマからサイクルを削除します。たとえば、再帰を固定の深さまで展開し、それより深いネストについては最も内側のレベルの`description`で説明するか、再帰的なプロパティを、期待される形状を`description`で説明したプレーンな`{"type": "object"}`に置き換えます。

### ツールの制限

以下のツールはプログラム的に呼び出すことができません：

* [MCPコネクタ](https://platform.claude.com/docs/ja/agents-and-tools/mcp-connector)によって提供されるツール
* [コンピュータ使用](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)ツールセット（`computer_toolset_20260801`および`browser_toolset_20260801`）。これらの`allowed_callers`フィールドは`"direct"`のみを受け付けます

### メッセージ形式の制限

プログラマティックツール呼び出しに応答する際には、厳格な形式要件があります：

**ツール結果のみのレスポンス：** 結果を待機している保留中のプログラマティックツール呼び出しがある場合、レスポンスメッセージには`tool_result`ブロック**のみ**を含める必要があります。ツール結果の後であっても、テキストコンテンツを含めることはできません。

無効 - プログラマティックツール呼び出しに応答する際にテキストを含めることはできません：

```json
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01",
      "content": "[{\"customer_id\": \"C1\", \"revenue\": 45000}]"
    },
    { "type": "text", "text": "What should I do next?" }
  ]
}
```

有効 - プログラマティックツール呼び出しに応答する際はツール結果のみ：

```json
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01",
      "content": "[{\"customer_id\": \"C1\", \"revenue\": 45000}]"
    }
  ]
}
```

この制限は、プログラマティック（コード実行）ツール呼び出しに応答する場合にのみ適用されます。通常のクライアント側ツール呼び出しでは、ツール結果の後にテキストコンテンツを含めることができます。

**テキストのみのツール結果コンテンツ：** プログラマティック呼び出しに応答する各`tool_result`の`content`は、文字列または`text`ブロックである必要があります。画像、ドキュメント、その他のコンテンツブロックタイプは拒否されます。

### レート制限

プログラマティックツール呼び出しは、通常のツール呼び出しと同じ「rate limit」（レート制限）の対象となります。コード実行からの各ツール呼び出しは、個別の呼び出しとしてカウントされます。

### 使用前にツール結果を検証する

プログラム的に呼び出されるユーザー定義ツールを実装する場合：

* **ツール結果は文字列として返されます：** 実行環境によって処理される可能性のあるコードスニペットや実行可能コマンドを含む、あらゆるコンテンツを含むことができます。
* **外部ツール結果を検証する：** ツールが外部ソースからデータを返す場合やユーザー入力を受け付ける場合、出力がコードとして解釈または実行されるのであれば、コードインジェクションのリスクに注意してください。

## トークン効率

プログラマティックツール呼び出しは、3つの方法でトークン消費を削減します：

* **プログラマティック呼び出しからのツール結果はClaudeのコンテキストに追加されません** - 最終的なコード出力のみが追加されます
* **中間処理はコード内で行われます** - フィルタリング、集計、その他の変換はモデルトークンを消費しません
* **1回のコード実行で複数のツール呼び出し** - 個別のモデルターンと比較してオーバーヘッドを削減します

たとえば、10個のツールを直接呼び出すと、プログラム的に呼び出して要約を返す場合の約10倍のトークンを使用します。

本番のClaudeモデルに対するAnthropicの内部評価では：

* 75ツールのプロジェクト管理エージェントベンチマークにおいて、プログラマティックツール呼び出しを有効にすると、タスクの精度に変化なく、課金対象の入力トークンが約38%削減されました。
* 各ターンで1〜2回の順次ツール呼び出しを行う[τ²-bench](https://arxiv.org/abs/2506.07982)（航空、小売、通信ドメイン）では、プログラマティックツール呼び出しによるスコアの変化はなく、コストは約8%増加しました。順次的な単一呼び出しワークフローには効果がありません。
* 本番APIトラフィック全体では、`tools`配列に10〜49個のツール定義を含むリクエストで、プログラマティックツール呼び出しを有効にすると通常20%〜40%のトークン節約が見られます。

実際の節約量はワークロードの形状によって異なります。[プログラマティック呼び出しを使用すべき場合](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/programmatic-tool-calling#when-to-use-programmatic-calling)を参照してください。

## 使用量と料金

プログラマティックツール呼び出しは、コード実行と同じ料金体系を使用します。詳細は[コード実行の料金](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#usage-and-pricing)を参照してください。

<Note>
  プログラマティックツール呼び出しのトークンカウント：プログラマティック呼び出しからのツール結果は、入力/出力トークン使用量にカウントされません。最終的なコード実行結果とClaudeのレスポンスのみがカウントされます。
</Note>

## ベストプラクティス

### ツール設計

* **詳細な出力説明を提供する：** Claudeはコード内でツール結果をデシリアライズするため、形式（JSON構造とフィールドの型）を文書化してください
* **構造化データを返す：** JSONやその他の機械可読形式がプログラム的な処理に最適です
* **レスポンスを簡潔に保つ：** 処理のオーバーヘッドを最小限に抑えるため、必要なデータのみを返してください

### プログラマティック呼び出しを使用すべき場合

プログラマティックツール呼び出しは、小さな固定オーバーヘッド（コンテナの起動、スクリプト生成）と引き換えに、ツール結果トークンとモデルラウンドトリップの大幅な節約を得るものです。このトレードオフが有利になるかどうかは、ワークロードの形状によって異なります。

**適している場合：**

* 多数の項目にわたるファンアウトまたは並列操作（たとえば、50個のエンドポイントの確認や20件のレコードの検索）
* Claudeのコンテキストに到達する前にフィルタリング、集計、または要約できる大規模なツール結果
* 反復的なクエリと結果のフィルタリングがワークフローの大部分を占めるエージェント型の検索と取得

**適していない場合：**

* 各呼び出しが前の結果に対するClaudeの推論に依存する厳密に順次的なワークフロー。この場合、スクリプトはモデルのラウンドトリップを省略できないためです
* レスポンスが小さい少数のツール呼び出し。特に会話の最初のターンでは、コンテナとスクリプトのオーバーヘッドが節約分を上回る可能性があります
* 呼び出しの間に即時のユーザーフィードバックを必要とするツール

判断がつかない場合は、広く有効にする前に、トラフィックの代表的なサンプルで`allowed_callers`の有無による課金対象の入力トークンを測定してください。

### パフォーマンスの最適化

* 状態を維持するため、複数の関連リクエストを行う際は**コンテナを再利用する**
* 可能な場合は、1回のコード実行で**類似の操作をバッチ処理する**

## トラブルシューティング

### 一般的な問題

**`tool_choice`設定時の`invalid_request_error`**

* `tool_choice`は、`allowed_callers`に`"direct"`を含まないツールを指定できません。そのツールの`allowed_callers`に`"direct"`を追加するか、`tool_choice`からそのツールを削除してClaudeにコードから呼び出させてください。

**コンテナの有効期限切れ**

* 一時停止したレスポンスの`expires_at`タイムスタンプより十分前に、各プログラマティックツール呼び出しに応答してください。Claudeのコードは約4分後に結果の待機を停止し、アイドル状態のコンテナは現在約5分後に回収されます。
* より高速なツール実行の実装を検討してください

**ツール結果が正しく解析されない**

* ツールがClaudeがデシリアライズできる文字列データを返すことを確認してください
* ツールの説明に明確な出力形式のドキュメントを記載してください

### デバッグのヒント

1. フローを追跡するために**すべてのツール呼び出しと結果をログに記録する**
2. プログラマティック呼び出しを確認するため&#x306B;**`caller`フィールドを確認する**
3. 適切な再利用を確保するために**コンテナIDを監視する**
4. プログラマティック呼び出しを有効にする前に**ツールを個別にテストする**

## プログラマティックツール呼び出しが機能する理由

Claudeは大量のコードで訓練されているため、ツールを呼び出し可能なPython関数として提示することで、その強みを活用できます：

* **ツールの合成：** 連鎖呼び出し、ループ、条件分岐は、一連のモデルラウンドトリップではなく、通常のPython制御フローになります
* **結果の処理：** Claudeのコードは大規模なツール出力をフィルタリングおよび集計したり、ファイルに書き込んだりし、最終出力のみがコンテキストウィンドウに入ります
* **レイテンシ：** 1回のコード実行内のツール呼び出しの間でモデルが再サンプリングされません

## 代替実装

プログラマティックツール呼び出しは、独自のインフラストラクチャ上でも実装できる汎用的なパターンです。各アプローチの比較は以下のとおりです：

### クライアント側での直接実行

Claudeにコード実行ツールを提供し、その環境で利用可能な関数を説明します。Claudeがコードでツールを呼び出すと、アプリケーションはそれらの関数が定義されているローカル環境でコードを実行します。

**利点：**

* アプリケーションの再設計が最小限
* 環境と指示を完全に制御できる

**欠点：**

* 信頼できないコードをサンドボックス外で実行する
* ツール呼び出しがコードインジェクションの経路になり得る

**使用すべき場合：** アプリケーションが任意のコードを安全に実行でき、最小限の実装を望み、Anthropicのマネージドサービスがニーズに合わない場合。

### 自己管理型のサンドボックス実行

Claudeの視点からは同じアプローチですが、コードはセキュリティ制限（たとえば、ネットワーク外部通信なし）のあるサンドボックス化されたコンテナ内で実行されます。ツールが外部リソースを必要とする場合、サンドボックス外でツール呼び出しを実行するためのプロトコルが必要になります。

**利点：**

* 独自のインフラストラクチャ上での安全なプログラマティックツール呼び出し
* 実行環境を完全に制御できる

**欠点：**

* 構築と保守が複雑
* インフラストラクチャとプロセス間通信の両方を管理する必要がある

**使用すべき場合：** セキュリティが重要で、Anthropicのマネージドソリューションが要件に合わない場合。

### Anthropicマネージド実行

Anthropicのプログラマティックツール呼び出しは、Claude向けに調整された独自方針のPython環境を備えた、サンドボックス実行のマネージド版です。Anthropicがコンテナ管理、コード実行、安全なツール呼び出し通信を処理します。

**利点：**

* デフォルトで安全かつセキュア
* ツール定義で有効化でき、運用するインフラストラクチャが不要
* Claude向けに最適化された環境と指示

Claude API、[Claude Platform on AWS](https://platform.claude.com/docs/ja/build-with-claude/claude-platform-on-aws)、または[Microsoft Foundry](https://platform.claude.com/docs/ja/build-with-claude/claude-in-microsoft-foundry)を使用している場合は、Anthropicのマネージドソリューションの使用を検討してください。Microsoft Foundryでは、プログラマティックツール呼び出しには[Hosted on Anthropicデプロイメント](https://platform.claude.com/docs/ja/build-with-claude/claude-in-microsoft-foundry#additional-features-not-supported-when-hosted-on-azure)が必要です。

## データ保持

プログラマティックツール呼び出しはコード実行インフラストラクチャ上に構築されており、同じサンドボックスコンテナを使用します。実行アーティファクトや出力を含むコンテナデータは、最大30日間保持されます。

すべての機能にわたるZDRの適格性については、[APIとデータ保持](https://platform.claude.com/docs/ja/manage-claude/api-and-data-retention)を参照してください。

## 次のステップ

<CardGroup cols={2}>
  <Card title="きめ細かいツールストリーミング" icon="bolt" href="https://platform.claude.com/docs/ja/agents-and-tools/tool-use/fine-grained-tool-streaming">
    レイテンシに敏感なアプリケーション向けに、サーバー側のJSONバッファリングなしでツール入力をストリーミングします。
  </Card>

  <Card title="コード実行ツール" icon="code" href="https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool">
    サンドボックス化されたコンテナでPythonとbashコードを実行し、データの分析、ファイルの生成、ソリューションの反復を行います。
  </Card>

  <Card title="Claudeでのツール使用" icon="wrench" href="https://platform.claude.com/docs/ja/agents-and-tools/tool-use/overview">
    Claudeを外部ツールやAPIに接続します。ツールがどこで実行されるか、Claudeがいつ呼び出すか、どのツールがタスクに適しているかを確認してください。
  </Card>

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