NerdlyBuilds

Stateless MCP, Two Workers, One Confirmation Prompt: Where the Round Trip Breaks

The 2026-07-28 MCP spec says any worker can serve any request. I put two behind a dumb round-robin balancer and found the three settings that make it true.

·8 min read

The headline feature of the 2026-07-28 Model Context Protocol spec is that the protocol went stateless. No initialize handshake, no Mcp-Session-Id header, no session pinned to one process. Every request carries its own protocol version, client info and capabilities. In theory you can put five copies of your MCP server behind any load balancer and stop caring which one answers.

That theory holds for plain tool calls. It gets interesting the moment a tool needs to ask the user something, like “really cancel that print job?” Under the new spec, that question is no longer a live server-to-client request on an open stream. The server answers the first call with “input required” plus a sealed blob called requestState, and the client retries the call with the user’s answer and that blob attached. If the retry lands on a different worker, that worker has to be able to open the blob.

So I set up the most hostile setup I could think of: two workers and a load balancer that strictly alternates between them, so the first call and its retry always hit different processes. Then I broke it in every way I could find and wrote down the fixes.

Tested with: Python 3.13.18, mcp 2.3.0 (server and client), mcp 1.30.0 (legacy client), uvicorn 0.54.0, starlette 1.10.0, httpx2 2.16.2, on Linux x86_64, 17 November 2026.

What changed in the spec, briefly

From the official 2026-07-28 announcement:

  • The initialize/initialized exchange and the Mcp-Session-Id header are retired. Each request carries its own context in _meta.
  • Streamable HTTP requests must include Mcp-Method and Mcp-Name headers, so gateways and rate limiters can route without parsing the JSON body.
  • Server-initiated elicitation/create, sampling/createMessage and roots/list are replaced by Multi Round-Trip Requests (MRTR): the server returns an input_required result and the client retries with answers attached.

The Python SDK’s deploy guide says the quiet part: by default each process generates its own random key for sealing requestState, so a retry that reaches a different worker fails. I wanted to see that failure for myself, see what it looks like from the client side, and check that the documented fix works.

If you haven’t touched the v2 Python SDK yet, my read-only SQLite MCP server guide covers the v1-to-v2 renames (FastMCP is now MCPServer) and is a gentler place to start.

The setup: a tool that asks before it acts

Two virtualenvs, because later I test an old client too:

python3 -m venv .venv
. .venv/bin/activate
pip install "mcp==2.3.0" "uvicorn==0.54.0"

The server has one tool. Cancelling a print job is the kind of thing you want a human to confirm, so the tool declares a parameter that’s filled by asking the user rather than by the model. In SDK 2.x you do that with Resolve and Elicit: the resolver returns an Elicit marker, and the framework turns it into an input_required round trip on 2026-07-28 clients.

# server.py, first version: SDK defaults
import os
from typing import Annotated

from pydantic import BaseModel
from mcp.server import MCPServer
from mcp.server.mcpserver.resolve import Elicit, Resolve

WORKER = os.environ.get("WORKER", "?")

mcp = MCPServer("print-queue")


class Confirm(BaseModel):
    confirm: bool


def ask_first(job_id: str) -> Elicit[Confirm]:
    return Elicit(f"Really cancel print job {job_id}?", Confirm)


@mcp.tool()
def cancel_print(job_id: str, answer: Annotated[Confirm, Resolve(ask_first)]) -> str:
    """Cancel a queued 3D print job, after the user confirms."""
    if not answer.confirm:
        return f"Kept job {job_id} (answered on worker {WORKER})"
    return f"Cancelled job {job_id} (answered on worker {WORKER})"


app = mcp.streamable_http_app()

The WORKER variable is only there so the result tells us which process produced it.

A load balancer with no manners

Real load balancers have sticky-session options. This one doesn’t. It forwards each request to the next backend in the list and logs the Mcp-Method header, which is exactly the kind of routing the new headers are meant to enable.

# lb.py
"""A deliberately dumb round-robin load balancer: no sticky sessions."""
import itertools

