Skip to content

MCP code mode: how it works and when it beats tool calling

MCP code mode has the model write one short program against a typed tool API and run it in a sandbox. How it works, three implementations, and when to use it.

Published
Reading time
14 min read

In short

  • MCP code mode exposes MCP tools as a typed API, has the model write one short program against it, runs that program in a sandbox, and returns only the program's output to the model.
  • It removes two costs of classic tool calling: tool definitions sent as input on every request, and intermediate tool results that pass through the model between calls.
  • Vendor numbers are not comparable. Cloudflare reports a 99.9% smaller tool footprint for one large API, Anthropic about 38% fewer billed input tokens on a 75-tool benchmark, and Maxim AI's published benchmarks 58.2% to 92.8% fewer input tokens for Bifrost as the tool count grows from 96 to 508.
  • Below about 20 tools with short results, plain tool calling with prompt caching is simpler and good enough. Code mode pays off on large catalogs and data-heavy, multi-step tasks, and it costs a sandbox to secure, coarser approvals, and harder debugging.

MCP code mode is a way of using Model Context Protocol tools in which the model writes a short program that calls the tools, instead of requesting each call one at a time. The tools are presented to the model as a typed API. The program runs in a sandbox, and only what it returns goes back into the model's context.

The pattern exists because classic tool calling gets expensive as a tool set grows. This article compares three public implementations as of November 2026: Cloudflare's Code Mode, Anthropic's code execution with MCP together with the programmatic tool calling feature in the Claude API, and Code Mode in Bifrost, an open-source AI gateway by Maxim AI. What is MCP? covers the protocol underneath all three.

Why classic tool calling gets expensive as tools multiply

Classic tool calling has two costs that grow with the tool set: every tool definition is sent as input on every request, and every intermediate tool result passes through the model before the next call. Both are paid before the agent produces anything useful, and together they are what people mean by MCP context bloat.

The first cost is definitions. An MCP server lists each tool with a name, a description, and a JSON Schema for its input, and most clients load every definition from every connected server into the prompt. Anthropic's engineering team counted 58 tools across five servers at about 55,000 tokens, and has seen definitions reach 134,000 tokens internally.

The agent loop resends the whole request on every turn, so a six-turn task reads that catalog six times. Prompt caching lowers the price of the repeated prefix, but cached tokens still occupy the context window.

The second cost is intermediate results. In Anthropic's example, an agent copies a meeting transcript from a document store into a CRM record. The transcript enters the context as a tool result, and the model writes it out again as the argument of the next call, which Anthropic puts at about 50,000 extra tokens for a two-hour meeting.

Accuracy drops as well. The Claude API docs say tool selection degrades once more than 30 to 50 tools are available, and OpenAI's function calling guide suggests fewer than 20 functions at the start of a turn. Context rot explains why extra context hurts, and context engineering covers how to budget it.

How MCP code mode works

Code mode replaces the tool list with an API the model can read and a single tool that runs code. The model looks up the functions it needs, writes one program that calls them, and receives the program's output.

CLASSIC TOOL CALLING · ONE MODEL TURN PER CALLMCP SERVERSTURN 1 · CALL OUT, FULL RESULT BACKTURN 2 · CALL OUT, FULL RESULT BACKTURN 3 · CALL OUT, FULL RESULT BACKModelIN CONTEXT EVERY TURNAll tool schemasEvery tool resultCRM serverOrders serverEmail serverCODE MODE · ONE PROGRAM, ONE RESULTMCP SERVERSONE PROGRAMFINAL RESULTModelIN CONTEXT EVERY TURNTool stubs it readThe final resultSandboxRUNS THE PROGRAMCalls the toolsKeeps raw resultsCRM serverOrders serverEmail server
The same three-tool task, twice. Classic tool calling spends a model turn on every call and reads every result. Code mode sends one program to a sandbox and reads one result.
  1. The client or gateway turns each MCP tool's schema into a typed function signature: TypeScript declarations in Cloudflare's version, Python stubs in Bifrost's.
  2. The model discovers signatures on demand, by listing stub files or calling a search function. Only the ones it reads enter the context.
  3. The model writes one program holding the tool calls, the control flow between them, and any filtering the task needs.
  4. A sandbox runs the program. Each function call leaves through a binding, reaches the real MCP server as an ordinary tool call, and hands a value back to the script. The model receives only what the script prints or returns.

Nothing changes on the MCP server, and credentials stay with the host, outside the sandbox.

