Nginx Reverse Proxy for Remote MCP SSE & Streamable HTTP
S L Manikanta
Nov 28, 2026 • 8 min read
bolt Key Takeaways
- Nginx enables proxy_buffering by default, which stalls MCP SSE and Streamable HTTP tool responses until the 4KB-8KB buffer fills or the request times out.
- Set proxy_buffering off, proxy_cache off, and X-Accel-Buffering: no on /mcp and /sse locations to flush Server-Sent Events immediately.
- Increase proxy_read_timeout to 3600s and enforce HTTP/1.1 with Connection '' so Nginx does not kill idle agent sessions after 60 seconds.
- Explicitly pass Mcp-Session-Id and Authorization headers through Nginx to preserve stateful session routing and Bearer token verification.
list On this page expand_more
- Quick Solution: Production Nginx Config for MCP Servers
- Why Default Nginx Breaks MCP Transports
- Transport Parameter Matrix: Default Nginx vs Production MCP
- Hardening the FastMCP Backend for Nginx Proxying
- Multi-Worker Scaling & Mcp-Session-Id Stickiness
- Verification & Smoke Testing the Proxy
- Frequently Asked Questions
- Why do MCP SSE connections drop after 60 seconds behind Nginx?
- Why are FastMCP tool results delayed until the connection closes in Nginx?
- Which headers must Nginx forward for MCP Streamable HTTP?
- Should I use HTTP/1.1 or HTTP/2 between Nginx and a Python FastMCP backend?
Want to build production-ready AI?
Subscribe to StackMindset to receive actionable systems engineering checklists and code walkthroughs. No spam, only technical insights.
Quick Solution: Production Nginx Config for MCP Servers
Remote Model Context Protocol (MCP) servers running SSE or Streamable HTTP fail behind default Nginx reverse proxies with ERR_INCOMPLETE_CHUNKED_ENCODING, silent 60-second disconnects, and stalled tool calls. Nginx buffers upstream responses and closes idle connections after 60 seconds by default.
Drop this location block into your Nginx server configuration (nginx>=1.24, tested with fastmcp==2.2.0 on Uvicorn 0.34.0 and Docker 26+) to disable buffering, preserve Mcp-Session-Id headers, and keep long-lived agent streams open:
upstream mcp_backend {
server mcp-server:8000;
keepalive 32;
}
server {
listen 443 ssl http2;
server_name mcp.internal.example.com;
location ~ ^/(mcp|sse|messages) {
proxy_pass http://mcp_backend;
proxy_http_version 1.1;
# Disable all buffering so JSON-RPC SSE chunks flush immediately
proxy_buffering off;
proxy_request_buffering off;
proxy_cache off;
chunked_transfer_encoding on;
# Prevent 60s idle drops during multi-step LLM reasoning
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_connect_timeout 10s;
# Clear Connection header for HTTP/1.1 keepalive; forward MCP headers
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Mcp-Session-Id $http_mcp_session_id;
proxy_set_header Last-Event-ID $http_last_event_id;
}
}
sequenceDiagram
participant Client as "MCP Client (Claude / Cursor / Agent)"
participant Nginx as "Nginx Reverse Proxy (TLS + HTTP/2)"
participant FastMCP as "FastMCP + Uvicorn (HTTP/1.1)"
Client->>Nginx: "POST /mcp (Authorization + Mcp-Session-Id)"
Nginx->>FastMCP: "Proxy HTTP/1.1 (proxy_buffering off)"
FastMCP-->>Nginx: "200 OK (text/event-stream + X-Accel-Buffering: no)"
Nginx-->>Client: "Immediate SSE Flush (0ms Buffer Hold)"
Note over Client,FastMCP: "Idle up to 3600s without 60s proxy_read_timeout"
Why Default Nginx Breaks MCP Transports
MCP Streamable HTTP and SSE transports rely on unbuffered, long-lived HTTP responses where individual JSON-RPC messages are flushed incrementally as
text/event-streamframes rather than delivered as a single content-length payload.
Standard REST APIs return complete JSON bodies and close or reuse the socket within milliseconds. MCP servers behave differently across three dimensions:
- Response Buffering Stalls: Nginx allocates
proxy_buffer_size(typically 4KB or 8KB depending on OS page size) before writing bytes to the client socket. A 180-byte MCPtools/listornotifications/progressframe sits in memory until the buffer fills or the backend closes the connection. - 60-Second Reasoning Timeouts: When an agent receives a tool result and spends 75 seconds running a reasoning model pass before issuing the next tool call, Nginx hits
proxy_read_timeout 60sand tears down the SSE stream. - Header Stripping & Multi-Worker Routing: By default, Nginx strips underscores or drops non-standard session affinity if
underscores_in_headersor explicit header forwarding is omitted, breaking statefulMcp-Session-Idtracking.
Transport Parameter Matrix: Default Nginx vs Production MCP
| Directive / Setting | Nginx Default | Production MCP Value | Impact on Agent Reliability |
|---|---|---|---|
proxy_buffering | on | off | Eliminates 4KB-8KB stall on SSE tool responses |
proxy_request_buffering | on | off | Streams large client POST /mcp payloads without temp disk writes |
proxy_read_timeout | 60s | 3600s | Prevents mid-session disconnects during slow LLM inference |
proxy_http_version | 1.0 | 1.1 | Enables keepalive upstream pools and clean chunked framing |
X-Accel-Buffering | Unset | no (from backend) | Acts as a per-response safety net if Nginx config is shared |
gzip on text/event-stream | Often on | off | Prevents compression buffers from holding small SSE events |
If you are migrating legacy stdio tools or upgrading older SSE endpoints, review the FastMCP Streamable HTTP and OAuth 2.1 migration guide before finalizing your Nginx routes.
Hardening the FastMCP Backend for Nginx Proxying
Nginx configuration alone is not enough if your Python backend omits X-Accel-Buffering: no, runs without Bearer token checks, or lacks an SSE keepalive heartbeat. The following complete FastAPI + FastMCP (fastmcp==2.2.0, fastapi==0.115.8, uvicorn==0.34.0) server enforces token verification, emits X-Accel-Buffering: no via ASGI middleware, and exposes a /healthz endpoint for Docker healthchecks.
import os
import secrets
from typing import Callable, Awaitable
from fastapi import FastAPI, Request, Response, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from starlette.middleware.base import BaseHTTPMiddleware
from fastmcp import FastMCP
import uvicorn
# Pinned expectations: fastmcp==2.2.0, fastapi==0.115.8, uvicorn==0.34.0
MCP_API_TOKEN = os.environ.get("MCP_API_TOKEN", "")
if not MCP_API_TOKEN:
raise RuntimeError("MCP_API_TOKEN environment variable must be set.")
mcp = FastMCP("production-proxy-server")
security = HTTPBearer(auto_error=False)
@mcp.tool()
def check_service_quota(service_name: str) -> dict[str, str | int]:
"""Return current rate-limit quota for an internal service."""
allowed_services = {"billing-api": 1200, "inventory-db": 450, "search-index": 3000}
if service_name not in allowed_services:
raise ValueError(f"Unknown service: {service_name}")
return {"service": service_name, "remaining_rpm": allowed_services[service_name]}
class SSEProxyHeadersMiddleware(BaseHTTPMiddleware):
"""Ensure Nginx and CDN proxies never buffer or compress MCP event streams."""
async def dispatch(
self, request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response:
if request.url.path.startswith(("/mcp", "/sse", "/messages")):
creds: HTTPAuthorizationCredentials | None = await security(request)
if creds is None or not secrets.compare_digest(creds.credentials, MCP_API_TOKEN):
return Response(
content='{"error":"Unauthorized MCP client"}',
status_code=status.HTTP_401_UNAUTHORIZED,
media_type="application/json",
)
response = await call_next(request)
response.headers["X-Accel-Buffering"] = "no"
response.headers["Cache-Control"] = "no-cache, no-transform"
return response
app = FastAPI(title="Hardened MCP Proxy Backend")
app.add_middleware(SSEProxyHeadersMiddleware)
@app.get("/healthz")
async def healthz() -> dict[str, str]:
return {"status": "ok"}
# Mount FastMCP Streamable HTTP / SSE ASGI app at root
app.mount("/", mcp.http_app())
if __name__ == "__main__":
uvicorn.run(
app,
host="0.0.0.0",
port=8000,
proxy_headers=True,
forwarded_allow_ips="*",
timeout_keep_alive=75,
)
Notice timeout_keep_alive=75 in uvicorn.run(). Uvicorn defaults to 5 seconds for idle keepalive sockets. If Nginx keeps an upstream connection pooled for 60 seconds and Uvicorn closes it at 5 seconds, Nginx intermittently logs upstream prematurely closed connection while reading response header from upstream (502 Bad Gateway). Setting Uvicorn’s keepalive above Nginx’s upstream idle timeout eliminates those race-condition 502s.
For deeper container isolation, non-root UID enforcement, and path allowlisting inside your tools, follow our Docker sandboxing and token auth guide for MCP servers.
Multi-Worker Scaling & Mcp-Session-Id Stickiness
When running multiple FastMCP replicas behind Nginx (uvicorn --workers 4 or multiple Docker containers), an in-memory MCP session created on Worker 1 will return 404 Session Not Found if the client’s next POST /mcp lands on Worker 2.
You have two production choices:
- Sticky Routing by
Mcp-Session-Id(Nginx Plus / OpenResty / Hash): Route requests usinghash $http_mcp_session_id consistent;in yourupstreamblock so a session always hits the same backend container. - Single Async Worker Per Container + External State: Run 1 async Uvicorn process per container (Python
asynciohandles hundreds of concurrent SSE streams easily) and store tool/agent state in Redis or Postgres.
Here is a complete docker-compose.yml pairing Nginx 1.27-alpine with a non-root FastMCP container and health checks:
services:
mcp-server:
build: .
image: stackmindset/mcp-backend:latest
environment:
- MCP_API_TOKEN=${MCP_API_TOKEN}
expose:
- "8000"
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthz')"]
interval: 10s
timeout: 3s
retries: 3
restart: unless-stopped
nginx-proxy:
image: nginx:1.27-alpine
ports:
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
- ./certs:/etc/nginx/certs:ro
depends_on:
mcp-server:
condition: service_healthy
restart: unless-stopped
When deploying MCP tools that process sensitive internal payloads, pair this network boundary with client-side prompt scrubbing using PriviPaste before data ever leaves your workstation, and check building production AI agents with MCP or our production FastMCP stdio server blueprint for local-only workflows.
Verification & Smoke Testing the Proxy
After reloading Nginx (nginx -t && nginx -s reload), verify that buffering is genuinely disabled by inspecting response headers and measuring chunk arrival with curl -N (the -N / --no-buffer flag disables curl’s own output buffering):
curl -N -i -X POST https://mcp.internal.example.com/mcp \
-H "Authorization: Bearer $MCP_API_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"curl-probe","version":"1.0"}}}'
Confirm three things in the output:
- HTTP status is
200 OK(and401 UnauthorizedwhenAuthorizationis omitted). - Response headers include
X-Accel-Buffering: noandMcp-Session-Id: <uuid>. - The
data:JSON-RPC payload prints instantaneously without waiting for the socket to close.
Frequently Asked Questions
Why do MCP SSE connections drop after 60 seconds behind Nginx?
Nginx defaults to proxy_read_timeout 60s and proxy_send_timeout 60s. If an LLM agent pauses between tool calls for more than 60 seconds without an SSE heartbeat, Nginx closes the upstream TCP socket and returns a 504 or premature stream EOF to the client.
Why are FastMCP tool results delayed until the connection closes in Nginx?
Nginx enables proxy_buffering on by default for upstream HTTP responses. Small JSON-RPC payloads over text/event-stream sit inside Nginx memory buffers instead of flushing to the client. Disabling proxy_buffering and setting proxy_cache off forces immediate chunked delivery.
Which headers must Nginx forward for MCP Streamable HTTP?
For the MCP 2025-03-26 Streamable HTTP transport, Nginx must preserve Authorization for Bearer tokens, Mcp-Session-Id for stateful session affinity, Accept for content negotiation (application/json or text/event-stream), and Last-Event-ID for stream resumption.
Should I use HTTP/1.1 or HTTP/2 between Nginx and a Python FastMCP backend?
Use HTTP/1.1 (proxy_http_version 1.1) with an empty Connection header between Nginx and Uvicorn or FastMCP. Clients can still connect to Nginx over HTTP/2 or HTTP/3 with TLS, while upstream keeps clean long-lived keepalive sockets without chunked-encoding translation bugs.
Want to build production-ready AI?
Subscribe to StackMindset to receive actionable systems engineering checklists and code walkthroughs. No spam, only technical insights.
Written by S L Manikanta
AI Engineer specializing in agentic workflows, multi-step LLM validation pipelines, and secure cloud environments. Sharing practical lessons from building software.
Related Articles
What is Model Context Protocol (MCP)? Complete Technical Reference (2026)
A definitive guide to the Model Context Protocol (MCP). Learn how Anthropic's open standard enables AI assistants to securely connect to external tools, databases, and APIs.
Building High-Throughput Production MCP Servers with Python FastMCP and stdio
Build a production-ready MCP server with FastMCP over stdio transport. Covers tool registration, schema validation, error handling, concurrency limits, and Claude Code integration.
Securing Local and Remote MCP Servers: Token Auth, Sandboxing, and Least Privilege
Harden your MCP server against prompt injection, unauthorized access, and filesystem escapes. Covers OAuth token verification, Docker sandboxing, path allowlists, and rate limiting.