cd /news/ai-agents/code-mode-a-smarter-way-to-use-mcp-t… Β· home β€Ί topics β€Ί ai-agents β€Ί article
[ARTICLE Β· art-182812] src=dev.to β†— pub= topic=ai-agents verified=true sentiment=↑ positive

Code Mode: A Smarter Way to Use MCP Tools and Reduce LLM Context Usage

A developer outlined an approach, based on Cloudflare's September 2025 "Code Mode" proposal, that converts MCP tools into a TypeScript API so an LLM writes code to call them instead of invoking each tool directly. The method targets two sources of token consumption in traditional tool-calling: large tool-definition catalogs and intermediate tool results that the model must process between dependent calls. The writeup argues that programmatic handling of intermediate results, such as extracting a single repository ID from a 100-record search, can cut context usage.

recommendation

When an agent connects to many MCP servers, expose their tools as a TypeScript API and let the model write code, handling intermediate results programmatically instead of returning every record to the LLM.

more in playbook: Designing agent systems
by read13 min views3 publishedDec 6, 2026

What if, instead of asking an LLM to call dozens of tools, we simply asked it to write code that uses those tools?

As AI agents become more capable, they are increasingly connected to external services through tools. GitHub, Slack, Jira, databases, browsers, and countless other integrations are becoming part of a single agent's workflow.

The Model Context Protocol (MCP) has made connecting these services significantly easier.

But there is another problem emerging: context window consumption and token cost.

Every tool definition, description, parameter schema, tool call, and returned result can consume tokens. As the number of connected tools increases, so does the amount of information an LLM must process.

Cloudflare proposed an interesting approach to this problem in its September 2025 article, Code Mode: The better way to use MCP.

The idea is surprisingly simple:

Instead of exposing MCP tools directly to an LLM, convert them into a TypeScript API and let the LLM write code to call them.

Let's understand why this works, how it is implemented, and how you can start applying the same architecture.

MCP (Model Context Protocol) provides a standardized way for AI applications to discover and interact with external tools and resources.

An MCP server exposes tools with information such as:

For example, imagine an MCP server that exposes these tools:

search_github_repositories(query)
get_repository_details(owner, repo)
list_repository_issues(owner, repo)
get_issue_details(owner, repo, issue_number)

When an agent connects to this server, its tool definitions are made available to the LLM.

When the user asks:

"Find the most popular repository related to FastAPI and summarize its open issues."

The agent might perform something like this:

LLM
 |
 |-- search_github_repositories()
 |        |
 |        v
 |    MCP Server
 |        |
 |        v
 |    Repository results
 |        |
 |        v
 |    LLM processes results
 |
 |-- get_repository_details()
 |        |
 |        v
 |    MCP Server
 |        |
 |        v
 |    Repository details
 |        |
 |        v
 |    LLM processes results
 |
 |-- list_repository_issues()
          |
          v
      MCP Server
          |
          v
      Issue results
          |
          v
      LLM generates summary

Notice what happens here.

The output of one tool call is returned to the LLM. The LLM processes that output, decides what to do next, and generates another tool call.

This is perfectly reasonable for simple workflows.

However, imagine an agent connected to 10 MCP servers, each exposing 15–20 tools.

Now the agent has to work with potentially hundreds of tool definitions.

That's where things get interesting.

There are two important sources of token consumption in traditional tool-calling workflows.

A. Tool definitions

The LLM needs information about available tools to decide which one to invoke and how to invoke it.

Each definition contains descriptions, parameters, types, and other metadata.

As the tool catalog grows, this information can occupy a significant portion of the context window.

B. Intermediate tool results

This is arguably the more interesting problem.

Consider a workflow involving five dependent tool calls.

The result of each call is returned to the LLM, which must understand it before generating the next call.

Sometimes, the LLM doesn't need to understand the entire result at all. It only needs to pass a particular ID or field into the next operation.

For example:

Search repositories
        |
        v
Get repository ID
        |
        v
Fetch repository issues
        |
        v
Filter open issues
        |
        v
