---
title: コード実行ツール
url: https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool
description: サンドボックス化されたコンテナでPythonとbashのコードを実行し、データの分析、ファイルの生成、ソリューションの反復改善を行います。
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
    - claude-haiku-4-5-20251001
  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:
    - サポートされているすべてのモデルは、3つの[ツールバージョン](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#tool-versions)すべてを受け付けます。Claude Haiku 4.5では、プログラムによるツール呼び出しとREPL状態の永続化が利用できないため、新しいバージョンは`code_execution_20250825`と同様に動作します。
    - "[Claude Mythos Preview](https://anthropic.com/glasswing)では、コード実行はClaude APIおよびMicrosoft Foundryでサポートされています。"
---

Claudeは、APIの会話内で直接、データの分析、可視化の作成、複雑な計算の実行、システムコマンドの実行、ファイルの作成と編集、アップロードされたファイルの処理を行うことができます。コード実行ツールを使用すると、Claudeは安全な「sandboxed」（サンドボックス化された）環境で、Bashコマンドの実行やファイルの操作（コードの記述を含む）を行えます。

**コード実行は、ウェブ検索またはウェブフェッチ（`web_search_20260209`、`web_fetch_20260209`、またはそれ以降）と併用する場合は無料です。** これらのツールのいずれかがリクエストに含まれている場合、そのリクエストでは標準のトークンコスト以外にコード実行の追加料金は発生しません。これは、動的フィルタリングの背後で行われるコード実行と、Claudeが直接実行するコードの両方に適用されます。これらのツールが含まれていない場合は、標準のコード実行料金が適用されます。

コード実行は、[ウェブ検索](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/web-search-tool)ツールと[ウェブフェッチ](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/web-fetch-tool)ツールにおける「dynamic filtering」（動的フィルタリング）も支えています。Claudeは、結果が「context window」（コンテキストウィンドウ）に到達する前に、コード実行環境内で結果をフィルタリングします。動的フィルタリングが実行される場合、APIはリクエストに必要なコード実行を自動的にプロビジョニングするため、そのためにコード実行ツールをリクエストに追加する必要はありません。

<Note>
  この機能に関するフィードバックは、[フィードバックフォーム](https://forms.gle/LTAU6Xn2puCJMi1n6)からお寄せください。
</Note>

## ツールバージョン

コード実行ツールには現在3つのバージョンがあり、[サポートされているすべてのモデル](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#compatibility)が3つすべてを受け付けます。各バージョンは前のバージョンを基に構築されています。

* `code_execution_20250825`は、Bashコマンドとファイル操作をサポートします。
* `code_execution_20260120`は、「read-eval-print loop」（対話型評価ループ）、すなわちREPLの状態の永続化と、サンドボックス内からの[「programmatic tool calling」（プログラムによるツール呼び出し）](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/programmatic-tool-calling)を追加します。Claude Haiku 4.5は`code_execution_20260120`および`code_execution_20260521`のツールタイプを受け付けますが、プログラムによるツール呼び出しと、それに依存するREPL状態の永続化は利用できないため、新しいバージョンは`code_execution_20250825`と同様に動作します。
* `code_execution_20260521`は、`code_execution_20260120`と同じランタイムです。違いは、ツールの説明がプログラムによるツール呼び出しにおける各Pythonセルの90秒の実時間制限についてClaudeに伝える点であり、これによりClaudeは長時間実行されるセルの時間配分を計画できます。制限を超えたセルは、ゼロ以外の`return_code`と、出力内の`detection_timeout`ステータスメッセージを含む通常のコード実行結果を返します。これは、ツール呼び出し全体が最大実行時間を超えた場合にAPIが返す`execution_time_exceeded`[エラーコード](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#errors)とは別のものです。

3つのツールバージョンのいずれも`anthropic-beta`ヘッダーを必要としません。従来のコード実行ベータヘッダーも、オプトインとして引き続き有効です。

このページの例では`code_execution_20250825`を使用しています。これは例で示すBashおよびファイル操作をカバーしており、サポートされているすべてのモデルで同じように動作します。プログラムによるツール呼び出しやREPL状態の永続化が必要な場合は、`code_execution_20260120`以降を使用してください。現在の[ウェブ検索](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/web-search-tool)ツールと[ウェブフェッチ](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/web-fetch-tool)ツール（`web_search_20260209`、`web_fetch_20260209`、およびそれ以降）では、コード実行バージョンとして`code_execution_20260120`以降が必要です。

古いツールバージョンは、新しいモデルとの互換性が維持されることは保証されていません。新しいモデルを採用する際は、[ツールバージョン](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#tool-versions)と[互換性](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#compatibility)を確認し、統合がサポートする最新のツールバージョンを優先して使用してください。

リクエストを送信する前に、モデルがコード実行ツールを受け付けるかどうかを確認するには、Models APIからそのモデルの`capabilities.server_tools.code_execution.supported`の値を読み取ってください。この目的にはトップレベルの`capabilities.code_execution`の値を使用しないでください。この値は、プログラムによるツール呼び出しのように、このツール内で実行されるコードがリクエストの他のツールを呼び出せるかどうかを示すものです。両方のフィールドについては、[Models APIの使用](https://platform.claude.com/docs/ja/models/overview#using-the-models-api)で説明しています。

<Note>
  従来の`code_execution_20250522`（Pythonのみ）をまだ使用している場合は、[最新のツールバージョンへのアップグレード](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#upgrade-to-latest-tool-version)を参照して移行してください。
</Note>

## クイックスタート

以下は、Claudeに計算を実行するよう依頼する例です。

<CodeGroup>
  ```bash cURL
  curl --fail-with-body -sS https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [
        {
          "role": "user",
          "content": "Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
        }
      ],
      "tools": [
        {
          "type": "code_execution_20250825",
          "name": "code_execution"
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 4096 \
    --message '{
      role: user,
      content: "Use the code execution tool to calculate the mean and standard
        deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
    }' \
    --tool '{type: code_execution_20250825, name: code_execution}'
  ```

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

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[
          {
              "role": "user",
              "content": "Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]",
          }
      ],
      tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
  )

  print(response.to_json())
  ```

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

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content:
          "Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
      }
    ],
    tools: [{ type: "code_execution_20250825", name: "code_execution" }]
  });

  console.log(JSON.stringify(response));
  ```

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

  var message = await client.Messages.Create(new()
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new() { Role = Role.User, Content = "Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" }],
      Tools = [new CodeExecutionTool20250825()]
  });

  Console.WriteLine(message);
  ```

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

  response, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]")),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfCodeExecutionTool20250825: &anthropic.CodeExecutionTool20250825Param{}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(4096L)
      .addUserMessage("Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]")
      .addTool(CodeExecutionTool20250825.builder().build())
      .build();

  Message response = client.messages().create(params);
  IO.println(ObjectMappers.jsonMapper().valueToTree(response));
  ```

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

  $message = $client->messages->create(
      maxTokens: 4096,
      messages: [
          [
              'role' => 'user',
              'content' => 'Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]',
          ],
      ],
      model: Model::CLAUDE_OPUS_5_5,
      tools: [new CodeExecutionTool20250825()],
  );

  echo json_encode($message, JSON_PRETTY_PRINT), PHP_EOL;
  ```

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

  message = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Use the code execution tool to calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
      }
    ],
    tools: [Anthropic::CodeExecutionTool20250825.new]
  )

  puts message.to_json
  ```
</CodeGroup>

レスポンスでは、`server_tool_use`ブロック（Claudeが実行したコマンド）とそのツール結果ブロックが交互に並び、その後にClaudeのテキストが続きます。トップレベルには`container`オブジェクトも含まれており、その`id`は[リクエスト間で再利用](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#container-reuse)できます。ブロックの形式については[レスポンス形式](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#response-format)を参照してください。

## コード実行の仕組み

APIリクエストにコード実行ツールを追加すると、次のようになります。

1. Claudeは、コード実行が質問への回答に役立つかどうかを評価します

2. ツールは自動的にClaudeに以下の機能を提供します。

   * **Bashコマンド：** システム操作のためのシェルコマンドを実行します
   * **ファイル操作：** コードの記述を含め、ファイルを直接作成、表示、編集します

3. Claudeは、1回のリクエストでこれらの機能を任意に組み合わせて使用できます

4. すべての操作は、安全なサンドボックス化された「container」（コンテナ）内で実行されます。コンテナにはインターネットアクセスがないため、Claudeは実行時にパッケージをダウンロードできません。利用できるのは[プリインストールされたライブラリ](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#pre-installed-libraries)のみです

5. APIはすべてのコマンドをサーバー側で実行し、同じリクエスト内で結果をClaudeに返すため、ユーザー自身がコードを実行したり`tool_result`ブロックを送り返したりする必要はありません。例外の1つは、Claudeがコード実行と並行してクライアントツールのいずれかを呼び出す場合です。この場合、APIはコード実行の呼び出しを結果なしで返します。結果は、クライアントツールの`tool_result`ブロックを送り返した後の、後続のレスポンスで届きます

6. 以前のレスポンスのコンテナIDを渡さない限り、各リクエストは新しいコンテナで実行されます（[コンテナの再利用](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#container-reuse)を参照）

7. Claudeは、生成されたグラフ、計算、または分析とともに結果を提供します

コンテナにはPythonがプリインストールされています。Claudeはファイル操作サブツールでPythonを記述し、Bashコマンドで実行します。`code_execution_20260120`以降と[プログラムによるツール呼び出し](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/programmatic-tool-calling)を使用すると、Pythonインタープリターの状態（変数のバインディングなど）も、コンテナを再利用するリクエスト間で永続化されます。

### Claudeがコードを実行するタイミング

Claudeは、計算やファイル処理がリクエストに役立つ場合にコードを実行します。

* 自明でない数学（大きな数値、多くのステップ、精度が重要な結果）
* データ分析、ファイルの解析、または可視化
* アルゴリズムの実行またはシミュレーション
* 「run」、「compute」、「execute」などの明示的な依頼

Claudeは、以下の場合にはコードを実行せずに直接回答します。

* 単純な算術やよく知られた数学的事実
* 事実に関する、会話的な、または創作的なリクエスト
* 単純な単位変換や翻訳

判断が分かれるリクエストでClaudeにコードを実行させたい場合は、明示的に依頼してください（例：「これを検証するためにコードを実行してください」）。

## ファイルの操作

### 独自のファイルをアップロードして分析する

独自のデータファイル（CSV、Excel、画像など）を分析するには、Files APIを通じてアップロードし、リクエストで参照します。

Python環境は、Files APIを通じてアップロードされたさまざまなファイルタイプを処理できます。これには以下が含まれます。

* CSV
* Excel（.xlsx、.xls）
* JSON
* XML
* 画像（JPEG、PNG、GIF、WebP）
* テキストファイル（.txt、.md、.pyなど）

#### ファイルをアップロードして分析する

1. [Files API](https://platform.claude.com/docs/ja/build-with-claude/files)を使用して**ファイルをアップロード**します
2. `container_upload`コンテンツブロックを使用して、メッセージ内で**ファイルを参照**します
3. APIリクエストに**コード実行ツールを含めます**

<CodeGroup>
  ```bash cURL
  # まず、ファイルをアップロードしてファイルIDを取得します（jqを使用）
  FILE_ID=$(curl --fail-with-body -sS https://api.anthropic.com/v1/files \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -F "file=@data.csv" | jq -r '.id')

  # 次に、file_idをコード実行で使用します
  curl --fail-with-body -sS https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [{
        "role": "user",
        "content": [
          {"type": "text", "text": "Analyze this CSV data"},
          {"type": "container_upload", "file_id": "'"$FILE_ID"'"}
        ]
      }],
      "tools": [{
        "type": "code_execution_20250825",
        "name": "code_execution"
      }]
    }'
  ```

  ```bash CLI
  # まず、ファイルをアップロードしてファイルIDを取得します
  FILE_ID=$(ant files upload --file ./data.csv --transform id --raw-output)

  # 次に、file_idをコード実行で使用します
  ant messages create <<YAML
  model: claude-opus-5-5
  max_tokens: 4096
  messages:
    - role: user
      content:
        - type: text
          text: Analyze this CSV data
        - type: container_upload
          file_id: $FILE_ID
  tools:
    - type: code_execution_20250825
      name: code_execution
  YAML
  ```

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

  # ファイルをアップロードします
  file_object = client.files.upload(file=Path("data.csv"))

  # file_id をコード実行で使用します
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[
          {
              "role": "user",
              "content": [
                  {"type": "text", "text": "Analyze this CSV data"},
                  {"type": "container_upload", "file_id": file_object.id},
              ],
          }
      ],
      tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
  )

  print(response.to_json())
  ```

  ```typescript TypeScript
  import { createReadStream } from "node:fs";
  // ...
  const client = new Anthropic();

  // ファイルをアップロードします
  const fileObject = await client.files.upload({
    file: createReadStream("data.csv")
  });

  // コード実行で file_id を使用します
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: [
          { type: "text", text: "Analyze this CSV data" },
          { type: "container_upload", file_id: fileObject.id }
        ]
      }
    ],
    tools: [
      {
        type: "code_execution_20250825",
        name: "code_execution"
      }
    ]
  });

  console.log(JSON.stringify(response));
  ```

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

  // ファイルをアップロードします
  var fileObject = await client.Files.Upload(new FileUploadParams
  {
      File = File.OpenRead("data.csv")
  });

  // コード実行で file_id を使用します
  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [
          new()
          {
              Role = Role.User,
              Content = new([
                  new TextBlockParam { Text = "Analyze this CSV data" },
                  new ContainerUploadBlockParam { FileID = fileObject.ID }
              ])
          }
      ],
      Tools = [new CodeExecutionTool20250825()]
  };

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

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

  // ファイルをアップロードします
  file, err := os.Open("data.csv")
  if err != nil {
  	log.Fatal(err)
  }
  defer file.Close()

  fileObject, err := client.Files.Upload(ctx, anthropic.FileUploadParams{
  	File: file,
  })
  if err != nil {
  	log.Fatal(err)
  }

  // コード実行で file_id を使用します
  response, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(
  			anthropic.NewTextBlock("Analyze this CSV data"),
  			anthropic.NewContainerUploadBlock(fileObject.ID),
  		),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfCodeExecutionTool20250825: &anthropic.CodeExecutionTool20250825Param{}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(response.RawJSON())
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  // ファイルをアップロードします
  FileMetadata fileObject = client.files().upload(
      FileUploadParams.builder()
          .file(Path.of("data.csv"))
          .build()
  );

  // コード実行で file_id を使用します
  Message response = client.messages().create(
      MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessageOfBlockParams(List.of(
              ContentBlockParam.ofText(TextBlockParam.builder()
                  .text("Analyze this CSV data")
                  .build()),
              ContentBlockParam.ofContainerUpload(ContainerUploadBlockParam.builder()
                  .fileId(fileObject.id())
                  .build())
          ))
          .addTool(CodeExecutionTool20250825.builder().build())
          .build()
  );

  IO.println(ObjectMappers.jsonMapper().valueToTree(response));
  ```

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

  // ファイルをアップロードします
  $fileObject = $client->files->upload(
      file: FileParam::fromResource(fopen('data.csv', 'r')),
  );

  // file_id をコード実行で使用します
  $response = $client->messages->create(
      model: Model::CLAUDE_OPUS_5_5,
      maxTokens: 4096,
      messages: [
          [
              'role' => 'user',
              'content' => [
                  TextBlockParam::with(text: 'Analyze this CSV data'),
                  ContainerUploadBlockParam::with(fileID: $fileObject->id),
              ],
          ],
      ],
      tools: [new CodeExecutionTool20250825()],
  );

  echo json_encode($response), PHP_EOL;
  ```

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

  # ファイルをアップロードします
  file_object = client.files.upload(
    file: Pathname("data.csv")
  )

  # file_id をコード実行で使用します
  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: [
          { type: "text", text: "Analyze this CSV data" },
          { type: "container_upload", file_id: file_object.id }
        ]
      }
    ],
    tools: [
      Anthropic::CodeExecutionTool20250825.new
    ]
  )

  puts response.to_json
  ```
</CodeGroup>

### 生成されたファイルを取得する

コード実行中にClaudeが出力ディレクトリにファイルを保存すると（[生成されたファイルのキャプチャ方法](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#how-generated-files-are-captured)を参照）、各ファイルのIDがコード実行ツールの結果に表示され、[Files API](https://platform.claude.com/docs/ja/build-with-claude/files)でダウンロードできます。

<CodeGroup exclude="shell">
  <CodeGroupItem language="cURL">
    生成されたすべてのファイルをダウンロードするには、ツール結果内のファイルIDをループ処理する必要があり、単一のシェルコマンドよりも多くのロジックが必要です。これには[Claude SDK](https://platform.claude.com/docs/ja/cli-sdks-libraries/overview)を使用してください。
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    生成されたすべてのファイルをダウンロードするには、ツール結果内のファイルIDをループ処理する必要があり、単一のシェルコマンドよりも多くのロジックが必要です。これには[Claude SDK](https://platform.claude.com/docs/ja/cli-sdks-libraries/overview)を使用してください。
  </CodeGroupItem>

  ```python Python
  client = Anthropic()

  # ファイルを作成するコード実行をリクエストします
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[
          {
              "role": "user",
              "content": "Create a matplotlib visualization and save it as output.png",
          }
      ],
      tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
  )


  # レスポンスからファイルIDを抽出します
  def extract_file_ids(response: Message) -> list[str]:
      file_ids: list[str] = []
      for item in response.content:
          if item.type == "bash_code_execution_tool_result":
              content_item = item.content
              if content_item.type == "bash_code_execution_result":
                  for output_block in content_item.content:
                      file_ids.append(output_block.file_id)
      return file_ids


  # 作成されたファイルをダウンロードします
  for file_id in extract_file_ids(response):
      file_metadata = client.files.retrieve_metadata(file_id)
      file_content = client.files.download(file_id)
      file_content.write_to_file(file_metadata.filename)
      print(f"Downloaded: {file_metadata.filename}")
  ```

  ```typescript TypeScript
  import { writeFile } from "node:fs/promises";

  const client = new Anthropic();

  // ファイルを作成するコード実行をリクエストします
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Create a matplotlib visualization and save it as output.png"
      }
    ],
    tools: [
      {
        type: "code_execution_20250825",
        name: "code_execution"
      }
    ]
  });

  // レスポンスからファイルIDを抽出し、作成された各ファイルをダウンロードします
  for (const block of response.content) {
    if (block.type === "bash_code_execution_tool_result") {
      const result = block.content;
      if (result.type === "bash_code_execution_result") {
        for (const outputBlock of result.content) {
          const [fileMetadata, fileResponse] = await Promise.all([
            client.files.retrieveMetadata(outputBlock.file_id),
            client.files.download(outputBlock.file_id)
          ]);
          await writeFile(fileMetadata.filename, await fileResponse.bytes());
          console.log(`Downloaded: ${fileMetadata.filename}`);
        }
      }
    }
  }
  ```

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

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new() { Role = Role.User, Content = "Create a matplotlib visualization and save it as output.png" }],
      Tools = [new CodeExecutionTool20250825()]
  };

  var response = await client.Messages.Create(parameters);

  // ツール結果からファイルIDを収集します
  List<string> fileIds = [];
  foreach (var block in response.Content)
  {
      if (!block.TryPickBashCodeExecutionToolResult(out var toolResult))
          continue;
      if (!toolResult.Content.TryPickBashCodeExecutionResultBlock(out var result))
          continue;
      foreach (var output in result.Content)
      {
          fileIds.Add(output.FileID);
      }
  }

  // 作成された各ファイルをダウンロードします
  foreach (var fileId in fileIds)
  {
      var fileMetadata = await client.Files.RetrieveMetadata(fileId);
      using var download = await client.Files.Download(fileId);
      var downloadStream = await download.ReadAsStream();
      await using var target = File.Create(fileMetadata.Filename);
      await downloadStream.CopyToAsync(target);
      Console.WriteLine($"Downloaded: {fileMetadata.Filename}");
  }
  ```

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

  	response, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  		Model:     anthropic.ModelClaudeOpus5_5,
  		MaxTokens: 4096,
  		Messages: []anthropic.MessageParam{
  			anthropic.NewUserMessage(anthropic.NewTextBlock("Create a matplotlib visualization and save it as output.png")),
  		},
  		Tools: []anthropic.ToolUnionParam{
  			{OfCodeExecutionTool20250825: &anthropic.CodeExecutionTool20250825Param{}},
  		},
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	fileIDs := extractFileIDs(response)

  	for _, fileID := range fileIDs {
  		fileMetadata, err := client.Files.GetMetadata(ctx, fileID, anthropic.FileGetMetadataParams{})
  		if err != nil {
  			log.Fatal(err)
  		}

  		fileContent, err := client.Files.Download(ctx, fileID, anthropic.FileDownloadParams{})
  		if err != nil {
  			log.Fatal(err)
  		}

  		outFile, err := os.Create(fileMetadata.Filename)
  		if err != nil {
  			log.Fatal(err)
  		}

  		_, err = io.Copy(outFile, fileContent.Body)
  		if err != nil {
  			log.Fatal(err)
  		}
  		outFile.Close()
  		fileContent.Body.Close()

  		fmt.Printf("Downloaded: %s\n", fileMetadata.Filename)
  	}
  // ...

  func extractFileIDs(response *anthropic.Message) []string {
  	var fileIDs []string
  	for _, item := range response.Content {
  		switch variant := item.AsAny().(type) {
  		case anthropic.BashCodeExecutionToolResultBlock:
  			// ツール結果からファイルIDを収集します
  			for _, file := range variant.Content.Content {
  				if file.FileID != "" {
  					fileIDs = append(fileIDs, file.FileID)
  				}
  			}
  		}
  	}
  	return fileIDs
  }
  ```

  ```java Java
  void main() throws Exception {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessage("Create a matplotlib visualization and save it as output.png")
          .addTool(CodeExecutionTool20250825.builder().build())
          .build();

      Message response = client.messages().create(params);

      List<String> fileIds = extractFileIds(response);

      for (String fileId : fileIds) {
          FileMetadata fileMetadata = client.files().retrieveMetadata(fileId);
          try (HttpResponse fileContent = client.files().download(fileId)) {
              Files.copy(
                  fileContent.body(),
                  Path.of(fileMetadata.filename()),
                  StandardCopyOption.REPLACE_EXISTING);
          }
          IO.println("Downloaded: " + fileMetadata.filename());
      }
  }

  List<String> extractFileIds(Message response) {
      List<String> fileIds = new ArrayList<>();
      // ツール結果からファイルIDを収集します
      for (ContentBlock item : response.content()) {
          item.bashCodeExecutionToolResult().ifPresent(toolResult -> {
              if (toolResult.content().isBashCodeExecutionResultBlock()) {
                  BashCodeExecutionResultBlock result =
                      toolResult.content().asBashCodeExecutionResultBlock();
                  for (BashCodeExecutionOutputBlock output : result.content()) {
                      fileIds.add(output.fileId());
                  }
              }
          });
      }
      return fileIds;
  }
  ```

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

  // ファイルを作成するコード実行をリクエストします
  $response = $client->messages->create(
      maxTokens: 4096,
      messages: [
          [
              'role' => 'user',
              'content' => 'Create a matplotlib visualization and save it as output.png',
          ],
      ],
      model: Model::CLAUDE_OPUS_5_5,
      tools: [new CodeExecutionTool20250825()],
  );

  /**
   * Extract file IDs from the response.
   *
   * @return list<string>
   */
  function extractFileIds(Message $response): array
  {
      $fileIds = [];
      foreach ($response->content as $block) {
          if ($block->type !== 'bash_code_execution_tool_result') {
              continue;
          }
          $resultBlock = $block->content;
          if ($resultBlock->type !== 'bash_code_execution_result') {
              continue;
          }
          foreach ($resultBlock->content as $outputBlock) {
              $fileIds[] = $outputBlock->fileID;
          }
      }
      return $fileIds;
  }

  // 作成されたファイルをダウンロードします
  foreach (extractFileIds($response) as $fileId) {
      $fileMetadata = $client->files->retrieveMetadata($fileId);
      $fileContent = $client->files->download($fileId);

      file_put_contents($fileMetadata->filename, $fileContent);
      echo "Downloaded: {$fileMetadata->filename}\n";
  }
  ```

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

  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Create a matplotlib visualization and save it as output.png"
      }
    ],
    tools: [
      {
        type: "code_execution_20250825",
        name: "code_execution"
      }
    ]
  )

  def extract_file_ids(response)
    file_ids = []
    response.content.each do |item|
      if item.type == :bash_code_execution_tool_result
        # anthropic-sdk-ruby の union 型変換バグ (SDK-636) の回避策: item.content は
        # ネストされた content union であるため、`item.content` の型付きアクセサは信頼できません。
        # 代わりに公開 API の `BaseModel#[]` を使って生のレスポンスデータを読み取ります。
        content_item = item.content
        if content_item[:type].to_s == "bash_code_execution_result"
          Array(content_item[:content]).each do |output_block|
            file_ids << output_block[:file_id]
          end
        end
      end
    end
    file_ids
  end

  extract_file_ids(response).each do |file_id|
    file_metadata = client.files.retrieve_metadata(file_id)
    file_content = client.files.download(file_id)

    File.open(file_metadata.filename, "wb") do |f|
      f.write(file_content.read)
    end

    puts "Downloaded: #{file_metadata.filename}"
  end
  ```
</CodeGroup>

#### 生成されたファイルのキャプチャ方法

各`bash_code_execution`呼び出しには新しい空のディレクトリが割り当てられ、コマンドからは`$OUTPUT_DIR`として利用できます。コマンドが終了すると、そのディレクトリの最上位にあるファイルがキャプチャされ、結果の`content`リスト内の`file_id`エントリとして返されます。それ以外の場所に書き込まれたファイルはコンテナ内に残り、返されません。

ツールの説明は、ファイルを`$OUTPUT_DIR`にコピーして共有するようClaudeに指示しています。アプリケーションがファイルの受け取りに依存している場合は、ファイルを`$OUTPUT_DIR`にコピーし、同じコマンド内でディレクトリの内容を一覧表示するようClaudeにプロンプトで指示してください。これにより、`ls`の出力でキャプチャを確認できます（Claudeには`content`リストが見えません）。

```bash
python /tmp/make_report.py && cp /tmp/report.pdf "$OUTPUT_DIR/" && ls "$OUTPUT_DIR"
```

Claudeが別の場所に書き込んだファイルはコンテナ内に残っているため、[コンテナを再利用](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#container-reuse)して、そのファイルを`$OUTPUT_DIR`にコピーするようClaudeに依頼できます。

### 生成されたファイルのContent Credentials

Claude APIでは、Claudeがコード実行サンドボックス内で生成したサポート対象の画像、動画、音声ファイルを[Files API](https://platform.claude.com/docs/ja/build-with-claude/files)を通じてダウンロードすると、「Coalition for Content Provenance and Authenticity」（コンテンツの来歴と真正性のための連合）、すなわち[C2PA](https://c2pa.org/)のContent Credentialsが付与されています。[サポートされている形式](https://opensource.contentauthenticity.org/docs/sdk-repos/c2pa-python/docs/supported-formats/)には、PNG、JPEG、GIF、WebP、TIFF、HEIC、AVIF、SVG、MP4、MOV、MP3、WAV、FLAC、M4Aが含まれます。クレデンシャルは、ファイルのメタデータに埋め込まれた暗号署名付きのマニフェストです。Anthropicを発行者として識別し、タイムスタンプを含み、「Claude provided this file at the request of a user and may have created or modified the file contents.」というアクションの説明を記録します。

署名のためにリクエストやレスポンス処理を変更する必要はなく、マニフェストにはユーザー、組織、またはリクエストに関する情報は一切記録されません。ファイルの表示内容は変更されません。マニフェストによって数キロバイトが追加されるため、ダウンロードしたファイルのサイズとチェックサムは、コンテナ内に存在するファイルとは異なります。テキストファイル、PDF、オフィス文書は署名のサポート対象形式ではないため、署名されません。アップロードしたファイルは、すでに付与されているContent Credentialsを含め、そのまま保存されます。

クレデンシャルを検証するには、オープンソースの[c2patoolコマンドラインユーティリティ](https://github.com/contentauth/c2pa-rs)など、C2PA互換の任意のツールでファイルを検査してください。再エンコード、形式変換、スクリーンショット、メタデータを削除するツールによってクレデンシャルは除去されるため、クレデンシャルがないことは、そのファイルがClaudeで生成されていないことを意味するわけではありません。クレデンシャルが欠落する理由の詳細については、[How Claude marks AI-generated content](https://support.claude.com/en/articles/16266773-how-claude-marks-ai-generated-content)を参照してください。

## ツール定義

コード実行ツールには追加のパラメータは必要ありません。

```json JSON
{
  "type": "code_execution_20250825",
  "name": "code_execution"
}
```

両方のフィールドは固定です。`type`はツールバージョンを選択し、`name`は`code_execution`である必要があります。

このツールを提供すると、Claudeは自動的に2つのサブツールにアクセスできるようになります。

* `bash_code_execution`：シェルコマンドを実行します
* `text_editor_code_execution`：コードの記述を含め、ファイルを表示、作成、編集します

Claudeがコードを実行すると、レスポンスにはコンテナの`id`と`expires_at`タイムスタンプを含むトップレベルの`container`オブジェクトも含まれます。同じコンテナを引き続き使用するには、そのIDをトップレベルの`container`リクエストパラメータで渡してください。[コンテナの再利用](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#container-reuse)を参照してください。

## レスポンス形式

コード実行ツールは、操作に応じて2種類の結果を返すことができます。

### Bashコマンドのレスポンス

```json Output
{
  "type": "server_tool_use",
  "id": "srvtoolu_01B3C4D5E6F7G8H9I0J1K2L3",
  "name": "bash_code_execution",
  "input": {
    "command": "ls -la | head -5"
  }
},
{
  "type": "bash_code_execution_tool_result",
  "tool_use_id": "srvtoolu_01B3C4D5E6F7G8H9I0J1K2L3",
  "content": {
    "type": "bash_code_execution_result",
    "stdout": "total 24\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 11:00 ..\n-rw-r--r-- 1 user user  220 Jan 1 12:00 data.csv\n-rw-r--r-- 1 user user  180 Jan 1 12:00 config.json",
    "stderr": "",
    "return_code": 0,
    "content": []
  }
}
```

### ファイル操作のレスポンス

**ファイルの表示：**

```json Output
{
  "type": "server_tool_use",
  "id": "srvtoolu_01C4D5E6F7G8H9I0J1K2L3M4",
  "name": "text_editor_code_execution",
  "input": {
    "command": "view",
    "path": "config.json"
  }
},
{
  "type": "text_editor_code_execution_tool_result",
  "tool_use_id": "srvtoolu_01C4D5E6F7G8H9I0J1K2L3M4",
  "content": {
    "type": "text_editor_code_execution_view_result",
    "file_type": "text",
    "content": "{\n  \"setting\": \"value\",\n  \"debug\": true\n}",
    "num_lines": 4,
    "start_line": 1,
    "total_lines": 4
  }
}
```

**ファイルの作成：**

```json Output
{
  "type": "server_tool_use",
  "id": "srvtoolu_01D5E6F7G8H9I0J1K2L3M4N5",
  "name": "text_editor_code_execution",
  "input": {
    "command": "create",
    "path": "new_file.txt",
    "file_text": "Hello, World!"
  }
},
{
  "type": "text_editor_code_execution_tool_result",
  "tool_use_id": "srvtoolu_01D5E6F7G8H9I0J1K2L3M4N5",
  "content": {
    "type": "text_editor_code_execution_create_result",
    "is_file_update": false
  }
}
```

**ファイルの編集（str\_replace）：**

```json Output
{
  "type": "server_tool_use",
  "id": "srvtoolu_01E6F7G8H9I0J1K2L3M4N5O6",
  "name": "text_editor_code_execution",
  "input": {
    "command": "str_replace",
    "path": "config.json",
    "old_str": "\"debug\": true",
    "new_str": "\"debug\": false"
  }
},
{
  "type": "text_editor_code_execution_tool_result",
  "tool_use_id": "srvtoolu_01E6F7G8H9I0J1K2L3M4N5O6",
  "content": {
    "type": "text_editor_code_execution_str_replace_result",
    "old_start": 3,
    "old_lines": 1,
    "new_start": 3,
    "new_lines": 1,
    "lines": ["-  \"debug\": true", "+  \"debug\": false"]
  }
}
```

### 結果

Bashコマンドの結果（`bash_code_execution_result`）には以下が含まれます。

* `stdout`：実行成功時の出力
* `stderr`：実行失敗時のエラーメッセージ
* `return_code`：成功時は0、失敗時はゼロ以外
* `content`：コマンドが`$OUTPUT_DIR`に残した各ファイルのエントリを含むリスト（[生成されたファイルのキャプチャ方法](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#how-generated-files-are-captured)を参照）。各エントリには、Files APIで[ファイルを取得](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#retrieve-generated-files)するための`file_id`が含まれます

ファイル操作の結果には、それぞれ独自のフィールドがあります。

* **表示**（`text_editor_code_execution_view_result`）：`file_type`、`content`、`num_lines`、`start_line`、`total_lines`
* **作成**（`text_editor_code_execution_create_result`）：`is_file_update`（ファイルがすでに存在していたかどうか）
* **編集**（`text_editor_code_execution_str_replace_result`）：`old_start`、`old_lines`、`new_start`、`new_lines`、`lines`（diff形式）

### エラー

各ツールタイプは、固有のエラーを返すことがあります。

**共通エラー（すべてのツール）：**

```json Output
{
  "type": "bash_code_execution_tool_result",
  "tool_use_id": "srvtoolu_01VfmxgZ46TiHbmXgy928hQR",
  "content": {
    "type": "bash_code_execution_tool_result_error",
    "error_code": "unavailable"
  }
}
```

**ツールタイプ別のエラーコード：**

| ツール          | エラーコード                    | 説明                      |
| ------------ | ------------------------- | ----------------------- |
| すべてのツール      | `unavailable`             | ツールが一時的に利用できません         |
| すべてのツール      | `execution_time_exceeded` | ツール呼び出しが最大実行時間を超えました    |
| すべてのツール      | `invalid_tool_input`      | ツールに無効なパラメータが指定されました    |
| すべてのツール      | `too_many_requests`       | ツール使用のレート制限を超えました       |
| bash         | `output_file_too_large`   | コマンド出力が最大サイズを超えました      |
| text\_editor | `file_not_found`          | ファイルが存在しません（表示/編集操作の場合） |

期限切れのコンテナは再利用できません。期限切れのコンテナを参照するリクエストは、コンテナを復元する代わりにエラーを返します。新しいコンテナを取得するには、`container`パラメータを指定せずにリクエストを再送信してください。

### `pause_turn`停止理由

レスポンスには`pause_turn`停止理由が含まれる場合があります。これは、APIが長時間実行されているターンを一時停止したことを示します。 Claudeにターンを続行させるには、後続のリクエストでレスポンスをそのまま返すことができます。会話を中断したい場合は、 コンテンツを変更することもできます。

## コンテナ

コード実行ツールは、コード実行専用に設計された安全なコンテナ化環境で実行され、特にPythonに重点が置かれています。

### ランタイム環境

* **Pythonバージョン：** 3.11
* **オペレーティングシステム：** Linuxベースのコンテナ
* **アーキテクチャ：** x86\_64（AMD64）

### リソース制限

* **メモリ：** 5 GiB RAM
* **ディスク容量：** 5 GiBのワークスペースストレージ
* **CPU：** 1 CPU
* **実行時間：** 最大実行時間を超えて実行されたツール呼び出しは、`execution_time_exceeded`[エラー](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#errors)を返します。[プログラムによるツール呼び出し](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/programmatic-tool-calling)では、各REPLセルにも90秒の実時間制限があります

### ネットワークとセキュリティ

* **インターネットアクセス：** セキュリティのため完全に無効化されています
* **外部接続：** アウトバウンドのネットワークリクエストは許可されていません
* **サンドボックスの分離：** ホストシステムおよび他のコンテナから完全に分離されています
* **ファイルアクセス：** ワークスペースディレクトリのみに制限されています
* **ワークスペースのスコープ：** [Files API](https://platform.claude.com/docs/ja/build-with-claude/files)と同様に、コンテナはリクエストのワークスペースにスコープされます
* **有効期限：** コンテナは作成から30日後に期限切れになります

### プリインストールされたライブラリ

サンドボックス化されたPython環境には、以下のよく使用されるライブラリが含まれています。

* **データサイエンス：** pandas、numpy、scipy、scikit-learn、statsmodels
* **可視化：** matplotlib、seaborn
* **ファイル処理：** pyarrow、openpyxl、xlsxwriter、xlrd、pillow、python-pptx、python-docx、pypdf、pdfplumber、pypdfium2、pdf2image、pdfkit、tabula-py、reportlab\[pycairo]、Img2pdf
* **数学と計算：** sympy、mpmath
* **ユーティリティ：** tqdm、python-dateutil、pytz、joblib

コンテナには、unzip、unrar、7zip、bc、rg（ripgrep）、fd、sqliteなどのコマンドラインツールも含まれています。

コンテナにはインターネットアクセスがないため、Claudeは実行時に追加のパッケージをダウンロードまたはインストールできません。利用できるのはプリインストールされたライブラリのみです。

## コンテナの再利用

以前のレスポンスのコンテナIDを指定することで、複数のAPIリクエストにわたって既存のコンテナを再利用できます。 これにより、リクエスト間で作成したファイルを保持できます。`code_execution_20260120`以降と[プログラムによるツール呼び出し](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/programmatic-tool-calling)を使用すると、Pythonインタープリターの状態も永続化されます。

コンテナは作成から30日後に期限切れになります。約5分間操作がないとコンテナはチェックポイント化され、30日の期間内にそのIDを指定してリクエストを送信すると復元されます。レスポンスの`container`オブジェクト内の`expires_at`タイムスタンプは、より短いローリング値であり、30日の制限を示すものではありません。期限切れになったコンテナは再利用できません。新しいコンテナを取得するには、`container`パラメータを指定せずにリクエストを再送信してください。

### 例

<CodeGroup>
  ```bash cURL
  # 最初のリクエスト：乱数を含むファイルを作成し、コンテナIDを取得します（jqを使用）
  CONTAINER_ID=$(curl -s https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [{
        "role": "user",
        "content": "Write a file with a random number and save it to \"/tmp/number.txt\""
      }],
      "tools": [{
        "type": "code_execution_20250825",
        "name": "code_execution"
      }]
    }' | jq -r '.container.id')

  # 2回目のリクエスト：コンテナを再利用してファイルを読み取ります
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "container": "'"$CONTAINER_ID"'",
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [{
        "role": "user",
        "content": "Read the number from \"/tmp/number.txt\" and calculate its square"
      }],
      "tools": [{
        "type": "code_execution_20250825",
        "name": "code_execution"
      }]
    }'
  ```

  ```bash CLI
  # 最初のリクエスト：ランダムな数値を含むファイルを作成します
  CONTAINER_ID=$(ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 4096 \
    --message '{role: user, content: Write a file with a random number and save it to "/tmp/number.txt"}' \
    --tool '{type: code_execution_20250825, name: code_execution}' \
    --transform container.id --raw-output)

  # 2番目のリクエスト：コンテナを再利用してファイルを読み取ります
  ant messages create \
    --container "$CONTAINER_ID" \
    --model claude-opus-5-5 \
    --max-tokens 4096 \
    --message '{role: user, content: Read the number from "/tmp/number.txt" and calculate its square}' \
    --tool '{type: code_execution_20250825, name: code_execution}'
  ```

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

  # 最初のリクエスト：新しいコンテナ内にランダムな数値を含むファイルを作成します
  response1 = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[
          {
              "role": "user",
              "content": "Write a file with a random number and save it to '/tmp/number.txt'",
          }
      ],
      tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
  )

  # 2回目のリクエスト：Claude が同じコンテナを再利用できるよう、コンテナIDを渡します
  response2 = client.messages.create(
      container=response1.container.id,
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[
          {
              "role": "user",
              "content": "Read the number from '/tmp/number.txt' and calculate its square",
          }
      ],
      tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
  )

  print(response2.to_json())
  ```

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

  // 最初のリクエスト：Claude が新しいコード実行コンテナ内にファイルを作成します
  const response1 = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Write a file with a random number and save it to '/tmp/number.txt'"
      }
    ],
    tools: [{ type: "code_execution_20250825", name: "code_execution" }]
  });

  // コード実行ツールの実行後、レスポンスにはコンテナが含まれます
  if (!response1.container) {
    throw new Error("Expected the first response to include a container");
  }

  // 2回目のリクエスト：同じコンテナを再利用するため、コンテナIDを渡し返します
  const response2 = await client.messages.create({
    container: response1.container.id,
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      { role: "user", content: "Read the number from /tmp/number.txt and calculate its square" }
    ],
    tools: [{ type: "code_execution_20250825", name: "code_execution" }]
  });

  console.log(JSON.stringify(response2));
  ```

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

  // 最初のリクエスト：Claude が新しいコード実行コンテナ内にファイルを作成します
  var response1 = await client.Messages.Create(new()
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new() { Role = Role.User, Content = "Write a file with a random number and save it to '/tmp/number.txt'" }],
      Tools = [new CodeExecutionTool20250825()]
  });

  // 2 回目のリクエスト：コンテナ ID を渡し返して、Claude が同じコンテナを再利用するようにします
  var response2 = await client.Messages.Create(new()
  {
      Container = response1.Container!.ID,
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new() { Role = Role.User, Content = "Read the number from '/tmp/number.txt' and calculate its square" }],
      Tools = [new CodeExecutionTool20250825()]
  });

  Console.WriteLine(response2);
  ```

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

  codeExecution := []anthropic.ToolUnionParam{
  	{OfCodeExecutionTool20250825: &anthropic.CodeExecutionTool20250825Param{}},
  }

  // 最初のリクエスト：新しいコンテナ内にランダムな数値を含むファイルを作成します
  response1, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Write a file with a random number and save it to '/tmp/number.txt'")),
  	},
  	Tools: codeExecution,
  })
  if err != nil {
  	log.Fatal(err)
  }

  // ファイルが残っているように、最初のリクエストのコンテナを再利用します。
  response2, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  	Container: anthropic.MessageCreateParamsContainerUnion{
  		OfString: anthropic.String(response1.Container.ID),
  	},
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Read the number from '/tmp/number.txt' and calculate its square")),
  	},
  	Tools: codeExecution,
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(response2.RawJSON())
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  // 最初のリクエスト：新しいコンテナ内にランダムな数値を含むファイルを作成します
  MessageCreateParams params1 = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(4096L)
      .addUserMessage("Write a file with a random number and save it to '/tmp/number.txt'")
      .addTool(CodeExecutionTool20250825.builder().build())
      .build();

  Message response1 = client.messages().create(params1);

  // 2回目のリクエスト：コンテナIDを渡して、同じコンテナを再利用します
  MessageCreateParams params2 = MessageCreateParams.builder()
      .container(response1.container().orElseThrow().id())
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(4096L)
      .addUserMessage("Read the number from '/tmp/number.txt' and calculate its square")
      .addTool(CodeExecutionTool20250825.builder().build())
      .build();

  Message response2 = client.messages().create(params2);
  IO.println(ObjectMappers.jsonMapper().valueToTree(response2));
  ```

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

  // 最初のリクエスト：Claude が新しいコード実行コンテナ内でファイルを書き込みます
  $response1 = $client->messages->create(
      maxTokens: 4096,
      messages: [
          [
              'role' => 'user',
              'content' => "Write a file with a random number and save it to '/tmp/number.txt'",
          ],
      ],
      model: Model::CLAUDE_OPUS_5_5,
      tools: [new CodeExecutionTool20250825()],
  );

  // 2 回目のリクエスト：コンテナを再利用するため、'/tmp/number.txt' はまだ存在します
  $response2 = $client->messages->create(
      container: $response1->container->id,
      maxTokens: 4096,
      messages: [
          [
              'role' => 'user',
              'content' => "Read the number from '/tmp/number.txt' and calculate its square",
          ],
      ],
      model: Model::CLAUDE_OPUS_5_5,
      tools: [new CodeExecutionTool20250825()],
  );

  echo json_encode($response2), PHP_EOL;
  ```

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

  # 最初のリクエスト：Claude が新しいコード実行コンテナ内でファイルを作成します
  response1 = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Write a file with a random number and save it to '/tmp/number.txt'"
      }
    ],
    tools: [Anthropic::CodeExecutionTool20250825.new]
  )

  # 2回目のリクエスト：コンテナIDを渡し返して、Claude が同じコンテナを再利用するようにします
  response2 = client.messages.create(
    container: response1.container.id,
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: "Read the number from '/tmp/number.txt' and calculate its square"
      }
    ],
    tools: [Anthropic::CodeExecutionTool20250825.new]
  )

  puts response2.to_json
  ```
</CodeGroup>

## 他の実行ツールとコード実行を併用する

コードを実行する他のクライアント提供ツール（[Bashツール](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/bash-tool)やカスタムREPLなど）と一緒にコード実行を提供する場合、Claudeはマルチコンピューター環境で動作することになります。コード実行ツールはAnthropicのサンドボックス化されたコンテナで実行される一方、クライアント提供ツールはユーザーが管理する別の環境で実行されます。Claudeはこれらの環境を混同することがあり、誤ったツールを使用しようとしたり、環境間で状態が共有されていると想定したりする場合があります。

これを避けるには、違いを明確にする指示を「system prompt」（システムプロンプト）に追加してください。

```text wrap
When multiple code execution environments are available, be aware that:
- Variables, files, and state do NOT persist between different execution environments
- Use the code_execution tool for general-purpose computation in Anthropic's sandboxed environment
- Use client-provided execution tools (e.g., bash) when you need access to the user's local system, files, or data
- If you need to pass results between environments, explicitly include outputs in subsequent tool calls rather than assuming shared state
```

これは、コード実行を自動的に有効にする[ウェブ検索](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/web-search-tool)や[ウェブフェッチ](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/web-fetch-tool)とコード実行を組み合わせる場合に特に重要です。アプリケーションがすでにクライアント側のシェルツールを提供している場合、自動的なコード実行によって2つ目の実行環境が作成されるため、Claudeはそれらを区別する必要があります。

Claudeがコード実行と並行してクライアントツールのいずれかを呼び出すと、APIはコード実行の呼び出しを結果なしで返します。結果は、クライアントツールの`tool_result`ブロックを送り返した後の、後続のレスポンスで届きます。

## ストリーミング

[「streaming」（ストリーミング）](https://platform.claude.com/docs/ja/build-with-claude/streaming)を有効にすると（`"stream": true`）、コード実行イベントが発生するたびに受信できます。サブツールの入力は`input_json_delta`イベントとしてストリーミングされ、各結果ブロックは単一の`content_block_start`イベントでまとめて届きます。

```sse
event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "bash_code_execution"}}

