Skip to content

Programmatic tool calling: when Claude writes the loop and your app runs the tools

On this page

Programmatic tool calling is a Claude API feature where Claude writes Python that runs in the code execution tool’s container and calls your tools as functions. You opt a tool in by adding allowed_callers: ["code_execution_20260120"] to its definition. When the code calls it, the API pauses and returns a tool_use block to your application, you send back a tool_result, and the code continues. Results go to the running code, not into Claude’s context; only the script’s final output reaches the model. It pays off for fan-out, loops over many items and large results that need filtering, and costs extra for one or two small calls.

Checked as of November 2026 against Anthropic’s programmatic tool calling docs, the code execution tool docs, the engineering posts Code execution with MCP and Introducing advanced tool use, and the MCP tools specification (revision 2026-07-28).

How programmatic tool calling works

With normal tool use, every full result lands in the context, and calls that depend on earlier results each need a model turn. Twenty sequential lookups mean twenty round trips. With programmatic tool calling, the documented flow is:

  1. Claude writes Python that calls your tools, with whatever loops, filters and branches it needs.
  2. The code runs in a sandboxed code execution container.
  3. When the code calls one of your tools, execution pauses and the API returns a tool_use block.
  4. You return the result, and the code resumes with it. The result is not loaded into Claude’s context.
  5. When the code finishes, Claude receives its output and continues the turn.

Inside the container, opted-in tools are async Python functions that take one dict of arguments and return your tool_result text, so the code can run several at once with asyncio.gather. Keeping tool output out of the window is part of context engineering.

Opting a tool in with allowed_callers

You need two things in tools: the code execution tool at version code_execution_20260120 or later, and allowed_callers on each custom tool the code may call. This is the quick-start request from Anthropic’s docs:

Shell
curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -H "content-type: application/json" \
  -d '{
    "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"]
      }
    ]
  }'

allowed_callers takes ["direct"] (the default), ["code_execution_20260120"], or both; code_execution_20260521 is accepted as an equivalent value. Anthropic recommends one mode per tool. The field is guidance, not enforcement: your client must still handle a direct tool_use for any tool it defines, and the docs say not to rely on it as a security boundary. Describe the output format in the tool description, because Claude’s code will parse it.

The request and response flow

When the code calls query_database, the response stops with stop_reason: "tool_use". It contains a server_tool_use block holding the code, a tool_use block for your tool, and a container object:

JSON
{
  "type": "tool_use",
  "id": "toolu_def456",
  "name": "query_database",
  "input": { "sql": "<sql>" },
  "caller": {
    "type": "code_execution_20260120",
    "tool_id": "srvtoolu_abc123"
  }
}

caller marks a call from code (a direct call has "type": "direct"), and tool_id points to the server_tool_use block that made it. To continue, send the conversation back with three rules:

  • The user message answering pending programmatic calls may contain only tool_result blocks, with string or text content. No text block, no images.
  • Pass the container ID from the paused response. The API rejects a continuation with pending programmatic calls and no container.
  • Send the same tools array, including the code execution tool.

A minimal application loop in TypeScript looks like this, with callTool standing in for however you actually execute the tool:

ts
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

// Runs one tool call (for example, forwards it to an MCP server) and returns text.
declare function callTool(name: string, input: unknown): Promise<string>;

async function run(
  messages: Anthropic.MessageParam[],
  tools: Anthropic.Messages.ToolUnion[],
) {
  let container: string | undefined;
  for (;;) {
    const response = await client.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 16000,
      messages,
      tools, // same array on every request
      ...(container ? { container } : {}),
    });
    container = response.container?.id ?? container;
    messages.push({ role: "assistant", content: response.content });

    if (response.stop_reason === "pause_turn") continue;
    if (response.stop_reason !== "tool_use") return response;

    const results: Anthropic.ToolResultBlockParam[] = [];
    for (const block of response.content) {
      if (block.type !== "tool_use") continue;
      console.log(JSON.stringify({ tool: block.name, caller: block.caller, input: block.input }));
      results.push({
        type: "tool_result",
        tool_use_id: block.id,
        content: await callTool(block.name, block.input),
      });
    }
    messages.push({ role: "user", content: results });
  }
}

Each continuation either pauses for more calls or finishes the code, returning a code_execution_tool_result with stdout, stderr and return_code, then Claude’s answer. Timing is tight: a pending call raises TimeoutError in the code after about 4 minutes, and Claude typically retries it. Each Python cell also has a 90-second wall-clock limit.

Models, platforms and pricing

Current documentation
Tool versioncode_execution_20260120 or later; no anthropic-beta header
ModelsClaude Opus 4.5 and Sonnet 4.5 onward, Haiku 5.5, and the Fable and Mythos models; Haiku 4.5 accepts the tool but not programmatic calls
Check supportcapabilities.code_execution.supported in the Models API
PlatformsClaude API, Claude Platform on AWS, Claude Models on Google Cloud (Anthropic managed), Microsoft Foundry hosted on Anthropic; not Managed Agents
ContainerPython 3.11, 5 GiB RAM, 5 GiB disk, 1 CPU, no internet access
PricingCode execution pricing: 1,550 free hours per organization per month, then $0.05 per container hour, 5-minute minimum; free when web_search_20260209 or web_fetch_20260209 is in the request
TokensResults of programmatic calls don’t count as input or output tokens; the final code output and Claude’s response do
DataNot eligible for zero data retention; container data kept up to 30 days

The feature launched in beta on November 24, 2025, with the header advanced-tool-use-2025-11-20. The current docs need no beta header.