Fetch details of selected issues

If the repository search returns 100 records, does the LLM really need to process all 100 records just to extract one repository ID?

Not necessarily.

The application could handle that operation programmatically.

But in a traditional tool-calling loop, intermediate results are often sent back through the model, consuming additional tokens and inference time.

This is the problem Code Mode tries to address.

Cloudflare's approach changes the interaction between the LLM and MCP tools.

Instead of exposing every MCP tool as an individual callable tool, the system:

The architecture looks like this:

              User Request
                   |
                   v
                  LLM
                   |
          Generates TypeScript
                   |
                   v
           Code Execution Tool
                   |
                   v
             Secure Sandbox
                   |
          TypeScript API bindings
                   |
          +--------+--------+
          |        |        |
          v        v        v
        GitHub    Slack    Jira
          |        |        |
          +--------+--------+
                   |
                   v
            Filter / Process
             Intermediate Data
                   |
                   v
             Final Results
                   |
                   v
                  LLM

The important difference:

The LLM writes the orchestration logic, but the actual tool-to-tool data processing happens inside the execution environment.

The LLM doesn't have to inspect every intermediate result.

This is probably the most interesting reasoning behind Cloudflare's approach.

LLMs are trained on enormous amounts of programming code.

They have seen countless examples of:

On the other hand, structured tool calling is a relatively different interaction pattern.

When an LLM invokes a tool, it typically generates a structured message that the surrounding application interprets.

Conceptually, it looks like this:

<tool_call>
{
  "name": "search_repositories",
  "arguments": {
    "query": "FastAPI"
  }
}
</tool_call>

The application executes the requested tool and returns its result:

<tool_result>
{
  "repository": "example/fastapi",
  "stars": 12000
}
</tool_result>

These markers are illustrative representations of special tokens, not literal text that every model uses.

Cloudflare's observation is that LLMs often handle complex programming APIs more naturally than large collections of individual tool definitions.

The hypothesis is that models have encountered substantially more real-world code during training than examples of structured tool calling.

Instead of making the LLM navigate a large collection of tool calls, Code Mode lets it use familiar programming constructs.

For example, rather than making the LLM repeatedly invoke tools and inspect their results:

const repositories = await searchRepositories({
  query: "FastAPI"
});

const popular = repositories
  .filter(repo => repo.stars > 1000)
  .sort((a, b) => b.stars - a.stars);

const issues = await getOpenIssues({
  owner: popular[0].owner,
  repo: popular[0].name
});

console.log(issues.slice(0, 5));

The entire orchestration can happen in one execution.

Note: This is an illustrative TypeScript example. The exact method signatures depend on the generated API.

Let's get into the implementation.

Cloudflare extended its Agents SDK to support Code Mode.

The first step is retrieving the MCP server's tool definitions and generating TypeScript interfaces and function declarations from their schemas.

For example, imagine an MCP server exposing a repository search tool.

Its generated TypeScript definition could look like this:

interface SearchRepositoriesInput {
  query: string;
  page?: number;
}

interface SearchRepositoriesOutput {
  repositories: Array<{
    name: string;
    owner: string;
    stars: number;
  }>;
}

The generated API can then expose a function:

declare const github: {
  search_repositories(
    input: SearchRepositoriesInput
  ): Promise<SearchRepositoriesOutput>;
};

Notice something important.

The LLM now has a programming interface with:

This makes the MCP tools accessible through familiar TypeScript syntax.

Cloudflare's actual example generates interfaces and declarations from MCP schemas, including documentation comments.

For instance, it demonstrates converting a documentation-search MCP server into functions such as:

declare const codemode: {
  fetch_agents_documentation(
    input: FetchAgentsDocumentationInput
  ): Promise<FetchAgentsDocumentationOutput>;

  search_agents_documentation(
    input: SearchAgentsDocumentationInput
  ): Promise<SearchAgentsDocumentationOutput>;

  search_agents_code(
    input: SearchAgentsCodeInput
  ): Promise<SearchAgentsCodeOutput>;
};

