Sub topic 3
Handling MCP Results, Errors, and Runaway Loops
Assume you know Python async/await, JSON Schema, and an LLM API's tool-calling format. Your host must treat every MCP call as fallible and bounded.
Handle results and errors
MCP results can contain several content items. Check isError before passing text to the model. Add a timeout and a maximum number of model-tool turns.
import asyncio
async def safe_call(session, name, arguments):
try:
result = await asyncio.wait_for(
session.call_tool(name, arguments),
timeout=10,
)
except asyncio.TimeoutError:
return {"ok": False, "error": "The tool timed out."}
text = "\n".join(
item.text for item in result.content
if getattr(item, "type", None) == "text"
)
if result.isError:
return {"ok": False, "error": text or "The tool failed."}
return {"ok": True, "text": text}Return a useful error to the model, but do not expose secrets, stack traces, or internal paths. Stop after a fixed step limit such as 10.
Work with several servers
Connect to each server separately and namespace discovered tools:
github__search_issuesfilesystem__read_file
Keep the server identity with every call. This prevents collisions and makes audit logs understandable.
Use resources and prompts
Resources usually provide context, such as a document identified by a URI. Prompts provide reusable message templates. The host should choose when to read a resource or offer a prompt. Do not automatically load every resource into the model context because context size and cost grow quickly.
Remote servers and authorization
For a remote server, use its documented authenticated transport. Store tokens in an environment variable or secret manager. Use HTTPS, short-lived credentials where possible, and explicit server allowlists.
Security and trust boundaries
Ask the user before consequential actions such as sending messages, deleting data, or changing permissions. Give each server only the access it needs. Treat tool descriptions and returned content as untrusted data. A tool result can contain misleading instructions, so the model must not gain authority merely by reading it.
Test, debug, and operate
Use the MCP Inspector to inspect initialization, capabilities, schemas, and calls. Log server name, tool name, duration, request identifiers, and error type. Redact arguments that contain secrets. In production, supervise subprocesses, close sessions, retry only safe operations, limit context growth, and track tool-call cost.
Exercise
Why should an agent loop have both a timeout and a step limit?
Show answer
A timeout bounds one stuck operation; a step limit bounds repeated model-tool calls that never reach a final answer.