What isn’t supported

  • MCP connector tools. Tools provided through the API’s MCP connector can’t be called programmatically. Neither can the computer use and browser use toolsets.
  • Strict tools. Tools with strict: true don’t work with programmatic calling.
  • Forcing. tool_choice can’t force a programmatic call, and naming a tool without "direct" in allowed_callers returns a 400.
  • Disabling parallel calls. disable_parallel_tool_use: true isn’t supported.
  • Recursive schemas. An input_schema with a $ref cycle fails with Circular $ref detected.

The MCP connector limit is the one MCP users hit first. To call MCP tools from code, your application lists them as ordinary custom tools and executes each call itself, for example by forwarding it as an MCP tools/call.

Code execution with MCP

Anthropic’s engineering post Code execution with MCP (Adam Jones and Conor Kelly, November 4, 2025) describes a broader pattern for agents that already have a code sandbox. It names two costs of direct MCP tool use: every tool definition loaded up front, and every intermediate result passing through the model.

Its answer is to present MCP servers as code on a filesystem. A ./servers/ directory holds one folder per server and one TypeScript file per tool, each a thin wrapper around an MCP client call. The agent lists directories and reads only the definitions it needs, or uses a search_tools tool. In the post’s example, an agent copies a meeting transcript from Google Drive into Salesforce without the transcript entering the context, which “reduces the token usage from 150,000 tokens to 2,000 tokens,” a 98.7% saving.

The post also covers privacy: intermediate data stays in the execution environment unless logged, and the harness can tokenize personal data so the model sees placeholders such as [EMAIL_1] while the MCP client substitutes real values between tools. Agents can write state to files and resume later, and save working code under ./skills/ with a SKILL.md to reuse it. The stated cost is that agent-written code “requires a secure execution environment with appropriate sandboxing, resource limits, and monitoring.”

The two are related but not the same:

Programmatic tool callingCode execution with MCP
What it isAn API featureAn architecture pattern
LanguagePython in Anthropic’s containerTypeScript in the post’s examples
Tool discoveryTools sent in the request’s tools arrayAgent browses tool files or searches
Who executes callsYour application, per tool_use blockThe MCP client inside your environment
SandboxRun by AnthropicYours to build and operate
MCP toolsOnly as custom tools you defineNative, by design

For loading definitions on demand without a filesystem, see MCP tool search.

When to use it and when not

Gains depend on workload shape. In Anthropic’s evaluations, a 75-tool project-management benchmark used about 38% fewer billed input tokens with unchanged accuracy, while τ²-bench, where each turn makes one or two sequential calls, kept the same scores at about 8% more cost.

Use it for fan-out across many items (50 endpoints, 20 records), large results the code can filter or aggregate, and loops with early exit or polling. Skip it for one or two small calls, where container and script overhead outweigh the savings; for sequential work where each step needs Claude to reason over the last result; for tools that need a person between calls; and while debugging a tool, when you want every raw result in the transcript. Anthropic advises measuring billed input tokens with and without allowed_callers on real traffic first.

Risks and operations

Model-written code runs against real tools. The sandbox has no network, but your tools do. A script that loops over 200 customers calling update_record makes 200 real writes that Claude never reviews. Keep write tools direct-only unless batching them is the point.

Partial runs and duplicates. A script can fail after item 7 of 20, and rerunning it repeats items 1 to 6. A call that outlives the 4-minute timeout may still complete on your side while the code retries it. Writes reachable from code need idempotency keys or a check before writing.

Intermediate data is out of view. Data the script doesn’t print never reaches the model, so instructions hidden in it can’t steer the model directly. The code can still move private data into a tool that sends it out, so the lethal trifecta applies to scripts too, and the docs warn to validate tool results for code injection.

Approval-required results inside a script. If a person must approve a tool, the script receives that outcome as a string. Code that expects JSON can fail to parse it, a broad try/except can swallow it, and retrying in a loop won’t make it run. Tell Claude in the tool description to stop, print the message and end the script, so the request reaches the user. Human in the loop for AI agents covers where approvals belong.

Log every call. The MCP specification says clients should log tool usage for audit, and Anthropic’s debugging tips start with logging all calls and results. Record the caller, its tool_id and the code in the matching server_tool_use block, so a reviewer can tie each call to the script that made it.

Compared with Cloudflare’s Code Mode

Cloudflare’s Code Mode, which the Anthropic post cites as a similar approach, turns MCP tools into a TypeScript API and runs model-written code in a V8 isolate with no network access by default, with credentials held outside the sandbox. Programmatic tool calling runs Python in Anthropic’s container instead, and hands every call back to your application as a tool_use block. Code Mode for MCP covers Cloudflare’s version.

Programmatic tool calling with Toolstile

Toolstile is a managed MCP gateway; it doesn’t run code and has no programmatic tool calling feature. When your application lists gateway tools as custom tools and executes each call, every call the code makes is an ordinary MCP tools/call that reaches the gateway, so per-agent allow, block and require-approval rules and the call log apply per call, not per script. Tools appear as <namespace>__<upstream name>, and namespaces are never reassigned to a different connection, so a name in a saved script can’t quietly start calling another connection.

For a Require approval tool, the caller gets a tool error (isError: true) whose _meta["toolstile/approval"] holds the request ID, status, expiry and review link. A person approves or denies, approving doesn’t run anything, and the identical call has to be retried; different arguments need a new approval, and pending requests expire after 15 minutes. With programmatic tool calling, your application sees that result before the script does, so it can end the run and show the review link instead of handing the script an error string. Code that does receive it should stop and surface it, not loop on it or swallow it. What an MCP gateway is describes the rest of the model.