The program below is illustrative: the servers and tools are invented, and the syntax follows the Python subset that Bifrost's sandbox accepts.

illustrative-program.py
# Illustrative only. crm, orders, and email stand for three connected MCP servers.
customer = crm.find_customer(email="dana@example.com")
history = orders.list_orders(customer_id=customer["id"], status="delivered")
 
late = [o for o in history["items"] if o["days_late"] > 3]
 
if len(late) > 0:
    email.send_template(
        to=customer["email"],
        template="late_delivery_credit",
        order_ids=[o["id"] for o in late],
    )
 
result = {"orders_checked": len(history["items"]), "late": len(late)}

Three tools ran with no model turn between them. The order history, which could be hundreds of rows, never entered the context, and the model reads back two integers.

Three implementations of MCP code mode compared

The three implementations share the mechanism and differ in where the code runs, which language the model writes, and who executes the tool.

Design choiceCloudflare Code ModeAnthropic programmatic tool callingBifrost Code Mode
Where the code runsA V8 isolate on Cloudflare Workers, created for each executionAnthropic's managed code execution containerA Starlark interpreter inside the self-hosted gateway process
Language the model writesJavaScript, against generated TypeScript typesPythonStarlark, a Python dialect
What the model is givenOne codemode toolThe code execution tool, plus your tool definitionsFour meta-tools
How it finds toolscodemode.search() and codemode.describe()A separate feature, the tool search toollistToolFiles, readToolFile, and getToolDocs
Who executes each toolThe host Worker, through connectorsYour application, one tool_use block at a timeThe gateway, under the caller's tool filters
Status, November 2026ExperimentalStableOpen source, v1.4.0-prerelease1 and later

Cloudflare: Code Mode on Workers isolates

Cloudflare introduced the name in September 2025. Its Agents SDK converts an MCP server's schema into a TypeScript API and gives the model a single tool that executes code in a V8 isolate. The isolate has no internet access. Its only exits are bindings to the connected MCP servers, and the host adds credentials on the far side, so generated code never holds an API key.

The current @cloudflare/codemode package accepts a JavaScript async arrow function and offers codemode.search() and codemode.describe() for discovery inside the sandbox. A durable runtime records every connector call, can pause for approval, and can roll back.

Cloudflare also runs the pattern on the server side. Its MCP server for the Cloudflare API exposes only search() and execute(), both of which take code, so any MCP client can use it without a sandbox of its own.

Anthropic's November 2025 engineering post describes the pattern as something you build. Each MCP server becomes a directory of TypeScript files, one per tool, and an agent with a code execution environment reads the files it needs.

The Claude API packages the two halves of the problem as separate features, both listed as stable as of November 2026. Programmatic tool calling handles intermediate results. You add allowed_callers to a tool definition, Claude writes Python in Anthropic's code execution container, and each time the script calls a tool the API hands your application a tool_use block. Your code runs the tool and returns the result to the script, not to the model.

The tool search tool handles definitions. Tools marked defer_loading: true stay out of the context until Claude searches for them.

Two limits matter for MCP users. Tools supplied through Anthropic's MCP connector cannot be called programmatically, and neither can tools with strict: true, the schema guarantee described in the tool calling article.

How Bifrost runs code mode at the gateway

Bifrost implements code mode in the gateway, so every agent behind it gets the pattern without operating a sandbox of its own. What an MCP gateway does covers the role, and Code Mode changes how the tools behind the gateway are shown to the model. It is switched on per connected MCP server, with one field.

config.json
{
  "mcp": {
    "client_configs": [
      {
        "name": "crm",
        "connection_type": "http",
        "connection_string": "http://localhost:3001/mcp",
        "tools_to_execute": ["*"],
        "is_code_mode_client": true
      }
    ]
  }
}

A server in code mode disappears from the tool list. In its place, every request carries four meta-tools:

  • listToolFiles lists virtual .pyi stub files, one per server or one per tool.
  • readToolFile returns compact Python signatures from one file.
  • getToolDocs returns full documentation for a single tool.
  • executeToolCode runs the model's program.

The program runs in a Starlark interpreter inside the gateway process. Starlark is a Python dialect built for hermetic, deterministic execution, and the sandbox has no imports, no classes, no file access, and no network access. Each execution gets a budget, by default 1,000,000 computation steps, 64 MiB of memory, 64 nested tool calls, and 30 seconds per tool call. The model sees only the script's print output and its result variable.

