|
| 1 | +# Troubleshooting |
| 2 | + |
| 3 | +This guide helps you resolve common issues when using the MCP Python SDK. |
| 4 | + |
| 5 | +## 421 Invalid Host Header (DNS Rebinding Protection) |
| 6 | + |
| 7 | +A recent update introduced [DNS rebinding protection](./transports.md#dns-rebinding-protection) to the MCP Python SDK. While this improves security, it may cause existing setups to fail with a **421 Misdirected Request / Invalid Host Header** error if the host header doesn't match the allowed list (common when using proxies, gateways, or custom domains). |
| 8 | + |
| 9 | +### Solutions |
| 10 | + |
| 11 | +Depending on your security requirements, you can resolve this in two ways: |
| 12 | + |
| 13 | +#### Option 1: Explicitly Allow Specific Hosts (Recommended) |
| 14 | + |
| 15 | +Use this approach if you are running in production or through a gateway. You can wildcard the ports using `*`. |
| 16 | + |
| 17 | +```python |
| 18 | +from mcp.server.fastmcp import FastMCP |
| 19 | +from mcp.server.transport_security import TransportSecuritySettings |
| 20 | + |
| 21 | +mcp = FastMCP( |
| 22 | + "MyServer", |
| 23 | + transport_security=TransportSecuritySettings( |
| 24 | + enable_dns_rebinding_protection=True, |
| 25 | + # Add your specific gateway or domain here |
| 26 | + allowed_hosts=["localhost:*", "127.0.0.1:*", "your-gateway-host:*"], |
| 27 | + allowed_origins=["http://localhost:*", "http://your-gateway-host:*"], |
| 28 | + ) |
| 29 | +) |
| 30 | +``` |
| 31 | + |
| 32 | +#### Option 2: Disable DNS Rebinding Protection |
| 33 | + |
| 34 | +Use this approach for local development or if you are managing security at a different layer of your infrastructure. |
| 35 | + |
| 36 | +```python |
| 37 | +from mcp.server.fastmcp import FastMCP |
| 38 | +from mcp.server.transport_security import TransportSecuritySettings |
| 39 | + |
| 40 | +mcp = FastMCP( |
| 41 | + "MyServer", |
| 42 | + transport_security=TransportSecuritySettings( |
| 43 | + enable_dns_rebinding_protection=False, |
| 44 | + ) |
| 45 | +) |
| 46 | +``` |
| 47 | + |
| 48 | +### Reverse Proxy Configuration |
| 49 | + |
| 50 | +If you are using a reverse proxy (like Nginx or Caddy), ensure your proxy is passing the correct `Host` header to the MCP server. |
| 51 | + |
| 52 | +**Nginx example:** |
| 53 | +```nginx |
| 54 | +location / { |
| 55 | + proxy_pass http://localhost:8000; |
| 56 | + proxy_set_header Host $host; |
| 57 | + proxy_set_header X-Real-IP $remote_addr; |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +**Caddy example:** |
| 62 | +```caddy |
| 63 | +reverse_proxy localhost:8000 { |
| 64 | + header_up Host {upstream_hostport} |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +## See Also |
| 69 | + |
| 70 | +- [Transport Security](./transports.md#dns-rebinding-protection) |
| 71 | +- [FastMCP Server Documentation](./servers.md) |
0 commit comments