Code Mode: From Tool Calls to ArchitectureLesson 01

Mastering Code Mode: How Programmatic Tool Calling Redefines AI Efficiency

Why tool definitions and intermediate results consume agent context, how Code Mode changes the workflow, and how to try it in Claude Code.

Transfer a transcript without routing it through model context1 · Readtranscript2 · Scripttransfers data3 · UpdateCRM4 · Modelreads resultReturn confirmation, not transcript

Asking an AI agent to perform a routine task, such as fetching a sales meeting transcript and updating a customer record, can consume much of its working memory just moving data between tools. This overhead becomes a bottleneck in AI workflows, and Code Mode changes how agents interact with those tools.

Cloudflare engineers Kenton Varda and Sunil Pai introduced the approach in September 2025. Since then it has appeared in Anthropic's code execution with MCP, Claude Code, and Datadog's MCP server. The idea is the same in each: instead of a loop of JSON tool calls, the model writes a program that calls the tools.

This is the first article in a series on Code Mode. It explains where traditional tool calling spends tokens, walks through a five-step execution pipeline, examines sandboxing and permission controls, and shows how to run a controlled comparison in Claude Code.

The Token Trap: Why Classic Tool Calling Becomes Expensive at Scale

Traditional AI agents talk to external software through protocols like the Model Context Protocol (MCP). In classic tool calling, whenever an AI reads a file, searches the web, or updates an app like Notion or Salesforce, it follows a step-by-step routine. This architecture has two structural sources of token overhead, which this article calls token leaks.

Leak 1: Tool Definition Overload

In systems that load all tools upfront, every available tool definition, including function names, descriptions, and parameter schemas, goes directly into the model's working memory, known as the context window. Cloudflare's API contains over 2,500 endpoints, and Cloudflare reports that exposing these endpoints as individual MCP tools would require 1.17 million tokens in its comparison. That can exceed a model's context window before any work has begun.

Leak 2: Intermediate Data Redundancy

When an AI chains multiple tools together, every intermediate piece of data must travel back through the AI model. Consider a simple task: grabbing a meeting transcript from Google Drive and saving it into a CRM.

  1. The model calls the get_document tool.
  2. The entire raw transcript flows back into the model's context window.
  3. The model processes the text and writes the entire transcript back out as the input argument for the update_record tool to update a record.

In this pipeline, the heavy transcript passes through the model's memory twice. Anthropic estimates that a 2-hour sales meeting transcript passing through memory like this burns around 50,000 extra tokens in redundant work.

The expensive part of this transfer is the full text entering the model and being generated again as the next call's input.

The "Shakespeare in Mandarin" Problem

Why might models benefit from writing code to call tools? Cloudflare's explanation starts with what a tool call is. Under the hood, a tool call is a sequence of special tokens that the model was fine-tuned to emit, wrapped around a JSON message. The model never sees those tokens in ordinary text, so its only exposure to them is a synthetic training set built by the model's developers. Tool-call examples are scarce and contrived.

Code is different. Large language models are trained on large repositories of production code, full of loops, async operations, conditional logic, and type definitions. Asked to write code against a full developer API, they manage well. Cloudflare draws the conclusion with an analogy: relying on a specialized tool-calling format is like putting Shakespeare through a month-long class in Mandarin and then asking him to write a play in it. Code Mode lets the model communicate in the language it has actually seen, structured and executable code.

This motivates the Code Mode approach; it does not prove that code generation outperforms direct tool calling on every task.

Two data flows

The difference shows up in where the data travels. The two diagrams below trace the same kind of task through each architecture.

Each number comes from a different published example, so read them as illustrations of scale rather than one measured task. The 1.17M figure is Cloudflare's count for exposing its whole API as tools. The 50k payloads match Anthropic's two-hour transcript example, where a single transfer puts the text in context twice. The 1k figure is Cloudflare's size for its two-tool Code Mode surface.

Classic tool callingCode Mode
Tool definitions in contextUp to 1.17M tokens for a large APIAbout 1,000 tokens for the execution tool
What the model emitsOne JSON call per stepA script that makes several calls
Where the payload goesInto context, then back out as the next call's inputBetween the tools, inside the sandbox
What returns to the modelEvery raw responseA summary or confirmation

In the classic flow, a single transfer can put a 50,000-token payload in context twice: once when it arrives, once when the model writes it out again. In the Code Mode flow, the payload moves from one API to the other inside the execution environment, and the model sees only the result.

The Architecture of Code Mode: Write Code to Call Tools

Instead of requesting each tool call individually, the model writes a small program that interacts with tools or APIs through an execution environment.

The Moving Company Analogy

