A Step-by-Step Guide to Claude’s Code Execution Tool: Real Numbers, Not Guesses

Rows of server racks in a data center, illustrating the sandboxed infrastructure behind cloud-based AI tool execution

Claude’s code execution tool is a server-side sandbox that runs real Python inside the Anthropic API, so instead of estimating an average or guessing at a date calculation, the model writes a script, runs it, and reads back the actual output. You turn it on by adding one object to the tools array in your Messages API request — no separate beta header is required for the current versions. The rest of this guide walks through enabling it, what the sandbox can and can’t do, and where it tends to surprise people in production.

What the sandbox actually is

The code execution tool gives Claude a secure, sandboxed container that executes server-side, inside the same API request — Claude doesn’t call out to your infrastructure, and you don’t need to run anything yourself. Each container is a Linux x86_64 machine with Python 3.11, 5 GiB of RAM, 5 GiB of workspace storage, and a single CPU. Anthropic’s documentation is explicit that network access is “completely disabled for security”: the container can’t make outbound requests, and Claude can’t pip install anything at runtime beyond what’s preloaded.

That preloaded set covers most real analysis work without a network call: pandas, numpy, scipy, scikit-learn, and statsmodels for data science; matplotlib and seaborn for charts; openpyxl, xlrd, pypdf, pdfplumber, python-docx, and python-pptx for file formats; sympy and mpmath for symbolic and arbitrary-precision math; plus command-line tools like ripgrep, fd, sqlite, and 7zip. If a task needs a library outside that list, the tool can’t fetch it — that’s the first wall most people hit.

Containers aren’t single-use in the way you might expect. A new one spins up per request by default, but it checkpoints after about five minutes of inactivity and can be restored for up to 30 days by passing its ID back in a later request. Anthropic’s docs draw a specific distinction here: the expires_at field on the response’s container object is a short rolling value, not the real 30-day limit — don’t build logic around it expecting the longer window.

Step 1: Add the tool to your request

Enabling the tool is a single entry in the tools array. The name field must be exactly code_execution; the type field picks which version of the tool you get:

"tools": [
  {
    "type": "code_execution_20250825",
    "name": "code_execution"
  }
]

There are three current type values, and the difference between them matters more than it looks. code_execution_20250825 supports bash commands and file operations. code_execution_20260120 adds REPL state persistence (variables survive between tool calls in the same conversation) and programmatic tool calling from inside the sandbox. code_execution_20260521 runs on the same engine as 20260120, but its tool description additionally tells Claude about a 90-second per-cell wall-clock limit, which changes how the model paces long computations. If you’re using Claude’s dynamic web search or web fetch filtering (the web_search_20260209 or web_fetch_20260209 tool versions and later), you need 20260120 or newer for them to work together.

A legacy header, code-execution-2025-05-22, still works as an opt-in for the older Python-only code_execution_20250522 tool type, but there’s no reason to start a new integration on it.

“Programmatic tool calling” is the detail most people skim past, and it’s the one that changes how you design a multi-step workflow. On the older tool version, Claude’s code and your other tools (a database lookup, a search call, a custom function) stay in separate turns — the model writes code, gets a result, then decides what to call next in a new round trip. With code_execution_20260120 or later, Claude can invoke your other defined tools directly from inside the running Python session, chain their outputs together, and keep variables alive across those calls in the same REPL, instead of serializing everything back through you between steps.

Step 2: Check model support before you ship

Not every model supports every tool version the same way, and the documentation itself warns about checking the wrong field. Anthropic’s guidance is to read capabilities.server_tools.code_execution.supported from the Models API for the model you’re targeting, rather than the top-level capabilities.code_execution field — that top-level field actually refers to programmatic tool calling, a narrower capability. As one concrete example from the docs, Claude Haiku 4.5 accepts the 20260120 and 20260521 tool types but without REPL state persistence or programmatic tool calling, so a script that assumes those features will behave differently depending on which model is behind the request.

Step 3: A worked before/after example

Here’s the practical difference the tool makes, using Anthropic’s own sample calculation. Without the tool, you’d prompt: “What’s the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]?” and Claude answers from reasoning alone — for a list this short it usually lands close to correct, but there’s no execution behind the number, and the risk compounds fast with larger or messier datasets, floating-point edge cases, or multi-step statistics.