import httpx2
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import StreamingResponse
from starlette.routing import Route

BACKENDS = itertools.cycle(["http://127.0.0.1:8001", "http://127.0.0.1:8002"])
client = httpx2.AsyncClient(timeout=30)


async def forward(request: Request):
    backend = next(BACKENDS)
    print(f"{request.method} {request.headers.get('mcp-method', '-')} -> {backend}", flush=True)
    headers = {k: v for k, v in request.headers.items() if k.lower() not in ("host", "content-length")}
    upstream = await client.send(
        client.build_request(request.method, backend + request.url.path,
                             headers=headers, content=await request.body()),
        stream=True,
    )
    return StreamingResponse(upstream.aiter_raw(), status_code=upstream.status_code,
                             headers={k: v for k, v in upstream.headers.items()
                                      if k.lower() not in ("content-length", "transfer-encoding")})


app = Starlette(routes=[Route("/{path:path}", forward, methods=["GET", "POST", "DELETE"])])

httpx2 is the HTTP client that mcp 2.3.0 pulls in as a dependency, so it was already installed. Plain httpx was not, which surprised me the first time I typed import httpx.

And a client that always says yes:

# client.py
import asyncio
import sys

from mcp import Client
from mcp.shared.exceptions import MCPError
from mcp.types import ElicitResult


async def say_yes(context, params):
    print("server asks:", params.message)
    return ElicitResult(action="accept", content={"confirm": True})


async def main(url):
    async with Client(url, elicitation_callback=say_yes) as client:
        try:
            result = await client.call_tool("cancel_print", {"job_id": "benchy-042"})
        except MCPError as e:
            print(f"MCPError {e.code}: {e}")
            return
        print("result:", result.content[0].text)


asyncio.run(main(sys.argv[1]))

Start everything:

WORKER=A uvicorn server:app --port 8001 > a.log 2>&1 &
WORKER=B uvicorn server:app --port 8002 > b.log 2>&1 &
uvicorn lb:app --port 8000 > lb.log 2>&1 &

Run 1: straight to one worker

Pointing the client at worker A directly works, as expected:

$ python client.py http://127.0.0.1:8001/mcp
server asks: Really cancel print job benchy-042?
result: Cancelled job benchy-042 (answered on worker A)

Run 2: through the balancer

$ python client.py http://127.0.0.1:8000/mcp
server asks: Really cancel print job benchy-042?
MCPError -32602: Invalid or expired requestState

The balancer log shows why:

POST server/discover -> http://127.0.0.1:8001
POST tools/call -> http://127.0.0.1:8002
POST tools/call -> http://127.0.0.1:8001

The client calls server/discover first, then the first tools/call lands on B. B seals the question into requestState with its own key. The retry lands on A, and A has never seen that key. Worker A’s log says so plainly:

requestState rejected on tools/call: unknown key

That log line is the only place the real reason shows up. The client gets a generic -32602, which is the JSON-RPC “invalid params” code. If your logs are scattered across replicas, you would be chasing this for a while. The SDK docs warn about exactly this, but it’s easy to miss until you see it.

Sequence diagram: the client's first tools/call goes through the round-robin balancer to worker B, which returns input_required with a requestState sealed by B's key; the retry with the user's answer goes to worker A, which cannot unseal it and returns error -32602 unless both workers share the same key and audience

What’s actually on the wire

I added a debug print to the balancer to see the retry. Here are the headers and the body of the second tools/call, with the sealed blob shortened:

{'mcp-protocol-version': '2026-07-28', 'mcp-method': 'tools/call', 'mcp-name': 'cancel_print'}
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{
  "inputResponses":{"server:ask_first":{"action":"accept","content":{"confirm":true}}},
  "requestState":"v1.AqR-zYe90R1M5Atjul23D7ee…",
  "name":"cancel_print","arguments":{"job_id":"benchy-042"},
  "_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28", …}}}

And this is the first response, which I got by calling worker A with curl:

curl -sS http://127.0.0.1:8001/mcp \
  -H 'content-type: application/json' \
  -H 'accept: application/json, text/event-stream' \
  -H 'mcp-protocol-version: 2026-07-28' \
  -H 'mcp-method: tools/call' -H 'mcp-name: cancel_print' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"cancel_print","arguments":{"job_id":"benchy-042"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"curl","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}}}'
{"jsonrpc":"2.0","id":1,"result":{
  "inputRequests":{"server:ask_first":{"method":"elicitation/create","params":{
    "message":"Really cancel print job benchy-042?","mode":"form",
    "requestedSchema":{"properties":{"confirm":{"title":"Confirm","type":"boolean"}},"required":["confirm"],"type":"object"}}}},
  "requestState":"v1.AqR-zde_HOrD-D4KADjiGf1W…",
  "resultType":"input_required",
  "_meta":{"io.modelcontextprotocol/serverInfo":{"name":"print-queue-a","version":""}}}}

Two things worth noticing. The question key, server:ask_first, comes from the resolver’s function name. And the server is strict about the new headers: when I left out mcp-method, it refused with 400 and {"code":-32020,"message":"mcp-method header does not match the request body's method"}. If you write a gateway or a hand-rolled client, set both headers.

Fix 1: share the sealing key

MCPServer takes a request_state_security argument. Give every worker the same key:

# server.py, fixed
import os
from typing import Annotated

from pydantic import BaseModel
from mcp.server import MCPServer
from mcp.server.mcpserver.resolve import Elicit, Resolve
from mcp.server.request_state import RequestStateSecurity

WORKER = os.environ.get("WORKER", "?")

mcp = MCPServer(
    os.environ.get("SERVER_NAME", "print-queue"),
    request_state_security=RequestStateSecurity(
        keys=[os.environ["MCP_STATE_KEY"]],
        audience="print-queue-fleet",
    ),
)

# ... Confirm, ask_first and cancel_print exactly as before ...

app = mcp.streamable_http_app()
export MCP_STATE_KEY=$(python -c "import secrets; print(secrets.token_hex(32))")
WORKER=A uvicorn server:app --port 8001 > a.log 2>&1 &
WORKER=B uvicorn server:app --port 8002 > b.log 2>&1 &

I tested this in two steps. With only the shared key (no audience line, same server name on both workers):

$ python client.py http://127.0.0.1:8000/mcp
server asks: Really cancel print job benchy-042?
result: Cancelled job benchy-042 (answered on worker B)

Note what that result says: the tool body ran on whichever worker got the retry, not the one that asked the question. Keep your tool bodies free of per-process state, and keep resolvers cheap, since the SDK source notes they may re-run on every round.

The keys argument is a list for rotation. The SDK’s docstring describes the rollout: keys=[old, new], then keys=[new, old], then keys=[new] after one TTL. The default TTL is 600 seconds.

It also refuses weak keys at startup, which I found out by trying one:

ValueError: request-state keys must be at least 32 bytes of secret randomness; keys[0] is 7 bytes. Generate one with: python -c "import secrets; print(secrets.token_hex(32))"

Fix 2: same name, or a shared audience

This is the trap I’d most likely have walked into on a real cluster. It’s common to give each pod its own name so logs are easier to read. The server name ends up as an audience claim inside requestState. With a shared key but different names (SERVER_NAME=print-queue-a and print-queue-b, no audience line), the retry failed again:

server asks: Really cancel print job benchy-042?
MCPError -32602: Invalid or expired requestState

The worker log this time:

requestState rejected on tools/call: audience

Same client error, different cause. Adding audience="print-queue-fleet" to RequestStateSecurity, as in the fixed server above, made the per-pod names work:

server asks: Really cancel print job benchy-042?
result: Cancelled job benchy-042 (answered on worker A)

Old clients don’t get the stateless deal

Your server speaks 2026-07-28, but not every client does yet. I installed mcp==1.30.0 in a second virtualenv and used its classic ClientSession with the default (stateful) server:

# client_v1.py
import asyncio
import sys

from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
from mcp.types import ElicitResult


async def say_yes(context, params):
    print("server asks:", params.message)
    return ElicitResult(action="accept", content={"confirm": True})


async def main(url):
    async with streamablehttp_client(url) as (read, write, _):
        async with ClientSession(read, write, elicitation_callback=say_yes) as session:
            init = await session.initialize()
            print("negotiated:", init.protocolVersion)
            result = await session.call_tool("cancel_print", {"job_id": "benchy-042"})
            print("result:", result.content[0].text)


asyncio.run(main(sys.argv[1]))

Directly against worker A it negotiated 2025-11-25 and worked fine, elicitation included. Through the balancer it died after the handshake:

negotiated: 2025-11-25
mcp.shared.exceptions.McpError: Session terminated

The workers’ logs show 404 Not Found: the legacy session lives in one worker’s memory, and the next request went to the other one. A second v1 script that only calls list_tools() failed the same way, so this isn’t about elicitation. Legacy clients need sticky sessions.

The deploy guide’s other option is stateless_http=True:

app = mcp.streamable_http_app(stateless_http=True)

With that, the v1 list_tools() script worked through the balancer (tools: ['cancel_print']), and the v2 client still did its elicitation round trip fine. But the v1 client’s cancel_print failed:

McpError: Cannot send 'elicitation/create': this transport context has no back-channel for server-initiated requests.

That matches the docs: in legacy stateless mode there is no open stream for the server to ask questions on. I didn’t test sticky sessions here, since my toy balancer doesn’t have them.

Results table for the eight runs through the round-robin balancer: v2 client with default per-process keys fails with -32602; shared key works; shared key with per-pod names fails on audience; shared key plus shared audience works; v1 client in default mode fails with Session terminated; with stateless_http=True the v1 client can list tools but its elicitation fails, while the v2 client works

What went wrong when I tested it

Apart from the failures above, which were the point, a few self-inflicted ones:

  • Crashed workers, misleading error. After restarting in a fresh shell, the client got 500 Internal Server Error from the balancer. Both workers had exited with code 1 because MCP_STATE_KEY wasn’t set in that shell, and os.environ["MCP_STATE_KEY"] raised on import. The balancer turned “backend is down” into a 500. Fail loudly at startup is the right behavior, but check the worker logs before the client error.
  • Wrong virtualenv. With the v1 venv active, uvicorn server:app ran against mcp 1.30.0, which has no mcp.server.MCPServer, and the workers exited at once. The client reported All connection attempts failed. I fixed it by calling .venv/bin/uvicorn explicitly.
  • No httpx. The 2.x SDK depends on httpx2, not httpx, so import httpx failed in the fresh venv. The balancer uses httpx2.
  • Traceback noise. My first client had no try/except, so the -32602 came out as a long ExceptionGroup traceback with the useful line at the very bottom. Catching MCPError and printing e.code made the runs readable.

When this matters and when it doesn’t

You need the shared key and audience if you run more than one process behind anything that can route requests differently (Kubernetes services, uvicorn --workers N, a serverless platform) and any tool asks for input, samples, or uses Resolve(...). The deploy guide notes that tools using Resolve(...) dependencies count as multi-round-trip tools and are affected too.

You can skip it if you run a single process, or your tools never ask for anything mid-call. Plain tool calls from 2026-07-28 clients don’t depend on which worker answers. For a local stdio server, none of this applies; see my notes on startup time for stdio MCP servers instead.

Keep sticky sessions anyway if you still have clients on the 2025-11-25 protocol and need their elicitation to work. stateless_http=True gets old clients through for plain calls only.

Two things I didn’t test: change notifications across replicas (the deploy guide says the SDK only ships an in-process SubscriptionBus, so you need your own Redis or NATS adapter), and the TLS and --proxy-headers setup for a real reverse proxy.

Sources

How this was made: researched and drafted with AI assistance, with every code sample run and tested before publishing, then reviewed by Colby.

Get an email when I publish something new