# Code Mode MCP Benchmark: Typed Tool Outputs Matter More Than the Sandbox

- URL: https://www.dhruvvakharwala.dev/blogs/code-mode-mcp-benchmark-typed-tool-outputs
- Author: Dhruv Vakharwala (https://www.dhruvvakharwala.dev/about)
- Published: November 27, 2026
- Category: Engineering
- Keywords: code mode mcp benchmark, cloudflare code mode, codemcpserver, mcp outputschema, code mode vs tool calling, mcp prompt caching, parallel tool calling, agents sdk codemode, mcp tool annotations

> I benchmarked Code Mode MCP against plain tool calling on Claude. With typed tool outputs it cost 66% less. Two codemode bugs and six proposals, tested.

**TL;DR:** In my [last post](https://www.dhruvvakharwala.dev/blogs/code-mode-mcp-cloudflare-agents-sdk) I read Cloudflare's Code Mode code and promised to measure it. This is the **Code Mode MCP benchmark**. Same Claude agent (Claude Opus 5.5), same MCP client, same mock MCP server with 8 tools, same 4 tasks, three ways: plain tool calling, `codeMcpServer` from `@cloudflare/codemode` 0.5.6 as shipped, and `codeMcpServer` with **typed tool outputs**. 60 measured runs, every one correct. Code Mode as shipped cost **34% less** than plain tool calling across the four tasks ($0.454 vs $0.687 for 20 runs). With typed outputs it cost **66% less** ($0.234), and was 1.5x to 2.7x faster on the multi-call tasks. The gap between the two Code Mode variants is the real finding: without output types the model cannot see result shapes, so it writes defensive code and returns raw data to check itself. On the largest task that sent **20,324 characters** back to the model; with types, **283**. Getting typed outputs took two fixes to `codeMcpServer`, one of them a crash on Workers. Plain tool calling still wins on a single-call task, and Claude's parallel tool calling makes it a much tougher baseline than the published 98 to 99% numbers suggest. I also tested all six proposals from the last post: three were dropped by the data, three were filed upstream, and upstream kept one of them open.


![Cover card: total API cost of 20 measured runs per mode. Plain MCP tool calling $0.687, codeMcpServer as shipped $0.454 (34% less), codeMcpServer with output types $0.234 (66% less). Claude Opus 5.5, every run correct](https://www.dhruvvakharwala.dev/images/blog/code-mode-mcp-benchmark-typed-tool-outputs/cover.png)

## What did I say I would measure?

The last post ended with a plan. I would wire `@cloudflare/codemode` into a small agent that chains MCP tool calls, run the same tasks with plain tool calling and with Code Mode, and record input tokens, output tokens, wall-clock time, round trips and correctness. Then I would try my six optimization ideas one at a time. And I wrote that I would publish the numbers that make Code Mode look worse, too.

This post is that plan, done. Three things came out of it that I did not expect:

1. The biggest lever was not on my list. It was **typed tool outputs**: whether the TypeScript declarations the model sees say what each tool *returns*.
2. Turning typed outputs on in `codeMcpServer` needed two bug fixes, one of them a crash on Cloudflare Workers.
3. Of my six proposals, the data killed three. The other three I filed upstream, and the repository's automated triage closed two of those within a minute.

If you have not read the previous post, the one-paragraph version: Code Mode converts an MCP server's tools into a TypeScript API, gives the model **one** tool that takes JavaScript, and runs that code in a disposable V8 isolate (a Dynamic Worker) whose only way out is RPC back to the host. Intermediate tool results stay inside the sandbox; only what the code returns or logs goes back to the model. Cloudflare and Anthropic published reductions of 98 to 99.9% in token counts for very large tool catalogs. My question was what happens on a small, realistic catalog.

---

## How does the Code Mode MCP benchmark work?

The whole benchmark is one Cloudflare Worker ([`examples/codemode-bench`](https://github.com/vakharwalad23/agents/tree/experiment/codemode-bench/examples/codemode-bench) in my fork of the Agents SDK) plus a Node script that calls it.

```mermaid
flowchart LR
    R["bench.ts runner (Node)"] --> W["Worker /run endpoint"]
    W --> C["Claude Messages API"]
    C -- "tool_use" --> M["MCP client"]
    M -- "tools mode" --> S[("mock MCP server<br/>8 tools")]
    M -- "codemode modes" --> X["codeMcpServer<br/>one code tool"]
    X --> D["Dynamic Worker sandbox"]
    D -- "RPC" --> S
```

The agent loop is deliberately boring. `src/server.ts` sends the task to Claude, executes whatever tool calls come back through an MCP `Client`, appends the results, and repeats until the model stops asking for tools (capped at 25 turns). The **only** thing that changes between modes is which MCP server that client connects to:

| Mode | What the client connects to | What Claude sees |
|---|---|---|
| `tools` | the mock server directly | 8 tools, one per MCP tool, with JSON schemas |
| `codemode` | `codeMcpServer({ server: mock, executor })` | 1 tool, `code`, with TypeScript declarations in its description |
| `codemode-typed` | the same, but the mock declares an `outputSchema` per tool | 1 tool, `code`, whose declarations now include result types |

The sandbox is `DynamicWorkerExecutor` with a `worker_loaders` binding, running under local `wrangler dev`. The `codemode-typed` mode needs two fixes to `codeMcpServer` (more on those below); the benchmark ran against the fixed package.

### The mock MCP server

`src/mock.ts` is a fake support-operations backend: 12 customers, 49 orders, 10 products and 22 support tickets, generated from a fixed seed (seed 7) so every run sees the same data. Six tools read (`list_customers`, `get_customer`, `list_orders`, `get_order`, `get_product`, `list_tickets`) and two write (`create_ticket`, `send_email`).

Order payloads are fat on purpose. Every line item carries the full product description (40 filler words) and every order carries 30 words of notes. That makes the cost of passing intermediate results through the model visible, which is the cost Code Mode claims to remove.

All three modes return byte-for-byte the same results. Each tool returns its value both as JSON text and as MCP `structuredContent`; the only difference in `codemode-typed` is that each tool also *declares* an `outputSchema`.

### The four tasks

| Task | What it needs | What it tests |
|---|---|---|
| `lookup` | 1 call | Nothing to batch; Code Mode should not win |
| `eu-shipped` | list customers, then orders per customer, then a sum | Fan-out and aggregation |
| `top-sku` | about 20 calls, most of them `get_order` with large payloads | Intermediate results that never need to reach the model |
| `priority-emails` | find gold customers with open high-priority tickets, email each | Conditional writes; the emails actually sent are checked, not just the reply |

Every task has a checker that computes the right answer from the same seeded data. For `priority-emails` the checker looks at the mock's recorded `send_email` calls, so a model that claims it sent two emails but sent three fails.

### Configuration

| Setting | Value |
|---|---|
| Model | Claude Opus 5.5, effort `medium` |
| Prompt caching | explicit breakpoint after the system prompt, plus automatic caching inside each conversation |
| Runs | 1 warm-up (discarded) + 5 measured per task and mode, mode order rotated per repetition |
| Sandbox | `DynamicWorkerExecutor` under local `wrangler dev` |
| Packages | `@cloudflare/codemode` 0.5.6 (workspace build), `@modelcontextprotocol/sdk` 1.32.2 |

Rotating the order matters more than it looks. If `tools` always ran first, it would always pay for the cold cache, and any drift in API latency over a run would land on the same mode every time. `bench.ts` shifts the mode list by one position each repetition.

---

## Code Mode MCP benchmark results

Medians of 5 runs per cell.

| Task | Mode | Round trips | Input tokens | Time | $/run |
|---|---|---|---|---|---|
| lookup | tools | 2 | 2,626 | 2.3s | **0.0038** |
| | codemode | 2 | 3,669 | 2.3s | 0.0044 |
| | codemode-typed | 2 | 4,734 | 2.2s | 0.0046 |
| eu-shipped | tools | 3 | 4,763 | 5.7s | 0.0159 |
| | codemode | 2 | 4,198 | 4.4s | 0.0129 |
| | codemode-typed | 2 | 4,967 | 3.8s | **0.0104** |
| top-sku | tools | 4 | 17,885 | 12.9s | 0.0878 |
| | codemode | 2 | 11,102 | 6.4s | 0.0513 |
| | codemode-typed | 2 | 5,112 | 4.7s | **0.0128** |
| priority-emails | tools | 5 | 10,580 | 9.7s | 0.0297 |
| | codemode | 3 | 7,430 | 8.0s | 0.0191 |
| | codemode-typed | 2 | 5,225 | 5.4s | **0.0153** |

"Input tokens" is the total the model read: uncached input plus cache writes plus cache reads. Total cost of the 20 measured runs per mode:

| Mode | Cost of 20 runs | vs `tools` |
|---|---|---|
| `tools` | $0.687 | baseline |
| `codemode` | $0.454 | 34% less |
| `codemode-typed` | $0.234 | 66% less |

![Small multiples of median cost per run for each task, same dollar scale in every panel: lookup is cheapest with plain tools ($0.0038), while on top-sku plain tools costs $0.0878, codemode $0.0513 and codemode-typed $0.0128](https://www.dhruvvakharwala.dev/images/blog/code-mode-mcp-benchmark-typed-tool-outputs/cost-by-task.png)

On time, typed Code Mode was 1.5x faster than plain tools on `eu-shipped` (5.7s vs 3.8s), 1.8x on `priority-emails` (9.7s vs 5.4s) and 2.7x on `top-sku` (12.9s vs 4.7s). On `lookup` all three took about 2.2 to 2.3 seconds.

### How is the cost computed?

The benchmark records four token counts per run from the API's `usage` block, and `bench.ts` prices them with the Opus 5.5 rates in its price table:

```text
cost = (4 * I + 5 * W + 0.2 * R + 20 * O) / 1,000,000

I = uncached input tokens          $4.00 per million
W = tokens written to the cache    $5.00 per million (1.25x input, 5-minute TTL)
R = tokens read from the cache     $0.20 per million
O = output tokens, thinking incl.  $20.00 per million
```

Worked example, the median `top-sku` run in the two extreme modes:

| Mode | I | W | R | O | Cost |
|---|---|---|---|---|---|
| tools | 10 | 11,322 | 6,553 | 1,492 | (40 + 56,610 + 1,311 + 29,840) / 10^6 = $0.0878 |
| codemode-typed | 6 | 629 | 4,477 | 437 | (24 + 3,145 + 895 + 8,740) / 10^6 = $0.0128 |

The two "Input tokens" figures in the results table are these columns added up: 10 + 11,322 + 6,553 = 17,885 and 6 + 629 + 4,477 = 5,112.

Two things dominate the plain tools bill. First, 11,322 tokens, most of them order data, are written to the cache as the tool results flow into the conversation, and every later turn reads them back. Second, 1,492 output tokens are spent emitting 20 tool calls, at the most expensive per-token rate. Typed Code Mode writes one short script (437 output tokens, thinking included) and gets back a few hundred characters.

---

## Why does Code Mode only win when there is something to batch?

On the three multi-call tasks, Code Mode needed fewer round trips and fewer output tokens. Claude writes one script instead of a run of tool calls, and the loop, the filtering and the sum happen in the isolate at no token cost.

On `lookup`, a single `get_customer` call, there is nothing to batch. Both modes take two round trips (one to call, one to answer), and Code Mode costs more because its one tool definition is bigger than all eight plain ones:

| What Claude receives as tool definitions | Characters |
|---|---|
| 8 plain MCP tools (JSON schemas) | 1,947 |
| 1 `code` tool, untyped declarations | 2,903 |
| 1 `code` tool, typed declarations | 4,120 |

That is the `createCodeTool` shape from the last post: every declaration goes into the tool description, plus the wrapper instructions ("Write an async arrow function in JavaScript...", "Do NOT use TypeScript syntax..."). With 8 small tools those instructions are a meaningful fixed cost. The "search and execute" shape that Cloudflare uses for its 2,500-endpoint API flips this around, but with 8 tools there is nothing to search.

So the corollary I guessed at last time holds: for one-call tasks, Code Mode is overhead. It cost $0.0044 to $0.0046 per run against $0.0038, about 16 to 21% more.

## Is parallel tool calling a tougher baseline than the 99% numbers suggest?

Yes, and this is the result that most changes how I read the published numbers.

The figures I quoted last time (1.17 million tokens down to about 1,000 for the Cloudflare API, 150,000 down to 2,000 for Anthropic's Drive-to-Salesforce example) both measure tool definitions in huge catalogs. The published case for chaining adds flows where each call waits for the previous one, so every step is a model round trip. Neither applies here. Eight tools are cheap to define, and Claude Opus 5.5 makes **parallel tool calls** in plain tool mode.

In one measured `top-sku` run, plain tool calling issued 1, then 5, then 14 tool calls per turn (the median run made 20 calls in 4 round trips):

```mermaid
sequenceDiagram
    participant C as Claude
    participant H as Agent loop
    participant S as MCP server
    C->>H: turn 1, list_customers (1 call)
    H->>S: 1 call
    S-->>H: customers, 5 of them gold
    H-->>C: tool results
    C->>H: turn 2, list_orders x5 (parallel)
    H->>S: 5 calls
    S-->>H: order summaries
    H-->>C: tool results
    C->>H: turn 3, get_order x14 (parallel)
    H->>S: 14 calls
    S-->>H: 14 full orders, long descriptions
    H-->>C: tool results, most of the run's tokens
    C->>H: turn 4, Answer line
```

All 14 `get_order` calls went out in a single turn, and my agent loop executes a turn's calls with `Promise.all`. That is why plain tool calling needed only 4 round trips for 20 calls, not 21. A naive mental model of tool calling ("one call per round trip") would predict a much larger Code Mode win. The measured savings are tens of percent, not 99%.

What parallel calling cannot fix is the data. Those 14 full orders still land in the conversation, get written to the cache, and get read back on the final turn. That is exactly the cost the typed Code Mode run avoids, and why `top-sku` is where Code Mode wins biggest (85% cheaper with types).

---

## Why do typed tool outputs matter so much for Code Mode?

When an MCP tool declares no `outputSchema`, the TypeScript that `codeMcpServer` generates for it says nothing about its result:

```typescript
type GetOrderOutput = unknown

declare const codemode: {
  /**
   * Get one order with its line items, shipping address and notes.
   * @param input.id - Order id, e.g. O-1001
   */
  get_order: (input: GetOrderInput) => Promise<GetOrderOutput>;
  // ... seven more
}
```

The model knows how to *call* `get_order`. It has no idea what comes back. Is it an array or an object with an array inside? Are line items `items`, `line_items` or `lines`? Is the count `qty` or `quantity`? This is the code Claude wrote for `top-sku` in that situation:

```javascript
const cs = await codemode.list_customers({tier:"gold"});
const list = Array.isArray(cs)?cs:(cs.customers||cs.items||cs.data||[]);
...
const items = od.items||od.line_items||od.lines||[];
for (const it of items) { const s=it.sku; qty[s]=(qty[s]||0)+(it.quantity??it.qty??0); }
log.push({c:c.id,o:o.id,items});
...
return {raw: list.length, qty, log, sample: cs};
```

It guesses field names with fallbacks, which is reasonable. Then it does the expensive thing: it returns every order it read (`log`) and a raw sample alongside the answer, so it can check its own guesses on the next turn. That return value was 20,324 characters, just under the 24,000-character response cap in `codeMcpServer`, so it came back in full, as compact JSON. The intermediate results Code Mode is supposed to keep out of context came straight back into it.

With output schemas declared, the same tool is described like this:

```typescript
type GetOrderOutput = {
    id: string;
    status: "pending" | "shipped" | "delivered" | "cancelled";
    total: number;
    created: string;
    customer_id: string;
    items: Array<{
        sku: string;
        qty: number;
        unit_price: number;
        description: string;
    }>;
    shipping_address: string;
    notes: string;
}
```

And the code becomes direct:

```javascript
const {customers} = await codemode.list_customers({tier:"gold"});
...
for (const it of d.items) qty[it.sku]=(qty[it.sku]||0)+it.qty;
```

No fallbacks. In the measured runs it returned a median of 283 characters, little more than the answer. (This sample is from my first run, before the cache fix described below. That fix changed what each run was billed, not the tool declarations Claude saw.)

![Left: the untyped declaration, type GetOrderOutput = unknown, and the defensive code Claude wrote that returns the raw log. Right: the typed declaration with items, sku and qty, and the direct code. Below: median characters returned to the model per run, 20,324 vs 283 on top-sku, 1,847 vs 313 on priority-emails, 1,055 vs 223 on eu-shipped](https://www.dhruvvakharwala.dev/images/blog/code-mode-mcp-benchmark-typed-tool-outputs/typed-vs-untyped.png)

Median characters returned to the model per run:

| Task | codemode | codemode-typed |
|---|---|---|
| top-sku | 20,324 | 283 |
| priority-emails | 1,847 | 313 |
| eu-shipped | 1,055 | 223 |

In `priority-emails` the untyped runs also spent an extra round trip (3 vs 2) just looking at data shapes before writing the emails. The loop looks like this:

```mermaid
flowchart TD
    A["Tool declares no outputSchema"] --> B["Declaration says<br/>Promise of unknown"]
    B --> C["Model guesses field names<br/>with fallbacks"]
    C --> D["Model returns raw data<br/>to verify its guesses"]
    D --> E["Raw data re-enters context<br/>up to the 24,000-char cap"]
    E --> F["Extra round trip<br/>or larger next turn"]
    G["Tool declares outputSchema"] --> H["Declaration has the<br/>exact result shape"]
    H --> I["Model writes direct code"]
    I --> J["Returns only the answer<br/>a few hundred chars"]
```

### Output types roughly halve the cost of Code Mode

Across all four tasks, typed outputs took Code Mode from $0.454 to $0.234 per 20 runs, a **48% drop**, with the same correctness. Most of the benefit I expected from Code Mode only showed up once the model knew what the tools return.

There is a nice irony in that. Code Mode's own pitch is that models are better at writing code against a typed API than at emitting tool calls. The "typed" part turns out to carry a lot of the weight. A TypeScript API whose every function returns `unknown` is not much of an API.

### On a smaller model the effect is larger

I also ran the same three modes on Claude Haiku 5.5 (more on why in proposal 3). Untyped Code Mode on Haiku needed 4 round trips on `top-sku` and 5 on `priority-emails`, exploring data shapes before doing the work, and on `top-sku` it used more input tokens than plain tool calling (19,544 against 18,032). With typed outputs both tasks took 2 round trips, and typed Code Mode was the cheapest mode on Haiku too: $0.0077 for 20 runs, against $0.0192 for plain tools.

So "Code Mode beats tool calling" is not a property of Code Mode alone. On a small model with untyped tools, it can lose.

---

## Which two codemode bugs blocked typed outputs?

Typed outputs did not work out of the box. `codeMcpServer` in 0.5.6 had two problems with upstream tools that declare an `outputSchema`, and the first one hides the second.

### Bug 1: a crash on Workers

`codeMcpServer` talks to the upstream server through its own MCP `Client`, created with no options:

```typescript
const client = new Client({ name: "codemode-proxy", version: "1.0.0" });
```

Without options, the MCP SDK falls back to its default JSON Schema validator, which is built on Ajv. `Client.listTools()` compiles a validator for every tool that declares an `outputSchema`, and Ajv compiles validators by generating JavaScript source and running it with `new Function`. workerd, the Workers runtime, does not allow that, so `codeMcpServer()` throws before it returns:

```text
Error compiling schema, function code: const schema0 = scope.schema[0];return function validate0(data, ...
Code generation from strings disallowed for this context
```

Any upstream MCP server with even one `outputSchema` could not be wrapped on Workers. The same class of bug had already been fixed for `openApiMcpServer` in [#1555](https://github.com/cloudflare/agents/pull/1555) ("use Workers-safe MCP validator") and, per the issue I filed, for Agents MCP client connections in #1902. The client inside `codeMcpServer` was missed.

Why did no test catch it? Two reasons. There was no test with an upstream `outputSchema` at all. And the package's tests run in the vitest Workers pool, which allows eval, so a straightforward behavioral test would pass anyway. The regression test I wrote checks which validator the client is configured with instead.

### Bug 2: dropped output schemas

Even with the crash fixed, every result was still `unknown`. `codeMcpServer` built its tool descriptors from `inputSchema` only, although the type generator (`generateTypesFromJsonSchema`) already supports `outputSchema` and the `McpConnector` path already forwards it. Someone else had reported this one a month earlier as [#2708](https://github.com/cloudflare/agents/issues/2708), with the one-line fix.

### The fix

Both fixes together, in `packages/codemode/src/mcp.ts`:

```diff
-  const client = new Client({ name: "codemode-proxy", version: "1.0.0" });
+  // The SDK's default Ajv validator compiles outputSchemas with eval, which Workers forbid
+  const client = new Client(
+    { name: "codemode-proxy", version: "1.0.0" },
+    { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() }
+  );
   ...
     toolDescriptors[tool.name] = {
       description: tool.description,
-      inputSchema: tool.inputSchema as JSONSchema7
+      inputSchema: tool.inputSchema as JSONSchema7,
+      outputSchema: tool.outputSchema as JSONSchema7 | undefined
     };
```

`CfWorkerJsonSchemaValidator` was already imported in that file for another code path. Each fix comes with a regression test that fails on `main`.

The Agents SDK README says plainly: "We are not accepting external pull requests at this time". So instead of a PR, I filed the crash as [#3458](https://github.com/cloudflare/agents/issues/3458), added the benchmark numbers to [#2708](https://github.com/cloudflare/agents/issues/2708), and put both commits on a [fork branch](https://github.com/vakharwalad23/agents/tree/fix/codemode-mcp-output-types) that maintainers can cherry-pick. Two minutes after I filed #3458, the repository's automation opened [PR #3459](https://github.com/cloudflare/agents/pull/3459) with the validator fix; as I write this, it is open and not merged, and #2708 is still open.

---

## What mistake did I make in my first measurement?

My first full run sent byte-identical conversations on every repetition. Same system prompt, same tools, same first user message. With automatic prompt caching, that meant each repetition could read the previous repetition's cache, not just the shared prefix.

In tools mode the effect was dramatic: the entire `top-sku` transcript, all 20 tool results included, was served from a cache written by the previous repetition. 0 tokens written, 17,719 read. Cache reads cost 25 times less than cache writes here ($0.20 vs $5 per million), so tools mode looked far cheaper than it is. Real conversations never repeat byte for byte like that.

The fix was two small changes to the agent loop:

- a per-run `<request_id>` (a random UUID) at the start of the first user message, so no two conversations share anything past the system prompt;
- an explicit cache breakpoint after the system prompt, so the tools and system prompt **are** shared across conversations, as they would be in a deployed agent.

In tools mode, token counts, round trips and timings barely moved, but the cost of its 20 measured runs went from $0.348 to $0.687. Every number in this post is from the corrected runs. If you benchmark anything with prompt caching on, check your cache-read counts on the second repetition before you trust a cost figure.

---

## Did my six proposals survive the data?

The last post ended with six ideas for optimizing Code Mode, each marked as untested. Here is each one, tested.

### Proposal 1: stable declarations and prompt caching

The proposal: keep the generated declarations byte-identical across turns so a provider's prompt cache can hit on them.

**Byte stability.** Two fresh `codeMcpServer` instances over the same upstream server produce byte-identical tool definitions, in every mode. The benchmark's `/selftest` endpoint checks exactly that. The declarations are already a stable prefix; there is nothing to fix in the package.

**What caching that prefix is worth.** I ran the same tasks on Opus 5.5 under three cache settings: off, caching only within a conversation (automatic caching), and an explicit breakpoint after the system prompt so tools and system are shared across conversations. Sum of the per-task median costs for one pass over the four tasks:

| Mode | Off | Within a conversation | Shared tools + system | Shared vs within |
|---|---|---|---|---|
| tools | $0.2048 | $0.1585 | $0.1371 | -13% |
| codemode | $0.1567 | $0.1191 | $0.0878 | -26% |
| **codemode-typed** | $0.1242 | $0.0883 | $0.0432 | **-51%** |

![Bar chart of the sum of per-task median costs by cache setting. Cache off: tools $0.2048, codemode $0.1567, codemode-typed $0.1242. Within a conversation: $0.1585, $0.1191, $0.0883. Shared tools and system: $0.1371, $0.0878, $0.0432. Shared vs within: -13%, -26%, -51%](https://www.dhruvvakharwala.dev/images/blog/code-mode-mcp-benchmark-typed-tool-outputs/cache-modes.png)

Code Mode gains the most because its declarations are a large share of each request and the rest of the conversation stays small. In tools mode the conversation fills up with tool results, so a shared prefix is a smaller fraction of what is read. Even with caching off the order holds: typed Code Mode is the cheapest of the three.

So proposal 1 turned into a host setting, not a package change: put a cache breakpoint after the tool definitions and system prompt. The Code Mode docs do not mention prompt caching, so I filed a docs note as [#3462](https://github.com/cloudflare/agents/issues/3462) with byte-stability tests and a short docs section on a [fork branch](https://github.com/vakharwalad23/agents/tree/docs/codemode-prompt-caching). The repository's automated triage closed it as not planned within a minute: "Prompt caching is provider-level guidance that isn't specific to Codemode". That is a fair position for a library, and the number above is now public either way.

### Proposal 2: cache declarations by a hash of the tool list

The premise was that generating declarations costs host CPU. I had already called this my weakest idea. Timing `codeMcpServer()` in Node for synthetic catalogs of 10 to 1,000 tools with nested schemas says otherwise:

| What | 300 tools | 1,000 tools |
|---|---|---|
| Type generation | 2.4 ms | 8.7 ms |

Most of the construction time was not type generation at all. It was the MCP client compiling output-schema validators with Ajv, the same code path behind the Workers crash. With the Workers-safe validator, `listTools()` at 300 tools dropped from 103.4 ms to 19.9 ms (medians of 7 runs), and the whole `codeMcpServer()` took 23.9 ms. A hash cache would save about 10% of an already small number. Dropped. The validator timing went onto [#3458](https://github.com/cloudflare/agents/issues/3458) instead, because it is a free side benefit of the crash fix: hosts that build `codeMcpServer` per request pay that cost every time.

### Proposal 3: a pre-flight check before the sandbox runs

The proposal: walk the generated code's AST with acorn and reject unknown tool names before spending a sandbox run. That only pays off if the model actually calls tools that do not exist, so I counted every failed `code` call.

| Model | Code Mode runs | Runs with any tool error | Unknown tool names |
|---|---|---|---|
| Claude Opus 5.5 | 40 | 0 | 0 |
| Claude Haiku 5.5 | 40 | 0 | 0 |

All 120 Haiku and Opus runs in these sets were correct, plain tools included. With generated declarations in front of it, even the smallest current Claude model did not invent a tool name once, so a pre-flight check would have caught nothing here. Dropped as a performance idea. It might still matter for catalogs with hundreds of similar names, which this benchmark does not cover.

### Proposal 4: adaptive truncation budgets

`codeMcpServer` caps what the `code` tool returns at 24,000 characters. I made that budget configurable locally (a `maxResponseChars` option on my experiment branch) and re-ran `top-sku`, the task whose return came closest to the cap, at 6,000 and 96,000 characters:

| Mode | 6,000 | 24,000 (default) | 96,000 |
|---|---|---|---|
| codemode | $0.028, 3/3 correct | $0.051, 5/5 | $0.055, 3/3 |
| codemode-typed | $0.012, 3/3 | $0.013, 5/5 | $0.012, 3/3 |

With typed outputs the budget never matters: the model returns 283 characters at every setting. Without them, only the hedged return gets near the cap, and a *smaller* cap was cheaper with the same correctness. No task needed a larger budget. Typed outputs fix the case this proposal targeted better than any budget, so it is dropped.

### Proposal 5: `Promise.all` without breaking replay

Two questions: is concurrency inside the sandbox worth anything, and does the durable runtime break on it?

**Is it worth anything?** The mock tools answer instantly, so to make concurrency visible I added 150 ms of latency to every mock tool call, as a stand-in for a network hop. Claude already wrote `Promise.all` in 7 of 9 typed Code Mode runs without being asked, and in 9 of 9 with a one-line hint appended to the tool description ("Calls that do not depend on each other can run concurrently..."). On `top-sku` the hint took the median from 7.4 s to 5.0 s, about 32% faster: with it, every `top-sku` run used `Promise.all`; without it, 1 of 3 did.

**Does replay break?** The durable runtime (the abort-and-replay machinery from the last post, used for approvals) numbers each tool call when it reaches the host. The runtime docs already warn that even a flat `Promise.all([a(), b()])` can arrive in either order, although in my repro the flat calls kept their order, since the code issues them in sequence. Nested awaits break reliably:

```javascript
async () => {
  const ids = await Promise.all([1, 2].map(async (id) => {
    const item = await items.get_item({ id, delayMs: id === 1 ? 50 : 0 });
    return (await items.get_item({ id: item.id + 10 })).id;
  }));
  return await items.create_item({ title: "after " + ids.join(",") });
}
```

The second `get_item` in each branch is issued only after the first one resolves, so it gets a sequence number in **completion** order. On resume after an approval, replayed reads resolve from the log in log order, so the nested calls arrive in a different order:

```mermaid
sequenceDiagram
    participant Code as Model code
    participant RT as Durable runtime
    Note over Code,RT: First pass, live tools
    Code->>RT: get_item 1 (seq 0), get_item 2 (seq 1)
    RT-->>Code: item 2 resolves first (no delay)
    Code->>RT: get_item 12 (seq 2)
    RT-->>Code: item 1 resolves after 50 ms
    Code->>RT: get_item 11 (seq 3)
    Code->>RT: create_item, needs approval, pause
    Note over Code,RT: Approved, replay from the log
    Code->>RT: get_item 1 (seq 0), get_item 2 (seq 1)
    RT-->>Code: both served from the log, in log order
    Code->>RT: get_item 11 arrives as seq 2
    RT-->>Code: replay divergence, seq 2 was get_item 12
    Note over Code,RT: The approved create_item never runs
```

The run fails with this error, even though every argument is deterministic:

```text
Codemode replay divergence at step 2: items.get_item was called with different arguments than the recorded run. Arguments must be deterministic across replays. Wrap nondeterministic inputs in codemode.step(name, fn).
```

`docs/codemode/runtime.md` tells developers to issue calls one at a time in runs that might pause, but the model never reads that file. The runtime tool's description does not warn the model, models write `Promise.all` on their own (7 of 9 above), and the error suggests `codemode.step`, which does not help here. I reproduced it in 3 of 3 runs on the package's existing runtime test harness and filed it as [#3464](https://github.com/cloudflare/agents/issues/3464), with the repro test on a [fork branch](https://github.com/vakharwalad23/agents/tree/test/codemode-concurrent-replay).

This is the one that stuck. The triage response confirmed the design gap and recommended matching replayed reads "by connector, method, stable args and occurrence index", which is the fix I proposed in the last post. It noted that this changes the replay contract and needs a maintainer decision, and it ruled out a prompt-only hint, because models would still run calls concurrently. The issue is open.

### Proposal 6: approval defaults from MCP annotations

`McpConnector` drops MCP tool annotations. A tool the server marks `destructiveHint: true` runs without approval unless a developer overrides `tool(name, t)` for it by hand, and keeps that list in sync as the server adds tools.

I implemented the opt-in policy from the last post:

```typescript
class GithubConnector extends McpConnector<Env> {
  protected override readonly requireApprovalUnlessReadOnly = true;
}
```

With it, every tool not marked `readOnlyHint: true` requires approval, unannotated tools included. It is off by default, so existing connectors do not change, and the `tool(name, t)` hook still runs afterwards and can override either way. It fails closed on purpose, because the MCP spec says "Clients should never make tool use decisions based on ToolAnnotations received from untrusted servers": only `readOnlyHint` can relax approval, and only if you turn the policy on for a server you trust.

Filed as [#3465](https://github.com/cloudflare/agents/issues/3465) with the implementation, a test and a docs paragraph on a [fork branch](https://github.com/vakharwalad23/agents/tree/feat/codemode-mcp-annotation-approvals). Closed as not planned within a minute: approval is already opt-in per tool through the `tool(name, t)` hook, "and a new policy flag would be a permanent public API for a narrow case". Also a fair position. The same reply confirmed that `tools()` drops the annotations.

---

## What happened upstream?

All of it happened on the same day, 2026-11-27. Times are UTC, from the GitHub issue and PR timestamps.

```mermaid
timeline
    title Upstream on 2026-11-27 (UTC)
    10.44 : #3458 filed, Workers crash : benchmark numbers added to #2708
    10.46 : automation opens PR #3459 with the validator fix
    10.53 : #3462 filed, prompt caching docs note
    10.54 : #3462 closed as not planned
    11.11 : #3464 filed, replay divergence, triaged as a confirmed design gap : #3465 filed, annotation approvals, closed as not planned : validator timing added to #3458
```

| Proposal | Result | Upstream, as of 2026-11-27 |
|---|---|---|
| 1. Stable declarations first, for prompt caching | Already byte-stable; sharing the prefix cuts typed Code Mode cost by 51% | [#3462](https://github.com/cloudflare/agents/issues/3462), closed as not planned |
| 2. Cache declarations by a hash of the tool list | Type generation is 2.4 ms at 300 tools; dropped | Validator timing added to [#3458](https://github.com/cloudflare/agents/issues/3458) |
| 3. Static pre-flight check | Zero unknown tool names in 80 runs on two models; dropped | None |
| 4. Adaptive truncation budgets | Typed outputs make the budget irrelevant; dropped | None |
| 5. `Promise.all` without breaking replay | Concurrency is worth about 32% on a fan-out task; nested concurrency breaks resume after approval | [#3464](https://github.com/cloudflare/agents/issues/3464), open, design gap confirmed |
| 6. Approval defaults from MCP annotations | Destructive tools run ungated by default; opt-in policy implemented | [#3465](https://github.com/cloudflare/agents/issues/3465), closed as not planned |
| Not on my list: typed tool outputs | Halves Code Mode cost; needed two fixes | [#3458](https://github.com/cloudflare/agents/issues/3458) open with automated [PR #3459](https://github.com/cloudflare/agents/pull/3459); [#2708](https://github.com/cloudflare/agents/issues/2708) open |

Three of six proposals survived the data. Upstream kept one of those open. The idea that mattered most was not on my list at all.

I do not read the closures as a verdict on the measurements. A library that is still marked experimental has good reasons to say no to docs about provider features and to new public flags. The numbers and the branches are public either way, and each issue says I am happy to open a pull request if that policy changes.

---

## What are the limits of this benchmark?

- **One mock domain, 8 tools, 3 to 5 runs per cell.** The main results are on one model (Opus 5.5) at one effort level. Haiku 5.5 ran the same 60-run matrix once, used for the error count and the untyped-vs-typed comparison; the cache, latency and budget runs were Opus only.
- **Mock tools answer instantly**, except in the 150 ms latency runs for proposal 5. Real tools have network latency, which would make every saved round trip and every parallel call count for more.
- **Local sandbox.** `DynamicWorkerExecutor` ran under local `wrangler dev`, not deployed Workers. Isolate start-up on the edge may differ.
- **Typed outputs need the upstream server's cooperation.** The MCP server has to declare `outputSchema` for each tool. Many servers do not yet, and `codeMcpServer` needs the two fixes above before it can use them on Workers.
- **Small catalog.** With 8 tools, definitions are cheap. This benchmark says nothing about the 2,500-endpoint case where Cloudflare's search-and-execute numbers come from.

## What did this experiment cost?

$7.63 of API usage across 366 runs, including warm-ups and the flawed first run. Every run was correct.

---

## FAQ

### Is Code Mode MCP cheaper than plain tool calling?

In this benchmark, yes on multi-call tasks. Across four tasks on Claude Opus 5.5, `codeMcpServer` as shipped cost 34% less than plain MCP tool calling, and 66% less with typed tool outputs. On a single-call task plain tool calling was cheapest.

### Why do typed tool outputs make Code Mode cheaper?

Without an `outputSchema`, the generated declaration types every result as `unknown`, so the model writes defensive code and returns raw data to check its guesses. With result types it writes direct code and returns only the answer: 283 characters instead of 20,324 on the largest task.

### Does codeMcpServer support MCP outputSchema?

Not in `@cloudflare/codemode` 0.5.6. It drops `outputSchema` when building types (issue #2708), and on Workers it crashes when any upstream tool declares one, because the default Ajv validator uses `new Function` (issue #3458). Both fixes are a few lines and sit on a public fork branch.

### Why were the savings smaller than Cloudflare's 99.9%?

The published numbers come from very large tool catalogs, where tool definitions dominate. With 8 tools, definitions are cheap, and Claude makes parallel tool calls, so plain tool calling did 20 calls in 4 round trips. The measured savings were tens of percent.

### Is Promise.all safe inside Code Mode's durable runtime?

Not in a run that can pause for approval. The runtime docs say to await connector calls one at a time there. Flat `Promise.all` over independent calls kept its order in my repro, but nested awaits inside `Promise.all` make the run fail to resume with a replay divergence, reported as issue #3464.

**Takeaway:** Code Mode delivered on a small catalog, but not for the reason I expected. Batching calls in a sandbox saved 34% against plain tool calling, which is real but far from the published 99%, because modern parallel tool calling is a strong baseline. The bigger lever was telling the model what each tool returns: typed outputs took Code Mode from 34% to 66% cheaper, cut what came back to the model from 20,324 characters to 283 on the largest task, and needed two small fixes to `codeMcpServer` to work at all. If you run Code Mode, declare `outputSchema` on your MCP tools, put a cache breakpoint after your tool definitions, and keep calls one at a time in any run that can pause for approval.


## References

- Previous post: [Code Mode MCP: How Cloudflare Lets Models Write Code Instead of Calling Tools](https://www.dhruvvakharwala.dev/blogs/code-mode-mcp-cloudflare-agents-sdk)
- Upstream issues: [#3458 codeMcpServer throws on Workers when an upstream tool declares an outputSchema](https://github.com/cloudflare/agents/issues/3458), [#2708 codeMcpServer ignores tool outputSchema](https://github.com/cloudflare/agents/issues/2708), [#3462 prompt caching docs note](https://github.com/cloudflare/agents/issues/3462), [#3464 nested Promise.all replay divergence](https://github.com/cloudflare/agents/issues/3464), [#3465 MCP tool annotations and approvals](https://github.com/cloudflare/agents/issues/3465)
- Upstream PRs: [#3459 Workers-safe validator in codeMcpServer](https://github.com/cloudflare/agents/pull/3459), [#1555 Workers-safe MCP validator for openApiMcpServer](https://github.com/cloudflare/agents/pull/1555)
- Benchmark code: [examples/codemode-bench](https://github.com/vakharwalad23/agents/tree/experiment/codemode-bench/examples/codemode-bench)
- Fork branches: [fix/codemode-mcp-output-types](https://github.com/vakharwalad23/agents/tree/fix/codemode-mcp-output-types), [docs/codemode-prompt-caching](https://github.com/vakharwalad23/agents/tree/docs/codemode-prompt-caching), [test/codemode-concurrent-replay](https://github.com/vakharwalad23/agents/tree/test/codemode-concurrent-replay), [feat/codemode-mcp-annotation-approvals](https://github.com/vakharwalad23/agents/tree/feat/codemode-mcp-annotation-approvals)
- [cloudflare/agents](https://github.com/cloudflare/agents), `packages/codemode` (version 0.5.6)
- [MCP schema, 2025-06-18, `ToolAnnotations`](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/2025-06-18/schema.ts)
- Kenton Varda and Sunil Pai, ["Code Mode: The better way to use MCP"](https://blog.cloudflare.com/code-mode/), Cloudflare, 2025-09-26
- Matt Carey, ["Code Mode: give agents an entire API in 1,000 tokens"](https://blog.cloudflare.com/code-mode-mcp/), Cloudflare, 2026-02-20
- Anthropic Engineering, ["Code execution with MCP: Building more efficient agents"](https://www.anthropic.com/engineering/code-execution-with-mcp), 2025-11-04
- Related posts: [Talk to Chart: a model that returns typed ops instead of running a tool-calling loop](https://www.dhruvvakharwala.dev/blogs/talk-to-chart-jev-gpt5-tradingview-pine)