With the tool enabled, the same request actually runs numpy:

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"}],
)

Claude writes something equivalent to numpy.mean([1..10]) and numpy.std([1..10]), executes it in the container, and reports back the real result: a mean of 5.5, and — because numpy.std() defaults to the population formula (dividing by n, not n−1) — a standard deviation of roughly 2.87. If you asked for the sample standard deviation instead (dividing by n−1, which is what pandas’ .std() defaults to), the correct figure is roughly 3.03. That distinction between population and sample standard deviation is exactly the kind of silent discrepancy that’s easy to get wrong when a model reasons in prose and easy to get right when it executes code and you can inspect which formula it actually used.

The response comes back as a server_tool_use block named bash_code_execution, followed by a bash_code_execution_tool_result containing stdout, stderr, and return_code. That result structure is what you’d parse to pull the verified number out programmatically, instead of trusting whatever number appears in Claude’s prose.

Step 4: Feed it files instead of pasting data into the prompt

For anything bigger than a short list, upload the file through the Files API first and reference it with a container_upload content block rather than pasting raw data into the message:

file_object = client.files.upload(file=Path("data.csv"))

messages=[{
    "role": "user",
    "content": [
        {"type": "text", "text": "Analyze this CSV data"},
        {"type": "container_upload", "file_id": file_object.id},
    ]
}]

Supported input types include CSV, Excel (.xlsx, .xls), JSON, XML, images (JPEG, PNG, GIF, WebP), and plain-text formats like .txt, .md, and .py. On the way out, each bash execution gets a fresh, empty $OUTPUT_DIR; any file Claude writes at the top level of that directory is captured and returned as a file_id you can retrieve with client.files.download(file_id). Anything the model writes elsewhere in the container stays in the container and isn’t returned to you — a common cause of “the model said it saved the file but I can’t find it.”

What it costs

Code execution is billed separately from tokens, by execution time, with one notable exception: if your request also uses web_search_20260209, web_fetch_20260209, or later versions of those tools, code execution runs at no extra charge beyond standard token costs. Outside that case, here’s what the documentation lists:

FactorWhat Anthropic’s docs say
Minimum charge5 minutes per execution
Free allowance1,550 free hours per organization, per month
Beyond the free tier$0.05 USD per hour, per container
Files attached but tool unusedStill billed, because files are preloaded onto the container regardless
Batch API requestsPriced the same as regular Messages API requests
Usage field to watchusage.server_tool_use.code_execution_requests

Common pitfalls

  • Assuming it can reach the internet. It can’t. Network access is fully disabled, so any workflow that needs to call an external API or download a package mid-run has to happen outside the container.
  • Losing a paused turn. The API can return a pause_turn stop reason mid-execution. If you don’t send the container ID back on the next call, files created earlier in that turn are gone — the fix is to always round-trip the container.id from the response.
  • Hitting the per-cell timeout. With programmatic tool calling, each Python cell has a 90-second wall-clock limit; a cell that runs longer returns a non-zero return_code with a detection_timeout status rather than finishing late.
  • Oversized bash output. A bash command that prints too much can return output_file_too_large. Anthropic’s page doesn’t publish an exact byte threshold, so treat verbose debug printing as a risk, not just a readability issue.
  • Checking the wrong capability field. capabilities.code_execution on the Models API refers to programmatic tool calling, not whether the tool is supported at all — use capabilities.server_tools.code_execution.supported instead.
  • Paying for files you never used. If a request includes a container_upload, execution time gets billed because the files are preloaded onto the container the moment the request starts — even if Claude’s response never ends up calling the tool.

Once the sandbox is wired in, it pairs naturally with a few other pieces of Claude’s tool-use stack: Claude’s extended thinking budget tokens for deciding how much the model reasons before it even writes code, parallel tool calls in Claude vs. OpenAI vs. Gemini for when a task needs the sandbox alongside other tools in the same turn, and Claude’s Files API for PDFs when the input is a document rather than a spreadsheet. If you’re weighing code execution against just embedding a schema and asking Claude to compute in plain text, the gap is exactly what this guide has been pointing at: one approach produces a number, the other produces a number you can trace back to the exact script that made it.

Sources: Anthropic — Code execution tool, Anthropic — Files API, Anthropic — Tool use overview, Anthropic — Models overview.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top