Skip to content
Autonomous Agents & MCP #mcp#fastmcp#oauth2#streamable-http#python#ai-agents

Migrating MCP Servers to Streamable HTTP with OAuth 2.1

S

S L Manikanta

Nov 28, 2026 • 8 min read

bolt Key Takeaways

  • MCP deprecated the split HTTP+SSE transport in favor of a single /mcp endpoint using Streamable HTTP (POST for JSON-RPC requests, optional SSE for server-to-client streams).
  • Stateless Streamable HTTP servers run behind standard round-robin load balancers without sticky sessions or shared Redis session registries.
  • Remote MCP servers must act as OAuth 2.1 Resource Servers exposing /.well-known/oauth-protected-resource metadata and validating JWT Bearer scopes per tool.
  • Pin fastmcp>=2.3.0 and mcp>=1.8.0 to get native Streamable HTTP and TokenVerifier middleware without custom Starlette ASGI plumbing.
✉ Newsletter

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: Stateless Streamable HTTP with OAuth 2.1

Legacy Model Context Protocol (MCP) HTTP+SSE servers fail behind round-robin load balancers because they require a persistent /sse stream pinned to the same worker that handles /messages. Switching to Streamable HTTP (fastmcp>=2.3.0, mcp>=1.8.0, Python 3.12+) consolidates all traffic onto a single /mcp endpoint and enables stateless horizontal scaling with OAuth 2.1 Bearer token verification.

pip install "fastmcp>=2.3.0,<3.0.0" "mcp>=1.8.0" "pyjwt[crypto]>=2.9.0" "httpx>=0.27.2" "uvicorn>=0.32.0"

Run the minimal stateless Streamable HTTP server:

from fastmcp import FastMCP

mcp = FastMCP(name="billing-mcp", stateless_http=True)

@mcp.tool()
async def get_invoice_status(invoice_id: str) -> dict[str, str]:
    """Return settlement status for an invoice ID."""
    return {"invoice_id": invoice_id, "status": "settled"}

if __name__ == "__main__":
    mcp.run(transport="streamable-http", host="0.0.0.0", port=8000, path="/mcp")
sequenceDiagram
    participant Client as MCP Client (Agent)
    participant LB as Round-Robin ALB
    participant AS as OAuth 2.1 Auth Server
    participant RS as FastMCP Streamable HTTP (/mcp)

    Client->>RS: POST /mcp (no token)
    RS-->>Client: 401 Unauthorized + WWW-Authenticate (resource_metadata)
    Client->>RS: GET /.well-known/oauth-protected-resource
    RS-->>Client: AS issuer URL + required scopes
    Client->>AS: Auth Code + PKCE S256
    AS-->>Client: Signed JWT Access Token
    Client->>LB: POST /mcp + Bearer JWT
    LB->>RS: Forward to any stateless worker
    RS-->>Client: 200 application/json or text/event-stream

Why Legacy HTTP+SSE Fails in Production

Streamable HTTP is the modern MCP transport specification that replaces dual-endpoint HTTP+SSE with a single /mcp endpoint, supporting both synchronous JSON responses and per-request Server-Sent Events over standard stateless HTTP infrastructure.

In the 2024-11-05 MCP specification, remote servers exposed /sse for server-to-client messages and /messages?sessionId=... for client-to-server JSON-RPC calls. When deployed across multiple Kubernetes pods or ECS tasks, three failure modes occur:

  1. Split-Brain Session Routing: A client opens /sse on Pod A, then its POST /messages lands on Pod B. Pod B has no in-memory queue for sessionId and returns 404 Session not found.
  2. Idle Connection Drops: Cloud ALBs and corporate NAT gateways terminate idle SSE sockets after 60 to 300 seconds, forcing full MCP initialize handshakes on every drop.
  3. Ad-Hoc Auth Headers: Legacy deployments relied on static X-API-Key headers that couldn’t enforce per-user scopes, short-lived tokens, or dynamic client registration.
Transport & Auth MetricLegacy HTTP+SSE (2024-11-05)Streamable HTTP + OAuth 2.1 (2025-03-26+)Production Impact
Endpoint TopologyDual (/sse + /messages)Single (/mcp)Eliminates split-brain routing across pods
Load Balancer RequirementSticky sessions (cookie/IP hash)Standard round-robinZero sticky-session state or Redis dependency
Response ModeAlways async over persistent SSEapplication/json or per-request SSESimple tool calls skip SSE framing overhead
Auth StandardStatic API key / custom headersOAuth 2.1 Resource Server + PKCEPer-user JWT scopes and short-lived tokens
DiscoveryManual endpoint configuration/.well-known/oauth-protected-resourceCompliant clients auto-discover Auth Server

