Blog · · 11 min read

Run product MCP servers behind an MCP gateway on the stateless 2026-07-28 spec without leaking per-user catalogs or state

Run product MCP servers behind an MCP gateway on the stateless 2026-07-28 spec without leaking per-user catalogs or state

If your product's MCP servers sit behind an MCP gateway, the 2026-07-28 revision of the Model Context Protocol changed that gateway's job. The session is gone, and with it the key that sticky routing, stream resumption, and per-session capability caches were built on. Gateways that kept their old habits have already shipped tool lists that strict clients refuse to parse, so the server looks connected and exposes zero tools. This guide covers what the session used to carry, what replaces each piece, and the tests that prove a gateway can route, cache, and authorize every request on its own.

What the session used to carry

The 2026-07-28 key changes remove protocol sessions and the Mcp-Session-Id header, remove the initialize handshake, add an optional server/discover call, add subscriptions/listen for change notifications, require Mcp-Method and Mcp-Name routing headers, and make list and read results cacheable. The MCP release post says any request can now land on any instance behind a plain round-robin load balancer, and that gateways can route and authorize on headers directly.

Under the old transport a multiplexing gateway leaned on the session for almost everything. Envoy AI Gateway's version 1.0 MCP documentation describes unified sessions that encode multiple backend session IDs, with reconnection through Last-Event-ID. The project's 2026-07-28 design issue shows the encrypted client-facing session ID packing the route, the caller subject, each backend's session ID, and each backend's capabilities, and notes that in 2026-07-28 there is no session ID to carry any of this.

What the session carriedWhere it lives now
Route and backend choiceA route header on every request, plus the backend prefix in the tool name or resource URI that now also travels in Mcp-Name
Backend session IDsNothing, because modern backends are stateless
Backend capabilitiesA per-backend server/discover result cached for its ttlMs
Caller identity and anti-hijack checksPer-request bearer-token authentication
Application state such as a draft or cartAn explicit state handle returned by a tool and passed back as an argument
Resumable streamsNothing; a broken stream means a new request

SEP-2567 addresses gateways directly. Gateways that routed by Mcp-Session-Id lose their routing key, but they only needed one because their upstreams were stateful. If the upstream is stateless, no sticky routing is needed. Explainers that still sell session affinity as a core feature, such as Kong's MCP gateway overview, describe the older transport.

The gateway contract in eight checks

  1. Detect the protocol era of each client and each backend before choosing a code path.
  2. Authenticate and authorize every request on its own credentials.
  3. Validate mirrored headers against the body, and recompute them after any rewrite.
  4. Preserve or tighten cache hints when you merge or re-encode results.
  5. Keep permission-filtered catalogs private and keyed to one authorization context.
  6. Move application state into handles that the backend authorizes on every call.
  7. Treat a closed response stream as a cancel, and never retry side effects automatically.
  8. Prove all of it with tests on the serialized wire JSON.

Detect the era of each side before routing

A gateway is a server to clients and a client to backends, and each face can be legacy or modern. The Envoy design issue maps the four combinations. Modern to modern is fully stateless, legacy to legacy works as before, a modern client calling a legacy backend forces the gateway to own an upstream session, and a legacy client calling a modern backend keeps a client-facing session with empty backend session IDs.

Detect the client's era from how it opens. An initialize request means legacy, and a request carrying modern per-request _meta means stateless. For backends, the Streamable HTTP transport specification tells dual-era clients to try a modern request first and to inspect the body of a 400 before falling back, because modern servers also use 400 for unsupported versions and header failures. The versioning page defines UnsupportedProtocolVersion (-32022) and the list of supported versions it returns. Cache each backend's era and re-probe when calls start failing.

You may decide not to serve the whole matrix. Microsoft's MCP Gateway migration guide takes that route. It has no legacy mode or automatic downgrade, legacy-only adapters stay on a pinned older image, and old and new images must not share a backend pool. That works when you control the clients. A product exposing MCP servers to customers' agent hosts usually does not, so plan for at least two cells during the deprecation window and record which cell each route is in.

Route and authorize per request from validated headers

Every modern request carries its protocol version, client capabilities, and client info in params._meta. The method travels in Mcp-Method, and tools/call, prompts/get, and resources/read also carry the tool name, prompt name, or URI in Mcp-Name. The Streamable HTTP specification makes the body the source of truth. Servers that process the body must reject requests whose headers do not match it, returning 400 with HeaderMismatch (-32020). Without that rule, the specification notes, a load balancer could route on the header value while the MCP server executes based on the body value.

