Sub topic 12
Handling results, errors and runaway loops
This chapter assumes you have the agent loop from the previous chapter working. It also assumes you are comfortable with asyncio. The loop there trusts every tool call to succeed quickly. Real servers fail, hang, and return too much text.
Two kinds of failure
MCP reports problems in two different ways.
- Protocol errors. The request itself failed, for example an unknown tool name or invalid arguments. The SDK raises
McpError. - Tool execution errors. The tool ran and failed, such as a missing file or an API rejection. The call returns normally with
result.isErrorset toTrueand an explanation incontent.
Send both back to the model as a tool_result. The model can often fix its own mistake, such as a wrong argument, if it sees the message. Don't let an exception end the conversation.
A safe wrapper for tool calls
This function adds a timeout, catches both failure kinds, and caps the size of the result.
import asyncio
from mcp import McpError
TOOL_TIMEOUT_S = 30
MAX_RESULT_CHARS = 8000
async def safe_call(session, name, arguments):
"""Return (text, is_error) for one tool call."""
try:
result = await asyncio.wait_for(
session.call_tool(name, arguments), timeout=TOOL_TIMEOUT_S
)
except asyncio.TimeoutError:
return f"Tool {name} timed out after {TOOL_TIMEOUT_S} seconds.", True
except McpError as exc:
return f"Protocol error calling {name}: {exc}", True
parts = []
for c in result.content:
if c.type == "text":
parts.append(c.text)
else:
parts.append(f"[{c.type} content omitted]")
text = "\n".join(parts)
if len(text) > MAX_RESULT_CHARS:
text = text[:MAX_RESULT_CHARS] + "\n[truncated]"
return text, bool(result.isError)In the loop, replace the direct session.call_tool call with text, is_error = await safe_call(session, block.name, block.input). Then put text in content and is_error in is_error of the tool_result block.
Stopping runaway loops
A model can call the same failing tool again and again. MAX_STEPS is the hard limit. Two further guards help.
- Return a final message at the limit. Raising
RuntimeErrorloses the conversation. Instead, return a text such as "I could not finish within the step limit." - Detect repeats. If the model sends the same tool name and arguments twice in a row, stop and tell it to try something different.
import json
def is_repeat(history, name, arguments):
key = (name, json.dumps(arguments, sort_keys=True))
repeated = bool(history) and history[-1] == key
history.append(key)
return repeatedCreate history = [] at the start of run_turn. When is_repeat returns True, skip the call and answer with an error result such as "Repeated identical call. Change your approach."
Common mistakes
- Dropping a
tool_useblock without sending a matchingtool_result. The API rejects the next request. - Putting stack traces in error text. Send a short, useful message instead.
- Forgetting that truncation cuts text only. Large images or embedded resources also cost context.
Exercise
A tool returns normally, but result.isError is True. Should your loop raise an exception? Why or why not?
Show answer
No. This is a tool execution error, not a protocol failure. Return the error text to the model as a tool_result with is_error set, so the model can adjust its arguments or choose another approach.