Access control carries into the sandbox:

  • With a virtual key on the request, discovery shows only the tools that key may execute.
  • Nested calls run with the original request's authorization and tool filters.
  • In Agent Mode, a program runs unattended only if every tool it calls is on the auto-execute list. Bifrost checks each call again when the running code makes it, so indirection in the script cannot reach a tool that needs approval.

Code Mode is part of the open-source gateway, licensed under Apache 2.0, and requires v1.4.0-prerelease1 or later as of November 2026. The in-process design avoids container startup, but its limits come from the interpreter's own accounting and not from the operating system, so size the memory budget against the gateway's memory and the concurrency you expect.

What the published numbers measure

Each vendor measured something different, so the percentages cannot be ranked against each other.

SourceWhat was measuredResult
Cloudflare, February 2026Tool definitions for the full Cloudflare API, more than 2,500 endpoints, as classic MCP tools versus two code toolsAbout 1.17 million tokens down to about 1,000, a 99.9% reduction
Anthropic engineering post, November 2025One example workflow, with tools loaded up front versus read from files on demand150,000 tokens down to 2,000, a 98.7% reduction
Claude API docsBilled input tokens on a 75-tool project-management agent benchmark, programmatic tool calling on versus offAbout 38% lower, with no change in task accuracy
Claude API docsτ²-bench, where each turn makes one or two sequential tool callsScores unchanged, cost about 8% higher
Maxim AI's published benchmarks for BifrostCumulative input tokens over 64 or 65 agent queries, Code Mode on versus off58.2% lower at 96 tools, 84.5% at 251 tools, 92.8% at 508 tools

In Maxim AI's published benchmarks, the largest round connected 508 tools across 16 servers. Input tokens fell from 75.1 million to 5.4 million and estimated cost from $377.00 to $29.00, and all 65 queries passed in both modes. The benchmark report qualifies those figures:

  • Every round ran on one model, Claude Sonnet 4.6.
  • Classic runs sent about 39,000 tokens of tool schemas per model call at 96 tools and 275,000 at 508, which is why the saving grows with the catalog.
  • The cost estimate prices every input token at one list rate. Caching the tool prefix would shrink the classic baseline, since Anthropic bills cache reads at 0.1 times the base input price as its standard multiplier.
  • Output tokens rose 72.2% in the largest round, because the model writes programs, and wall-clock time fell 6.8% to 26.8% across rounds.
  • In the 96-tool round, 3 of the 14 hard queries used more input tokens with Code Mode on.

Whatever a script prints or returns enters the context, so code mode saves tokens only when the program filters data first.

When code mode pays off, and when plain tool calling is enough

Code mode pays off when the catalog is large or the task moves a lot of data between calls, and it is overhead when neither is true. The thresholds below are a judgment drawn from the vendor guidance above, to be checked against your own traffic.

SituationUseReason
Fewer than about 20 tools, short results, one or two calls per taskPlain tool calling with prompt cachingLittle to save, and a script adds a step
20 to 50 tools, mostly single callsTool filtering per caller, or tool searchKeeps strict schemas and per-call approval
More than 50 tools or several MCP servers, with tasks that chain three or more callsCode modeOne program replaces several model turns
Fan-out over many records, or large results that need filteringCode mode, at any tool countThe data never enters the context
Each step needs the model's judgment on the previous resultPlain tool callingA script cannot skip that model turn
Writes that need a person's approval for every actionDirect calls for those tools, code mode for readsApproval stays per action

Anthropic reports typical savings of 20% to 40% from programmatic tool calling on production requests carrying 10 to 49 tool definitions, and Bifrost's guidance is Code Mode from three servers up.

All three let you choose which tools go behind code: Bifrost per server, Anthropic per tool, and Cloudflare by the connectors you pass to a runtime. Put heavy read tools behind code and keep sensitive write tools as direct calls.

What the sandbox costs you

Code mode trades token cost for an execution environment that you have to secure, approve, debug, and trace. Anthropic's own post makes the same point: agent-written code needs sandboxing, resource limits, and monitoring that direct tool calls avoid.

A code-execution surface. The sandbox must run without network access or credentials, and with hard limits on time and memory. All three implementations block outbound network access by default, which leaves the bindings as the main risk. A model steered by prompt injection now writes a whole program, and that program can do anything the bindings allow. MCP security covers the attacks underneath, such as poisoned tool descriptions.

