Once an agent can write code to call tools, the next decision is where to run that code. The app that hosts the model and connects it to tools, often called the agent harness, can run the code itself. Or the MCP server can run it on the client's behalf. That choice decides who ships a sandbox, how the model discovers operations, and where authorization happens.
This is the second article in a series. Mastering Code Mode covers token overhead, the execution pipeline, sandbox fundamentals, and Claude Code setup. Here, we compare classic MCP tool calling, client-side Code Mode, and server-side Code Mode. Client-side and server-side describe where Code Mode is integrated relative to MCP; both approaches can still use MCP.
1. Paradigm 1: Classic MCP (the model relays every result)
In classic MCP the model calls tools turn by turn and reads every result before it decides what to do next. Three pieces take part, and the model does the relay work:
| Piece | What it does here |
|---|---|
| Model | Names a tool and writes its arguments on each turn; every result lands in its context |
| Agent harness | Sends each call to the right MCP server and hands the result back to the model |
| MCP servers | Expose tools, each with a name, a description, and a parameter schema |
Before any work starts, the harness sends the model the list of tools with their descriptions and parameters. On each turn the model answers with one or more calls, each a tool name plus its arguments in JSON. The harness passes that to the server (via an MCP client) and returns the result, and the model reads it before choosing the next call. A call that depends on an earlier result therefore needs a turn of its own.
Here is the transcript transfer in that style, in simplified JSON. The model asks for the document, the whole transcript comes back into its context, and the model has to write the transcript out again as the argument of the CRM call:
// Turn 1: the model asks for the document
{ "tool": "get_document", "arguments": { "documentId": "sales_meeting_2026_11_29" } }
// The result lands in the model's context
{ "result": "…the whole transcript…" }
// Turn 2: the model writes the transcript out again, as the next call's argument
{ "tool": "update_record", "arguments": { "recordId": "cust_9872", "notes": "…the whole transcript, again…" } }sequenceDiagram
accTitle: Classic MCP transcript transfer
accDescr: The model calls the Drive tool and the full transcript returns into its context. The model then calls the CRM tool and has to write the whole transcript out again as the argument. The transcript passes through the model twice, and each call is a model turn.
autonumber
participant M as Model
participant H as Agent harness
participant D as Drive server
participant C as CRM server
M->>H: get_document()
H->>D: Call the Drive tool
D-->>H: Full transcript
H-->>M: Full transcript
M->>H: update_record(notes)
H->>C: Call the CRM tool
C-->>H: Done
H-->>M: DoneRead the diagram from left to right. The model takes part in lines 1, 4, 5, and 8, and the transcript crosses into its column twice: it arrives on line 4 and leaves again on line 5, when the model writes it back out. Each of those calls is also a full model turn.
The next section draws the same task in client-side Code Mode with the same columns. Comparing the two diagrams is the quickest way to see what Code Mode changes: the transcript stops crossing into the model's column.
This works well when a server exposes a handful of tools and returns short results. The cost appears with scale: a long tool list sits in the model's context before any work starts, and every intermediate result passes through the model. Part one walks through where the tokens go.
2. Paradigm 2: Client-Side Code Mode (the agent runs the script)
In classic MCP the model calls tools turn by turn and reads each result. In client-side Code Mode it writes one script that calls several tools, and the agent harness runs that script. "Client-side" means the agent's side of the MCP connection; the agent itself can run on a laptop or in the cloud. Three pieces take part:
| Piece | What it does here |
|---|---|
| Model | Writes the script and receives only its return value |
| Agent harness | The app the user runs, such as Claude Code or an agent built on Cloudflare's Agents SDK. It runs the script and holds the connections to the MCP servers |
| Sandbox | An isolated environment the harness starts for the script. The script reaches the outside only through what the harness hands it |
The piece that makes this work is how a script calls a tool. The harness has already read each connected MCP server's tool list, and it turns every tool into an ordinary function the script can call. When the script calls one of those functions, the harness forwards the call to the real MCP server. The MCP servers do not change at all.
Here is the script the model writes for the transcript transfer. gdrive and crm are the functions the harness generated from the two servers:
// Sent to the harness's "run this code" tool
async () => {
const doc = await gdrive.get_document({ documentId: "sales_meeting_2026_11_29" });
await crm.update_record({ recordId: "cust_9872", notes: doc.content });
// The only value that returns to the model
return "Updated cust_9872";
}Claude Code's scripts look different because they call Claude Code's own tools, such as edit(file, old, new) and a $`command` shell helper. The shape is the same: one script in, one return value out.
sequenceDiagram
accTitle: Client-side Code Mode transcript transfer
accDescr: The model sends one script to the agent harness, which runs it in a sandbox. The script calls the Drive and CRM tools through the harness, so the transcript travels between the servers and the sandbox. Only the script's return value goes back to the model.
autonumber
participant M as Model
participant H as Agent harness<br/>with its sandbox
participant D as Drive server
participant C as CRM server
M->>H: Send one script
H->>D: get_document()
D-->>H: Full transcript
H->>C: update_record(notes)
C-->>H: Done
H-->>M: "Updated cust_9872"Read the diagram from left to right. The model takes part in the first line and the last. In between, the script runs inside the harness's sandbox and reaches the servers only through the harness: it fetches the document (lines 2 and 3) and updates the CRM (lines 4 and 5). The transcript arrives on line 3 and leaves on line 4. It never crosses to the model.
Compare that with classic MCP, where the same transfer puts the transcript into the model's context twice. Here the model sends a few lines of code and gets back one short string.
The cost is that the harness has to ship with that sandbox, and what the sandbox isolates varies. Cloudflare's Agents SDK runs each script in an isolated Worker and blocks outbound network access by default, so the script reaches the outside only through the generated functions. Claude Code's sandbox covers only the shell commands the script runs; the JavaScript itself and its file, web, and MCP calls run outside it, and its documentation recommends a container or virtual machine when those need isolating too. Part one covers the security differences.
3. Paradigm 3: Server-Side Code Mode (the server runs the script)
Server-side Code Mode moves the work to the other side of the connection. The MCP server offers code execution as a tool and runs the model's script itself. Any MCP client can use it without shipping a sandbox, which is how a platform can bring Code Mode to everyone who connects to it. Cloudflare's API server works this way.
It also solves a size problem. A platform like Cloudflare's has thousands of REST endpoints, described in an OpenAPI document: a standard JSON or YAML file that lists every endpoint with its parameters and request bodies. An excerpt for the warehouse API used below might read:
/warehouses/{warehouseId}/reservations:
get:
summary: List the stock reservations in one warehouse
parameters:
- name: status
in: query
schema: { type: string }
post:
summary: Create a stock reservation
requestBody:
content:
application/json:
schema:
type: object
required: [stockItemId, quantity]Turned into MCP tools, every operation in that document becomes a tool definition the model has to load. Cloudflare reports about 1.17 million tokens for its whole API that way. So the server keeps the document on its own side and exposes two tools instead:
searchruns a script against the OpenAPI document and returns only the entries the script picks out.executeruns a script that calls the real endpoints through a request function, to which the server attaches the user's credentials.
The model calls search to find the few endpoints it needs, then writes an execute script for them. The document never enters its context.
Cloudflare's @cloudflare/codemode package implements this pattern in two sizes. codeMcpServer() adds a single code tool to an MCP server that already has a manageable set of tools. openApiMcpServer() builds the search and execute pair from an OpenAPI document. The two scripts below follow the documented openApiMcpServer() interface against the warehouse API above. The paths and response shapes are examples; the codemode.spec() and codemode.request() calls are the real interface.
Tool 1: Finding endpoints with search
Calling codemode.spec() returns the whole OpenAPI document as JSON the script can walk. This script picks out the reservation endpoints and the fields a create request needs, and returns only those. The rest of the document stays on the server and never enters the model's context:
// Script sent to the search tool
async () => {
const spec = await codemode.spec();
const httpMethods = ["get", "post", "put", "patch", "delete"];
// 1. Find the operations that manage stock reservations
const matches = [];
for (const [path, operations] of Object.entries(spec.paths)) {
if (!path.includes("/reservations")) continue;
for (const [method, operation] of Object.entries(operations)) {
if (!httpMethods.includes(method)) continue;
matches.push({ method: method.toUpperCase(), path, summary: operation.summary });
}
}
// 2. Read the required fields of the create request
const create = spec.paths["/warehouses/{warehouseId}/reservations"]?.post;
const schema = create?.requestBody?.content?.["application/json"]?.schema;
return { matches, required: schema?.required ?? [] };
}Tool 2: Calling the API with execute
The model then writes a second script for execute, which calls real endpoints through codemode.request(). The server adds the credentials, so the script never handles them. This script lists the pending reservations in one warehouse, looks up each reserved item, and returns a compact array. The full API responses stay on the server:
// Script sent to the execute tool
async () => {
// 1. List the pending reservations in one warehouse
const pending = await codemode.request({
method: "GET",
path: "/warehouses/wh-42/reservations",
query: { status: "pending" }
});
// 2. Resolve each reservation to its stock item
const summary = [];
for (const reservation of pending.items) {
const item = await codemode.request({
method: "GET",
path: `/stock-items/${reservation.stockItemId}`
});
summary.push({
reservation: reservation.id,
sku: item.sku,
quantity: reservation.quantity
});
}
// Only this array returns to the model
return summary;
}The credentials never enter the sandbox. By Cloudflare's count the model loads about 1,000 tokens of tool definitions this way, against 1.17 million for the full list; part one covers the tool-surface reduction.
Discovery results, generated scripts, and execution results still consume context. A search that returns too much of the document can undo much of the saving, so it should narrow the endpoints to the current task. The server also truncates final responses at about 6,000 tokens, so an execute script should return selected fields rather than raw API responses.
flowchart TD
accTitle: Server-side Code Mode with search and execute
accDescr: Search filters the server-held schema. The model uses the returned operations to write an execute script. A host callback authenticates API requests, and only a focused result returns to the model.
M["Model writes search script"]
S["Search sandbox<br/>filters server-held schema"]
P["Model writes execute script"]
E["Execution sandbox"]
H["Host callback<br/>adds credential"]
A["API"]
R["Model receives focused result"]
M --> S
S -->|"Matching operations"| P
P --> E
E -->|"Request"| H
H --> A
A -->|"Response via host"| E
E -->|"Selected output"| RRead the diagram from top to bottom. The three model boxes show successive steps for the same model. Search returns matching operations; execution uses the host callback to call the API and returns selected output. The full schema stays on the server, and the credential stays outside the execution sandbox.
4. Architectural comparison
| Dimension | Classic MCP | Client-Side Code Mode | Server-Side Code Mode |
|---|---|---|---|
| Operation discovery | Individual tool definitions | Callable interfaces supplied by the harness | Server-side search returns relevant operations |
| Intermediate payloads | Pass through the model's context twice in this transfer example | Processed in the execution runtime's memory | Processed in a server-side Worker |
| Model round trips | One per step | One script, possibly followed by a fix | One search, then one execute |
| Where code runs | No generated code; the host calls tools | A harness-managed runtime; location and isolation vary | A server-side Worker |
| Credentials | Held by the host, added to each request | Isolated in the host supervisor | Held by the server, added by the host callback |
| Fits | Small tool sets with short payloads | Local file and SaaS workflows | APIs with hundreds or thousands of endpoints |
Two rows deserve a note. The round-trip count is a best case: a script that fails or returns an unexpected result sends the model back for another turn, the same as a failed tool call would. And the credential row describes where the secret is stored, not what the code is allowed to do. A binding or request function with write permission can still make destructive calls.
flowchart LR
accTitle: Execution and credential boundaries
accDescr: An agent-side runtime calls tools through a credential-holding host. A server-side sandbox calls an API through a credential-holding callback. Runtime location and isolation depend on the implementation.
subgraph Client["Client-side Code Mode"]
direction TB
CM["Model"] -->|"script"| CS["Agent-side runtime"]
CS -->|"tool call"| CH["Tool host<br/>holds credential"]
CH --> CA["API"]
end
subgraph Server["Server-side Code Mode"]
direction TB
SM["Model"] -->|"script"| SS["Server sandbox"]
SS -->|"request"| SH["Host callback<br/>holds credential"]
SH --> SA["API"]
endRead each path from top to bottom. These are illustrative credential boundaries: the script calls a host-mediated interface, and the host adds the credential. The client-side path uses the agent's tool host; the server-side path uses a callback managed by the MCP server operator. Neither path by itself specifies which operations are authorized.
5. Choosing a paradigm
Start with who can provide the runtime and which services the workflow must reach.
- Stay with Classic MCP when a server exposes a handful of tools and returns short results. The setup is simple, and the context cost is small.
- Use Client-Side Code Mode when you control the agent harness and need to compose calls across its connected tools. The harness supplies the execution integration and exposes the required services.
- Use Server-Side Code Mode when you operate a large API and want MCP clients to use code execution without providing their own runtime. The server supplies discovery, execution limits, and the authenticated API interface.
To try the client-side approach, follow the Claude Code setup and benchmark guide in part one.
One caution applies across all three. Code execution changes where authorization is enforced, not whether it is needed. Cloudflare's documentation is explicit that its Code Mode servers do not provide per-operation approval: generated code can call any operation the token allows. Enforce permissions in the upstream tool handler or the host request callback, and scope tokens to the minimum a task requires.
Knowledge check
References
- Cloudflare: Code Mode: the better way to use MCP
- Cloudflare: Code Mode: give agents an entire API in 1,000 tokens
- Cloudflare: Build a Code Mode MCP server
- Claude Code documentation: Run tool calls from code with Code Mode