// Tool input streamed as partial JSON
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"command\": \"python analyze.py\"}"}}

// Pause while the command runs

// Execution result delivered as a complete block
event: content_block_start
data: {"type": "content_block_start", "index": 2, "content_block": {"type": "bash_code_execution_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"type": "bash_code_execution_result", "stdout": "   A  B  C\n0  1  2  3\n1  4  5  6", "stderr": "", "return_code": 0, "content": []}}}
```

## バッチリクエスト

コード実行ツールは[Messages Batches API](https://platform.claude.com/docs/ja/build-with-claude/batch-processing)に含めることができます。Messages Batches APIを通じたコード実行ツールの呼び出しは、通常のMessages APIリクエストと同じ料金です。

## 使用量と料金

**コード実行は、web searchまたはweb fetchと併用する場合は無料です。** APIリクエストに `web_search_20260209`（またはそれ以降）もしくは `web_fetch_20260209`（またはそれ以降）が含まれている場合、標準の入力トークンおよび出力トークンのコスト以外に、コード実行ツールの呼び出しに対する追加料金は発生しません。

これらのツールなしで使用する場合、コード実行は実行時間に基づいて課金され、トークン使用量とは別に追跡されます。

* 実行時間の最小単位は5分です
* 各組織には、毎月**1,550時間の無料**使用枠が付与されます
* 1,550時間を超える追加使用分は、**コンテナごとに1時間あたり$0.05 USD**で課金されます
* リクエストにファイルが含まれている場合、ファイルはコンテナに事前にロードされるため、ツールが呼び出されなくても実行時間が課金されます

コード実行の使用量はレスポンス内で追跡されます。

```json
{
  "usage": {
    "input_tokens": 105,
    "output_tokens": 239,
    "server_tool_use": {
      "code_execution_requests": 1
    }
  }
}
```

## 最新のツールバージョンへのアップグレード

最新のツールバージョンは`code_execution_20260521`です。現在の3つのバージョン間で移行するには、リクエスト内の`type`文字列を更新してください。3つすべてが[レスポンス形式](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#response-format)に記載されたレスポンスブロックを返します。各バージョンで追加される機能については[ツールバージョン](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#tool-versions)を、それらをサポートするモデルについては[互換性](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#compatibility)を参照してください。

このセクションの残りの部分では、従来のPython専用の`code_execution_20250522`から現在のツールバージョンへの移行について説明します。

### 変更点

| コンポーネント  | 従来                          | 現在                                                                 |
| -------- | --------------------------- | ------------------------------------------------------------------ |
| ベータヘッダー  | `code-execution-2025-05-22` | 不要                                                                 |
| ツールタイプ   | `code_execution_20250522`   | `code_execution_20250825`以降                                        |
| 機能       | Pythonのみ                    | Bashコマンド、ファイル操作                                                    |
| レスポンスタイプ | `code_execution_result`     | `bash_code_execution_result`、`text_editor_code_execution_*_result` |

### 後方互換性

* 既存のPythonコード実行はすべて、これまでとまったく同じように動作し続けます
* 既存のPython専用ワークフローに変更は必要ありません

### アップグレード手順

アップグレードするには、APIリクエスト内のツールタイプを更新します。

```diff
- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"
```

**レスポンス処理を確認する**（プログラムでレスポンスを解析している場合）：

* APIは、Python実行のレスポンスに対して以前のブロックを送信しなくなりました
* 代わりに、APIはBashおよびファイル操作用の新しいレスポンスタイプを送信します（[レスポンス形式](https://platform.claude.com/docs/ja/agents-and-tools/tool-use/code-execution-tool#response-format)を参照）

## データ保持

コード実行は、サーバー側のサンドボックスコンテナで実行されます。実行アーティファクト、アップロードされたファイル、出力を含むコンテナデータは、最大30日間保持されます。この保持は、コンテナ環境内で処理されるすべてのデータに適用されます。コード実行が[Files API](https://platform.claude.com/docs/ja/build-with-claude/files)に作成したファイル（`client.files.download()` (csharp, go: `client.Files.Download()`; java: `client.files().download()`; php: `$client->files->download()`)で取得可能）は、明示的に削除されるまで保持されます。

すべての機能における「Zero Data Retention」（ゼロデータ保持）、すなわちZDRの適格性については、[APIとデータ保持](https://platform.claude.com/docs/ja/manage-claude/api-and-data-retention)を参照してください。

## 次のステップ

<CardGroup cols={2}>
  <Card title="アドバイザーツール" icon="compass" href="https://platform.claude.com/docs/ja/agents-and-tools/tool-use/advisor-tool">
    高速な実行モデルと、生成の途中で戦略的なガイダンスを提供する より高度な知能を持つアドバイザーモデルを組み合わせます。
  </Card>

  <Card title="プログラムによるツール呼び出し" icon="code" href="https://platform.claude.com/docs/ja/agents-and-tools/tool-use/programmatic-tool-calling">
    コード実行コンテナ内で実行されるコードから、独自のツールを呼び出します。
  </Card>

  <Card title="Files API" icon="file" href="https://platform.claude.com/docs/ja/build-with-claude/files">
    分析用のファイルをアップロードし、コード実行が作成したファイルをダウンロードします。
  </Card>

  <Card title="APIでAgent Skillsを使用する" icon="book" href="https://platform.claude.com/docs/ja/build-with-claude/skills-guide">
    Agent Skillsを使用して、API経由でClaudeの機能を拡張する方法を学びます。
  </Card>
</CardGroup>