Coarser approvals. With classic tool calling your application sees every call before it runs, and a program may make dozens. Cloudflare's runtime pauses at a method marked as requiring approval and replays the program after the decision. Bifrost returns the whole script for one approval when it calls a tool that is off the auto-execute list. Anthropic hands every call to your code, so per-call checks remain possible.

Harder debugging. A failure is now a program that stopped halfway, possibly after some writes succeeded. Bifrost returns a traceback with line numbers, and notes that a timed-out call may still have completed on the server. Cloudflare can run a connector's revert method for each applied call, which it describes as compensation, not a transaction. Store the generated source with every run.

Tracing inside the sandbox. One tool call in the transcript now hides several real ones, so a trace needs a span for each nested call, parented to the execution that made it. Anthropic tags each programmatic tool_use with a caller field naming the execution, and Cloudflare's runtime logs each connector call with a sequence number. Confirm that nested calls reach your logs with their arguments and the caller's identity, as agent observability describes.

Which models write the code reliably

Code mode depends on a model's code generation, so the risk sits with small models and restricted dialects. None of the sources above reports code mode results across model tiers, so treat reliability as something to measure.

The evidence is narrow. Cloudflare argues that models have seen far more real code in training than tool-call syntax. Anthropic limits programmatic tool calling to a list of supported models, and Claude Haiku 4.5 is not on it. Bifrost's benchmark used one model.

The dialect matters as much as the model. A model trained on ordinary Python can reach for imports, classes, and standard-library calls that Starlark lacks. Bifrost answers with error messages that carry hints, but each failed attempt costs a model turn.

Before turning code mode on widely, run a representative sample of tasks with it on and off, on the cheapest model you plan to use. Compare the share of programs that run without error on the first attempt, the model turns per task, and billed input tokens.

Frequently asked questions

What is MCP code mode?

MCP code mode is a way of using MCP tools in which the model writes a short program that calls them, instead of emitting one tool call per step. The tools are exposed as a typed API, the program runs in a sandbox, and only its output returns to the model's context.

Is code mode part of the MCP specification?

No. The specification defines how servers list tools and how clients call them, and code mode is a choice the client or gateway makes about how to present those tools to a model. MCP servers need no changes, because each call the program makes still reaches the server as a standard tool call.

How much does code mode reduce MCP token usage?

It depends on the tool count and on how much data moves between calls. Cloudflare reports a 99.9% smaller tool footprint for its full API, Anthropic about 38% fewer billed input tokens on a 75-tool benchmark, and Maxim AI's published benchmarks for Bifrost 58.2% to 92.8% fewer input tokens as tools rise from 96 to 508. These figures measure different things and are not comparable.

What is the difference between code mode and programmatic tool calling?

They are the same pattern under two names. Code mode is the name Cloudflare and Bifrost use, and programmatic tool calling is the Claude API feature in which Claude writes Python that calls your tools from Anthropic's code execution container. In Anthropic's version the tools still execute in your application, and loading definitions on demand is a separate feature, the tool search tool.

When should I not use code mode?

Skip it when the agent has fewer than about 20 tools, when tool results are small, or when each step needs the model to reason about the previous result before choosing the next call. Plain tool calling with prompt caching is simpler there, and the token saving is small. Keep tools that need a person's approval for every action as direct calls.

Is it safe to let a model run code against my tools?

It is safe only inside a sandbox with no network access, no credentials, resource limits, and bindings scoped to the tools the caller may use. The program can do anything those bindings allow, as many times as it likes, so the tool allowlist matters more than it does with single calls. Log the generated code and every nested call it makes.

Sources

  1. 01Code Mode: the better way to use MCPCloudflare Blog
  2. 02Code Mode: give agents an entire API in 1,000 tokensCloudflare Blog
  3. 03How Code Mode worksCloudflare Agents docs
  4. 04Code execution with MCP: building more efficient agentsAnthropic Engineering
  5. 05Introducing advanced tool use on the Claude Developer PlatformAnthropic Engineering
  6. 06Programmatic tool callingClaude API docs
  7. 07Tool search toolClaude API docs
  8. 08Code ModeBifrost docs
  9. 09MCP Code Mode benchmark reportGitHub, maximhq/bifrost-benchmarking
  10. 10Function callingOpenAI API docs
  11. 11Tools, revision 2026-07-28Model Context Protocol
  12. 12StarlarkGitHub, bazelbuild/starlark