{"slug": "code-mode-a-smarter-way-to-use-mcp-tools-and-reduce-llm-context-usage", "title": "Code Mode: A Smarter Way to Use MCP Tools and Reduce LLM Context Usage", "summary": "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.", "body_md": "**What if, instead of asking an LLM to call dozens of tools, we simply asked it to write code that uses those tools?**\n\nAs 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.\n\nThe Model Context Protocol (MCP) has made connecting these services significantly easier.\n\nBut there is another problem emerging: **context window consumption and token cost.**\n\nEvery 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.\n\nCloudflare proposed an interesting approach to this problem in its September 2025 article, *Code Mode: The better way to use MCP*.\n\nThe idea is surprisingly simple:\n\n**Instead of exposing MCP tools directly to an LLM, convert them into a TypeScript API and let the LLM write code to call them.**\n\nLet's understand why this works, how it is implemented, and how you can start applying the same architecture.\n\nMCP (Model Context Protocol) provides a standardized way for AI applications to discover and interact with external tools and resources.\n\nAn MCP server exposes tools with information such as:\n\nFor example, imagine an MCP server that exposes these tools:\n\n```\nsearch_github_repositories(query)\nget_repository_details(owner, repo)\nlist_repository_issues(owner, repo)\nget_issue_details(owner, repo, issue_number)\n```\n\nWhen an agent connects to this server, its tool definitions are made available to the LLM.\n\nWhen the user asks:\n\n\"Find the most popular repository related to FastAPI and summarize its open issues.\"\n\nThe agent might perform something like this:\n\n```\nLLM\n |\n |-- search_github_repositories()\n |        |\n |        v\n |    MCP Server\n |        |\n |        v\n |    Repository results\n |        |\n |        v\n |    LLM processes results\n |\n |-- get_repository_details()\n |        |\n |        v\n |    MCP Server\n |        |\n |        v\n |    Repository details\n |        |\n |        v\n |    LLM processes results\n |\n |-- list_repository_issues()\n          |\n          v\n      MCP Server\n          |\n          v\n      Issue results\n          |\n          v\n      LLM generates summary\n```\n\nNotice what happens here.\n\nThe 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.\n\nThis is perfectly reasonable for simple workflows.\n\nHowever, imagine an agent connected to 10 MCP servers, each exposing 15–20 tools.\n\nNow the agent has to work with potentially hundreds of tool definitions.\n\nThat's where things get interesting.\n\nThere are two important sources of token consumption in traditional tool-calling workflows.\n\n**A. Tool definitions**\n\nThe LLM needs information about available tools to decide which one to invoke and how to invoke it.\n\nEach definition contains descriptions, parameters, types, and other metadata.\n\nAs the tool catalog grows, this information can occupy a significant portion of the context window.\n\n**B. Intermediate tool results**\n\nThis is arguably the more interesting problem.\n\nConsider a workflow involving five dependent tool calls.\n\nThe result of each call is returned to the LLM, which must understand it before generating the next call.\n\nSometimes, 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.\n\nFor example:\n\n```\nSearch repositories\n        |\n        v\nGet repository ID\n        |\n        v\nFetch repository issues\n        |\n        v\nFilter open issues\n        |\n        v\nFetch details of selected issues\n```\n\nIf the repository search returns 100 records, does the LLM really need to process all 100 records just to extract one repository ID?\n\nNot necessarily.\n\nThe application could handle that operation programmatically.\n\nBut in a traditional tool-calling loop, intermediate results are often sent back through the model, consuming additional tokens and inference time.\n\nThis is the problem Code Mode tries to address.\n\nCloudflare's approach changes the interaction between the LLM and MCP tools.\n\nInstead of exposing every MCP tool as an individual callable tool, the system:\n\nThe architecture looks like this:\n\n```\n              User Request\n                   |\n                   v\n                  LLM\n                   |\n          Generates TypeScript\n                   |\n                   v\n           Code Execution Tool\n                   |\n                   v\n             Secure Sandbox\n                   |\n          TypeScript API bindings\n                   |\n          +--------+--------+\n          |        |        |\n          v        v        v\n        GitHub    Slack    Jira\n          |        |        |\n          +--------+--------+\n                   |\n                   v\n            Filter / Process\n             Intermediate Data\n                   |\n                   v\n             Final Results\n                   |\n                   v\n                  LLM\n```\n\nThe important difference:\n\n**The LLM writes the orchestration logic, but the actual tool-to-tool data processing happens inside the execution environment.**\n\nThe LLM doesn't have to inspect every intermediate result.\n\nThis is probably the most interesting reasoning behind Cloudflare's approach.\n\nLLMs are trained on enormous amounts of programming code.\n\nThey have seen countless examples of:\n\nOn the other hand, structured tool calling is a relatively different interaction pattern.\n\nWhen an LLM invokes a tool, it typically generates a structured message that the surrounding application interprets.\n\nConceptually, it looks like this:\n\n```\n<tool_call>\n{\n  \"name\": \"search_repositories\",\n  \"arguments\": {\n    \"query\": \"FastAPI\"\n  }\n}\n</tool_call>\n```\n\nThe application executes the requested tool and returns its result:\n\n```\n<tool_result>\n{\n  \"repository\": \"example/fastapi\",\n  \"stars\": 12000\n}\n</tool_result>\n```\n\nThese markers are illustrative representations of special tokens, not literal text that every model uses.\n\nCloudflare's observation is that LLMs often handle complex programming APIs more naturally than large collections of individual tool definitions.\n\nThe hypothesis is that models have encountered substantially more real-world code during training than examples of structured tool calling.\n\nInstead of making the LLM navigate a large collection of tool calls, Code Mode lets it use familiar programming constructs.\n\nFor example, rather than making the LLM repeatedly invoke tools and inspect their results:\n\n``` js\nconst repositories = await searchRepositories({\n  query: \"FastAPI\"\n});\n\nconst popular = repositories\n  .filter(repo => repo.stars > 1000)\n  .sort((a, b) => b.stars - a.stars);\n\nconst issues = await getOpenIssues({\n  owner: popular[0].owner,\n  repo: popular[0].name\n});\n\nconsole.log(issues.slice(0, 5));\n```\n\nThe entire orchestration can happen in one execution.\n\n*Note: This is an illustrative TypeScript example. The exact method signatures depend on the generated API.*\n\nLet's get into the implementation.\n\nCloudflare extended its Agents SDK to support Code Mode.\n\nThe first step is retrieving the MCP server's tool definitions and generating TypeScript interfaces and function declarations from their schemas.\n\nFor example, imagine an MCP server exposing a repository search tool.\n\nIts generated TypeScript definition could look like this:\n\n```\ninterface SearchRepositoriesInput {\n  query: string;\n  page?: number;\n}\n\ninterface SearchRepositoriesOutput {\n  repositories: Array<{\n    name: string;\n    owner: string;\n    stars: number;\n  }>;\n}\n```\n\nThe generated API can then expose a function:\n\n``` js\ndeclare const github: {\n  search_repositories(\n    input: SearchRepositoriesInput\n  ): Promise<SearchRepositoriesOutput>;\n};\n```\n\nNotice something important.\n\nThe LLM now has a programming interface with:\n\nThis makes the MCP tools accessible through familiar TypeScript syntax.\n\nCloudflare's actual example generates interfaces and declarations from MCP schemas, including documentation comments.\n\nFor instance, it demonstrates converting a documentation-search MCP server into functions such as:\n\n``` js\ndeclare const codemode: {\n  fetch_agents_documentation(\n    input: FetchAgentsDocumentationInput\n  ): Promise<FetchAgentsDocumentationOutput>;\n\n  search_agents_documentation(\n    input: SearchAgentsDocumentationInput\n  ): Promise<SearchAgentsDocumentationOutput>;\n\n  search_agents_code(\n    input: SearchAgentsCodeInput\n  ): Promise<SearchAgentsCodeOutput>;\n};\n```\n\nThis 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.\n\nOne 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.\n\nSo Code Mode doesn't magically eliminate the cost of large tool schemas. Its biggest immediate advantage is reducing unnecessary intermediate model interactions.\n\nCloudflare provides a `codemode` helper in its Agents SDK.\n\nConsider a typical application using the AI SDK:\n\n``` js\nconst stream = streamText({\n  model: openai(\"gpt-5\"),\n  system: \"You are a helpful assistant\",\n\n  messages: [\n    {\n      role: \"user\",\n      content: \"Write a function that adds two numbers\"\n    }\n  ],\n\n  tools: {\n    // Tool definitions\n  }\n});\n```\n\nWith Code Mode, you can wrap the system prompt and tools:\n\n``` js\nimport { codemode } from \"agents/codemode/ai\";\n\nconst { system, tools } = codemode({\n  system: \"You are a helpful assistant\",\n\n  tools: {\n    // Tool definitions\n  },\n\n  // Additional configuration\n});\n\nconst stream = streamText({\n  model: openai(\"gpt-5\"),\n  system,\n  tools,\n\n  messages: [\n    {\n      role: \"user\",\n      content: \"Write a function that adds two numbers\"\n    }\n  ]\n});\n```\n\nThe important change is that the LLM is now instructed to generate code that invokes the available tools.\n\nInstead of directly selecting and invoking multiple tools, it uses the code-execution interface.\n\nThis is Cloudflare's documented integration pattern, not a generic drop-in API available in every MCP framework.\n\nThis is where Cloudflare's implementation becomes particularly interesting.\n\nAllowing an LLM to generate and execute arbitrary code introduces a serious security concern.\n\nYou cannot simply take generated TypeScript and execute it using unrestricted `eval()`.\n\nThe code might attempt to:\n\nCloudflare addresses this through sandboxed execution.\n\nInstead of running generated code directly inside the main application, it executes the code inside an isolated environment.\n\nCloudflare Workers are built on V8 isolates.\n\nAn isolate is an isolated JavaScript runtime powered by Google's V8 engine.\n\nCompared with traditional containers, isolates are lightweight and can start very quickly.\n\nCloudflare uses these isolates to execute generated code on demand.\n\nThe execution lifecycle looks like this:\n\n```\nLLM generates TypeScript\n          |\n          v\nCode sent to sandbox\n          |\n          v\nCreate isolated runtime\n          |\n          v\nExecute generated code\n          |\n          v\nInvoke permitted MCP APIs\n          |\n          v\nCollect execution output\n          |\n          v\nReturn results to agent\n```\n\nThe sandbox is disposable, so the execution environment doesn't need to remain alive after the task finishes.\n\nCloudflare introduced the Dynamic Worker Loader API to support loading Worker code dynamically.\n\nA simplified example from the article:\n\n``` js\nlet worker = env.LOADER.get(id, async () => {\n  return {\n    compatibilityDate: \"2025-06-01\",\n\n    mainModule: \"foo.js\",\n\n    modules: {\n      \"foo.js\": `\n        export default {\n          fetch(req, env, ctx) {\n            return new Response(\"Hello\");\n          }\n        }\n      `\n    },\n\n    env: {\n      SOME_NUMBER: 123\n    },\n\n    globalOutbound: null\n  };\n});\n\nlet entrypoint = worker.getEntrypoint();\n\nawait entrypoint.fetch(\"http://example.com\");\n```\n\nThis example illustrates dynamically loading code into a Worker.\n\nThe exact configuration and runtime bindings depend on the application.\n\nThe important concept is that generated code can execute in an isolated runtime without deploying a new Worker globally for every execution.\n\nThis is one of the strongest parts of the architecture.\n\nIf the sandbox is isolated from the Internet, how can it communicate with GitHub, Slack, or Jira?\n\nCloudflare uses something called **bindings**.\n\nInstead of giving generated code unrestricted network access and API keys, the sandbox receives specific authorized interfaces to the connected MCP servers.\n\nConceptually:\n\n``` js\nconst github = {\n  searchRepositories: async (query: string) => {\n    // RPC call to the agent supervisor\n  }\n};\n```\n\nThe generated code can call the provided interface, but it doesn't need to know the underlying authentication credentials.\n\n```\n       Generated Code\n              |\n              v\n        Secure Sandbox\n              |\n              v\n        GitHub Binding\n              |\n              v\n       Agent Supervisor\n              |\n        Adds credentials\n              |\n              v\n         GitHub MCP\n```\n\nThis provides several advantages:\n\nThis is an important distinction: sandboxing generated code is not optional just because the LLM is capable of writing code.\n\nThe execution environment must enforce permissions independently of the model.\n\nCode Mode is not necessarily better for every agent.\n\nIt makes the most sense when the complexity of the workflow justifies the additional execution layer.\n\n| Scenario | Better approach | \n|---|---|\n| 3–5 simple, independent tools | Direct tool calling | \n| Large MCP tool catalogs | Code Mode | \n| Multiple dependent tool calls | Code Mode | \n| Filtering thousands of returned records | Code Mode | \n| Complex loops and branching | Code Mode | \n| Simple single-step actions | Direct tool calling | \n\n**Direct tool calling**\n\n\"Check the weather in Lucknow.\"\n\nThere is little reason to introduce a code-execution layer for one straightforward operation.\n\n**Code Mode**\n\n\"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.\"\n\nThis involves multiple calls, filtering, sorting, and data transformation.\n\nCode Mode allows the LLM to write the orchestration once and let the sandbox handle the intermediate operations.\n\nYou don't necessarily need to build your own version of Cloudflare Workers to understand or experiment with Code Mode.\n\nYou can start by implementing the underlying pattern with an existing MCP client.\n\nHere is a practical implementation roadmap.\n\n**Step 1: Connect to MCP servers**\n\nUse an MCP client to connect to the services your agent needs.\n\nDiscover their available tools and schemas.\n\n**Step 2: Generate TypeScript declarations**\n\nConvert the MCP tool definitions into TypeScript interfaces.\n\nFor every tool, generate:\n\nYou can use the schemas already provided by MCP instead of manually rewriting every tool definition.\n\n**Step 3: Build a restricted execution interface**\n\nInstead of exposing every tool directly to the LLM, expose a single code-execution tool.\n\nIts input can be as simple as:\n\n```\ninterface ExecuteCodeInput {\n  code: string;\n}\n```\n\nThe generated code should have access only to the permitted TypeScript APIs.\n\n**Step 4: Execute generated code safely**\n\nUse an appropriate sandbox rather than unrestricted JavaScript execution.\n\nYour execution layer should enforce:\n\n**Step 5: Return only useful results**\n\nThis is where much of the potential token savings come from.\n\nSuppose a tool returns 500 records, but the user only needs five.\n\nInstead of returning all 500 records to the LLM, let the generated code filter, sort, and select the relevant records.\n\nReturn only those five.\n\n**Step 6: Measure the difference**\n\nDon't assume Code Mode is automatically cheaper.\n\nCompare both approaches using the same tasks.\n\nTrack:\n\nThis will tell you whether Code Mode actually improves your agent's efficiency.\n\nNo. And this is an important distinction.\n\nIf we already have traditional APIs, why not expose those APIs directly to the LLM?\n\nBecause MCP solves a different problem.\n\nIt provides a standardized way for an agent to discover tools, understand their interfaces, connect to servers, and handle authorization.\n\nAn agent developer doesn't need to build custom integration logic for every service.\n\nFor example, GitHub, Jira, and Slack can expose their capabilities through MCP, even if their developers have never coordinated with the developer building the agent.\n\nCode Mode preserves that interoperability.\n\nThe difference is in how the agent consumes the tools.\n\nThink of it this way:\n\n**MCP handles the connectivity. Code Mode handles the orchestration.**\n\nThey complement each other rather than compete.\n\nOne of the most interesting things about Code Mode is that it challenges how we think about agent-tool interaction.\n\nWe have spent a lot of time making tools easier for LLMs to call individually.\n\nBut perhaps, for sufficiently complex workflows, we should stop making the LLM manage every individual call.\n\nInstead, let it write a program that handles the workflow.\n\nThe potential benefits are significant:\n\nThere 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.\n\n**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.**\n\nThat is what makes this approach worth exploring when building production-grade AI agents.\n\nIf you want to explore the actual implementation, these are the resources I'd recommend:\n\n*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.*", "url": "https://wpnews.pro/news/code-mode-a-smarter-way-to-use-mcp-tools-and-reduce-llm-context-usage", "canonical_source": "https://dev.to/aanshojha/code-mode-a-smarter-way-to-use-mcp-tools-and-reduce-llm-context-usage-egh", "published_at": "2026-12-06 09:34:58+00:00", "updated_at": "2026-12-06 09:45:25.660439+00:00", "lang": "en", "topics": ["ai-agents", "agent-protocols", "ai-tools", "large-language-models", "developer-tools"], "entities": ["Cloudflare", "Model Context Protocol", "GitHub", "Slack", "Jira", "TypeScript", "FastAPI"], "also_reported_by": [], "takeaway": "Converting MCP tools into a TypeScript API and letting the LLM write code to call them avoids loading hundreds of tool definitions and intermediate results into context, since the app can programmatically extract fields like a repository ID instead of having the model process all 100 search records.", "recommendation": {"advice": "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.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/code-mode-a-smarter-way-to-use-mcp-tools-and-reduce-llm-context-usage", "markdown": "https://wpnews.pro/news/code-mode-a-smarter-way-to-use-mcp-tools-and-reduce-llm-context-usage.md", "text": "https://wpnews.pro/news/code-mode-a-smarter-way-to-use-mcp-tools-and-reduce-llm-context-usage.txt", "jsonld": "https://wpnews.pro/news/code-mode-a-smarter-way-to-use-mcp-tools-and-reduce-llm-context-usage.jsonld"}}