How to debug MCP server
Quick answer
To debug an MCP server, start by verifying your server setup using the official mcp Python SDK and ensure correct usage of stdio_server or other transports. Use detailed logging around message handling and validate JSON message formats to catch protocol errors early.
ERROR TYPE
code_error ⚡ QUICK FIX
Add detailed logging around mcp.server.stdio.stdio_server message handling and validate JSON message formats to identify malformed requests.
Why this happens
Debugging issues with an MCP server often arise from incorrect message formatting, improper server initialization, or transport misconfiguration. For example, using TCP ports like 25565 instead of stdio_server causes connection failures. Errors typically manifest as JSON decode errors, unexpected message types, or silent failures in message processing.
Example broken code initializing MCP server incorrectly:
from mcp.server import Server
from mcp.server.stdio import stdio_server
# Incorrect: trying to bind TCP port (not supported)
server = Server(transport='tcp', port=25565)
server.serve() output
TypeError: 'tcp' transport not supported; use stdio or SSE
The fix
Use the official stdio_server transport for MCP servers and add logging to trace message flow. Validate incoming messages to ensure they conform to MCP JSON schema. This prevents silent failures and helps identify malformed requests.
import logging
from mcp.server.stdio import stdio_server
logging.basicConfig(level=logging.DEBUG)
# Correct MCP server setup using stdio transport
stdio_server() # This blocks and handles MCP messages over stdio
# For custom handling, wrap message processing with try-except and log errors output
DEBUG:root:Received MCP message: {...}
DEBUG:root:Processed MCP message successfully Preventing it in production
Implement robust error handling with retries and validation before processing messages. Use structured logging to capture message payloads and errors. Monitor server health and use automated tests to simulate MCP message flows. Avoid unsupported transports and always use the mcp SDK's recommended server methods.
Key Takeaways
- Always use stdio_server or supported transports for MCP servers.
- Add detailed logging around message receipt and processing to catch errors early.
- Validate all incoming MCP messages for correct JSON format before handling.
- Avoid unsupported transports like TCP ports for MCP protocol servers.
- Implement retries and monitoring to maintain MCP server reliability in production.