Architecture
MCP has an N+1 problem
Updated
In this post
Moving 12 to-dos to another project used to take an assistant 13 tool calls in Milieu: one to read the project, then one for each to-do. It’s the N+1 query problem again, but with a language model writing every query.
Each call means generating arguments, crossing the network and reading an answer. Suppose the calls run one after another, taking a second each to write and a third of a second for each round trip. Moving those 12 to-dos takes about 17 seconds.
The model also reads far more than the job requires. Our old project tool returned a whole project when the model only needed the to-do IDs. Those records enter the model’s context window, followed by 12 calls that copy the IDs back to us and 12 answers confirming the moves.
And each move is saved separately. If the ninth fails, the first eight have already happened. Even when all 12 succeed, undoing the job means undoing 12 changes.
We could add a tool for moving a batch. But an assistant can only call the operations we thought to provide. For every combination we haven’t packaged into a tool, the model has to coordinate the calls itself: read an answer, decide what comes next, write another call.
Models are good at writing code, though. A short script could do that coordination, keep intermediate results in variables and return only what the model needs to know. Could we let the model write the whole job and run it on our server?
Let the model write the job
Our MCP server used to have about 70 tools. Now it has four. The assistant asks for just the types its script needs, writes the script and sends it to us. We run the script beside the database and return the result.
Our old tools became functions. The assistant can combine those functions to do things we never wrote a tool for, and the model has less to read because it chooses what the script returns.
The four tools divide the work: docs returns TypeScript signatures, read runs a script that only reads, write runs a script that can change things, and show draws an interactive card in the conversation. The assistant needs no special support for executing code; these are ordinary MCP tools.
For the move, the assistant asks docs for the to-do query types and the signature of updateTodo. The answer describes the available query fields, the function’s signature and the transaction API. An assistant that already has those types can skip this call.
The next call sends this script to write. Here launch and website stand in for two project IDs the assistant already knows. The example handles up to 100 to-dos:
const { todos } = await m.query({
todos: {
where: { project: launch, status: "open" },
limit: 100,
select: { id: true }
}
});
await m.transaction("Move launch prep to Website", (t) =>
t.updateTodo(
todos.map((todo) => todo.id),
{ project: website }
)
);
return `Moved ${todos.length} to-dos.`; The script reads through m and changes data through t, inside a transaction. The query filters in the database and returns only IDs. Those IDs go straight into the update, without the model copying them into another call. The model receives the sentence the script returns and a summary counting the changed records. The full to-do records never pass through the model.
The same functions can answer a different request, such as moving only the overdue to-dos, without us adding another tool. The model writes the selection and the sequence; ordinary JavaScript carries them out.
Using scripts also reduces the number of tokens needed to describe our tools. Our old tool list came to about 45,000 characters. The new list is under 11,000: the four tools’ descriptions name the available functions, while docs supplies their types only when asked.
Where the script runs matters
The assistant could run the script itself. Cloudflare’s Code Mode and Anthropic’s ‘Code execution with MCP’ are examples of that approach: code on the assistant’s side calls an MCP server’s tools. The model no longer writes every call, but each call to a remote server still crosses the network.
The race below compares separate model-written calls, a script beside the assistant and a script on our server. It uses the timings above and allows 4 seconds to write a script. Calls run sequentially; parallel calls would change the comparison. Drag the slider to change the number of to-dos, then press race.
a tool call for each 13 trips · 17.4 s
- read the project
- move “Book venue”
- move “Confirm caterer”
- move “Draft invitations”
- move “Order signage”
- move “Brief the speakers”
- move “Test the projector”
- move “Print name badges”
- move “Arrange parking”
- move “Write the running order”
- move “Send reminders”
- move “Check accessibility”
- move “Plan the clear-up”
12 saves, each with its own undo
programmatic tool calling 14 trips · 9.8 s
- ask what the tools take
- write the script: read the project
- move “Book venue”
- move “Confirm caterer”
- move “Draft invitations”
- move “Order signage”
- move “Brief the speakers”
- move “Test the projector”
- move “Print name badges”
- move “Arrange parking”
- move “Write the running order”
- move “Send reminders”
- move “Check accessibility”
- move “Plan the clear-up”
12 saves, each with its own undo
a script on our server 2 trips · 5.7 s
- ask what the functions take
- write the script, and run it
1 save, with one undo
on our server it's 3.1 times as quick as tool calls.
For a few to-dos, separate calls win: writing a script costs more than writing a call. As the number grows, our server’s script pulls ahead. Moving 12 to-dos or 100 takes just two tool calls. In this simplified race, the extra database work is too small to show.
Running the job on our server also lets us save the moves together. In the example, m.transaction makes all the moves succeed or fail together. If moving any to-do fails, none of the moves are saved. If all succeed, ‘Move launch prep to Website’ appears in Activity, Milieu’s log of changes, with one undo for the entire job.
Give the script a small world
Running code written by a model on the machine that holds everyone’s data needs strict boundaries. The scripts run in QuickJS, a JavaScript interpreter compiled to WebAssembly, in a process separate from the web server.
The interpreter has no network, file system or direct database connection. A script can do its own computing and call our functions. Those calls go to the web server, which validates the arguments and applies the same permission checks as the app. Writing JavaScript gives the assistant more ways to combine operations, without giving it access to more data.
Each script gets fresh interpreter memory, a 64MB memory limit and 5 seconds overall, with at most 1 second spent running its own code. Calls and returned output have limits too, and account-level rate limits cap the number of scripts and their total runtime.
We don’t rely on the interpreter alone. The web server enforces the deadline from outside, because QuickJS can’t interrupt a script that is inside one of QuickJS’s built-in functions. Each account’s scripts run in a process of their own, and on our server that process runs as a temporary Linux user with no network and no access to the database. A script that found a bug in QuickJS would still have to get out of WebAssembly, and would then be in a process with nothing to reach.
Transactions need a different kind of boundary. SQLite allows only one writer at a time, so we can’t let a script hold the write lock while it runs. Instead, calls inside m.transaction only add changes to a queue. Once the transaction’s callback returns, the web server applies the queued changes in a database transaction. None of the script’s code runs while we hold the write lock.
How it’s worked in practice
In our testing, models have been reliable at using these tools. They tend to write scripts that work first time and do what we intended. What started as a small experiment worked well enough that we removed all the old tools. Having one way to do things is simpler, and the smaller tool list uses less context even for small jobs.
Writing a script can still be slower for a small job. But the number of tool calls doesn’t grow with every to-do: moving 12 or 100 takes two calls, or one if the assistant already has the types.