Imagine moving out of an apartment:

  • Classic tool calling: The movers carry every box into your living room, open it so you can inspect the contents, close it, and then carry it out to the moving truck. Your living room, the context window, fills up with boxes you only needed to check once.
  • Code Mode: The movers carry the boxes straight out the side door into the truck and hand you a clipboard summary reading: "40 boxes safely loaded."

The model still decides what work to perform. The program handles the data movement and returns the information needed to assess the result.

The Five-Step Code Mode Pipeline

Implementations vary, but a sandboxed, API-oriented implementation can be understood in five phases:

  1. Schema Translation: The agent SDK reads the target server's tool definitions and auto-generates a lightweight TypeScript API with clear documentation comments.
  2. Meta-Tool Exposure: The model no longer sees thousands of individual tools. Instead, it sees just one primary meta-tool: run_code (or paired primitives like search and execute).
  3. Program Generation: The model writes a short, typed script designed to query, loop, paginate, or transform data directly.
  4. Sandboxed Execution: The generated script runs inside an isolated, millisecond-fast execution environment right next to the data source.
  5. Filtered Output: The script logs only the final answer or a brief confirmation (console.log) back to the model's memory.

Intermediate data can stay between the runtime and the tools. Only the output selected by the script returns to the model; printing every response would bring that data back into context.

Extreme Compression in Practice

By shifting tool execution to server-side code generation, Cloudflare reduced its 2,500+ API endpoints to two meta-tools: search, which searches the API types, and execute, which runs TypeScript against matched endpoints. This shrank the initial context requirement from 1.17 million tokens to roughly 1,000 tokens, a 99.9% reduction.

The Security Engine: Sandboxing, Isolates, and Capability Controls

Allowing an AI model to dynamically generate and execute code presents an obvious security question: How do we limit what that code can access or change?

Code Mode needs explicit security boundaries. The following architecture describes Cloudflare's sandboxed approach; it is not a guarantee attached to every feature called Code Mode.

V8 Isolates vs. Containers and Virtual Machines

Cloudflare uses V8 isolates, the lightweight JavaScript execution environments behind Cloudflare Workers. Cloudflare describes startup times of a handful of milliseconds and memory requirements of a few megabytes, making a fresh environment for each script practical.

Containers and virtual machines offer different isolation and compatibility tradeoffs. Code Mode does not require one particular runtime, and a V8 isolate alone does not define which tools, network destinations, or data a script can access.

The Supervisor and Credential Isolation

Cloudflare's binding-based design provides credential isolation. The supervisor's API credentials are never exposed to the generated script's sandbox environment or to the AI model. Instead:

  • Secrets remain outside the sandbox with a host supervisor process.
  • The sandbox receives authenticated function bindings.
  • The AI script calls the function, but cannot read, print, or exfiltrate the underlying credentials.

The script never receives the underlying API keys, so it cannot read or print them. That does not prevent misuse of an authorized function: a binding with permission to delete records can still perform a destructive operation. Credential isolation keeps sensitive information away from the model and the generated script, but the permissions granted to each binding still matter.

Capability-Based Security

Under a capability-based security model, the sandbox starts with zero default permissions. It has no access to host environment variables, local file systems, or arbitrary outbound internet fetches. Access is granted only through controlled API bindings, and each binding grants access to a specific service.

The following sketch summarizes that design:

Read the diagram from top to bottom. The generated code requests an operation through a controlled binding. The supervisor checks access and adds credentials outside the sandbox, and the response travels back through the supervisor. The script then chooses what to return to the model, and the credentials stay with the host. This is the Cloudflare-style architecture described here, and the same boundary should not be assumed for every Code Mode implementation.

Permissions on those bindings determine what the script can do. Resource limits and error handling matter too: a failed script does not automatically undo API calls that already succeeded.

Security Nuance: Auto Mode vs. Step-by-Step Auditing

In Claude Code's auto mode, the classifier reviews each generated script rather than each individual tool call. Tool-specific permission rules and hooks still apply. The classifier cannot see values computed at runtime, so permission rules and scope limits remain important.

Claude Code does not inherit the Cloudflare isolation model above. Its sandbox settings apply to shell commands, while the generated JavaScript and its file, web, and MCP calls run outside that sandbox. The official documentation recommends a container or virtual machine when those operations also need isolation.

Enabling and Benchmarking Code Mode in Claude Code

Anthropic introduced experimental Code Mode in Claude Code version 2.1.323. It is off by default. The instructions below were checked against the official documentation on November 30, 2026. Requirements may change while the feature is experimental.

Step 1: Verify Version Requirements

Code Mode requires an interactive terminal session. It is not supported in the VS Code panel, Desktop app, or cloud sessions. Check your installation:

BASH
claude --version

If your installation is older than the version required for your setup, update it:

BASH
claude update

The minimum version is 2.1.323, but cloud-provider support and some integrations require later versions. You also need the native installation and a supported model, account, and organization configuration. Check the current requirements before enabling the feature.

