Code Mode MCP Explained With a Working Example
Code Mode MCP is a way of building an MCP server so that the agent does its work by writing a small program instead of making a long series of tool calls. The server exposes very few tools. One of them runs code in a sandbox, and inside that sandbox the server's whole API is available as ordinary functions. Cloudflare introduced the name; Anthropic has described the same idea. This guide explains the pattern through one real implementation, Forkit's execute_code, with examples you can adapt.
The problem Code Mode MCP solves
A conventional MCP server exposes one tool per operation. That has two costs, and the first is a plain token cost.
First, every tool's definition sits in the model's context on every request. A server with sixty operations spends thousands of tokens before the agent does anything.
Second, multi-step work becomes many round trips. To find overdue tasks and raise their priority, the agent calls a list tool, reads the whole list, then calls an update tool once per task. Each result travels through the model. Cloudflare's post describes this as output feeding into the model just to be copied over to the inputs of the next call.
Code Mode replaces the sixty tools with a function library and one tool to run code against it. Cloudflare's own API server is the well-known example: over 2,500 endpoints behind a search tool and an execute tool.
The three parts
1. A typed SDK. The server's operations as functions, described by TypeScript type definitions. Models read and write TypeScript well.
2. A discovery tool. Instead of loading every definition up front, the agent asks for them when needed. In Forkit this is search_api, which returns the type definitions for the SDK. The documentation puts the cost at about a thousand tokens, paid once.
3. An execution tool. In Forkit, execute_code. It takes a string of async JavaScript, runs it and returns whatever the code returns, along with anything it logged.
A first example
The agent wants the three most urgent tasks it can start, and wants to claim them.
const ready = await codemode.ready_tasks();
const urgent = ready
.filter(t => t.priority === 'urgent' || t.priority === 'high')
.slice(0, 3);
for (const t of urgent) {
await codemode.claim_task({ task_id: t.id, agent_id: 'api-agent' });
}
return urgent.map(t => ({ id: t.id, title: t.title }));
One tool call. The model sees three ids and titles, not the full list of ready tasks. The filtering is exact, because code did it.
A second example: bulk changes
const overdue = await codemode.list_tasks({ overdue: true, status: 'pending' });
let changed = 0;
for (const t of overdue) {
await codemode.update_task({ task_id: t.id, priority: 'high' });
changed++;
}
return { overdue: overdue.length, changed };
With direct tool calls this is one list call plus one update per task, each a round trip through the model. Here it is a loop.
A third example: building a plan
const a = await codemode.create_task({ title: 'Add tax_cents column', priority: 'high' });
const b = await codemode.create_task({ title: 'Expose tax on invoice API' });
const c = await codemode.create_task({ title: 'Show tax on invoice page' });
await codemode.add_dependency({ blocker_id: a.id, blocked_id: b.id });
await codemode.add_dependency({ blocker_id: b.id, blocked_id: c.id });
return [a.id, b.id, c.id];
Three tasks and their order, created together. Composition like this is where the pattern earns its keep.
What is inside the sandbox
Running model-written code is only acceptable if the code can do nothing except what you intended. Forkit's documentation describes its sandbox as follows:
- A real V8 isolate. The code runs in a fresh isolate through Cloudflare's Worker Loader, using the
@cloudflare/codemodelibrary. It is notevalin the server's own process. - No network. Outbound network access is disabled. The script cannot call other services or send data anywhere.
- One way out. The
codemodefunctions are the only connection to anything. Each one is wired back to a real database operation over Workers RPC. - Tenant scope. Every query includes the caller's workspace. A script cannot name another workspace.
- Identity from the key. The actor is built from the API key and passed into the sandbox. Arguments cannot change who the script acts as.
Limits
Forkit caps every execution:
| Limit | Value |
|---|---|
| Code size | 50 KB |
| Output size | 500 KB (serialized result) |
| Run time | 30 seconds maximum |
| Rate | 20 executions per 60 seconds per workspace |
A script that returns too much is refused, which pushes agents to return summaries instead of dumps. That is good for their context too.
The audit log
A single tool that can do anything needs a record. Every execute_code call, successful or failed, is stored with its code, result, error, logs, duration and status. The list_executions tool reads that log.
This is one consequence to design for: because results are kept, anything that returns a secret must not run through execute_code. Forkit's own example is starting a fan-out, which returns keys. It is available over HTTP only.
What stays a normal tool
Not everything belongs behind the script. Forkit keeps nine MCP tools in total:
execute_codeandsearch_api, the Code Mode pair.ready_tasksandclaim_task, because agents call them constantly and claiming must be atomic.wait_for_task,wait_for_replyandwait_for_message, which are long-polls of up to 120 seconds. A wait does not fit inside a 30-second script.summarize_sessionandlist_executions.
A reasonable rule: operations that are frequent and simple, that block for a long time, or that need their own approval stay as tools. The long tail goes behind the script.
How an agent learns the SDK
A new session follows this sequence:
tools/listshows nine tools with short descriptions.- The agent calls
search_apionce and receives the type definitions. - From then on it writes
execute_codescripts.
Forkit's notes mention a practical detail: the discovery schema that tools/list serves is maintained separately from the handlers, so the two must be kept in sync when tools change. If you build a Code Mode server, generate both from one source if you can.
When not to use Code Mode
- Small servers. With five tools, the sandbox is overhead.
- Clients you do not control that handle code poorly. Most current coding agents write short scripts well. Some simpler clients do not.
- Actions that each need a person's approval. One script that performs ten sensitive writes is one decision. Keep those as separate calls.
- No safe sandbox available. Do not run model-written code without real isolation.
Code Mode vs MCP tool calls compares the two approaches side by side.
Writing good scripts: advice for agents
If you maintain instructions for agents that use a Code Mode server, include these:
- Return little. Return ids, counts and the fields you need, not whole objects.
- Do related work in one script. Read, decide and write together.
- Check for null.
claim_taskreturns nothing when another agent won the race. Handle it. - Stay inside the limits. Thirty seconds and 500 KB are plenty for bookkeeping and too little for bulk export.
- Do not put waits in scripts. Use the long-poll tools.
Try it
Any MCP client can connect to Forkit's endpoint with a guest identifier (Authorization: Guest <any-stable-id>), call search_api and then run the first example above. That gives an isolated workspace with no sign-up. See what is an MCP server for connection basics and task dependencies for agents for what the task functions do.
Where Forkit fits
Forkit's MCP server is Code Mode in production form: nine tools, a typed SDK, a V8 sandbox with no network, hard limits and a full audit log. The same endpoint carries threads, messages and file claims. It is free to try. More at forkit-mcp.com.