entry
No. 26
date
filed under
mcp, tool use, agents
checked against
9 sources

Stateless MCP Server: Keep State With Explicit Handles

Since the 2026-07-28 revision of the Model Context Protocol, an MCP server has no session to keep state in. The changelog's first major change reads: "Remove protocol-level sessions and the Mcp-Session-Id header from the Streamable HTTP transport," and it names the replacement in the same sentence: "Servers that need cross-call state use explicit, server-minted handles passed as ordinary tool arguments." So a stateless MCP server that still needs a shopping cart, a browser context or a database connection exposes a create_* tool that returns an ID, and every later tool takes that ID as an argument. This post covers what changed, why, a tested Python server built this way, and the rules for handles that the spec and its design proposal recommend.

The code was run with the official mcp Python package, version 2.3.0, on Python 3.13, using the SDK's in-process client and a local Streamable HTTP server. No real users, tokens or model were involved.

What the 2026-07-28 spec removed

Two proposals did the work. SEP-2575 removed the initialize handshake: every request now carries its protocol version and client capabilities in _meta. SEP-2567 removed sessions. The release post from the MCP maintainers sums it up: "MCP is transforming from a bidirectional stateful protocol into a request/response stateless protocol," and any request can reach any server instance behind a plain round-robin load balancer.

In practice, for a server author:

  • There is no Mcp-Session-Id to key state on, and no handshake marking where a client "starts."
  • tools/list is not allowed to change per connection. The tools spec says the list "MUST NOT vary per-connection or as a side effect of other requests on the connection." It MAY vary by the authorization on the request, since "credentials are per-request input, not connection state."
  • State that lasted "as long as the session" now needs an explicit name.

A raw POST shows the new shape. Against the test server below, one tools/call with MCP-Protocol-Version: 2026-07-28, the Mcp-Method and Mcp-Name headers and the version in _meta, sent with no handshake first, came back 200 OK with "resultType":"complete" and no Mcp-Session-Id header in the response.

Why sessions went away

SEP-2567 lists three problems, and they explain why handles work better.

Nobody agreed on what a session was. The SEP reports that "ChatGPT creates a fresh session for every individual tool call," that most desktop and IDE clients keep one session per application launch, and that web clients typically create one per page load. A server that tied a browser to the session could not know if that meant one turn or one long-lived chat.

One session, one of everything. A session holds exactly one cart and one browser. The SEP's example is an orchestrator whose subagents should share a cart but each browse separately. No session boundary gives both; separate handles do.

Lists could not be cached. If tools/list might change per session, a client must re-fetch it for every session, which the SEP puts at O(subagents × servers) calls. With sessions gone, it becomes O(servers).

Most servers are unaffected. The SEP's survey of a random sample of 1,000 open source MCP servers found 90.0% with no application-level reference to the session ID, and 2.5% using it for application state, the case this post is about.

The handle pattern

The spec's Stateful Tools section, which it marks as non-normative guidance, uses a cart:

// → tools/call
{ "name": "create_basket", "arguments": {} }

// ← result
{
  "content": [{ "type": "text", "text": "Created basket bsk_a1b2c3" }],
  "structuredContent": { "basket_id": "bsk_a1b2c3" }
}

// → tools/call
{ "name": "add_item", "arguments": { "basket_id": "bsk_a1b2c3", "sku": "..." } }

There is nothing new on the wire. As SEP-2567 puts it, "a handle is a string in a tool result and a string in a tool argument, indistinguishable from any other tool data." The model carries the ID forward; the server stores the state under it.

This is already how large remote servers work. The SEP points to Linear (create_issue returns an issue ID used by update_issue), GitHub (a PR number used by merge_pull_request) and Stripe (a customer ID used by create_invoice). The change is applying the same idea to short-lived things like a cart or a browser context.

A working server in Python

In version 2 of the Python SDK, FastMCP is renamed MCPServer; the migration guide says "The FastMCP class has been renamed to MCPServer." The 60-line server post covers the basics. Here is a basket server that keeps state only in handles:

import secrets
import time
from dataclasses import dataclass, field
from typing import TypedDict

from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.auth.provider import principal_components
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

IDLE_TTL_SECONDS = 30 * 60

mcp = MCPServer("baskets")


class BasketRef(TypedDict):
    basket_id: str


class BasketView(TypedDict):
    basket_id: str
    items: dict[str, int]


