Skip to content
Stateless MCP in Python: The 2026-07-28 Handle Pattern — ContentBuffer guide

Stateless MCP in Python: The 2026-07-28 Handle Pattern

K
Kodetra Technologies··10 min read Intermediate

Summary

Port your MCP server to the stateless 2026-07-28 spec using the explicit-handle pattern.

MCP just shipped its biggest revision since launch, and it changes how you deploy a server. The release candidate tagged 2026-07-28 was locked on May 21, 2026, and the final spec lands on July 28. The headline: MCP is now stateless at the protocol layer. The initialize handshake and the Mcp-Session-Id header are gone, so any request can land on any server instance.

Why this matters right now: SDK maintainers are validating against real workloads during the ten-week window before July 28, and Tier 1 SDKs are expected to ship support inside it. If you run a remote MCP server, the sticky sessions, shared session store, and gateway packet inspection you needed before are no longer required. This guide builds a working stateless endpoint from scratch in Python so you understand the wire format, not just an SDK call.

You will learn the new request shape, the explicit-handle pattern that replaces session state, multi round-trip elicitation, and the Tasks extension for long-running work. Every snippet here was run and verified before publishing.

Prerequisites

  • Python 3.10+ and a terminal.
  • Comfort reading JSON-RPC 2.0 (request/response with method, params, id).
  • pip install starlette uvicorn httpx for the HTTP and client sections.
  • Basic familiarity with what an MCP tool is (a named function with a JSON input schema). No prior MCP server experience needed.

Step 1: What 'stateless' actually changes

In the 2025-11-25 spec, calling a tool over Streamable HTTP meant establishing a session first. You sent initialize, the server returned an Mcp-Session-Id, and every later request had to carry it, pinning you to one instance:

POST /mcp HTTP/1.1
Content-Type: application/json

{"jsonrpc":"2.0","id":1,"method":"initialize",
 "params":{"protocolVersion":"2025-11-25","capabilities":{},
           "clientInfo":{"name":"my-app","version":"1.0"}}}

# server replies with an Mcp-Session-Id you must echo on EVERY later request,
# pinning you to whichever instance issued it:
POST /mcp HTTP/1.1
Mcp-Session-Id: 1868a90c-3a3f-4f5b
Content-Type: application/json

{"jsonrpc":"2.0","id":2,"method":"tools/call",
 "params":{"name":"search","arguments":{"q":"otters"}}}

In 2026-07-28 the same call is a single self-contained request. The protocol version, client info, and capabilities that used to be exchanged once now travel in _meta on every request, and routing metadata moves into headers:

POST /mcp HTTP/1.1
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tools/call
Mcp-Name: search
Content-Type: application/json

{"jsonrpc":"2.0","id":1,"method":"tools/call",
 "params":{"name":"search","arguments":{"q":"otters"},
           "_meta":{"io.modelcontextprotocol/clientInfo":
                    {"name":"my-app","version":"1.0"}}}}

Two SEPs do the heavy lifting: SEP-2575 removes the initialize/initialized handshake (a new server/discover method fetches capabilities when a client needs them up front), and SEP-2567 removes the Mcp-Session-Id header and the protocol-level session. With both gone, sticky routing and shared session stores are no longer a protocol requirement.

Step 2: Build a stateless endpoint

Here is the whole server as one pure function. It takes the request headers and the parsed JSON body and returns a JSON-RPC response. Because nothing is stored in transport state, any instance can run this for any request, which is exactly the point. Save it as stateless_mcp.py:

# stateless_mcp.py - a stateless MCP endpoint for the 2026-07-28 spec.
# No initialize handshake, no Mcp-Session-Id. Every request is self-contained.
import json, base64, secrets

PROTOCOL = "2026-07-28"
BASKETS, TASKS = {}, {}          # state lives in the APP, never the protocol