For local subprocess integrations that don’t cross network boundaries, building FastMCP Python stdio servers remains the lowest-overhead option. Streamable HTTP is specifically for shared, remote, or multi-tenant deployments.


Production Implementation: FastMCP Streamable HTTP with JWT Scope Enforcement

To harden a remote MCP server, configure it as an OAuth 2.1 Resource Server. The server never handles user passwords or mints tokens; it validates asymmetric RS256/ES256 JWTs against your Identity Provider’s JWKS endpoint (Auth0, Keycloak, Okta, or Entra ID) and enforces tool-level scopes.

Save the following production-ready server as server.py. Tested on Python 3.12, fastmcp==2.3.4, pyjwt==2.9.0, and httpx==0.27.2.

import os
import time
import logging
from typing import Any

import httpx
import jwt
from jwt import PyJWKClient, InvalidTokenError
from fastmcp import FastMCP
from fastmcp.server.auth import TokenVerifier, AccessToken
from fastmcp.server.dependencies import get_access_token
from mcp.server.auth.settings import AuthSettings
from pydantic import AnyHttpUrl, BaseModel, Field

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("mcp.oauth")

ISSUER_URL = os.environ.get("OAUTH_ISSUER_URL", "https://auth.example.com/")
JWKS_URL = os.environ.get("OAUTH_JWKS_URL", "https://auth.example.com/.well-known/jwks.json")
AUDIENCE = os.environ.get("OAUTH_AUDIENCE", "https://mcp.example.com/mcp")
RESOURCE_URL = os.environ.get("MCP_RESOURCE_URL", "https://mcp.example.com/mcp")


class JWTScopeVerifier(TokenVerifier):
    """Validates OAuth 2.1 Bearer JWTs using cached JWKS keys."""

    def __init__(self, jwks_url: str, issuer: str, audience: str) -> None:
        self._jwk_client = PyJWKClient(jwks_url, cache_keys=True, lifespan=3600)
        self._issuer = issuer
        self._audience = audience

    async def verify_token(self, token: str) -> AccessToken | None:
        try:
            signing_key = self._jwk_client.get_signing_key_from_jwt(token)
            claims: dict[str, Any] = jwt.decode(
                token,
                signing_key.key,
                algorithms=["RS256", "ES256"],
                audience=self._audience,
                issuer=self._issuer,
                options={"require": ["exp", "iss", "aud", "sub"]},
            )
            raw_scope = claims.get("scope", "")
            scopes = raw_scope.split() if isinstance(raw_scope, str) else list(raw_scope)
            return AccessToken(
                token=token,
                client_id=str(claims.get("azp") or claims["sub"]),
                scopes=scopes,
                expires_at=int(claims["exp"]),
            )
        except InvalidTokenError as exc:
            logger.warning("JWT verification failed: %s", exc)
            return None
        except Exception as exc:
            logger.error("Unexpected JWKS verification error: %s", exc)
            return None


auth_settings = AuthSettings(
    issuer_url=AnyHttpUrl(ISSUER_URL),
    resource_server_url=AnyHttpUrl(RESOURCE_URL),
    required_scopes=["mcp:read"],
)

mcp = FastMCP(
    name="enterprise-ledger-mcp",
    stateless_http=True,
    token_verifier=JWTScopeVerifier(JWKS_URL, ISSUER_URL, AUDIENCE),
    auth=auth_settings,
)


class LedgerQuery(BaseModel):
    account_id: str = Field(..., min_length=4, max_length=64)
    limit: int = Field(default=10, ge=1, le=100)


@mcp.tool()
async def query_ledger(params: LedgerQuery) -> dict[str, Any]:
    """Read-only ledger query requiring mcp:read scope."""
    token = get_access_token()
    if token is None or "mcp:read" not in token.scopes:
        raise PermissionError("Missing required scope: mcp:read")

    return {
        "account_id": params.account_id,
        "principal": token.client_id,
        "returned_at": int(time.time()),
        "entries": [{"tx_id": "tx_9901", "amount_cents": 42500}],
    }


@mcp.tool()
async def approve_payout(payout_id: str, amount_cents: int) -> dict[str, Any]:
    """Privileged payout approval requiring elevated mcp:write scope."""
    token = get_access_token()
    if token is None or "mcp:write" not in token.scopes:
        raise PermissionError("Insufficient privileges: mcp:write scope required")

    if amount_cents <= 0:
        raise ValueError("amount_cents must be positive")

    return {
        "payout_id": payout_id,
        "approved_by": token.client_id,
        "amount_cents": amount_cents,
        "status": "queued",
    }


