r/mcp • • 19h ago

question Does MCP code mode introduce a trade-off between token efficiency, context retention, and error recovery?

One of the main arguments for code mode seems to be that intermediate tool calls happen within the execution environment rather than being individually exposed to the llm. This reduces the number of tool call interactions and avoids injecting potentially large intermediate responses into the model's context.

While this makes sense, I see a few potential problems, particularly in multi turn conversational workflows.

1. Loss of intermediate context across user queries

Consider an e-commerce order management system exposed through mcp tools.

A user asks:

Query 1: "Find all orders above $500 placed in the last 30 days."

To accomplish this, the LLM might need to orchestrate several MCP tools:

  1. Get available stores/accounts.

  2. Get available order resources.

  3. Get order fields and their metadata.

  4. Fetch and filter the relevant orders.

With traditional mcp tool calling, the intermediate responses from these calls are available in the llm's conversation context. Also, for the scope of this problem, please assume that the tools are paginated, allows searches and the results are pretty scoped and limited.

Now suppose the user follows up with:

Query 2: "Which customer has placed the most orders?"

The llms might already have the relevant account, order resource, and field metadata from the previous interaction. It could potentially reuse that information without repeating the discovery process.

However, with code mode, if only the final result from query 1 is returned to the llm, the intermediate metadata might no longer be available in its context. Consequently, the LLM might have to execute the initial discovery sequence all over again. Am I right in thinking that this can lead to redundant tool executions in multi-turn workflows?

2. What about retaining intermediate information?

One possible solution would be to guide the llm (through a skill that ships with the mcp server) to generate code such that it accumulates all intermediate tool responses in a variable and return them alongside the final result. However, this seems to defeat the original purpose of code mode.

If we return all intermediate information to the llm, aren't we effectively bringing back the same context/token consumption that code mode was supposed to eliminate?

Another possibility is to selectively return only important metadata. But here's the problem: the next user query is unpredictable**.** The llm cannot necessarily know which pieces of intermediate information will become relevant in the next turn.

For example, the next question could concern customer information, payment fields, shipping details, product information, or some other metadata retrieved during the initial orchestration. How do you handle this without either losing potentially useful context or returning large amounts of intermediate data?

3. Error handling and recovery

Imagine a sequence of four tool calls where the fourth call fails.

  • How does the LLM get sufficiently detailed error information to identify and correct the problem?

  • If the LLM modifies the code and retries, the first three successful tool calls have to execute again.

  • The LLM has to always generate code such that any intermediate tool call errors are properly fallbacked with a proper error message with a possible response that helps the LLM to not execute the initial 3 tools again. All the error cases and null and other cases needs to be handled properly by the LLM for this.

Without proper checkpointing and error propagation, it seems that recovering from failures could introduce additional tool executions and latency.

Is this fundamentally a trade-off?

My current understanding is that Code Mode optimizes token consumption and tool orchestration, but potentially introduces trade-offs around retaining intermediate information across multiple user turns, avoiding redundant tool executions, debugging (error visibility), recovering from partial execution failures.

perhaps persistent execution state with on-demand retrieval could address some of these concerns, but that introduces additional architectural complexity.

I'd particularly like to hear from people who have implemented or used MCP Code Mode in real-world, multi-turn workflows.

Note: My examples might not be perfect but please consider examples of tasks where the intermediate tool call responses would help with certain follow up questions.

1 Upvotes

9 comments sorted by

2

u/Okoear 19h ago

I don't see why the code in 2 couldn't log the results somewhere(at this point everything my agents do is logged and cached for later analysis) so you can reach in the results of needed without having an agent in mid turn.

I fail to see the issue, it's a tool in the box.

1

u/Longjumping_Bad_879 19h ago

You're suggesting a temporary short lived session store that can later be queried by the agent when required ? I haven't tried this and this might really work.

But wouldn't that also mean I need to provide the knowledge to the agent on the existence of such a store and how and when to use it using Agent skills or similar mechanisms ?

