Anthropic's Model Context Protocol (MCP) has established itself as the open universal standard connecting AI coding assistants (Claude Code, Cursor, Windsurf) with real-world infrastructure, local databases, and execution runtimes. Here is how to engineer production-ready FastMCP servers in Python without crashing your JSON-RPC connection.
1. The Architecture of FastMCP
FastMCP simplifies server creation by eliminating boilerplate JSON-RPC protocol handlers. Using straightforward Python decorators, you expose native functions directly as LLM tools with strict Pydantic type safety.
from mcp.server.fastmcp import FastMCP
import psycopg2, os
mcp = FastMCP("postgres-inspector")
@mcp.tool()
def inspect_schema(table_name: str) -> str:
"""Introspect PostgreSQL table schema and return column definitions safely."""
# Read-only query execution with bounded output
return query_db_schema_safely(table_name)
if __name__ == "__main__":
mcp.run()
2. Solving Stdio Pollution & 'Connection Closed' Errors
The #1 error developers encounter when running local MCP servers is the fatal 'Connection closed' crash. This is caused by stray print() statements or third-party libraries writing debug output to standard output (stdout), which corrupts the JSON-RPC message frame.
- Stderr Isolation: Redirect all application logs exclusively to
sys.stderror dedicated log files on disk. - Virtualenv PATH Resolution: Explicitly specify the absolute path to your Python interpreter inside
claude_desktop_config.json. - Graceful Shutdown: Implement SIGINT and SIGTERM traps to release database connection pools cleanly.