Sub topic 7
Reporting errors the model can act on
This chapter assumes you have built a tool with the Python SDK's FastMCP helper and know how its type hints become a JSON Schema. It also assumes you know what a JSON-RPC request and response look like. If a tool call fails, the model needs enough information to retry, change its arguments, or tell the user what went wrong. Your server should also keep running.
Two kinds of failure
MCP separates failures into two layers, and they reach the model differently.
| Kind | Example | How it is reported | Who sees it |
|---|---|---|---|
| Protocol error | Unknown tool name, malformed request, unsupported method | JSON-RPC `error` object with a numeric code | Usually the client library, not the model |
| Tool execution error | Service not found, upstream API timed out, permission denied | Normal result with `isError: true` and text content | The model, as part of the conversation |
A protocol error means the request itself was broken. A tool execution error means the request was valid but the work failed. The second kind is the one you design, because the model reads it and decides what to do next.
Tool errors are returned as results, not JSON-RPC errors. That lets the model treat the failure as information in the conversation. A model that gets "Unknown service: biling. Known services: billing, search" can correct the typo and call the tool again.
What FastMCP does when a tool raises
In the Python SDK you do not build the isError result by hand. If your tool function raises an exception, FastMCP catches it. It then returns a result with isError set to true. The text content is Error executing tool <name>: <exception message>. The server process keeps running and serves the next request.
This is why the first example in this tutorial raises ValueError for an unknown service. That code already produces a tool execution error. The weak point is the message. Compare these two:
Unknown service: xUnknown service: 'biling'. Valid services: billing, search.
The second tells the model how to fix the call. The first forces it to guess or give up.
Input validation works in a similar way. When a call violates the schema, for example limit=50 where the schema says le=20, the SDK rejects it before your function runs. Current SDK versions return the validation message as a tool error. The spec allows either layer for invalid arguments, and the behavior has varied across SDK versions. Test with the Inspector, which you will meet in a later chapter, instead of assuming.
Writing messages a model can use
A good error message answers three questions: what failed, why, and what the caller can do.
- Name the bad input. Quote the value the model sent, so it can see its own mistake.
- List valid options when the set is small. Service names, environments, and status values are good candidates.
- Say whether retrying can help. "Timed out after 10s, retry may succeed" and "Service is archived, do not retry" lead to different behavior.
- Stay short. The message occupies the model's context window, so omit stack traces.
Here is a complete server that applies these rules. It defines its own exception types and translates upstream failures into messages the model can act on.
import logging
import sys
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.exceptions import ToolError
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
logger = logging.getLogger("team-tools")
mcp = FastMCP("team-tools")
OWNERS = {"billing": "payments-team", "search": "discovery-team"}
ARCHIVED = {"legacy-reports"}
class UpstreamTimeout(Exception):
"""Raised when the internal directory API does not answer in time."""
def lookup_owner(service: str) -> str:
# Stand-in for a real HTTP call to an internal directory.
if service == "flaky":
raise UpstreamTimeout()
return OWNERS[service]
@mcp.tool()
def get_service_owner(service: str) -> str:
"""Return the team that owns a service, given its short name."""
name = service.strip().lower()
if name in ARCHIVED:
raise ToolError(
f"Service '{name}' is archived and has no owner. Do not retry."
)
if name not in OWNERS and name != "flaky":
valid = ", ".join(sorted(OWNERS))
raise ToolError(
f"Unknown service '{service}'. Valid services: {valid}."
)
try:
return lookup_owner(name)
except UpstreamTimeout:
logger.warning("directory timeout for %s", name)
raise ToolError(
"The ownership directory timed out. Retrying once may succeed."
)
except Exception:
logger.exception("unexpected failure in get_service_owner")
raise ToolError(
"Internal error while looking up the owner. Tell the user to "
"check the server logs."
)
if __name__ == "__main__":
mcp.run()The example does four things worth copying.
- Normalizes input. It strips and lowercases the name, so
"Billing "still works. Where the model's input is almost right, accept it instead of failing. - Uses
ToolErrorfor messages you wrote. It signals that the text is meant for the model. - Logs details to stderr. Under the stdio transport, stdout carries protocol messages. A stray
printcorrupts the stream, so logs go to stderr as in the logging example from earlier chapters. - Keeps a catch-all. An unexpected exception can contain file paths, hostnames, or SQL. The generic message keeps those out of the model's context. The full traceback stays in your log.
Errors that are not exceptions
Some failures are better expressed as normal results. If a search returns no matches, that is a successful call with an empty answer. Returning an error would push the model into retry loops. Compare:
| Situation | Better as | Reason |
|---|---|---|
| Query matched nothing | Success with `[]` or "No matches" | The tool did its job |
| Caller passed an unknown ID | Error | The input was wrong and can be corrected |
| Upstream API returned 503 | Error, retry may help | The work did not complete |
| Caller lacks permission | Error, do not retry | Retrying cannot change the outcome |
| Result truncated at 100 rows | Success with a note | Data is valid but incomplete |
For partial results, say so in the output: "Showing 100 of 412 rows. Narrow the filter to see more." A silent truncation looks like a complete answer, and the model will report it as one.
Timeouts and long operations
A tool that waits forever on an upstream call blocks the session and may hit the client's own request timeout. The client then reports a protocol-level failure, and the model never sees a useful message. Set an explicit timeout shorter than the client's, and convert the timeout into a tool error:
import httpx
DIRECTORY_URL = "https://directory.internal.example/owners"
async def fetch_owner(service: str) -> str:
try:
async with httpx.AsyncClient(timeout=5.0) as client:
response = await client.get(f"{DIRECTORY_URL}/{service}")
response.raise_for_status()
return response.json()["team"]
except httpx.TimeoutException:
raise ToolError("Directory timed out after 5s. Retrying may succeed.")
except httpx.HTTPStatusError as exc:
if exc.response.status_code == 404:
raise ToolError(f"No directory entry for '{service}'.")
raise ToolError(
f"Directory returned HTTP {exc.response.status_code}."
)This snippet uses ToolError from the previous listing. It reports the HTTP status code but not the URL or response body. It also gives each failure its own message instead of one generic "request failed". The model can act on "no entry" and "timed out" differently.
Common mistakes
- Returning errors as normal strings. A tool that returns
"Error: not found"is a success from the protocol's point of view. The client cannot tell it apart from real data, and the model may use it as an answer. Raise instead. - Swallowing exceptions and returning an empty result. The model reports "no results" when the truth is that the backend was down.
- Using
printfor diagnostics under stdio. It writes to stdout and breaks the JSON-RPC stream. - Leaking internals. Stack traces, connection strings, and internal hostnames do not belong in error text.
- Over-long messages. Long messages cost context and bury the one sentence that matters.
- Asking the model to retry without a limit. "Retry" in a message can start a loop. State "retry once" or "do not retry".
Checking your errors
Before connecting a host, call each failure path from the Inspector. Check that the result is flagged as an error, that the message reads sensibly with no other context, and that the server still answers a normal call afterward. Also look at stderr to confirm the full detail was logged there.
Exercise
A tool queries an internal API and the API returns HTTP 503. Another tool searches tickets and finds no matches. Which should be reported as a tool error (isError true), which as a normal result, and what should each message say?
Show answer
The 503 is a tool error: the work did not complete. The message should say the upstream service is unavailable and that retrying once may succeed, without including the URL or response body. The empty search is a normal successful result, such as an empty list or "No tickets matched", because the tool did its job and an error would push the model into pointless retries.
Exercise
Your stdio server's tool contains print(f"looking up {service}") for debugging. Clients start failing with parse errors. Why, and what is the fix?
Show answer
With the stdio transport, stdout carries the JSON-RPC messages, so the extra line corrupts the stream. Remove the print and log to stderr instead, for example with logging.basicConfig(stream=sys.stderr).