Step 2: Launch Claude Code with Code Mode Enabled

To start a session with Code Mode active, set the experimental environment variable on launch.

On macOS or Linux:

BASH
CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude

On Windows PowerShell:

POWERSHELL
$env:CLAUDE_CODE_EXPERIMENTAL_CODE_MODE = "1"
claude

Upon launching for the first time, Claude Code asks for confirmation. Select Yes, turn on code mode. Check that the startup message says Code Mode is on. If it says the setting will apply after a restart, exit and launch again the same way.

To inspect the JavaScript behind the tool calls, press Ctrl+O and expand a Code row in the transcript viewer.

Step 3: Run a Controlled Benchmark Test

Choose a task involving several related tool calls, such as checking Markdown files in a docs/ directory for links to missing local files.

  1. Baseline run, Code Mode off: Start a fresh session with the environment variable set to 0. Run the task and record elapsed time, the result, and available token and cost measurements.
  2. Code Mode run, Code Mode on: Start another fresh session with the variable set to 1, provide the exact same prompt, and record the same measurements.
  3. Compare correctness as well as cost: Check whether both runs found the same broken links and whether those findings are accurate.

Keep the model, repository contents, permissions, and available tools the same. Repeat the comparison if you want to draw conclusions beyond a single run, and account for caching. For tasks that edit files, restore the same starting state before each run.

Use /context to inspect context usage, but do not treat the final context size as total billed tokens. Record usage and cost with the reporting available for your account. Subscription usage limits are not a per-task API cost measurement.

Interpreting Benchmark Results

Results vary with the workload, and the published numbers measure different things. Cloudflare's tool-definition reduction measures the cost of exposing an API. Anthropic's MCP article gives a separate example of reducing token usage from 150,000 to 2,000 through on-demand tool loading and code execution. Neither predicts the savings from a particular Claude Code task.

The most complete published evaluation comes from Datadog. When it added Code Execution to its MCP server, it ran 25 observability tasks across four models and compared the results with its standard toolset. Averaged across the models, Datadog reports:

  • Input tokens per task fell from 159k to 43k, a 73% reduction.
  • Answer accuracy rose from 74% to 90%, with every model improving.
  • Tool calls per task fell from 4.1 to 2.5, about 40% fewer.

The accuracy gain is worth noticing. The agents were not only cheaper to run; they answered better, because less intermediate data in context left more room for the reasoning the task needed. Datadog's tasks involved correlating metrics, logs, traces, and deployments, which is the kind of multi-source join where Code Mode earns its keep.

Code Mode is most promising when a task involves large intermediate results, repeated operations, filtering, or independent calls that can run in parallel. For a single small tool call, the additional code generation may offer little benefit. A useful benchmark measures successful completion, latency, and total cost together.

Key Limits to Remember

  • Execution timeout: Foreground code stops after ten minutes. Background execution has separate eligibility rules and can run for up to two hours under the current documented limits.
  • Session resumption: Sessions started in Code Mode must be resumed with Code Mode enabled.
  • Account and provider constraints: Claude subscriptions and Console accounts are supported, as are specified cloud providers starting with version 2.1.331. Gateways and some organization configurations remain unsupported. Check the current requirements for your setup.

Key Takeaways

  • Classic MCP limitations: Loading thousands of tool definitions upfront and passing intermediate data back and forth creates substantial token overhead.
  • Code as a wider pipe: LLMs write code well. Generating a script to filter, chain, and summarize data at the source keeps context consumption down.
  • Sandboxed security: V8 isolates, capability-based permissions, and isolated supervisors can restrict generated code and keep credentials outside its reach. The actual guarantees depend on the implementation and on the permissions granted to its tools.
  • Practical impact: Enabling Code Mode in tools like Claude Code can reduce context load, especially for tasks involving heavy file operations, web browsing, or multi-endpoint API queries.

This first part establishes the mechanics and a starting point for experimentation. Later articles in the series will build on these foundations.

Knowledge check

An agent only needs to copy a meeting transcript into a CRM, without summarizing it. Which workflow best reduces unnecessary model token usage?
A sandbox cannot read an API key, but its authorized binding can delete CRM records. What follows from this design?
A Code Mode run ends with a smaller context than the baseline, but misses several broken links. What conclusion does this comparison support?

References

Related Posts

A model delegates a transcript transfer to a script1 · Modelwrites code2 · Scripttransfers dataGoogle Drivetranscript3 · UpdateSalesforce4 · Return confirmation

Code Mode Architectures

  • Stackfable
  • 01 Dec 2026

Compare classic MCP, client-side Code Mode, and server-side Code Mode by execution ownership, schema discovery, and credential boundaries to choose an architecture.

Read More: Code Mode Architectures: Classic MCP vs Client-Side and Server-Side Code Mode