This is not a new API that the MCP server developer needs to build manually. The TypeScript interface is generated from the existing MCP tool schema.

One important implementation detail: Cloudflare notes that its current approach loads the entire generated API into the agent's context. Dynamic API discovery and browsing are described as possible future improvements.

So Code Mode doesn't magically eliminate the cost of large tool schemas. Its biggest immediate advantage is reducing unnecessary intermediate model interactions.

Cloudflare provides a codemode helper in its Agents SDK.

Consider a typical application using the AI SDK:

const stream = streamText({
  model: openai("gpt-5"),
  system: "You are a helpful assistant",

  messages: [
    {
      role: "user",
      content: "Write a function that adds two numbers"
    }
  ],

  tools: {
    // Tool definitions
  }
});

With Code Mode, you can wrap the system prompt and tools:

import { codemode } from "agents/codemode/ai";

const { system, tools } = codemode({
  system: "You are a helpful assistant",

  tools: {
    // Tool definitions
  },

  // Additional configuration
});

const stream = streamText({
  model: openai("gpt-5"),
  system,
  tools,

  messages: [
    {
      role: "user",
      content: "Write a function that adds two numbers"
    }
  ]
});

The important change is that the LLM is now instructed to generate code that invokes the available tools.

Instead of directly selecting and invoking multiple tools, it uses the code-execution interface.

This is Cloudflare's documented integration pattern, not a generic drop-in API available in every MCP framework.

This is where Cloudflare's implementation becomes particularly interesting.

Allowing an LLM to generate and execute arbitrary code introduces a serious security concern.

You cannot simply take generated TypeScript and execute it using unrestricted eval().

The code might attempt to:

Cloudflare addresses this through sandboxed execution.

Instead of running generated code directly inside the main application, it executes the code inside an isolated environment.

Cloudflare Workers are built on V8 isolates.

An isolate is an isolated JavaScript runtime powered by Google's V8 engine.

Compared with traditional containers, isolates are lightweight and can start very quickly.

Cloudflare uses these isolates to execute generated code on demand.

The execution lifecycle looks like this:

LLM generates TypeScript
          |
          v
Code sent to sandbox
          |
          v
Create isolated runtime
          |
          v
Execute generated code
          |
          v
Invoke permitted MCP APIs
          |
          v
Collect execution output
          |
          v
Return results to agent

The sandbox is disposable, so the execution environment doesn't need to remain alive after the task finishes.

Cloudflare introduced the Dynamic Worker API to support Worker code dynamically.

A simplified example from the article:

let worker = env..get(id, async () => {
  return {
    compatibilityDate: "2025-06-01",

    mainModule: "foo.js",

    modules: {
      "foo.js": `
        export default {
          fetch(req, env, ctx) {
            return new Response("Hello");
          }
        }
      `
    },

    env: {
      SOME_NUMBER: 123
    },

    globalOutbound: null
  };
});

let entrypoint = worker.getEntrypoint();

await entrypoint.fetch("http://example.com");

This example illustrates dynamically code into a Worker.

The exact configuration and runtime bindings depend on the application.

The important concept is that generated code can execute in an isolated runtime without deploying a new Worker globally for every execution.

This is one of the strongest parts of the architecture.

If the sandbox is isolated from the Internet, how can it communicate with GitHub, Slack, or Jira?

Cloudflare uses something called bindings.

Instead of giving generated code unrestricted network access and API keys, the sandbox receives specific authorized interfaces to the connected MCP servers.

Conceptually:

const github = {
  searchRepositories: async (query: string) => {
    // RPC call to the agent supervisor
  }
};

The generated code can call the provided interface, but it doesn't need to know the underlying authentication credentials.

       Generated Code
              |
              v
        Secure Sandbox
              |
              v
        GitHub Binding
              |
              v
       Agent Supervisor
              |
        Adds credentials
              |
              v
         GitHub MCP

This provides several advantages:

This is an important distinction: sandboxing generated code is not optional just because the LLM is capable of writing code.

The execution environment must enforce permissions independently of the model.