if __name__ == "__main__":
    mcp.run(
        transport="streamable-http",
        host="0.0.0.0",
        port=int(os.environ.get("PORT", "8000")),
        path="/mcp",
    )

How Client Discovery Works

When an agent client (such as a LangGraph agent connected to MCP tools or Claude Desktop) hits POST /mcp without a valid Bearer token, AuthSettings returns 401 Unauthorized with:

WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"

The client fetches /.well-known/oauth-protected-resource, reads authorization_servers, executes an OAuth 2.1 Authorization Code + PKCE (S256) flow against your IdP, and retries POST /mcp with the minted JWT. If you also run sensitive local data sanitization before sending payloads to external LLMs, pair this pattern with PriviPaste so PII never enters tool arguments.


Migrating an Existing SSE Client & Verifying Stateless Scaling

To connect a Python client to the migrated Streamable HTTP server with automatic OAuth handling and connection timeouts, use fastmcp.Client:

import asyncio
import logging
from fastmcp import Client
from fastmcp.client.auth import OAuth
from fastmcp.client.transports import StreamableHttpTransport

logging.basicConfig(level=logging.INFO)


async def run_client() -> None:
    transport = StreamableHttpTransport(
        url="https://mcp.example.com/mcp",
        auth=OAuth(scopes=["mcp:read"]),
    )
    try:
        async with Client(transport, timeout=15.0) as client:
            tools = await client.list_tools()
            logging.info("Discovered %d tools", len(tools))
            result = await client.call_tool(
                "query_ledger",
                {"params": {"account_id": "acct_1024", "limit": 5}},
            )
            logging.info("Tool response: %s", result.data)
    except Exception as exc:
        logging.error("MCP client call failed: %s", exc)
        raise


if __name__ == "__main__":
    asyncio.run(run_client())

Hardening Checklist for Containerized Deployments

Before cutting over production traffic from /sse to /mcp, verify these container and proxy settings (see hardening MCP servers in Docker sandboxes for seccomp and non-root container rules):

  1. Disable Proxy Buffering: If running behind Nginx or Envoy, set X-Accel-Buffering: no and proxy_buffering off; on /mcp so optional text/event-stream responses flush immediately instead of stalling until the response closes.
  2. Enforce Audience (aud) Claim Validation: Never skip audience=self._audience in jwt.decode. Without strict aud binding, a valid JWT issued for a different internal service can be replayed against your MCP server (confused deputy attack).
  3. Set stateless_http=True Explicitly: When stateless_http=False (legacy stateful mode), FastMCP tracks Mcp-Session-Id headers in process memory, which still breaks under multi-replica Kubernetes deployments unless you disable multi-pod scaling.
  4. Pin Timeout Budgets: Set timeout=15.0 on client transports and wrap upstream database calls inside tools with asyncio.wait_for(..., timeout=10.0) so slow downstream queries don’t exhaust Uvicorn worker slots.

Frequently Asked Questions

Why did MCP deprecate the legacy HTTP+SSE transport?

Legacy HTTP+SSE required two separate endpoints and a long-lived stateful SSE connection pinned to a single backend worker. That broke horizontal scaling behind standard round-robin load balancers and failed aggressively behind corporate proxies that drop idle connections.

How does Streamable HTTP handle server-initiated streaming without sticky sessions?

Streamable HTTP uses a single /mcp endpoint. Clients send JSON-RPC requests via HTTP POST, and the server either returns a standard application/json response or upgrades that specific HTTP response to text/event-stream for multi-step progress notifications.

How do you secure a remote Streamable HTTP MCP server with OAuth 2.1?

Configure the MCP server as an OAuth 2.1 Resource Server. Expose RFC 9728 protected resource metadata at /.well-known/oauth-protected-resource, require Bearer JWTs with PKCE-issued scopes, and reject unauthenticated requests with HTTP 401 and a WWW-Authenticate header.

Can existing stdio MCP servers migrate to Streamable HTTP without rewriting tool logic?

Yes. In FastMCP, your @mcp.tool() functions and Pydantic schemas remain unchanged. You only replace mcp.run(transport='stdio') with mcp.run(transport='streamable-http', host='0.0.0.0', port=8000) and attach an OAuth TokenVerifier.

✉ Newsletter

Want to build production-ready AI?

Subscribe to StackMindset to receive actionable systems engineering checklists and code walkthroughs. No spam, only technical insights.

S

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

Autonomous Agents & MCP
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.

Autonomous Agents & MCP
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.

Autonomous Agents & MCP
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.