AI Hints
Home›MCP Tutorial›Rich Inputs, Outputs and Errors
MCP · Lesson 18 of 120

Tool Errors

ToolError.

⏱ 2 min read▶ Video at 16:05🎓 Free
Watch this lesson in the MCP courseWatch on YouTube ↗Full MCP course

Tools fail. An order doesn't exist, or a service is down. The error should tell the model what went wrong, so it can explain or try again. But it shouldn't leak internal details.

Tool Errors
From the video: Tool Errors
  • Tools fail
  • Explain to the model
  • Don't leak internals

Two kinds of failure

Raise tool error for problems the model should know about, like an unknown order. Any other exception is a bug, so the SDK hides its message. Run it. The tool error's message reaches the client. The bug only says an error happened.

errors.pypython
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from tester import call

mcp = MCPServer("shop")
ORDERS = {1042: "shipped"}

@mcp.tool()
def order_status(order_id: int) -> str:
    """Look up an order."""
    if order_id == 0:
        raise KeyError("db_password=hunter2 table=orders_v2")
    if order_id not in ORDERS:
        raise ToolError(f"Order {order_id} not found. Check the number on the receipt.")
    return ORDERS[order_id]

for n in [7, 0]:
    r = call(mcp, "order_status", {"order_id": n})
    print(r.is_error, "|", r.content[0].text)
Output
True | Error executing tool order_status: Order 7 not found. Check the number on the
receipt.
True | Error executing tool order_status
Also uses tester.py
import asyncio
from mcp import Client

def call(server, tool, args=None, **options):
    async def go():
        async with Client(server, **options) as client:
            return await client.call_tool(tool, args or {})
    return asyncio.run(go())

def tools(server):
    async def go():
        async with Client(server) as client:
            return (await client.list_tools()).tools
    return asyncio.run(go())

Error tips

Errors come back as normal results, with is error set to true, so the model can read them. Say what went wrong, and how to fix it. Never put secrets or stack traces in an error message.

keyvalue
is_errortrue
Saywhat and how to fix
ToolErrorshown to the model
Other errorshidden

Summary

Raise tool error with a helpful message. Unexpected errors are hidden, so internals don't leak. Next, async tools.

Key takeaways
  • ToolError
  • Helpful message
  • Hide internals
Next up: Async Tools — waiting without blocking