@dataclass
class Basket:
    owner: tuple | None
    items: dict[str, int] = field(default_factory=dict)
    last_used: float = field(default_factory=time.monotonic)


# In one process this dict is enough. Behind a load balancer, keep it in
# shared storage (Redis, a database) so any replica can serve any handle.
BASKETS: dict[str, Basket] = {}


def current_owner() -> tuple | None:
    """(client_id, issuer, subject) of the caller, or None without auth."""
    token = get_access_token()
    return principal_components(token) if token else None


def load(basket_id: str) -> Basket:
    basket = BASKETS.get(basket_id)
    if basket is None:
        raise ToolError(
            f"Basket {basket_id} does not exist or has expired. "
            "Call create_basket to start a new one."
        )
    if time.monotonic() - basket.last_used > IDLE_TTL_SECONDS:
        del BASKETS[basket_id]
        raise ToolError(
            f"Basket {basket_id} has expired after 30 minutes idle. "
            "Call create_basket to start a new one."
        )
    if basket.owner != current_owner():
        # Same message as "missing", so a leaked id reveals nothing.
        raise ToolError(
            f"Basket {basket_id} does not exist or has expired. "
            "Call create_basket to start a new one."
        )
    basket.last_used = time.monotonic()
    return basket


@mcp.tool()
def create_basket() -> BasketRef:
    """Create an empty shopping basket and return its basket_id.

    Pass basket_id to add_item, get_basket and checkout. Baskets expire
    after 30 minutes without use.
    """
    basket_id = "bsk_" + secrets.token_urlsafe(16)  # 128 bits of randomness
    BASKETS[basket_id] = Basket(owner=current_owner())
    return {"basket_id": basket_id}


@mcp.tool()
def add_item(basket_id: str, sku: str, quantity: int = 1) -> BasketView:
    """Add quantity of sku to the basket created by create_basket."""
    basket = load(basket_id)
    basket.items[sku] = basket.items.get(sku, 0) + quantity
    return {"basket_id": basket_id, "items": basket.items}


@mcp.tool()
def get_basket(basket_id: str) -> BasketView:
    """Show what is in a basket."""
    return {"basket_id": basket_id, "items": load(basket_id).items}


@mcp.tool()
def checkout(basket_id: str) -> BasketView:
    """Place the order for a basket. The basket is deleted afterwards."""
    basket = load(basket_id)
    if not basket.items:
        raise ToolError(f"Basket {basket_id} is empty. Add items with add_item first.")
    del BASKETS[basket_id]
    return {"basket_id": basket_id, "items": basket.items}


if __name__ == "__main__":
    mcp.run(transport="streamable-http")

Three details are easy to get wrong:

  • Return a typed value. In the test, a tool annotated -> dict returned its JSON only as text, and structured_content on the client was None. With a TypedDict return type, the result carried structuredContent with the basket_id, which is where the spec's example puts it.
  • Owner is the full principal. principal_components() returns the token's (client_id, issuer, subject). Keying only on client_id would let every user of the same client app open each other's baskets.
  • One error for missing and not yours. A caller who guesses or finds another user's handle learns nothing from the reply.

The test, with the SDK's in-process Client, created two baskets and filled them separately ({'shoes': 1, 'socks': 2} and {'hat': 1}). A second, separate client then read the first basket by its ID, which is the point: state follows the handle, not the connection. Over HTTP, a basket created by one Client was filled by a second Client against the same server. A made-up ID, a basket aged past 30 minutes and a basket whose owner was set to another principal each came back with is_error true and the messages above, and a second checkout on the same basket failed because the first deleted it. The ownership check was tested by changing the stored owner, not with a real OAuth token.

Rules for handles

SEP-2567 gives server guidance, and the tools spec repeats the core of it. All of it is advice, not protocol requirements.

Possession is not authorization. For authenticated servers, the SEP says to "validate (handle, auth_context) on every call," because handles "will end up in chat logs, copy-paste buffers, and subagent prompts." It compares this to Google Doc IDs: the ID names the document, the ACL decides access.

Unauthenticated servers need unguessable handles. Without auth, the handle is a bearer token. The SEP asks for "at least 128 bits of cryptographically secure entropy," never derived from predictable inputs, with a bounded lifetime. secrets.token_urlsafe(16) draws 16 random bytes, which is 128 bits, and gives 22 characters, matching the SEP's "22+ characters of URL-safe base64."