TOOLS = [
    {"name": "search", "description": "Search the web.",
     "inputSchema": {"type": "object",
                     "properties": {"q": {"type": "string"}}, "required": ["q"]}},
    {"name": "create_basket", "description": "Create a basket, returns basket_id.",
     "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
    {"name": "add_item", "description": "Add an item to an existing basket.",
     "inputSchema": {"type": "object",
                     "properties": {"basket_id": {"type": "string"},
                                    "item": {"type": "string"}},
                     "required": ["basket_id", "item"]}},
    {"name": "delete_files", "description": "Delete files after confirmation.",
     "inputSchema": {"type": "object",
                     "properties": {"paths": {"type": "array",
                                              "items": {"type": "string"}}},
                     "required": ["paths"]}},
    {"name": "generate_report", "description": "Long-running report (runs as a task).",
     "inputSchema": {"type": "object",
                     "properties": {"topic": {"type": "string"}}, "required": ["topic"]}},
]

def ok(rid, result):  return {"jsonrpc": "2.0", "id": rid, "result": result}
def err(rid, c, m):   return {"jsonrpc": "2.0", "id": rid, "error": {"code": c, "message": m}}
def text(rid, s):     return ok(rid, {"content": [{"type": "text", "text": s}]})

def handle(headers, body):
    """(headers, parsed JSON body) -> JSON-RPC response. Any instance can run this."""
    rid    = body.get("id")
    method = headers.get("Mcp-Method")

    # SEP-2243: header and body method must agree so gateways can route on the header.
    if method != body.get("method"):
        return err(rid, -32600, "Mcp-Method header disagrees with body method")

    if method == "server/discover":
        return ok(rid, {"serverInfo": {"name": "shop", "version": "1.0"},
                        "capabilities": {"tools": {},
                                         "extensions": {"io.modelcontextprotocol/tasks": {}}}})

    if method == "tools/list":                       # SEP-2549: caching metadata
        return ok(rid, {"tools": TOOLS,
                        "_meta": {"ttlMs": 600000, "cacheScope": "shared"}})

    if method == "tasks/get":
        tid = body["params"]["taskId"]
        TASKS[tid] = {"status": "completed", "out": "Report ready (42 pages)."}
        t = TASKS[tid]
        return ok(rid, {"task": {"taskId": tid, "status": t["status"]},
                        "content": [{"type": "text", "text": t["out"]}]})

    if method == "tools/call":
        params = body.get("params", {})
        name, args = params.get("name"), params.get("arguments", {})
        if headers.get("Mcp-Name") != name:
            return err(rid, -32600, "Mcp-Name header disagrees with params.name")

        if name == "search":
            return text(rid, f"Top hit for {args['q']!r}: otters hold hands when asleep.")

        if name == "create_basket":
            bid = "bsk_" + secrets.token_hex(3); BASKETS[bid] = []
            return ok(rid, {"content": [{"type": "text", "text": f"Created {bid}"}],
                            "structuredContent": {"basket_id": bid}})

        if name == "add_item":
            bid = args["basket_id"]; BASKETS.setdefault(bid, []).append(args["item"])
            return text(rid, f"{bid} now holds {BASKETS[bid]}")

        if name == "delete_files":
            paths, responses = args["paths"], params.get("inputResponses")
            if responses is None:                    # SEP-2322: round 1
                state = base64.b64encode(json.dumps({"paths": paths}).encode()).decode()
                return ok(rid, {"resultType": "inputRequired",
                                "inputRequests": {"confirm": {
                                    "type": "elicitation",
                                    "message": f"Delete {len(paths)} files?",
                                    "schema": {"type": "boolean"}}},
                                "requestState": state})
            st = json.loads(base64.b64decode(params["requestState"]))   # round 2
            if responses.get("confirm") is True:
                return text(rid, f"Deleted {len(st['paths'])} files: {st['paths']}")
            return text(rid, "Cancelled. No files deleted.")

        if name == "generate_report":                # server-directed Tasks extension
            tid = "task_" + secrets.token_hex(3); TASKS[tid] = {"status": "working"}
            return ok(rid, {"task": {"taskId": tid, "status": "working"}})

        return err(rid, -32602, f"Unknown tool {name!r}")
    return err(rid, -32601, f"Unknown method {method!r}")

Notice three spec-accurate details. The handler rejects requests where the Mcp-Method header disagrees with the body (SEP-2243). tools/list returns ttlMs and cacheScope so clients know how long the list is fresh (SEP-2549). And the Tasks extension is advertised with its reverse-DNS id io.modelcontextprotocol/tasks in capabilities.

Step 3: Mount it in Starlette and scale it

The function has no framework dependency, so wiring it to HTTP is a single route. There is no session middleware to configure:

# http_app.py - mount handle() in Starlette. One POST route, zero sessions.
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from stateless_mcp import handle

async def mcp_endpoint(request):
    body = await request.json()
    resp = handle({"Mcp-Method":  request.headers.get("mcp-method"),
                   "Mcp-Name":    request.headers.get("mcp-name"),
                   "MCP-Protocol-Version": request.headers.get("mcp-protocol-version")},
                  body)
    return JSONResponse(resp)

app = Starlette(routes=[Route("/mcp", mcp_endpoint, methods=["POST"])])
# Run it:  uvicorn http_app:app --port 8000  (scale with --workers N behind any LB)

Run it with uvicorn http_app:app --port 8000. Because the endpoint holds no per-connection state, you can start it with --workers 4 or run a dozen pods behind a plain round-robin load balancer, and a client request will succeed no matter which one answers.

Step 4: The explicit-handle pattern

Stateless protocol does not mean stateless application. When your server needs to carry state across calls, do what HTTP APIs always have: mint an explicit handle from a tool and have the model pass it back as an ordinary argument. Here is a client that creates a basket, then threads the returned basket_id into the next call:

# client.py - a minimal stateless client. No handshake, no session id.
import httpx

URL = "http://localhost:8000/mcp"

def call(method, params, name=None, _id=1):
    headers = {"MCP-Protocol-Version": "2026-07-28", "Mcp-Method": method}
    if name:
        headers["Mcp-Name"] = name
    body = {"jsonrpc": "2.0", "id": _id, "method": method, "params": params}
    # clientInfo now rides in _meta on every request instead of initialize.
    params.setdefault("_meta", {})["io.modelcontextprotocol/clientInfo"] = \
        {"name": "my-app", "version": "1.0"}
    return httpx.post(URL, headers=headers, json=body).json()

# 1) one self-contained tool call - this used to require initialize first
print(call("tools/call", {"name": "search", "arguments": {"q": "otters"}}, name="search"))

# 2) the explicit-handle pattern: thread basket_id from one call into the next
made = call("tools/call", {"name": "create_basket", "arguments": {}}, name="create_basket")
bid  = made["result"]["structuredContent"]["basket_id"]
print(call("tools/call",
           {"name": "add_item", "arguments": {"basket_id": bid, "item": "kayak"}},
           name="add_item"))

Running client.py against the server prints the search result, then the basket id, then the basket holding the kayak. The model sees the handle as a normal argument, so it can compose handles across tools and reason about them, instead of relying on session state hidden in transport metadata.

Step 5: Server-to-client input mid-call

A stateless server still sometimes needs to ask the user something mid-call, such as a confirmation. SEP-2260 requires that server-initiated requests only happen while the server is processing a client request, and SEP-2322 (Multi Round-Trip Requests) delivers them without holding an SSE stream open. The server returns an InputRequiredResult with an opaque requestState; the client gathers answers and re-issues the original call with inputResponses and the echoed state:

# Round 1 response - server needs a yes/no before it acts:
{"jsonrpc":"2.0","id":5,"result":{
  "resultType":"inputRequired",
  "inputRequests":{"confirm":{"type":"elicitation",
                              "message":"Delete 3 files?",
                              "schema":{"type":"boolean"}}},
  "requestState":"eyJwYXRocyI6IFsiYSIsImIiLCJjIl19"}}

# Round 2 - client re-issues the SAME call with answers + the echoed requestState.
# Any instance can finish it because all the context is in the payload:
{"jsonrpc":"2.0","id":5,"method":"tools/call",
 "params":{"name":"delete_files","arguments":{"paths":["a","b","c"]},
           "inputResponses":{"confirm":true},
           "requestState":"eyJwYXRocyI6IFsiYSIsImIiLCJjIl19"}}
# -> {"result":{"content":[{"type":"text","text":"Deleted 3 files: ['a','b','c']"}]}}

Because requestState carries everything needed to resume, the retry can be picked up by a different instance than the one that asked. The delete_files tool in our server implements exactly this two-round flow.

Step 6: Long-running work with the Tasks extension

Tasks shipped as an experimental core feature in 2025-11-25; in this release it graduates to an opt-in extension and is redesigned around the stateless model. A server can answer tools/call with a task handle, and the client drives it with tasks/get, tasks/update, and tasks/cancel. Task creation is server-directed: the client advertises the extension and the server decides when a call runs as a task.

# Server hands back a task handle instead of blocking:
>>> r = call("tools/call", {"name":"generate_report","arguments":{"topic":"otters"}},
...          name="generate_report")
{'jsonrpc':'2.0','id':1,'result':{'task':{'taskId':'task_a7b75c','status':'working'}}}

# Client drives it with tasks/get (and tasks/update, tasks/cancel). No tasks/list:
# it cannot be scoped safely without sessions, so it was removed.
>>> tid = r["result"]["task"]["taskId"]
>>> call("tasks/get", {"taskId": tid})
{'jsonrpc':'2.0','id':1,'result':{'task':{'taskId':'task_a7b75c','status':'completed'},
 'content':[{'type':'text','text':'Report ready (42 pages).'}]}}

One migration note worth flagging loudly: tasks/list was removed because it cannot be scoped safely without sessions, and anyone who built against the experimental 2025-11-25 Tasks API must migrate to this new lifecycle.

Worked example: horizontal scaling with no shared store

Picture a shopping assistant deployed as three identical pods. A user's agent calls create_basket (lands on pod A), then add_item twice (lands on pods B and C), then delete_files with a confirmation round trip (rounds handled by different pods). Under the old spec, every one of those calls had to hit the pod that issued the session id, or you needed a Redis session store shared across pods plus sticky routing at the gateway.

Under 2026-07-28, the basket lives behind an explicit basket_id that the model threads through each call, and the confirmation state rides in requestState. The pods share a product database (real application state) but no protocol session state. You can autoscale on CPU, drain a pod mid-conversation, or deploy a new version with a rolling restart, and in-flight conversations keep working. That is the operational payoff the stateless core is designed to deliver.

Common pitfalls

  • Leaving initialize in your client. There is no handshake anymore. Sending initialize to a 2026-07-28 server is a wasted round trip; put clientInfo in _meta on each request and call server/discover only when you need capabilities up front.
  • Hiding state in transport metadata. Do not invent your own session header to replace Mcp-Session-Id. Mint an explicit handle from a tool and let the model pass it back. State the model can see is state the model can compose.
  • Forgetting the routing headers. Streamable HTTP now requires Mcp-Method and Mcp-Name, and servers must reject requests where the headers and body disagree. Set both on every call or your request is invalid.
  • Calling tasks/list. It was removed. Track task ids yourself; drive each task with tasks/get.
  • Matching on the old error code. A missing resource now returns the JSON-RPC standard -32602 Invalid Params instead of the MCP-custom -32002 (SEP-2164). Update any client that hard-codes -32002.
  • Assuming Roots, Sampling, and Logging still work forever. They are deprecated (SEP-2577), annotation-only for now, with at least twelve months before any removal. Plan migrations: tool parameters for Roots, direct LLM provider APIs for Sampling, stderr or OpenTelemetry for Logging.
  • Ignoring cache metadata. If you ignore ttlMs and re-fetch tools/list on every turn, you throw away a built-in optimization the spec hands you for free.

Quick reference

Topic2025-11-25 (old)2026-07-28 (new)
Connection startinitialize / initialized handshakenone; clientInfo in _meta per request
SessionMcp-Session-Id header, sticky routingstateless; any instance handles any request
App stateoften hidden in sessionexplicit handle returned by a tool
Routinginspect request bodyMcp-Method + Mcp-Name headers (required)
List freshnesslong-lived SSE notificationsttlMs + cacheScope on results
Mid-call inputopen SSE streamInputRequiredResult + requestState retry
Long-running workexperimental core TasksTasks extension; tasks/list removed
Missing-resource error-32002 (custom)-32602 Invalid Params (standard)

Next steps

  • Read the draft spec and the changelog against 2025-11-25 at modelcontextprotocol.io/specification/draft.
  • Add an extensions negotiation map and try MCP Apps (SEP-1865) to ship a server-rendered HTML UI in a sandboxed iframe.
  • Wire W3C Trace Context (traceparent, tracestate, baggage) into _meta and watch a tool call show up as one span tree in an OpenTelemetry backend.
  • Run your client and server against the official conformance suite; a Standards Track SEP cannot reach Final until a matching scenario lands there.
  • If you maintain a 2025-11-25 server, schedule the migration before July 28: remove the handshake, drop session storage, add the routing headers, and port any Tasks code to the new lifecycle.

Sources: the official MCP blog post 'The 2026-07-28 MCP Specification Release Candidate' (blog.modelcontextprotocol.io) and the linked SEPs. Code in this guide was executed and verified before publishing.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,604 newsletter subscribers.

Also get