Open History to see the last commit
1---
2title: MCP Server Sessions
3id: mcp-server-sessions
4order: 13
5description: "Route spec 2025 sessions to the instance that opened them, and learn when a session closes."
6keywords:
7 - tanstack ai
8 - mcp
9 - model context protocol
10 - createMCPServer
11 - sticky sessions
12 - spec 2025
13 - mcp-session-id
14---
15
16A spec 2025 client opens a session, then sends the same session id on each later request. On a deploy with more than one instance, a later request can reach an instance that did not open the session. That request gets 404.
17
18Route each session to one instance. Use the `mcp-session-id` header as the key for sticky routing on your load balancer. If you cannot route by header, [turn sessions off](#turn-sessions-off).
19
20## Where a session lives
21
22A spec 2025 session keeps a live connection object. That object stays in the process that opened the session. Another process cannot read it.
23
24- The client sends the session id on the `mcp-session-id` header.
25- A request with an unknown session id gets 404 `Session not found`.
26- A spec 2026 client sends no session id. Any instance can serve a spec 2026 request.
27
28## When a session closes
29
30A session closes in two cases:
31
32- The client sends `DELETE` with its session id.
33- The session gets no request for 30 minutes.
34
35The server checks for idle sessions when a request comes in. After a session closes, the client must open a new session.
36
37The server has no limit on the number of open sessions. Each session stays in memory until it closes, which can take 30 minutes. On a public server, set `auth`, or limit new sessions at your proxy.
38
39## Turn sessions off
40
41On Cloudflare Workers, and on other hosts with many instances, a request can reach any instance. Sticky routing by header is not always possible. Set `sessions` to `'reject'`. The server then opens no session, and a spec 2025 request gets the SDK rejection. A spec 2026 request works as before.
42
43```ts
44import { createMCPServer } from '@tanstack/ai-mcp/server'
45
46const server = createMCPServer({
47 name: 'weather',
48 version: '1.0.0',
49 sessions: 'reject',
50})
51```
52
53A client that speaks only spec 2025 cannot use that server.
54
55## Sessions and auth
56
57When the server has `auth`, the session belongs to the caller that opened it: the `clientId` of the token plus its `sub` claim. A request from another caller gets 404, the same as an unknown id. [MCP Server Auth](./server-auth) shows how the verifier sets them.
58
59A client on one instance opens a session, sends its requests, and gets its answers from that same instance.