Sub topic 12
Handling results, errors and runaway loops
This chapter covers what happens after the model asks for a tool call and the call does not go as planned. It assumes you can read async Python and have built the agent loop from the previous chapter. You should also know how an LLM API represents tool calls and tool results.
The loop from the previous chapter works when every call succeeds. Real servers return errors, hang, produce huge outputs, or send the model in circles. This chapter shows how to keep the conversation valid and the application under control in each case.
Two kinds of failure
MCP separates failures into two layers. Handle them differently.
| Layer | What happened | How it shows up in the SDK | What to do |
|---|---|---|---|
| Tool execution error | The tool ran but failed, for example bad input or a missing file | `result.isError` is `True`, and `result.content` describes the problem | Pass the message to the model so it can retry or explain |
| Protocol error | The request itself was invalid, for example an unknown tool name or malformed arguments | The SDK raises an exception such as `McpError` | Catch it in your host, then decide whether to report it to the model |
A tool execution error is information for the model. A protocol error often points to a bug in your host, but it can also come from the model inventing a tool name, so reporting it to the model is usually the right recovery.
A transport failure is a third case. If the server process crashes, the session raises an exception or hangs. Treat that as a connection problem, not a tool problem.
The tool result contract
Every tool_use block from the model needs a matching tool_result block in the next user message. The match is made by tool_use_id. If you skip one, most LLM APIs reject the next request. This rule drives most of the design below: whatever goes wrong, you still return a result for each call.
A result that is not just text
result.content is a list. Each item has a type. Text is the common case, but a server may also return images, embedded resources, or other content. The previous chapter's loop kept only text items. That is a reasonable default, but make the choice visible.
def render_content(result) -> str:
parts = []
for item in result.content:
if item.type == "text":
parts.append(item.text)
else:
parts.append(f"[{item.type} content omitted]")
return "\n".join(parts) or "(no output)"Two details matter here. First, the placeholder tells the model something was dropped, so it does not assume the tool returned nothing. Second, the empty-string fallback avoids sending an empty content field, which some APIs reject for error results.
Wrapping a call safely
Put every failure mode behind one function that always returns a tool_result dictionary. The function below handles protocol errors, timeouts, and unexpected exceptions, and it truncates long output.
import asyncio
from mcp import McpError
CALL_TIMEOUT_SECONDS = 30
MAX_RESULT_CHARS = 8000
def truncate(text: str, limit: int = MAX_RESULT_CHARS) -> str:
if len(text) <= limit:
return text
omitted = len(text) - limit
return text[:limit] + f"\n[truncated: {omitted} more characters]"
def render_content(result) -> str:
parts = []
for item in result.content:
if item.type == "text":
parts.append(item.text)
else:
parts.append(f"[{item.type} content omitted]")
return "\n".join(parts) or "(no output)"
async def safe_call(session, block) -> dict:
try:
result = await asyncio.wait_for(
session.call_tool(block.name, block.input),
timeout=CALL_TIMEOUT_SECONDS,
)
return {
"type": "tool_result",
"tool_use_id": block.id,
"content": truncate(render_content(result)),
"is_error": bool(result.isError),
}
except asyncio.TimeoutError:
message = f"Tool '{block.name}' timed out after {CALL_TIMEOUT_SECONDS} seconds."
except McpError as exc:
message = f"Protocol error calling '{block.name}': {exc}"
except Exception as exc: # last resort so the conversation stays valid
message = f"Unexpected failure calling '{block.name}': {type(exc).__name__}: {exc}"
return {
"type": "tool_result",
"tool_use_id": block.id,
"content": message,
"is_error": True,
}The loop then calls safe_call for each tool-use block instead of calling the session directly.
results = [
await safe_call(session, block)
for block in response.content
if block.type == "tool_use"
]
messages.append({"role": "user", "content": results})Timeouts and cancellation
asyncio.wait_for cancels the awaiting task when the time runs out. That stops your host from waiting, but it does not guarantee that the server stops working. A tool that started a long database query may keep running. For tools with side effects, a timeout means the outcome is unknown, so word the message that way when the tool can change data. The model should not blindly retry a "create" operation after a timeout.
Large results and context size
Everything you return goes into the next model request, and it stays in the history for every later request. One 200 KB file listing can use a large share of the context window and raise the cost of every following step.
Truncating by characters is simple and predictable. Its weakness is that it can cut JSON in the middle. If your servers return structured data, consider truncating at item boundaries or asking the server for a smaller page. A tool that accepts limit and offset arguments lets the model fetch more only when it needs it.
Runaway loops
The loop has a step limit, MAX_STEPS, which is the last line of defense. Several patterns can still waste steps before you reach it:
- The model repeats the same call with the same arguments and gets the same result.
- The model retries a failing call with arguments that keep failing.
- Each step makes small progress but the task is too large for the budget.
Detect exact repeats cheaply by remembering what has been called.
import json
def call_key(block) -> str:
return block.name + ":" + json.dumps(block.input, sort_keys=True)Keep a set of keys per turn. If a key appears a third time, do not call the tool again. Return an error result such as "This exact call was already made twice with the same outcome. Try a different approach or answer with what you have." The model gets feedback instead of silence, and the server is spared a pointless call.
The diagram below shows where each guard sits in one pass of the loop.
What to do at the step limit
The previous chapter raised a RuntimeError when MAX_STEPS ran out. That is correct for a library, but a user-facing application can do better. One option is to make a final request without the tools parameter and ask the model to summarize what it found so far. The model cannot call tools in that request, so it must answer. Whether this is acceptable depends on the task. A partial answer is fine for research and wrong for a task that must finish all its steps, so there you should fail loudly.
Retries
Retry only when it is safe and likely to help. Reading data over a flaky connection is a good candidate. Writing data is not, unless the tool is idempotent, meaning that repeating it has the same effect as doing it once. Often the better design is to let the model decide: return the error as a result and let it choose a new approach. Automatic retries in the host should be limited to transport-level problems, with a small count and a delay between attempts.
Common mistakes
- Returning no
tool_resultfor a call that raised, which breaks the next API request. - Sending
is_error: Falsefor a timeout because no exception reached the model. - Dropping non-text content silently, so the model believes the tool returned nothing.
- Retrying side-effecting tools automatically after a timeout.
- Letting one slow server block every other call. Calls in one model turn are independent, so you can run them with
asyncio.gatherand give each its own timeout, as long as your tools allow concurrent use.
Exercise
A model turn contains two tool-use blocks. The first call succeeds. The second call times out. What should the next user message contain, and why?
Show answer
It should contain two toolresult blocks. The first holds the normal output with iserror set to false. The second holds a message saying the tool timed out, with iserror set to true, and it should say the outcome is unknown if the tool can change data. Both blocks are needed because the API requires one result for every tooluse_id from the previous assistant message. Dropping the failed one would make the next request invalid.
Exercise
Why is a step limit alone not enough to stop a model that keeps calling the same failing tool with the same arguments?
Show answer
The step limit only ends the loop after all the steps are used, so the server receives every wasted call and the history fills with identical errors. Tracking a key made of the tool name and sorted arguments lets the host spot the repeat early. It can then return an error result without calling the tool, which tells the model to change its approach.