Sub topic 7
Reporting errors the model can act on
This chapter assumes you have built a tool with FastMCP, as in "Your first tool", and that you know the basics of JSON-RPC. It covers how MCP reports failures and how to write error messages that let the model recover.
Two kinds of failure
MCP separates failures into two groups.
- Protocol errors are JSON-RPC error responses. They cover things like an unknown tool name or a malformed request. The SDK produces these, and the model usually never sees them.
- Tool execution errors are normal results with
isError: trueand a text message. They cover things like a missing record, a timeout, or a rejected input. The model reads the message and can decide what to do next.
Your job is mostly the second group. When a tool raises an exception, FastMCP catches it and returns it as a tool result with isError set. The server keeps running.
Write messages that say what to do next
A model can only recover from an error it understands. Compare these two messages:
Error: KeyError('payments')Unknown service 'payments'. Known services: billing, search.
The second names the bad input and lists valid values, so the model can correct itself without asking the user. A good error message states what failed, why, and what a valid call looks like.
import logging
import sys
from mcp.server.fastmcp import FastMCP
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
logger = logging.getLogger("team-tools")
mcp = FastMCP("team-tools")
OWNERS = {"billing": "payments-team", "search": "discovery-team"}
@mcp.tool()
def get_service_owner(service: str) -> str:
"""Return the team that owns a service, given its short name."""
key = service.strip().lower()
if key not in OWNERS:
known = ", ".join(sorted(OWNERS))
raise ValueError(f"Unknown service '{service}'. Known services: {known}.")
return OWNERS[key]
if __name__ == "__main__":
mcp.run()Wrap upstream failures
Tools that call internal APIs fail in more ways than lookups do. Catch the exceptions you expect and translate them. Log the details to stderr, and give the model a short, safe message.
import json
import urllib.error
import urllib.parse
import urllib.request
@mcp.tool()
def get_service_status(service: str) -> str:
"""Return the current status JSON for a service from the status API."""
url = "https://status.internal.example/api/" + urllib.parse.quote(service, safe="")
try:
with urllib.request.urlopen(url, timeout=5) as resp:
return json.dumps(json.load(resp))
except urllib.error.HTTPError as exc:
if exc.code == 404:
raise ValueError(
f"No status page for '{service}'. Call get_service_owner to check the name."
) from exc
logger.error("Status API returned HTTP %s for %s", exc.code, service)
raise RuntimeError(
f"The status API failed with HTTP {exc.code}. Retry once; if it fails again, tell the user."
) from exc
except (urllib.error.URLError, TimeoutError) as exc:
logger.error("Status API unreachable: %s", exc)
raise RuntimeError(
"The status API did not respond within 5 seconds. Retry once, then report the outage."
) from excThe timeout matters. Without one, a hung upstream call blocks the tool and the model waits forever.
Common mistakes
- Returning errors as normal strings. A result like
"Error: not found"withoutisErrorlooks like a success to the host, and the model may treat it as data. - Leaking internals. Stack traces, hostnames, and tokens in a message go straight into the model's context. Log them to stderr instead.
- Printing to stdout. On the stdio transport, stdout carries protocol messages. A stray
printcorrupts the stream. - Vague retry advice. Say whether retrying can help. "Retry once" and "do not retry, the input is wrong" lead to different behavior.
Exercise
A tool raises ValueError("bad input") when environment is not "staging" or "production". Rewrite the message so the model can fix the call without asking the user. Why is the original weak?
Show answer
Use something like: "Unknown environment 'prod'. Use 'staging' or 'production'." The original does not say which field was wrong, what value was received, or which values are valid. The improved message names all three, so the model can retry with a corrected argument.