The rule catches gateways that rewrite names. Envoy AI Gateway prefixes tool names with the backend (backend__tool) so a single route can expose several servers, then strips the prefix before forwarding, and its design notes list the header as part of that rewrite. After a gateway rewrites a tool name or resource URI, it must recompute the mirrored Mcp-Name header from the rewritten body, because the body is the source of truth and a compliant backend rejects any mismatch with HeaderMismatch.

// Forward a modern tools/call after stripping the backend prefix.
function forwardToolCall(req: McpRequest, route: Route): UpstreamRequest {
  const { backend, upstreamName } = route.resolveTool(req.body.params.name);
  const body = structuredClone(req.body);
  body.params.name = upstreamName;

  const headers = {
    ...req.forwardableHeaders(),
    "Mcp-Method": body.method,
    // Recompute from the rewritten body, never copy the client's header.
    "Mcp-Name": encodeHeaderValue(upstreamName),
    "MCP-Protocol-Version": body.params._meta["io.modelcontextprotocol/protocolVersion"],
  };
  return { backend, headers, body };
}

Apply the same rule to Mcp-Param-* headers that mirror arguments annotated with x-mcp-header.

Header-based authorization saves the gateway from parsing JSON, but the transport specification attaches a condition. An intermediary that routes or rate-limits on mirrored headers should first check that MCP-Protocol-Version names a version that requires header-body validation, and should reject older or header-less requests rather than trust unvalidated values. In a mixed fleet, header-based policy therefore belongs on the modern path. Legacy routes need body parsing or policy that does not depend on mirrored headers.

Authenticate each request on its own token. SEP-2567 notes that per-request authentication replaces the session-to-user pinning some servers used to keep. Move any telemetry or rate-limit buckets keyed on the session ID to the authenticated principal or a request correlation ID.

Preserve cache hints when you merge or re-encode results

List results and resources/read results now carry ttlMs and cacheScope. The caching specification says public responses contain no user-specific data, so any client, shared gateway, or caching proxy may serve them to any user. private responses may be reused only within the same authorization context, and caches must not be shared across authorization contexts. A missing ttlMs means immediately stale, and the specification names private as the right choice for filtered lists that vary per user.

Gateways that aggregate several backends build a new list result, and that is where the metadata goes wrong. In Envoy AI Gateway issue #2665, the merge functions rebuilt tools/list, resources/list, and resources/templates/list without the upstream hints, and Go zero values went out as ttlMs: 0 and cacheScope: "". An empty string is not a valid scope. The downstream report in openai/codex#41437 shows the result: OAuth succeeded, initialize succeeded, the wire carried 30 valid tools, and Codex still reported Unexpected response type with zero tools because its client library rejected the scope. Others reproduced it on Linux, macOS, and in ChatGPT. Upwork fixed it server side by 2026-09-12, and the gateway maintainers pointed to a fix for the list paths in PR #2545. On 2026-10-04 a commenter found the same empty scope on the resources/read re-encode path, which needed a separate fix.

The failure happened on a client that negotiated 2025-06-18, so a gateway can break discovery before anyone migrates, and because the payload was otherwise valid, nothing on the server side looked broken. A gateway that merges or re-encodes list results must carry the most restrictive upstream cacheScope and the smallest ttlMs forward, never emit an empty scope, and key any permission-filtered catalog to one authorization context, because a blank scope breaks strict clients and a public one lets a shared cache hand one user's tools to another.

type CacheScope = "public" | "private";
interface Hints { ttlMs?: number; cacheScope?: CacheScope | "" }

function mergeHints(parts: Hints[], filteredPerCaller: boolean) {
  const ttlMs = parts.length ? Math.min(...parts.map((p) => Math.max(0, p.ttlMs ?? 0))) : 0;
  const everyPartPublic = parts.length > 0 && parts.every((p) => p.cacheScope === "public");
  const cacheScope: CacheScope =
    !filteredPerCaller && everyPartPublic ? "public" : "private";
  return { ttlMs, cacheScope };
}

The specification does not require treating a missing or invalid upstream scope as private. Doing so costs a few extra fetches and removes a class of cross-tenant leaks.

Keep per-user catalogs private

Most product MCP servers filter tools by plan, role, or granted scopes. SEP-2567 allows that. Lists may vary by the authorization presented on each request, but not by connection, and a server can no longer add tools to a list as a side effect of another call. Microsoft's gateway returns permission-filtered catalogs in a deterministic order with cacheScope: "private" and ttlMs: 0, and warns never to share those catalogs across authorization contexts or treat a cached catalog as authorization to execute a tool.

