Skip to content
MikeDaDev

Code execution with MCP: from 150,000 to 2,000 tokens by letting the agent write code

Tung Bui Thanh (MikeDaDev)7 min read

Cable network
On this page

You plug ten MCP servers into your agent: Google Drive, Slack, Salesforce, Jira, GitHub, a database... Each one exposes a few dozen tools. Before you type your first question, the context is full of tool definitions. Then you ask it to "take the meeting notes from Drive and attach them to the customer record in Salesforce": the full transcript enters the context once when it is read, and passes through again when the model copies it into the next tool call.

A post on X from @0xwhrrari this week summarised the fix as "the six parts of code mode", with an eye-catching number: from about 150,000 tokens down to 2,000, a 98.7% saving. The source is Anthropic's engineering article Code execution with MCP by Adam Jones and Conor Kelly (4 November 2025). This post covers the idea, what that number measures, and the price that rarely gets mentioned.

# two places where tokens burn

Anthropic's article identifies two separate problems.

First, tool definitions take up room. The common way to use MCP is to load every tool definition into the context up front so the model can choose. For agents connected to thousands of tools, Anthropic writes that they have to process hundreds of thousands of tokens before reading a request.

Second, intermediate results flow through the model. When a tool returns a lot of data and that data has to go into another tool, the model has to read it and then write it out again. Anthropic's example is the transcript of a two-hour meeting: about 50,000 extra tokens just to hand it over, not counting the risk of the model miscopying a long document.

# the idea: turn tools into code and let the agent write programs

Instead of calling tools directly, the agent gets a code execution environment, and each MCP server shows up as a library. Anthropic's example is a directory tree:

servers/
  google-drive/
    getDocument.ts
    index.ts
  salesforce/
    updateRecord.ts
    index.ts

Each file wraps one tool and calls callMCPTool(...) inside. The agent writes a short TypeScript program: import the two servers, read the transcript, write it to Salesforce. The transcript goes straight from one tool to the other inside the execution environment, and the model never needs to see it.

# the six parts of "code mode"

The X post splits the idea into six parts that map to sections of the original:

  1. Each tool is a file in ./servers. The agent lists the directory and opens only the files it needs, the way a developer explores an unfamiliar codebase.
  2. Load definitions on demand. This is where the 150,000 to 2,000 figure comes from. Anthropic calls it progressive disclosure, and suggests a search_tools tool that lets the agent choose the level of detail: name only, name and description, or the full definition.
  3. Filter data in code. A 10,000-row sheet is filtered in the sandbox, and the model sees only the 5 rows it needs.
  4. Loops in code. Waiting for "deployment complete" in Slack is a while loop with setTimeout, not dozens of model turns calling a tool and sleeping.
  5. Privacy. Emails and phone numbers are replaced with tokens like [EMAIL_1] and [PHONE_1] before the model sees them, and swapped back for the real values on the way into Salesforce.
  6. Skills. Working code is saved to ./skills; add a SKILL.md and it becomes a structured skill. Over time the agent builds its own toolbox.

# what the 98.7% measures

The sentence in the original: this "reduces the token usage from 150,000 tokens to 2,000 tokens, a time and cost saving of 98.7%". Two things to know before you quote it:

  • It is one example, specifically the cost of loading tool definitions, not an average saving across all tasks. The original does not describe the setup behind it, and I have not seen independent verification.
  • The saving depends on how many tools you have. An agent with three tools gains almost nothing from this part; an agent with dozens of servers gains a lot.

The data-filtering part, on the other hand, is easy to check yourself. The snippet below simulates a 10,000-row sheet and compares how much data the model has to read either way. I estimate tokens roughly at about 4 characters per token.

// What the model would see: the whole sheet vs. only what the code keeps.
const rows = Array.from({ length: 10_000 }, (_, i) => ({
  id: i + 1,
  customer: `Customer ${i + 1}`,
  email: `customer${i + 1}@example.com`,
  status: i % 2000 === 0 ? 'pending' : 'shipped',
  total: Math.round((i * 37) % 900) + 100,
}))
 
const pending = rows.filter((r) => r.status === 'pending')
 
const tokens = (value) => Math.ceil(JSON.stringify(value).length / 4) // rough: ~4 chars per token
console.log(`rows in sheet:          ${rows.length}`)
console.log(`tokens if model reads:  ~${tokens(rows).toLocaleString()}`)
console.log(`rows after filter:      ${pending.length}`)
console.log(`tokens model sees now:  ~${tokens(pending.slice(0, 5)).toLocaleString()}`)
rows in sheet:          10000
tokens if model reads:  ~261,671
rows after filter:      5
tokens model sees now:  ~130

That is three orders of magnitude, and it does not even count the fact that a model reading 260,000 tokens is not only expensive but also more likely to miss the row you were looking for.

# the price: you are letting the model run code

The X post skims this part; the original is explicit: running agent-generated code requires a secure execution environment with sandboxing, resource limits and monitoring. That brings operational overhead and security concerns that direct tool calls do not have. Anthropic concludes that the benefits should be weighed against these implementation costs.

More concretely, these are the things you take on when you switch to code mode:

  • A properly isolated sandbox: a container or microVM, no sensitive directories mounted, and limits on CPU, memory and run time.
  • Egress control: code in the sandbox can now call anything. Use an allowlist, or a prompt injection from an email or a web page can get the agent to write code that sends data out.
  • Credentials: tool calls go through the MCP client; do not leave API tokens in environment variables that the agent's code can read.
  • The limits of masking: tokenising PII keeps the data away from the model, but code running in the sandbox still touches the real data. The risk moves, it does not disappear.

If you run an agent on your own machine with a handful of MCP servers, calling tools directly is still simple and good enough. Code mode pays off when you have many tools, a lot of data flowing through them and sandbox infrastructure already in place, which is exactly the situation of enterprise agent platforms. Cloudflare has gone in a similar direction with a feature it calls "Code Mode".

# the common thread with the last two posts

Put next to this week's other two posts, a common pattern is hard to miss:

  • Your second brain is a compiler: do not make the model rediscover knowledge on every question, compile it once.
  • Lessons from Spotify's Claude Code setup: do not pay frontier prices for reading files, route that work elsewhere and enforce it with a hook.
  • This post: do not push every tool definition and every intermediate result through the context, let code handle it.

All three say the same thing: context is an agent's most expensive resource, and most efficiency gains today come from deciding what goes into the context, not from switching to a stronger model.

References:


Just personal notes, shared in the hope they are useful. If you found this helpful, feel free to pass it on to your friends and colleagues!

Happy coding 😎 πŸ‘πŸ» πŸš€ πŸ”₯.