Even then the agent could simply choose to go with calling the same tools again to debug any issues or retrieve necessary context, right ?

1

u/prattle_dev 17h ago

You don't need a separate skill. If the next code call can query the same temp table, the runner can tell the model how to inspect it: Saved 142 rows for this session. Preview: SELECT * FROM orders_over_500 LIMIT 3. If a later step fails, put that hint in the error result so the model can inspect the rows it was working with.

And yes, the model can still call the original tool again. If you want retries to see the same orders, have the tool return the saved rows on a repeat read unless the caller asks for fresh data. The retry still happens, but you skip the second fetch. Keep writes out of that cache.

1

u/Okoear 1h ago

No, the tool call itself should log it's result(truncated, or simplified if too big) in a determinism way, no LLM involved. Either a file per call, or a line in an jsonl file.

Yeah a simple rule to point where to check. Or you automatically reinject relevant context to the agent deterministically.

For your last question, you can use hook to ensure that an agent take an action instead of it's non deterministic choice.

It's pretty standard and basic agent work.

1

u/Flash_NTWRK 18h ago

Yes, there's a trade-off, but you can get most of both by not returning the data and not throwing it away either.

Keep the intermediate results alive on the execution side, say in a persistent session or a temp table, and return a small manifest to the model instead: a name for the dataset, the fields, the row count and a few sample rows. Something like "orders_over_500: 142 rows, fields customer_id, total, created_at". The follow-up "which customer has the most orders" is then just new code against orders_over_500. The model knows what exists and what shape it is, without the rows ever entering context.

The rediscovery problem is mostly about schema, not data. If the model has to explore accounts, resources and fields every turn, that's the part to cache. A cheap describe tool, or putting the core schema in the tool description, fixes most of it.

For error recovery, have the code return structured errors along with whatever partial results it got, as named datasets. Then a retry can pick up from there rather than starting over.

The cost is you now have state to manage, so the datasets need a session scope and an expiry, or they pile up. But the manifest is usually a few hundred tokens, so you keep most of the token savings.

1

u/Easy-Purple-1659 9h ago

Observability is the part I'd worry about more than the token math. Once the intermediate calls happen inside the execution sandbox, you lose the record of which tools ran, in what order, with what arguments, and what each one returned. That record is the only thing that makes a wrong answer debuggable a week later.

The manifest pattern other people describe handles rediscovery well, and it is cheap: keep the payload server side, return the name, fields, row count and a two row preview. What it does not give you is the audit trail, so I would have the runner write a per call log next to the session store, separate from what the model sees. Same data, different consumer.

If you can replay a session from that log, code mode is a straight win. Without it, the first weird reply costs more than the tokens you saved.

1

u/Mother_Mail_8831 6h ago

Yes, it’s a trade-off, and the cases you walked through are the right ones. Two things from actually running this in multi-turn sessions:

First, normal tool calling doesn’t fully solve the follow-up problem either. In a long thread the client will compact or drop earlier tool results, and the model rediscovers anyway. Code mode just makes that loss obvious, because the intermediates never entered the context in the first place.

Second, the token win is uneven. If your tools already return small, scoped payloads, like the paginated order search in your example, classic tool calling is often simpler and you won’t miss much. Code mode pays off when intermediates are large: files, logs, compile output, unfiltered listings. That’s where you do not want those blobs in the prompt.

I wouldn’t try to return “just enough” metadata for the next question. You can’t predict it, and stuffing everything back in undoes the point. Keep the data in the execution environment (a session store, a temp table, or files) and return a handle plus the schema. The next turn writes new code against that handle. For errors, the runner should return which step failed, the exception, and the names of results that already landed, and the script should checkpoint so a retry can skip the first three calls instead of re-running them.

The persistent execution state with on-demand retrieval you mentioned at the end is the way through the trade-off. The extra complexity is real, but it belongs in the runner, not in a skill that teaches the model to dump every intermediate back into the prompt.