Build Your Own MCP Server · 25 min · Python · MCP Python SDK (FastMCP)
Error Handling and Production Patterns
An MCP tool that raises an unhandled exception won't crash your server, but it will hand the model a raw Python traceback instead of something it can actually act on.
Hiring signal: Error handling is the difference between a server you demo once and a server you actually keep running -- the same reliability instinct production engineers apply to any service boundary.
What you will learn
- Explain how an unhandled exception in one tool affects the whole server
- Validate tool inputs before acting on them
- Return structured, model-readable errors instead of raw tracebacks
Introduction
All 5 tools work when you call them correctly. Today you call them incorrectly, on purpose, and fix what breaks.
Break it: an empty or missing argument
Ask Claude something ambiguous enough that it calls get_weather with an empty string, or call read_workspace_file for a file that doesn't exist. Watch what comes back.
An unhandled exception here is worse than it looks
FastMCP will catch a raised exception and turn it into an MCP error response automatically -- your server process doesn't crash from one bad tool call. But the content of that automatic error is a raw Python traceback, which is both unhelpful to the model (it has no idea what "KeyError: 'results'" means in the context of your weather tool) and a minor information leak (file paths, internal variable names). The fix isn't "prevent all errors" -- it's "decide what the model should see when one happens."
Unlock the full lesson
You've read the first 2 sections. The rest of this lesson covers Validate before you act, not after you fail, Structured errors: the `isError` pattern, What You're Building — plus a hands-on lab, quiz, and project artifact.
Create a free account to unlock Phase 0 and Phase 1 of every course — no credit card.
Browse all courses · View pricing · DeVenture Academy