Keep handles opaque. A handle like cart_user42_2026-03-11 "invites clients to parse it or models to guess it." Use bsk_ plus random characters.

Put the lifetime in the tool description. Sessions used to imply cleanup. Now, the SEP says, "Put the policy in the create_* tool's description" so the model sees it when it decides to create state. A policy only in your README is invisible to the model.

Make expiry errors say what happened. The tools spec asks for "a tool execution error that says so, so the model can recover by creating a new one." Raising ToolError produces exactly that: a result with isError: true, which the spec says clients SHOULD pass to the model "to enable self-correction." An opaque "invalid argument" tends to cause the retry loops covered in agent tool retries.

Take parameters at creation. The SEP prefers create_context(cluster="staging") over creating and then configuring, so state never exists half set up.

Offer cleanup. A destroy_* tool and a list_* tool are optional, but let a model free resources or recover after losing track of what it made.

Tools that used to appear after connecting

Some servers grew their tool list as a side effect: call connect_database, and query shows up. The SEP says that pattern "is no longer permitted." The replacement is to list query and list_tables from the start, have them take a connection_id returned by connect_database(), and fail a call without a valid one "with an error directing the model to call connect_database() first." The dependency moves into the input schema and description, where the model can read it.

stdio servers and older clients

stdio servers never had Mcp-Session-Id, so the header removal does not touch them, and a server that keeps one browser per process still works when the client starts one process. The SEP still says such servers "SHOULD NOT rely on process-lifetime state and SHOULD migrate to explicit handles," because what a process corresponds to is up to the host, and the same server cannot behave the same way over HTTP. If a stdio server dies and the client reports a closed connection, see MCP error -32000: Connection closed.

There is no deprecation window for sessions. The SEP calls the rollout "a clean break": servers that rely on session state stay on the older protocol version until they migrate, and version negotiation lets a client speak the old protocol to them and the new one to everyone else.

What clients have to do

The client's main job, per the SEP, is "ensuring that string survives context compaction." If a summary drops the tool result that held basket_id, the cart is orphaned. If you compact agent history, keep live handles in the summary or in notes outside the window, as in budgeting the context window. The upside, the SEP notes, is resumption: handles live in the chat transcript, so reopening a saved conversation puts them back in front of the model with no extra machinery.

Checklist

  • Search your server for session IDs used as state keys, and replace each with a create_* tool.
  • Add the handle as a required argument to every tool that uses that state.
  • Return handles in structuredContent; in the Python SDK, use a typed return value.
  • Check (handle, caller) on every call when you have auth.
  • Use at least 128 random bits when you don't.
  • State the lifetime in the creation tool's description.
  • Return clear expiry errors with isError: true.
  • Keep state in shared storage if you run more than one replica.
  • Stop changing tools/list as a side effect of tool calls.

FAQ

Does MCP still have sessions?

Not in the 2026-07-28 revision. It removed protocol-level sessions, the Mcp-Session-Id header and the initialize handshake. Each request carries its own protocol version and capabilities in _meta.

How do I keep state in a stateless MCP server?

Return an ID from a creation tool, such as create_basket() returning basket_id, and accept that ID as an argument on later tools. The server stores the state under the ID, in shared storage if it runs more than one instance.

Are MCP state handles a protocol feature?

No. SEP-2567 says there is "no handles/* method, no handle type in the schema." A handle is an ordinary string in a tool result and an ordinary tool argument.

Is it safe to show a handle to the model?

Yes, if the server checks the caller's authorization on every call. Without auth, the handle is a bearer token and should have at least 128 bits of entropy and a bounded lifetime.

Can a tools/list result still change?

Yes, over time and by the authorization on the request, but it must not vary per connection or as a side effect of other requests.

Sources

Server not starting? Paste your config into the MCP config checker to find the usual causes.

Next in the notebook

  1. No. 9Build an MCP Server in Python: A Working 60-Line Example

    Build an MCP server in Python with the official SDK: a 60-line docs search server with tools, a resource and a prompt, plus tests and Claude Code setup.

  2. No. 2AI Agent Calling the Wrong Tool? 7 Causes and How to Fix Them

    A debugging checklist for tool-calling agents: overlapping tools, vague descriptions, ambiguous parameters, noisy output and bad errors, with a fix for each.

  3. No. 6Structured Outputs vs Function Calling: Which to Use When

    Structured outputs vs function calling: use tools when the model must act, a JSON schema when you need the answer in a fixed shape, and strict mode for both.