Code Mode: From Tool Calls to ArchitectureLesson 02

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

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

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

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:

PieceWhat it does here
ModelNames a tool and writes its arguments on each turn; every result lands in its context
Agent harnessSends each call to the right MCP server and hands the result back to the model
MCP serversExpose 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:

JSON
// 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…" } }

Read 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:

PieceWhat it does here
ModelWrites the script and receives only its return value
Agent harnessThe 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
SandboxAn 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:

JAVASCRIPT
// 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.

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:

YAML
/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:

  • search runs a script against the OpenAPI document and returns only the entries the script picks out.
  • execute runs 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.

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:

JAVASCRIPT
// 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:

JAVASCRIPT
// 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.

Read 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

DimensionClassic MCPClient-Side Code ModeServer-Side Code Mode
Operation discoveryIndividual tool definitionsCallable interfaces supplied by the harnessServer-side search returns relevant operations
Intermediate payloadsPass through the model's context twice in this transfer exampleProcessed in the execution runtime's memoryProcessed in a server-side Worker
Model round tripsOne per stepOne script, possibly followed by a fixOne search, then one execute
Where code runsNo generated code; the host calls toolsA harness-managed runtime; location and isolation varyA server-side Worker
CredentialsHeld by the host, added to each requestIsolated in the host supervisorHeld by the server, added by the host callback
FitsSmall tool sets with short payloadsLocal file and SaaS workflowsAPIs 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.

Read 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

You control an agent harness that already connects to separate document and CRM MCP servers. You want generated code to compose their tools while both servers keep their existing interfaces. Where should the execution integration go?
A platform exposes thousands of API operations, but a task needs only two. Why can server-side search and execute reduce the initial tool context?
An MCP client can call tools but cannot run generated scripts itself. You operate the API server and want this client to use Code Mode. Which design provides the missing execution capability?

References

Related Posts

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

Mastering Code Mode

  • Stackfable
  • 30 Nov 2026

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

Read More: Mastering Code Mode: How Programmatic Tool Calling Redefines AI Efficiency