Learn to handle failures gracefully — validation, try/except, timeouts, and logging.
MCP servers are subject to various types of failures. Understanding each error category is the first step toward handling them properly. A good server isn't one that never fails—it's one that fails in a predictable, informative, and recoverable.
Errors in an MCP server fall into four main categories: input errors (invalid parameters, incorrect types, values outside the expected range); execution errors (code bugs, division by zero, missing dictionary key); network errors (external API down, connection timeout, DNS unresolved); and permission errors (file access denied, token expired, invalid credentials). Each type requires a different handling strategy.
Software engineering studies show that more than 60% of production incidents are caused by inadequate error handling—not by the errors themselves. In MCP servers, this is even more critical because the AI model depends on clear error messages to inform the user about what happened and suggest next steps. A raw stack trace doesn't help anyone.
Invalid parameters, incorrect types, values outside the range. Detectable before running the main logic. Prevented through validation.
Bugs in the code, KeyError, IndexError, division by zero. They occur during processing. Prevent them with try/except and tests.
API down, timeout, DNS resolution failure. Unpredictable and transient. Handled with retries and clear messages.
Access denied, token expired, invalid credentials. These require action from the user or admin. Clear message about what’s missing.
The first line of defense against errors is input validation. Before processing any data, check that the parameters are correct—their type, format, range, and presence. Never trust incoming data. Return clear messages when something is wrong so the model can give the user useful information.
Robust validation at the start of the tool prevents cascading errors:
Never expose sensitive data in error messages. Avoid returning server file paths, environment variable names, database connection strings, or any information that could be used to exploit the system. Error messages should be useful to the user, not an attacker.
Even with perfect validation, runtime errors can happen. The structure try/except is your safety net—it catches exceptions before they bring down the server and lets you return useful error messages instead of incomprehensible stack traces.
Wrap the main logic in try/except with specific exceptions:
Always catch specific exceptions before the generic one. Start with the most likely errors (ValueError, KeyError, json.JSONDecodeError) and end with except Exception as the final safety net. Never use except: without a type—this catches even KeyboardInterrupt and SystemExit.
except: without an exception typepassWhen your tools make HTTP requests to external APIs, network failures are inevitable. The API server may be unavailable, the connection may time out, or the response may have an error status. Each type of network failure requires specific handling with messages that help the model tell the user what happened.
With httpx, the main network errors are:
httpx.ConnectError — couldn't connect to the server (DNS, closed port, unreachable host)httpx.TimeoutException — connection or read timed outhttpx.HTTPStatusError — the server responded with a 4xx or 5xx statusHandle each one separately to give the model precise messages.
Server is unreachable. Message: "Could not connect to service X. Check whether the service is online." Retry may help if the issue is temporary.
Timed out. Message: "The request to service X took longer than expected." Consider increasing the timeout or retrying with backoff.
Error response. 404 = resource not found, 401/403 = unauthorized, 500 = external server error. Adapt the message to the status code.
Be careful with infinite retries. If the API is down, retrying without limits will make your tool hang. Use retries with exponential backoff and a maximum number of attempts (e.g., 3 attempts with waits of 1s, 2s, and 4s). If they all fail, return a clear message saying the service is temporarily unavailable.
Configuring timeouts is essential for MCP servers. The AI model waits for the tool's response before continuing—if the tool gets stuck on an HTTP request without a timeout, the model waits indefinitely. Always set time limits for operations that may take a while.
Always configure a timeout for HTTP requests:
The value timeout=10.0 means the request will be canceled if it takes more than 10 seconds. For fast APIs, 5–10 seconds is enough. For heavy operations, 30 seconds or more may be necessary—but always set a limit.
You can configure granular timeouts with httpx.Timeout(connect=5.0, read=10.0, write=5.0, pool=5.0). This allows different limits for connection, reading, writing, and the pool. In most cases, timeout=10.0 as a single value is enough and easier to maintain.
Error messages returned to the model should be simple and useful. But you, the developer, need complete details to diagnose problems. That’s where logging comes in: recording detailed errors to stderr without interfering with the MCP protocol, which uses stdout.
Configure logging to record detailed errors in stderr:
O exc_info=True includes the full stack trace in the log — essential for debugging. The MCP protocol uses stdout for communication, so logs on stderr don’t interfere.
Use appropriate log levels: DEBUG for development details, INFO for normal operations (tool called, parameters received), WARNING for suspicious but non-critical situations, ERROR for failures that prevent operation. In production, set the level to INFO; in development, use DEBUG.
The MCP Inspector displays server logs in its interface, making debugging during development easier. Structured logs (with a timestamp, level, and logger name) are 3x faster to diagnose than scattered print statements, according to software engineering studies. Invest time in setting up proper logging from the start—you’ll be glad you did when the first production bug appears.
Next Module: 3.9 — Testing with MCP Inspector