Code Mode is not necessarily better for every agent.

It makes the most sense when the complexity of the workflow justifies the additional execution layer.

Scenario Better approach
3–5 simple, independent tools Direct tool calling
Large MCP tool catalogs Code Mode
Multiple dependent tool calls Code Mode
Filtering thousands of returned records Code Mode
Complex loops and branching Code Mode
Simple single-step actions Direct tool calling

Direct tool calling

"Check the weather in Lucknow."

There is little reason to introduce a code-execution layer for one straightforward operation.

Code Mode

"Search GitHub for the 20 most popular FastAPI repositories, inspect their open issues, identify issues labelled good first issue, and return the five most recently updated ones."

This involves multiple calls, filtering, sorting, and data transformation.

Code Mode allows the LLM to write the orchestration once and let the sandbox handle the intermediate operations.

You don't necessarily need to build your own version of Cloudflare Workers to understand or experiment with Code Mode.

You can start by implementing the underlying pattern with an existing MCP client.

Here is a practical implementation roadmap.

Step 1: Connect to MCP servers

Use an MCP client to connect to the services your agent needs.

Discover their available tools and schemas.

Step 2: Generate TypeScript declarations

Convert the MCP tool definitions into TypeScript interfaces.

For every tool, generate:

You can use the schemas already provided by MCP instead of manually rewriting every tool definition.

Step 3: Build a restricted execution interface

Instead of exposing every tool directly to the LLM, expose a single code-execution tool.

Its input can be as simple as:

interface ExecuteCodeInput {
  code: string;
}

The generated code should have access only to the permitted TypeScript APIs.

Step 4: Execute generated code safely

Use an appropriate sandbox rather than unrestricted JavaScript execution.

Your execution layer should enforce:

Step 5: Return only useful results

This is where much of the potential token savings come from.

Suppose a tool returns 500 records, but the user only needs five.

Instead of returning all 500 records to the LLM, let the generated code filter, sort, and select the relevant records.

Return only those five.

Step 6: Measure the difference

Don't assume Code Mode is automatically cheaper.

Compare both approaches using the same tasks.

Track:

This will tell you whether Code Mode actually improves your agent's efficiency.

No. And this is an important distinction.

If we already have traditional APIs, why not expose those APIs directly to the LLM?

Because MCP solves a different problem.

It provides a standardized way for an agent to discover tools, understand their interfaces, connect to servers, and handle authorization.

An agent developer doesn't need to build custom integration logic for every service.

For example, GitHub, Jira, and Slack can expose their capabilities through MCP, even if their developers have never coordinated with the developer building the agent.

Code Mode preserves that interoperability.

The difference is in how the agent consumes the tools.

Think of it this way:

MCP handles the connectivity. Code Mode handles the orchestration.

They complement each other rather than compete.

One of the most interesting things about Code Mode is that it challenges how we think about agent-tool interaction.

We have spent a lot of time making tools easier for LLMs to call individually.

But perhaps, for sufficiently complex workflows, we should stop making the LLM manage every individual call.

Instead, let it write a program that handles the workflow.

The potential benefits are significant:

There is one caveat worth remembering: Code Mode doesn't eliminate token consumption. Generated code, API definitions, and final results still consume context. Its biggest advantage comes from keeping intermediate computation outside the model.

The real optimization isn't simply reducing the number of tools. It's reducing how much work the LLM needs to do inside its context window.

That is what makes this approach worth exploring when building production-grade AI agents.

If you want to explore the actual implementation, these are the resources I'd recommend:

Originally inspired by Cloudflare's Code Mode architecture. The examples in this article are simplified for learning; consult the official documentation for production implementation details.

── more in #ai-agents 4 stories Β· sorted by recency
── more on @cloudflare 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain β€” perfect for shipping the agent you just read about.

$git push zahid main
β†’ Live at https://your-agent.zahid.host βœ“
Get free account β†’ Pricing
from €0/mo Β· no card required
LIVE [news/code-mode-a-smarter-…] indexed:0 read:13min 2026-12-06 Β· β€”