NewNode 26.14: mockResolvedValue and Friends in node:test →
w3/w3-tutorials

Build a Stateless MCP Server with the 2026-07-28 Spec

The 2026-07-28 MCP spec drops the handshake and session IDs. Build a server that any instance can answer, and run it behind a plain round-robin load balancer.

Updated Nov 12, 20268 min readIntermediatenode 22.22 · @modelcontextprotocol/server 2.4.0 · @modelcontextprotocol/client 2.4.0 · @modelcontextprotocol/node 2.1.2 · zod 4.6.7

You will build an MCP server that keeps no session state, run two copies of it behind a plain round-robin load balancer, and watch one client's requests land on different instances without anything breaking. No sticky sessions, no Redis session store.

This works because the 2026-07-28 MCP specification made the protocol stateless. The official TypeScript SDK v2 supports it out of the box.

What changed in 2026-07-28

Earlier revisions, up to 2025-11-25, opened every connection with an initialize / initialized handshake. Over HTTP, the server then issued an Mcp-Session-Id header and every later request had to carry it back to the same server. That is why remote MCP servers needed sticky sessions or a shared session store.

The 2026-07-28 release removes both:

  • No handshake, no session ID. Each request carries its protocol version, client info and client capabilities in _meta.
  • Optional discovery. A client that wants the server's capabilities up front can call the new server/discover method. It is not required.
  • Routing headers. Streamable HTTP requests must send Mcp-Method and Mcp-Name, so gateways and rate limiters can route without parsing the JSON body.
  • Cacheable lists. tools/list and similar results carry ttlMs and cacheScope hints.

The result: any request can be served by any instance. That suits serverless platforms, autoscaling groups and ordinary load balancers.

1. Install the SDK

The v2 SDK replaces the single @modelcontextprotocol/sdk package with separate server and client packages:

terminal
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server @modelcontextprotocol/node @modelcontextprotocol/client zod

This example used @modelcontextprotocol/server 2.4.0, @modelcontextprotocol/client 2.4.0, @modelcontextprotocol/node 2.1.2, zod 4.6.7 and Node.js 22.22. Node 22.18 and later run .ts files directly, so there is no build step.

2. Write the server

The server has one tool, days-until. It also reports which instance answered, so you can see the load balancer at work later.

server.ts
import { createServer } from 'node:http';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import { localhostHostValidation, localhostOriginValidation, toNodeHandler } from '@modelcontextprotocol/node';
import * as z from 'zod/v4';

const port = Number(process.env.PORT ?? 3001);
const instance = process.env.INSTANCE ?? 'a';

// Runs once per HTTP request. Nothing survives between requests.
const handler = createMcpHandler(() => {
  const server = new McpServer({ name: 'dates', version: '1.0.0' });

  server.registerTool(
    'days-until',
    {
      description: 'Count the days from today until a date',
      inputSchema: z.object({
        date: z.iso.date().describe('Target date, YYYY-MM-DD')
      }),
      outputSchema: z.object({ date: z.string(), days: z.number(), instance: z.string() })
    },
    async ({ date }) => {
      const today = new Date(new Date().toISOString().slice(0, 10));
      const days = Math.round((Date.parse(date) - today.getTime()) / 86_400_000);
      const output = { date, days, instance };
      return {
        content: [{ type: 'text', text: `${days} days until ${date}` }],
        structuredContent: output
      };
    }
  );

  return server;
});

const nodeHandler = toNodeHandler(handler);
const validateHost = localhostHostValidation();
const validateOrigin = localhostOriginValidation();

createServer((req, res) => {
  if (!validateHost(req, res) || !validateOrigin(req, res)) return;
  void nodeHandler(req, res);
}).listen(port, '127.0.0.1', () => {
  console.log(`instance ${instance} on http://127.0.0.1:${port}/mcp`);
});

createMcpHandler is the important part. It takes a factory and builds a fresh McpServer for every HTTP request. That is what makes the server stateless: there is no instance to keep alive between calls. Keep the factory cheap, and create database pools or caches once at module level.

The handler checks no headers by itself. The Host and Origin checks in front of it stop DNS rebinding attacks on a local server, as the SDK's HTTP guide explains.

Start two instances in separate terminals:

terminal
PORT=3001 INSTANCE=a node server.ts
PORT=3002 INSTANCE=b node server.ts
text
instance a on http://127.0.0.1:3001/mcp
instance b on http://127.0.0.1:3002/mcp

3. Call a tool with curl, no handshake

With the 2026-07-28 revision, the very first request can be a tool call:

terminal
curl -s -i http://127.0.0.1:3001/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: days-until' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"days-until","arguments":{"date":"2026-12-25"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"curl","version":"8"},"io.modelcontextprotocol/clientCapabilities":{}}}}'
text
HTTP/1.1 200 OK
content-type: application/json
Date: Thu, 12 Nov 2026 15:25:41 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked

