Code Execution Tool
The code execution tool runs Bash commands and file operations in a sandboxed container on Anthropic's infrastructure. Use it when the answer is "whatever the code prints", not when you only need code written.
When to Use
- Data analysis on uploaded files (CSV, JSON, Excel, PDF)
- Charts, reports, and other generated files returned through the Files API
- Math or statistics the model should verify by running, not estimate
- Running tests or scripts the model just wrote, inside an isolated environment
When NOT to Use
- Pure text tasks: the tool adds latency and cost for nothing
- Work that needs the internet or packages that are not pre-installed: the container has no internet access
- Long-running jobs (training, crawling): use your own compute
- Workloads that require zero data retention: the docs list code execution as not ZDR-eligible (container data is retained up to 30 days)
Workflow
Step 1: Pick a tool version
The tool is a server tool: declare it in tools and results arrive in the same response. Current versions need no beta header.
Tool type |
Adds | Use when |
|---|---|---|
code_execution_20250825 |
Bash commands and file operations | Plain analysis and file generation |
code_execution_20260120 |
REPL state persistence and programmatic tool calling | Claude should call your tools from inside code |
code_execution_20260521 |
Same runtime as 20260120; tells Claude about the per-cell time limit in programmatic tool calling |
Programmatic tool calling with long-running cells |
code_execution_20250522 was the original Python-only version; the docs include a migration section for it. Tool types are dated identifiers, so re-check the tool-version table whenever you adopt a new model and prefer the newest version your integration supports. To check support programmatically, read capabilities.server_tools.code_execution.supported from the Models API.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const MODEL = process.env.ANTHROPIC_MODEL!; // a current model ID from the models overview page
const response = await client.messages.create({
model: MODEL,
max_tokens: 16000,
tools: [{ type: "code_execution_20250825", name: "code_execution" }],
messages: [{ role: "user", content: "Compute the mean and standard deviation of [1,2,3,4,5,6,7,8,9,10]." }],
});
Step 2: Upload input files
Upload with the Files API, then reference the file in a container_upload content block. The Files API is generally available; current SDKs expose it as client.files. Older code used client.beta.files with a files-api-2025-04-14 beta header; check your SDK changelog before migrating, because the beta namespace changed shape.
import fs from "node:fs";
const file = await client.files.upload({ file: fs.createReadStream("sales.csv") });
const response = await client.messages.create({
model: MODEL,
max_tokens: 16000,
tools: [{ type: "code_execution_20250825", name: "code_execution" }],
messages: [{
role: "user",
content: [
{ type: "text", text: "Compute year-over-year growth from this CSV." },
{ type: "container_upload", file_id: file.id },
],
}],
});
Step 3: Read results correctly
The response interleaves server_tool_use blocks with result blocks. The current versions expose two sub-tools, bash_code_execution and text_editor_code_execution, so the result blocks are bash_code_execution_tool_result and text_editor_code_execution_tool_result, not the legacy code_execution_tool_result.
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") {
console.log("stdout:", result.stdout);
if (result.return_code !== 0) console.error("stderr:", result.stderr);
}
}
}
Always check return_code. A model can describe results confidently even when the command failed.
Step 4: Retrieve generated files
Each bash_code_execution call gets a fresh directory exposed as $OUTPUT_DIR. Only files at the top level of that directory are captured and returned as file_id entries; files written elsewhere stay in the container. If your application depends on a file, prompt Claude to copy it there and list the directory in the same command:
python /tmp/make_report.py && cp /tmp/report.pdf "$OUTPUT_DIR/" && ls "$OUTPUT_DIR"
Download returned files through the Files API.
Step 5: Reuse the container for multi-turn work
The response includes a top-level container object with an id. Pass it back as the top-level container parameter to keep files (and, with 20260120 or later, Python interpreter state) across requests.
const second = await client.messages.create({
model: MODEL,
max_tokens: 16000,
container: first.container!.id,
tools: [{ type: "code_execution_20250825", name: "code_execution" }],
messages: [/* full history plus the new question */],
});
The docs state that containers expire 30 days after creation and are checkpointed after a few minutes of inactivity. An expired container cannot be restored: retry without container to get a new one. The expires_at value in the response is a shorter rolling value, not the 30-day limit.
Sandbox Facts (as documented)
| Property | Documented value |
|---|---|
| Internet access | None; only pre-installed libraries are available |
| Python | 3.11 |
| Memory / disk / CPU | 5 GiB RAM, 5 GiB workspace, 1 CPU |
| Container lifetime | 30 days after creation |
Re-check the "Containers" section of the tool page before relying on these for capacity planning.
Pricing Notes
Code execution has its own pricing, except that the docs state it carries no extra charge in requests that also include the dynamic-filtering versions of web search or web fetch (web_search_20260209, web_fetch_20260209, or later). Look up current rates on the pricing page rather than hard-coding them.
Anti-Patterns
- Declaring code execution alongside dynamic-filtering web search or fetch: those tools provision code execution themselves
- Asking the model to "describe the chart" instead of downloading the file it produced
- Ignoring
return_codeandstderr - Starting a new container every turn for iterative analysis
- Uploading very large files when a sample would answer the question
Best Practices
- Enable the tool only on routes that need computation
- Use the simplest version that covers your needs, and re-check versions on every model upgrade
- Reuse the container for multi-turn analysis; handle expiry by starting fresh
- Instruct Claude to write deliverables to
$OUTPUT_DIRand list it - Treat outputs as untrusted: scrub secrets before you log or persist stdout
- Confirm data-retention requirements before sending regulated data
References
- Code execution tool: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool
- Programmatic tool calling: https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling
- Files API: https://platform.claude.com/docs/en/build-with-claude/files
- Pricing: https://platform.claude.com/docs/en/about-claude/pricing