D2 · Tool Design & MCP › Cluster 4 · Advanced Tool Use

4.4 · Programmatic Tool Calling & Code Execution

Let Claude orchestrate tools in code

CONCEPT The code-execution tool is a real, server-side sandbox

Code execution is an Anthropic-hosted, server-side tool: you declare it in tools (e.g. {"type": "code_execution_20260120", "name": "code_execution"}) and Claude runs Python/bash in an isolated container on Anthropic's infrastructure — no client-side execution loop. Results come back as content blocks in the same response (for bash, a bash_code_execution_tool_result block with .content.stdout / .stderr / .return_code). The container persists and can be reused across requests.

🔑 "Server-side" means Anthropic runs the code; you don't execute anything. Contrast with your own custom tools, which you run client-side and feed back as tool_result.

CONCEPT Programmatic tool calling: Claude composes tool calls in a script

Normally each tool call is a round trip: Claude calls → the result lands in Claude's context → Claude reasons → calls again. Three sequential lookups = three round trips, and every intermediate result burns context tokens. Programmatic tool calling (PTC) lets Claude write a script that invokes your tools as functions inside the code-execution container:

How to enable it (no beta header): add the code_execution_20260120 tool and set "allowed_callers": ["code_execution_20260120"] on each custom tool the script may call. Available on Opus 4.5+ / Sonnet 4.5+.

⚠️ PTC has hard incompatibilities: it does not work with strict: true, disable_parallel_tool_use, a forced tool_choice, or MCP tools. And when you respond to a pending programmatic call, the user message must contain only tool_result blocks (no text).

DIAGRAM Round trips vs. one script

flowchart TD subgraph STD["Standard tool use"] A1["Claude → get_profile"] --> A2["result into context"] A2 --> A3["Claude → get_orders"] --> A4["result into context"] A4 --> A5["Claude → check_stock"] --> A6["result into context"] A6 --> A7["🔴 3 round trips,
all payloads in window"] end subgraph PTC["Programmatic tool calling"] B1["Claude writes ONE script"] --> B2["code_exec container runs it"] B2 --> B3["script calls tools as fns
(pause → run → resume)"] B3 --> B4["results stay in the CODE,
filtered by loops/branches"] B4 --> B5["🟢 only final output
returns to Claude"] end classDef ok fill:#d4edda,stroke:#28a745,color:#155724; classDef bad fill:#f8d7da,stroke:#dc3545,color:#721c24; class B5 ok; class A7 bad;

CODE Enable code execution + a programmatically-callable tool

Declaring code_execution and marking lookup_orders with allowed_callers lets Claude invoke it from inside a script, keeping the (potentially large) order list out of its context.

resp = client.messages.create(
    model="claude-opus-4-8", max_tokens=16000,
    tools=[
        {"type": "code_execution_20260120", "name": "code_execution"},  # server sandbox
        {
            "name": "lookup_orders",
            "description": "Return all orders for a customer id.",
            "allowed_callers": ["code_execution_20260120"],   # callable from code
            "input_schema": {"type": "object",
                "properties": {"customer_id": {"type": "string"}},
                "required": ["customer_id"]},
        },
    ],
    messages=[{"role": "user",
               "content": "Of my orders, how many shipped late? Just the count."}],
)

# Claude writes code that calls lookup_orders(...), loops over the results
# INSIDE the container, and returns only the count. Read stdout:
for block in resp.content:
    if block.type == "bash_code_execution_tool_result":
        print(block.content.stdout)          # e.g. "7"
# NOTE: not compatible with strict / disable_parallel_tool_use /
# forced tool_choice / MCP tools. Replies to pending PTC calls =
# tool_result blocks ONLY (no text).

TRADE-OFFS When to hand orchestration to code

✅ Programmatic tool calling

  • Many sequential/looping tool calls collapse into one turn
  • Large intermediate results filtered before reaching context
  • Token cost tracks the final output, not the raw payloads

⚠️ Constraints & cost

  • No strict, no disable_parallel_tool_use, no forced tool, no MCP tools
  • Needs the code-execution sandbox (Opus 4.5+ / Sonnet 4.5+)
  • Overkill for one or two calls Claude can just make directly
Reach for PTC when the pattern is "fan out over N items / chain several lookups / crunch a big result." For a single tool call, standard round-trip tool use is simpler.

EXAM TRAPS

Trap: Thinking you execute the code-execution tool client-side. → It's server-side — Anthropic runs it in a sandbox and returns bash_code_execution_tool_result blocks. Nothing to run locally.
Trap: Combining PTC with tool_choice:{"type":"tool",…}, strict:true, disable_parallel_tool_use, or MCP tools. → All incompatible with programmatic tool calling.
Trap: Expecting every intermediate tool result in Claude's context with PTC. → The whole point is the opposite: results return to the running script; only the final output reaches Claude.
Trap: Adding text to the message that answers a pending programmatic call. → It must contain only tool_result blocks. And PTC needs no beta header — don't invent one.

PRACTICE

Q1 · Where do intermediate tool results go under programmatic tool calling?

Into the running code in the code-execution container — not into Claude's context. The script processes them with normal control flow and returns only its final output to Claude, so token cost tracks that output, not the raw payloads.

Q2 · What two things must you configure to let Claude call your tool from a script?

Declare the code-execution tool (code_execution_20260120) and set "allowed_callers": ["code_execution_20260120"] on the custom tool. No beta header is needed (Opus 4.5+ / Sonnet 4.5+).

Q3 · Name two features PTC is incompatible with, and why it matters.

Any of: strict: true, disable_parallel_tool_use, forced tool_choice, MCP tools. It matters because reaching for one of those alongside PTC will fail — you can't, say, force a tool and have Claude orchestrate tools in code at once.