Introducing Code Mode

Introduction to Code Mode

Model Context Protocol (MCP) has become the standard way for AI agents to use external tools. However, there is a tension at its core: agents need many tools to do useful work, yet every tool added fills the model’s context window, leaving less room for the actual task.

What is Code Mode?

Code Mode is a technique we first introduced for reducing context window usage during agent tool use. Instead of describing every operation as a separate tool, let the model write code against a typed SDK and execute the code safely in a Dynamic Worker Loader.

Benefits of Code Mode

The code acts as a compact plan. The model can explore tool operations, compose multiple calls, and return just the data it needs.

Introducing a new MCP server for Cloudflare API

Today we are introducing a new MCP server for the entire Cloudflare API — from DNS and Zero Trust to Workers and R2 — that uses Code Mode. With just two tools, search() and execute(), the server is able to provide access to the entire Cloudflare API over MCP, while consuming only around 1,000 tokens.

Example: Protecting an origin from DDoS attacks

Suppose a user tells their agent: “protect my origin from DDoS attacks.” The agent’s first step is to consult documentation. It might call the Cloudflare Docs MCP Server, use a Cloudflare Skill, or search the web directly.

How Code Mode works

The search tool gives the model a spec object: the full Cloudflare OpenAPI spec with all $refs pre-resolved. The model writes JavaScript against it.

Step 1: Search for the right endpoints

The model can filter endpoints by product, path, tags, or any other metadata and narrow thousands of endpoints to the handful it needs.

Conclusion

Code Mode reduces the number of input tokens used by 99.9%. An equivalent MCP server without Code Mode would consume 1.17 million tokens — more than the entire context window of the most advanced foundation models.

Call to Action

You can start using this new Cloudflare MCP server today. And we are also open-sourcing a new Code Mode SDK in the Cloudflare Agents SDK, so you can use the same approach in your own MCP servers and AI Agents.

Frequently Asked Questions

  1. What is Code Mode?
  2. How does Code Mode reduce context window usage?
  3. What are the benefits of using Code Mode?
  4. Can I use Code Mode with other APIs?
  5. How do I get started with Code Mode?