{"result":{"content":[{"type":"text","text":"43 days until 2026-12-25"}],"structuredContent":{"date":"2026-12-25","days":43,"instance":"a"},"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"dates","version":"1.0.0"}}},"jsonrpc":"2.0","id":1}

There is no Mcp-Session-Id in the response, and nothing for the client to remember. Send the same request to port 3002 and instance b answers it the same way.

The routing headers are not optional. Leave out Mcp-Method and the server rejects the request with HTTP 400:

text
{"jsonrpc":"2.0","error":{"code":-32020,"message":"Bad Request: the request headers and body disagree: the body names method tools/call but the required Mcp-Method header is absent","data":{"mismatch":{"header":"(missing)","body":"the body names method tools/call but the required Mcp-Method header is absent"}}},"id":3}

4. Put both instances behind a round-robin balancer

A real deployment would use nginx, a cloud load balancer or a serverless platform. This short balancer is enough to prove the point. It sends each request to the next backend in turn and keeps no affinity:

balancer.ts
import { createServer } from 'node:http';

// Plain round robin: no sticky sessions, no shared storage.
const backends = ['http://127.0.0.1:3001', 'http://127.0.0.1:3002'];
let next = 0;

createServer(async (req, res) => {
  const target = backends[next++ % backends.length];
  const chunks: Buffer[] = [];
  for await (const chunk of req) chunks.push(chunk);

  const upstream = await fetch(target + req.url, {
    method: req.method,
    headers: Object.fromEntries(
      Object.entries(req.headers).filter(([key]) => key !== 'host') as [string, string][]
    ),
    body: chunks.length ? Buffer.concat(chunks) : undefined
  });

  console.log(`${req.headers['mcp-method']} -> ${target}`);
  res.writeHead(upstream.status, Object.fromEntries(upstream.headers));
  res.end(Buffer.from(await upstream.arrayBuffer()));
}).listen(3000, '127.0.0.1');
terminal
node balancer.ts

Notice that the balancer logs the method from the Mcp-Method header without reading the body. Real gateways can do the same for routing, metering and authorization.

5. Connect with the SDK client

The client connects to the balancer, lists the tools and makes three calls:

client.ts
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';

const client = new Client(
  { name: 'demo-client', version: '1.0.0' },
  { versionNegotiation: { mode: { pin: '2026-07-28' } } }
);

await client.connect(new StreamableHTTPClientTransport(new URL('http://127.0.0.1:3000/mcp')));
console.log('era:', client.getProtocolEra());

const { tools } = await client.listTools();
console.log('tools:', tools.map(tool => tool.name));

for (const date of ['2026-12-25', '2027-01-01', '2027-03-01']) {
  const result = await client.callTool({ name: 'days-until', arguments: { date } });
  console.log(result.structuredContent);
}

await client.close();
terminal
node client.ts
text
era: modern
tools: [ 'days-until' ]
{ date: '2026-12-25', days: 43, instance: 'a' }
{ date: '2027-01-01', days: 50, instance: 'b' }
{ date: '2027-03-01', days: 109, instance: 'a' }

The balancer's log shows that every request went to whichever instance was next:

text
server/discover -> http://127.0.0.1:3001
tools/list -> http://127.0.0.1:3002
tools/call -> http://127.0.0.1:3001
tools/call -> http://127.0.0.1:3002
tools/call -> http://127.0.0.1:3001

The client discovered the server on instance a, listed tools on b, then alternated. A sessionful 2025-era server behind this balancer would have rejected the second request, because instance b never saw the session that instance a created.

What you give up

A stateless protocol does not make state disappear. It moves it somewhere you can see:

  • No hidden session state. If a tool needs context from an earlier call, return an explicit handle, such as a cart ID, and have the model pass it back as an argument. The spec announcement recommends this. The data behind the handle still has to live in storage every instance can reach.
  • Mid-call questions work differently. The server can no longer send requests down a held-open stream. A tool that needs user input returns resultType: "input_required", and the client retries the call with the answers. This is called Multi Round-Trip Requests (MRTR). Anything the server needs to remember between rounds goes in requestState, which the client echoes back. Sign it, because it is untrusted input. The SDK's createRequestStateCodec does that with HMAC.
  • Deprecated features. Sampling, Roots and Logging are deprecated. They keep working for at least twelve months.
  • Notifications across nodes need pub/sub. Change notifications now go through a subscriptions/listen stream. The SDK's default event bus lives in one process, so with several instances you need to pass every node a shared ServerEventBus, for example one built on Redis.

If your server runs locally over stdio for a single desktop client, none of the scaling benefits apply. Upgrade for compatibility, not for scale.

Migrating from a 2025-11-25 server

  • Both eras on one endpoint. By default createMcpHandler also serves 2025-era clients, each request from a fresh instance. A v2 client in its default legacy mode connected through the same balancer and got era: legacy with the same tool result. Legacy GET streams and DELETE session requests get 405, because there are no sessions.
  • Keeping a sessionful deployment. Put isLegacyRequest in front of a strict handler created with legacy: 'reject', and send legacy traffic to your existing transport. The legacy clients guide shows the full routing.
  • State keyed on the session ID. Code that read extra.sessionId needs explicit handles or requestState.
  • Coming from SDK v1. v2 ships a codemod for import paths and renamed APIs, such as registerTool in place of tool(). Start with the upgrade guide.

Next steps

Related tutorials