If your gateway caches discovery results to save upstream traffic, key the cache on the route, the backend, and the authorization context, not on the route alone. The caching page adds that servers must apply per-primitive access controls and must not rely on cacheScope alone to prevent unauthorized access. A tool that is missing from one user's list must still be rejected when that user calls it by name.

Move session state into handles the backend authorizes

Product servers that kept a draft, a cart, or a database connection in session state now return a handle from a creation tool and accept it on later calls. SEP-2567 calls this a tool-design pattern rather than a protocol feature. The gateway sees a handle as an ordinary string argument and cannot tell it apart from any other ID.

That puts the security check in the backend. State handles replace the session, so the backend must authorize every call on the handle together with the caller's identity, because handles travel through transcripts, subagent prompts, and copy-paste where session IDs never went. SEP-2567 gives that guidance for authenticated servers, phrased as validating the pair of handle and authentication context, and adds other users' screens to the places handles can land. For unauthenticated servers the handle is a bearer capability, so it needs at least 128 bits of cryptographically secure entropy and a bounded lifetime.

async function addLineItem(args: { draft_id: string; sku: string }, auth: AuthContext) {
  const draft = await drafts.find(args.draft_id);
  if (!draft || draft.tenantId !== auth.tenantId || !draft.canEdit(auth.subject)) {
    // Same answer for "missing" and "not yours", so handles cannot be probed.
    return toolError(`draft ${args.draft_id} was not found or has expired`);
  }
  return draft.addItem(args.sku, { actor: auth.subject });
}

Keep handles opaque, document their lifetime in the creation tool's description, and return a clear expiry error. One residual case still needs routing state: SEP-2567 notes that gateways bridging HTTP to stdio by spawning one subprocess per session need a correlation key, such as the authenticated principal or a gateway-issued header.

Treat a closed stream as a cancel, not a retry

The transport now scopes each response stream to one request, and the specification says closing that stream must be treated by the server as cancellation of the request. Resumption with Last-Event-ID is gone. Two gateway settings that used to be harmless now change application behavior.

First, buffering. The specification asks servers to send X-Accel-Buffering: no so proxies deliver events immediately, and encourages SSE comment keepalives on long streams. Microsoft's guide disables request and response buffering at its ingress, sets a 600-second backend timeout, and asks backends to send keepalives during quiet periods.

Second, timeouts and retries. If an ingress idle timeout is shorter than a tool's runtime, the gateway closes the stream, the backend cancels the call, and the client sees a failure for work that may already have partly committed. Microsoft's guide states that a failed connection is not permission to retry a tool with side effects automatically. Give side-effecting tools an idempotency key or a status tool, and make the gateway's retry policy method-aware so it never replays a tools/call on its own.

Verify the solution

Run these as integration tests against the gateway, and assert on the serialized JSON the client receives, not on in-process structs. Issue #2665's fix criteria asked for exactly that.

  • Send tools/list, resources/list, resources/templates/list, and resources/read through every route and both eras. Assert that cacheScope is always public or private and never empty.
  • Call a permission-filtered tools/list with token A, then with token B. Assert that B never receives A's cached catalog and that a tool missing from B's list fails when B calls it.
  • Call a prefixed tool and capture the upstream request. Assert that Mcp-Name equals the rewritten body name and that a deliberately mismatched header returns -32020.
  • Create a handle as user A and use it as user B. Assert a not-found style error.
  • Run a tool that takes longer than the ingress idle timeout. Assert that the test sees a cancellation and that no component retried the call.
  • Send initialize from a legacy client and a modern server/discover through the same route. Assert both reach discovery and list tools.
  • Send a request with an unsupported protocol version. Assert -32022 with the supported list, and assert that the client does not fall back to initialize.

Common mistakes

  • Treating every 400 from a backend as a reason to fall back to legacy initialization. Microsoft's troubleshooting table warns against this.
  • Upgrading the gateway before checking that every adapter speaks 2026-07-28.
  • Letting an HTTP client library retry a tools/call after a dropped stream.

What to do next

Label every gateway route with its client era and backend era. Run the wire-level tests against the merge and re-encode paths first, because that is where the empty-scope failure appeared. Then move session-keyed state in your product servers to handles with per-call authorization, and only then default clients to 2026-07-28. agentgateway's 1.4 announcement and Microsoft's guide show that gateway vendors have started shipping support, so check your gateway's release notes for which cells of the matrix it handles before you rely on it.

Be first in line.

Join the waitlist and we'll email you the moment it's ready. No sales call.

Try the demo →
or talk to us