# What If Your AI Agent Wrote the Loop?

If you ask an agent which customers were affected by late orders last week and which account managers need to follow up. It can fetch the orders, work out which ones were late, look up the customers, then group the results by account manager. With direct tool calling, the model may have to see the order pages and customer records just to decide which call to make next. Most of that data never belongs in the answer. What if the model wrote the loop once, ran it next to the data, and got back a summary? Thats the idea behind Code Mode. The model generates a short program for the task at hand. The runtime executes it against a limited set of APIs, and the program returns the result. The model still decides what work to do. Pagination, filtering and joins can happen in ordinary code.

## The problem Cloudflare ran into

Cloudflare's API is big enough to make the cost of exposing every operation as a model facing tool obvious. Each tool has a name, a description and a parameter schema. If the client loads all of those definitions up front, the model spends context on thousands of operations it may never use. In February 2026, Cloudflare reported that an equivalent MCP server exposing its full API as individual tools would take 1.17 million input tokens for the tool definitions. Its Code Mode implementation exposes the same API through two tools whose definitions take roughly 1,000 tokens, a reduction of about 99.9% in that comparison. Those figures describe the upfront tool definitions. Discovery results, generated code and execution results still use tokens. They had already experimented with wrapping MCP tools as a typed TypeScript API and having the model write code against it. The appeal was that models can express loops, conditionals and sequences of API calls directly in code. The later server-side design also made discovery selective. The model could ask for the operations relevant to the task and leave the rest of the API specification outside its context.

## What Cloudflare changed

Cloudflare's MCP server exposes two tools. `search()` runs model generated JavaScript against a representation of the OpenAPI specification. The script can filter by path, product or other metadata and return just the relevant operations. `execute()` runs a script that calls the Cloudflare API, handles pagination and composes operations. Both run inside Dynamic Worker isolates, with no filesystem or environment variables and external fetches disabled by default. There are two savings here. The model gets a smaller catalogue up front, and intermediate data can stay in the execution environment. Anthropic illustrated the second point with a Google Drive transcript being passed to Salesforce. Code could move the transcript between those systems without routing its full text through the model.

## What this could look like in a .NET system

Take the late orders example. Say an internal .NET application already exposes read APIs for fulfilment and customer accounts. A restricted execution environment could give generated code a typed client over those APIs. The discovery step would surface just the two relevant methods and their types. Here's illustrative C# for the code the agent could generate. The fulfilment API supplies the late orders for a resolved reporting window, and the accounts API resolves the current owners in a batch.

```csharp
var lateOrders = new List<OrderSummary>();

await foreach (var page in orders.ReadLateOrderPagesAsync(window, ct))
{
    lateOrders.AddRange(page.Items);
}

var customerIds = lateOrders.Select(order => order.CustomerId).Distinct().ToArray();
var ownersByCustomer = await accounts.GetOwnersAsync(customerIds, ct);

return lateOrders
    .GroupBy(order => ownersByCustomer.GetValueOrDefault(order.CustomerId))
    .OrderByDescending(group => group.Count())
    .Select(group => new
    {
        OwnerId = group.Key,
        LateOrderCount = group.Count(),
        AffectedCustomers = group.Select(order => order.CustomerId).Distinct().Count()
    })
    .ToArray();
```

The model receives counts by owner. A null owner marks orders whose customers need an ownership check. The fulfilment service still defines what counts as late, and the reporting window comes from the application’s date and time zone handling. The generated code handles the task specific composition. This example uses C# because the contracts should look familiar to .NET developers. A .NET host can expose the same APIs to an isolated JavaScript runner. For generated C#, compilation and execution need an isolation boundary outside the application process. The host should enforce caller permissions when the script uses a capability and bound its runtime, API calls and output size.

One script can still make several backend requests. The saving comes from keeping those requests out of the model’s tool-call loop. If the agent needs a detail it didn’t include in the script’s output, it may need another execution. For reports that people run every day with the same rules, a dedicated endpoint can do the whole job with a stable contract and predictable execution.

## Where code could actually replace MCP

Cloudflare replaced the flat, model facing tool catalogue while retaining MCP as the interface clients connect to. That's a useful design when you want different agent hosts to use the same integration. A client can discover a small set of standard tools while the server takes care of running the generated code. An internal agent has a different choice. If you own the agent host, runner and .NET APIs, the host can give the runner a typed SDK directly. The execution call then belongs to the agent’s own runtime, and there’s no MCP hop in that path. The team takes responsibility for discovery, compatibility and permission enforcement. That can be a reasonable trade when there’s one host and a defined set of internal systems.

Direct tool calls still make sense for discrete actions. If a user asks to look up one order, a single typed tool is straightforward. If an agent needs to sift through hundreds of orders across services, a short read only script can do the work without sending every record to the model. If the next step is to send account managers an email, expose that as an explicit operation so the application can enforce approval rules and handle retries without sending duplicates. My bet is that agents with large tool catalogues will increasingly use code to do the composition. Some will get there through MCP and others through their own SDKs. The part Id expect to disappear first is the model call that exists purely to ask for page two.

[Anthropic's code execution with MCP write-up](https://www.anthropic.com/research/code-execution-with-mcp)

[Cloudflare's server-side design](https://blog.cloudflare.com/code-mode-mcp/)

[Cloudflare's original Code Mode experiment](https://blog.cloudflare.com/code-mode/)

[Cloudflares February 2026 write-up](https://blog.cloudflare.com/code-mode-mcp/).
