Code execution with MCP lets an agent write a short script that calls MCP tools, instead of the model calling every tool itself. It saves tokens in two places. Tool definitions stay out of the context window until they are needed, and bulky tool results get filtered in code before the model sees them.
The best-known figure is Anthropic's, dated November 4, 2025. In one example workflow it reports 150,000 tokens falling to 2,000, a 98.7% cut. Cloudflare reports 1,170,523 tokens falling to about 1,100 for its own API. Both are vendor-reported. An independent test measured 78.5% fewer input tokens, with slower calls. Small tool sets save little, and you must run a sandbox.
Plan a creative job in an agent, then check what it calls
Agent Chat is Oakgen's conversational workspace for image, video and audio jobs. Oakgen is our product.
The short version
| Technique | What it cuts | Vendor-reported figure | Reported by, date | Sandbox needed |
|---|---|---|---|---|
| Tool search or deferred loading | Tool definitions | 85% fewer tokens | Anthropic, Nov 24 2025 | No |
| Programmatic tool calling | Tool results and model round trips | 37% fewer tokens on research tasks, about 8% more cost on sequential tasks | Anthropic, Nov 24 2025 and docs | Yes, Anthropic hosts it |
| Code execution with MCP (file tree) | Definitions and results | 150,000 to 2,000 tokens in one example | Anthropic, Nov 4 2025 | Yes, you run it |
| Server-side Code Mode | Definitions, for one big API | 1,170,523 to about 1,100 tokens | Cloudflare, Feb 20 2026 | Yes, Cloudflare runs it |
| Independent check | Input tokens, 63 tools, GPT-4.1 | 78.5% fewer, with 7% higher latency | AIMultiple, page updated Oct 16 2026 | Yes |
Every efficiency figure in this post is the vendor's own claim unless a row says independent. Disclosure. Oakgen is our product. We are not a vendor in this space, and we ran none of these benchmarks.
Who this is for
You connect an agent to several MCP servers and the bill or failure rate climbs as you add tools, or you build a server and wonder how many tools is too many. New to the protocol? Start with our guide to MCP servers for image generation. For when MCP is the wrong layer, see MCP versus a direct API.
How we checked this
As of November 12, 2026 we opened Anthropic's two engineering posts, its tool search and programmatic tool calling documentation, both Cloudflare posts, Cloudflare's MCP repository README and the AIMultiple benchmark page. Every number below comes from those pages, or is arithmetic we show.
We ran no benchmark. The calculator uses invented inputs and says so. Anthropic's post is a year old, so check the docs links before you build.
Why tool definitions bloat context
An MCP server describes its tools with a name, a description and a JSON schema. Most clients load every definition from every connected server into the context window before the model reads your request.
Anthropic's November 24, 2025 post gives a count. A five-server setup with GitHub (35 tools, about 26K tokens), Slack (11 tools, about 21K), Sentry, Grafana and Splunk is 58 tools and about 55K tokens before the conversation starts. Jira alone uses about 17K, and Anthropic says it has seen definitions consume 134K tokens internally. Dividing 55K by 58 gives about 950 tokens per tool, our arithmetic, which we reuse in the calculator.
Anthropic's code execution post names a second cost. Intermediate results also pass through the model. Its example moves a meeting transcript from Google Drive to Salesforce, so the transcript enters the context when fetched and the model writes it out again to save it. For a two-hour sales meeting, Anthropic says that could mean an additional 50,000 tokens.
Anthropic's tool search documentation also says Claude's tool selection degrades past 30 to 50 available tools.
Definitions are a fixed cost on every model call. Results are a variable cost that depends on the data. Tool search fixes the first. Code execution fixes both. Know which one eats your budget before you pick a fix.
How code execution with MCP works
The idea is to treat MCP tools as an API the model programs against, not a menu it picks from.
Anthropic's version, a file tree. The runtime generates a folder of TypeScript wrappers, one file per tool, grouped by server. The agent lists the folder, opens only the files it needs, and writes a script. The Drive to Salesforce example becomes this.
import * as gdrive from './servers/google-drive';
import * as salesforce from './servers/salesforce';
const transcript = (await gdrive.getDocument({ documentId: 'abc123' })).content;
await salesforce.updateRecord({
objectType: 'SalesMeeting',
recordId: '00Q5f000001abcXYZ',
data: { Notes: transcript }
});
The transcript never enters the model's context. Anthropic says this takes the example from 150,000 tokens to 2,000, a 98.7% saving. The post does not say how the figures were measured, which model was used or how many tools were connected, so treat it as an illustration of the pattern. Anthropic also shows an agent filtering a 10,000-row spreadsheet to five rows before logging.
Cloudflare's version, a typed API. Cloudflare's first post, dated September 26, 2025, turns an MCP server's schema into a TypeScript interface and runs the model's code in a V8 isolate. The sandbox has no internet access. Its only route out is bindings to the MCP servers it was given, and API keys stay with the supervisor. That post argues qualitatively that models handle more tools when they are presented as code. It gives no token figures. The number everyone quotes comes from the second post.
Cloudflare's server-side version. The February 20, 2026 post, by Matt Carey, applies Code Mode on the server. The Cloudflare API MCP server exposes search() and execute(). The model writes JavaScript against a typed OpenAPI spec to find endpoints, then more JavaScript to call them, and the spec never enters the context. Cloudflare says the footprint stays around 1,000 tokens however many endpoints exist. Each company's post cites the other.
See a small tool surface in practice
Oakgen is our product. Browse the image, video and audio models an agent can choose from.
The numbers, with who said them
| Claim | Who reported it, and when | Type | What to know |
|---|---|---|---|
| 150,000 to 2,000 tokens, 98.7% | Anthropic, Nov 4 2025 | Vendor, one example | No method published. (150,000 minus 2,000) divided by 150,000 is 98.67% |
| About 38% fewer billed input tokens | Anthropic docs, undated | Vendor, internal evaluation | A 75-tool benchmark, accuracy unchanged |
| About 8% more cost | Anthropic docs, undated | Vendor, internal evaluation | On tau-squared-bench, one or two sequential calls per turn |
| 1,170,523 to about 1,100 tokens, 99.9% | Cloudflare, Feb 20 2026 and README | Vendor, own API | Counted with tiktoken, 2,594 tools |
| 78.5% fewer input tokens | AIMultiple, updated Oct 16 2026 | Independent, small | GPT-4.1, 63 tools, two task types, 50 runs |
Three details change how to read it.
First, Cloudflare's 99.9% depends on the baseline. Its README lists two native MCP baselines for the same 2,594 tools, 1,170,523 tokens with full schemas and 244,047 with required parameters only. Against the smaller baseline, a roughly 1,100 token footprint is a 99.5% saving by our arithmetic. Still enormous, but a different number. The blog's summary line also quotes about 2 million tokens, which the README gives as the raw OpenAPI spec.
Second, Anthropic's documentation is more careful than the headline. Programmatic tool calling "trades a small fixed overhead" for savings, and sequential single-call workflows "do not benefit". Those are Anthropic's own numbers, and they sit beside the 98.7%.
Third, the one independent test is small, with a conflict worth stating. AIMultiple used GPT-4.1 against Bright Data's MCP server. Success was 100% for both approaches and average input tokens fell from 15,417 to 3,310. But output tokens rose 120% because the model writes code, and latency rose 7%, from 9.66 to 10.37 seconds. AIMultiple lists Bright Data among subscribers to its benchmarking services, and names two query types and one model as limits.
Token budget calculator (an illustration, not a measurement)
This is the original asset. Every input is hypothetical, chosen as round numbers near Anthropic's reported setup. None of it was measured on a real agent. Replace the inputs with your own.
Step 1. The invented inputs
| Input | Symbol | Value |
|---|---|---|
| Tools connected | N | 60, near Anthropic's 58-tool example |
| Tokens per tool definition | D | 900, rounded down from our roughly 950 |
| Task prompt and instructions | P | 2,000 |
| Large result passed between tools | R | 20,000 |
| Tokens the model writes back out | W | 20,000 |
| Output price against input price | 5 to 1, an assumption, not any vendor's price |
The task is the Drive to Salesforce pattern. Fetch one document, save it elsewhere, confirm. We count input tokens billed across model calls without caching, plus output tokens.
Step 2. Three setups, worked out
A. Direct tools, everything loaded. Definitions cost N times D, so 60 times 900 is 54,000 tokens. The model makes three calls.
- Call 1 reads 54,000 plus 2,000, so 56,000 input tokens.
- Call 2 adds the 20,000 token result, so 76,000.
- Call 3 adds the 20,000 tokens the model wrote, so 96,000.
- Input total 228,000. Output 20,000.
B. Tool search. A search tool of about 500 tokens loads first, then the two tools we need load after a search (2 times 900, so 1,800). That adds a call.
- Calls read 2,500, then 4,300, then 24,300 after the result, then 44,300 after the write.
- Input total 75,400. Output 20,000.
C. Code execution. The model lists a folder, reads two small wrapper files, writes a script and reads a short printed result. We assume 500 tokens for the code tool, 300 for the listing, 500 for the wrappers, 300 for the script and 100 for the output.
- Calls read 2,500, then 2,800, then 3,300, then 3,700.
- Input total 12,300. Output about 500.
Step 3. The result
| Setup | Input tokens | Output tokens | Input plus 5 times output | Against setup A |
|---|---|---|---|---|
| A. Direct, all loaded | 228,000 | 20,000 | 328,000 | baseline |
| B. Tool search | 75,400 | 20,000 | 175,400 | 46.5% less |
| C. Code execution | 12,300 | 500 | 14,800 | 95.5% less |
Setup B removed most definitions, yet the 40,000 tokens of document traffic stayed, so the saving is under half. Setup C fixed both leaks. That is a result of our invented numbers, not a finding.
Step 4. How fast definitions grow
At 900 tokens per tool, against a 200,000 token window (the yardstick Cloudflare's README uses), the fixed cost is straightforward arithmetic.
| Tools | Definition tokens (N times 900) | Share of a 200,000 token window |
|---|---|---|
| 10 | 9,000 | 4.5% |
| 30 | 27,000 | 13.5% |
| 60 | 54,000 | 27% |
| 100 | 90,000 | 45% |
| 200 | 180,000 | 90% |
Step 5. When the saving disappears
Now a small job. Five tools, so 4,500 definition tokens, and one call returning an 800 token result, with the same script overhead for code execution.
- Direct. Calls read 6,500 and 7,300, so 13,800 input. Output about 200, so 13,800 plus 1,000 is 14,800.
- Code execution. 12,300 input plus 5 times 500 output is 14,800.
A tie in tokens. Add the sandbox, extra latency and code the model might get wrong, and direct calling wins. Anthropic's docs agree, saying standard calling fits under 10 tools and listing a few calls with small responses as a weak fit for programmatic calling.
Your own numbers
- Count your tools and take the real definition size from your client's token counter. Do not trust 900.
- Multiply by the model calls in a typical task. That is your definition bill per task, before caching.
- Find the largest result in your commonest workflow. Does the model need to read it, or only an answer derived from it?
- Redo the sum for a deferred or code-based setup, add the script overhead, then compare billed tokens and success rate on 20 real tasks.
When to use it, a checklist
Answer yes or no for your own agent.
- Do you have 10 or more tools, or more than 10K tokens of definitions? Those are Anthropic's tool search thresholds.
- Does tool choice or parameter accuracy get worse as you add tools?
- Do tool results exceed a few thousand tokens that the model only needs to summarise, filter or pass on?
- Does a task need three or more dependent calls, or one call across many items?
- Can you run model-written code in a sandbox with no network by default, resource limits and logging?
- Can you keep credentials out of the code the model writes?
How to read it. Yes to 1 or 2 only, use tool search or deferred loading and skip the sandbox. Yes to 3 or 4 as well, code execution should pay for itself if 5 and 6 are also yes. If either is no, fix that first.
Approve costs before an agent spends them
Oakgen is our product. Our guide to human approval for creative agents shows where to put a stop before generation runs, which matters more once an agent can write its own scripts.
What code execution costs you
Anthropic's own post says code execution "introduces its own complexity", with sandboxing, resource limits and monitoring that direct tool calls avoid, and says to weigh the benefits against those costs.
Latency can go up. AIMultiple measured 7% higher average latency. One script can still speed up a whole task by removing model round trips, so track per-call and per-task latency separately.
Model-written code can fail. AIMultiple names code quality as a limit.
Results can carry injection. Anthropic's programmatic tool calling docs warn that tool results are strings that can contain code, and tell you to validate results from external sources.
Output can still flood the context. Cloudflare's server caps each search and execute result at about 6,000 tokens. A script that prints a whole table rebuilds the original problem.
Hosted features have limits. On Anthropic's API, the programmatic tool calling page lists tools from an MCP connector among those that cannot be called programmatically. The documented route for connector servers is deferred loading on the mcp_toolset entry. The page is undated, so confirm it before you design around it.
For permissions and approvals see our MCP security checklist for creative teams. Gateways are a separate layer, covered in MCP gateways explained, and Skills use a similar load-on-demand idea in Agent Skills versus MCP.
Common mistakes
- Treating 98.7% as a promise. It is one vendor example with no published method.
- Choosing a weak baseline. Cloudflare's own table shows one server at 1,170,523 and 244,047 tokens. Compare against what you would really ship.
- Adding a sandbox for six tools. Our illustration ties at five tools and one small result.
- Fixing definitions when results are the problem. Setup B saved under half because the document traffic remained.
- Giving the sandbox network and keys. Cloudflare denies both by default.
- Printing everything. Print a count and a sample, as Anthropic's spreadsheet example does.
- Not measuring. Compare billed tokens and success rate on your own tasks.
How a creative team would apply this
Creative agents hit both leaks. A model catalogue is long, and a long brief is a large result.
Oakgen is our product. Its MCP server exposes ordinary tools such as search_models, get_model_schema, get_pricing, start_generation and get_generation_status. That shape lets an agent narrow a catalogue before loading schemas, the discovery-first idea in our MCP server guide. We have not tested Oakgen behind a code-mode layer and make no claim about one. Generation costs credits, so a script should never loop over paid calls without a cap and an approval step.
Turn an agent's plan into product creative
Oakgen is our product. Take a brief and a shot list into the AI product creative studio and generate the images and video the plan calls for.
Decision framework
- Under 10 tools, small results. Stay direct. Spend your effort on clear tool descriptions.
- 10 or more tools, small results. Defer loading or add tool search. No sandbox, and Anthropic says it keeps prompt caching intact.
- Big results or chains of dependent calls. Add code execution or programmatic tool calling, with a sandbox.
- One huge API behind your own server. Consider a search tool plus an execute tool, as Cloudflare does, and cap result size.
- Cannot sandbox. Do not run model-written code. Trim and defer tools instead.
What I would do
I would count first, cut unused tools, then defer loading, because it needs no new infrastructure. I would add a sandbox only after seeing large intermediate results or long call chains, and I would run the 20-task comparison before and after, with success rate next to tokens.
For cost context see the Claude Fable 5.2 pricing and cost per task post and agentic creative pipelines.
Start with a brief and a small, clear tool set
Oakgen is our product. Bring a creative brief to Agent Chat and see how a short list of well-described tools gets the job done before you add anything heavier.
Frequently asked questions
What is code execution with MCP?
It is a way of using MCP servers where the agent writes code that calls the server's tools, instead of the model calling each tool directly. Anthropic's engineering post of November 4, 2025 describes presenting MCP tools as a file tree of code the agent reads on demand, then running the agent's script in a sandbox. Only what the script prints goes back to the model, so unused tool definitions and bulky intermediate results stay out of the context window.
How many tokens does code execution with MCP save?
It depends on tool count and data size, and the headline figures are vendor claims. Anthropic reports 150,000 tokens down to 2,000 (98.7%) in one example workflow and does not publish how it was measured. Cloudflare reports 1,170,523 tokens down to about 1,100 for its API with 2,594 tools. An independent AIMultiple test with GPT-4.1 and 63 tools measured 78.5% fewer input tokens, 7% higher latency and 2.2 times more output tokens. Small tool sets save much less.
What is Cloudflare Code Mode and how is it different from Anthropic's approach?
Cloudflare's September 26, 2025 post turns MCP tools into a TypeScript API the model writes code against. Its February 20, 2026 post applies the idea on the server side. The server exposes search and execute tools, and the model writes JavaScript that runs in an isolated Dynamic Worker, so the full API spec never enters the context. Anthropic's post uses a client-side file tree of tool wrappers. The core idea is the same, and each company's post cites the other.
Do I need a sandbox for code execution with MCP?
Yes. Anthropic's post says running agent-generated code needs sandboxing, resource limits and monitoring, and calls that operational overhead the cost of the approach. Cloudflare runs the code in a V8 isolate with no file system, no environment variables and external fetches disabled by default. If you cannot run a sandbox, deferred tool loading or tool search cuts definition tokens without executing model-written code.
Is tool search enough, or do I need code execution as well?
Tool search fixes only the definition cost. Anthropic's tool search documentation says a five-server setup can use about 55,000 tokens of definitions and that tool search typically cuts that by over 85 percent. It does nothing for large tool results that flow through the model, or for chains of calls that each cost a model turn. If your tokens go to results, programmatic or code execution helps. If they go to definitions, start with tool search.
Can I use Anthropic's programmatic tool calling with MCP connector tools?
Not as of the Claude documentation we read on November 12, 2026. The programmatic tool calling page lists tools provided by an MCP connector as tools that cannot be called programmatically. For connector servers, the documented option is deferred loading on the mcp_toolset entry. Check the page again before you build, because the restriction may change.
Does prompt caching make MCP tool definition bloat irrelevant?
No. Caching can lower the price of re-sending the same definitions, but the definitions still occupy context window space and still compete with your task, history and tool results for attention. Anthropic reports that tool selection accuracy degrades past roughly 30 to 50 available tools, which is a window and attention problem, not only a price problem. Measure billed tokens and success rate with and without your change.
Sources
- Anthropic, Code execution with MCP: Building more efficient agents, Nov 4 2025 (read 2026-11-12)
- Anthropic, Introducing advanced tool use for Claude, Nov 24 2025 (read 2026-11-12)
- Claude Platform Docs, Programmatic tool calling (undated page, read 2026-11-12)
- Claude Platform Docs, Tool search tool (undated page, read 2026-11-12)
- Cloudflare, Code Mode: the better way to use MCP, Sep 26 2025 (read 2026-11-12)
- Cloudflare, Code Mode: give agents an entire API in 1,000 tokens, Feb 20 2026 (read 2026-11-12)
- Cloudflare, cloudflare/mcp README with token comparison table, last commit Nov 6 2026 (read 2026-11-12)
- AIMultiple, Code Execution with MCP benchmark, updated Oct 16 2026 (read 2026-11-12)

