code mode
Code mode is a way for an AI agent to use its tools by writing a short program that calls them, instead of making one structured tool call at a time. The tools appear to the agent as functions in a language such as TypeScript or Python. The program runs in a sandbox whose only way out is through those functions, and only the value it returns goes back into the model’s context.
An agent connected to Model Context Protocol (MCP) servers normally works one tool call at a time. It calls a tool, the full result lands in its context window, it reads the result, and it decides on the next call. If the agent needs to move data from one tool to another, that data passes through the model on the way out and again on the way in.
In September 2025, Kenton Varda and Sunil Pai at Cloudflare named the alternative when they published Code Mode: the better way to use MCP. Their agent converted an MCP server’s tools into a TypeScript API, gave the model a single tool that runs code, and executed that code in a sandboxed V8 isolate with no internet access. Their argument was that “LLMs have seen a lot of code. They have not seen a lot of ‘tool calls’.” Anthropic followed in November 2025 with Code execution with MCP, and harnesses such as Pi, the open-source coding agent created by Mario Zechner, now ship it built in. Armin Ronacher, a Pi contributor, describes how Pi’s version works.
Code mode keeps tool results out of the model’s context, which tool search alone can’t do, but it moves the work into a sandbox someone has to run and govern. That trade-off decides where code mode belongs: in a single MCP server it is usually more infrastructure than the server needs, and in a gateway that already holds identity, credentials, and policy for every server, the cost is paid once.
How does code mode work?
Code mode replaces a long list of tools with a small programming interface:
- Tools become functions. The runtime reads each connected MCP server’s tool schemas and presents them as typed functions, with the tool descriptions as doc comments. Cloudflare’s version generates a TypeScript API, Pi exposes JavaScript functions, and Speakeasy’s gateway uses Python.
- The model gets one tool that runs code. Instead of seeing every tool from every server, the model sees an
execute-style tool, sometimes alongside a search tool for finding the functions it needs. - The script runs in a sandbox. The sandbox has no network access of its own. In Pi it runs in QuickJS inside a WebAssembly runtime with “no network, no file system, no timers, limited RAM.” The only way out is to call the tool functions, and the runtime forwards those calls to the MCP servers.
- Only the result comes back. Whatever the script logs or returns is the tool result the model reads. Everything the script fetched along the way stays in the sandbox.
In Cloudflare’s design, the sandbox reaches MCP servers through bindings, so API keys stay outside it and never appear in the code the model writes.
A script that copies contacts from a CRM into a data warehouse might look like this. The function names are illustrative, since each runtime generates its own from the connected servers’ schemas:
const contacts = await crm.listContacts({ updatedSince: "2026-11-01" });
const rows = contacts .filter((c) => c.lifecycleStage === "customer") .map((c) => ({ id: c.id, email: c.email, plan: c.plan }));
await warehouse.insertRows({ table: "customers", rows });
return { copied: rows.length };With direct tool calls, every contact would enter the model’s context as the result of listContacts, and the model would then repeat them as the arguments to insertRows. In code mode, the model reads only the number of rows copied.
The following diagram compares the two patterns. A code mode server runs the script and returns only its result, while a standard server returns its full response into context:
Code mode vs direct tool calls
The two patterns differ in what passes through the model:
| Direct tool calls | Code mode | |
|---|---|---|
| What the model sees up front | A definition for every tool, unless the client defers them | One code-execution tool, plus search where the runtime offers it |
| Where tool results go | Into the context window, in full | Into variables in the sandbox |
| Moving data between tools | Through the model, out and back in | Inside the script, without entering context |
| Loops and batches | One model turn per call | One script, with concurrency where the runtime allows it |
| Unit of audit | Each call is a discrete event | One script, made of many calls |
| What has to run | The MCP servers | The MCP servers plus a sandbox |
Code mode vs tool search
Tool search, also called progressive disclosure or deferred tools, is the other common answer to MCP context bloat. The model sees a search tool, finds the tools it needs, and only then loads their definitions. Anthropic ships tool search in the Claude API, and OpenAI, GitHub Copilot, and the other major harnesses offer their own versions.
Tool search reduces the cost of having many tools, because definitions stay out of context until they’re needed, but it leaves the cost of using them unchanged. Once the model calls a tool, the full result still lands in context, and data moving between two tools still passes through the model. Code mode addresses that second cost.
Speakeasy’s code mode article concludes that a single MCP server connected to a harness with tool search probably doesn’t need code mode. A server that adds its own search on top of the harness’s is “a hat on a hat,” because the labs are post-training their models on their own tool search. The case for code mode gets stronger as the number of servers grows and as agents start moving data between them.
What does code mode solve?
Code mode is most useful when an agent’s work involves large results, many items, or more than one system:
- Large outputs stay small. A script can filter a 10,000-row result down to the five rows that matter before anything reaches the model. In Anthropic’s example of copying a meeting transcript from Google Drive into Salesforce, direct tool calls send the full transcript through the model twice, which could add 50,000 tokens for a two-hour sales meeting.
- Data moves between systems without passing through the model. Records read from one server and written to another stay in the sandbox. That saves tokens and turns, and it keeps sensitive records out of the transcript.
- Batches run as one step. The agent can write a loop or run calls concurrently instead of spending a model turn on each item. Ronacher describes a common pattern where an agent probes 5 to 10 items by hand to see what the data looks like, then writes a script for the rest.
- State carries across steps. Pi provides a
store()call that saves a script’s result to the session so a later script can read it back. Anthropic’s version lets agents write intermediate results to files and resume from them. - More capabilities fit without more tool definitions. Pi exposes image generation and classifier models to code mode scripts instead of as regular tools, where they would take up context in every conversation.
What are the limits of code mode?
Code mode moves work out of the model and into a runtime, and that runtime brings its own problems:
- Someone has to run the sandbox. Executing code a model wrote requires isolation, resource limits, and monitoring. Anthropic’s own write-up notes that code execution “introduces its own complexity.” A company that sells sandboxes, such as Cloudflare, can treat that as a product, but most MCP server providers would have to build and operate it from scratch.
- Scripts are harder to govern than calls. A direct tool call is a discrete event that can be logged, approved, or blocked. A script that makes ten calls in a loop is one step from the client’s point of view, unless whatever runs it checks each call against policy.
- Smaller models struggle. Writing a correct script against an unfamiliar API is harder than filling in one tool’s arguments. Ronacher lists the pattern’s inability to work with smaller models as an open problem.
- Nested code mode compounds errors. Some MCP servers, such as Cloudflare’s, expose their own code-execution tool. Calling one from inside another code mode script means passing code inside code, which Ronacher describes as “double JSON escaping, easy for smaller models to get confused by.”
- Binary data doesn’t travel well. MCP does not yet support large binary payloads, so workflows involving images or files fall back on workarounds such as pre-signed URLs.
- Long scripts are hard to resume. Ronacher writes that “durability with Codemode is trickier” and suggests borrowing the snapshotting that durable workflow engines use, so a script that stops partway through a batch could pick up where it left off.
- Simple requests pay overhead. When a task needs only one tool call, wrapping that call in a script adds a step without saving anything.
Where should code mode run?
There are three places to put the sandbox, and each changes who carries the cost:
- In the MCP server. Each server provider builds and runs its own sandbox. Every server pays the infrastructure cost separately, and the benefit is limited to that one server’s tools. Cross-system work, such as reading from a CRM and writing to a warehouse, still goes through the model.
- In the harness. The agent’s own runtime runs the sandbox, as Pi does. This works across every server the harness connects to, but each team building its own agent on a raw model API or an open-source framework has to build it too.
- In an MCP gateway. An MCP gateway sits between an organization’s agents and every server they use. It already runs infrastructure, holds each user’s upstream credentials, and enforces policy on every call. Adding a sandbox there is an incremental cost paid once, and every agent that connects to the gateway gets code mode across every server behind it.
Because the gateway executes the script, every call inside it passes through the same checks as a direct call, which addresses the governance limit above:
How does Speakeasy implement code mode?
Speakeasy runs code mode in the gateway rather than asking each MCP server to build it. Organization and project gateways in the Speakeasy AI Control Plane let each connection choose a tool discovery mode on the sign-in consent page:
- Progressive serves the five gateway tools, and agents discover member tools as needed.
- Direct lists every available tool by its qualified name, for clients that can’t discover tools progressively.
- Code Mode serves one
executetool that runs short Python scripts with live tool search, schema lookups, and authorized calls across every hosted, remote, and tunneled server behind the gateway.
In Code Mode, the script runs at the gateway, and each upstream call it makes goes through the same identity, permission checks, and audit logging as a regular tool call. The gateway works out its member servers from the person’s live access, so a script reaches only the servers that person can connect to. Its calls appear in tool logs alongside direct calls. When one upstream needs re-authentication, the gateway prompts the person to reconnect that one server, and the rest of the session carries on.
Code Mode is most useful for workflows that move data between systems, and for agents without built-in tool search, such as internal agents built on raw model APIs or open-source frameworks, which get discovery from the gateway instead of implementing it.
Code Mode must be enabled for the organization before connections can choose it. The organization gateway docs cover the discovery modes and how to connect a client, and the Speakeasy blog explains why Speakeasy built code mode into the gateway after arguing against it for single servers. To turn on Code Mode for an organization, talk to us.