Skip to content

Commit 90f85b7

Browse files
authored
Merge pull request #5006 from modelcontextprotocol/v2/fix/4087-everything-streamable-http
fix(everything): Streamable HTTP 404 for unknown sessions, per-stream replay, shutdown closes sessions
2 parents 0c98518 + 3140924 commit 90f85b7

6 files changed

Lines changed: 334 additions & 104 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@modelcontextprotocol/server-everything": patch
3+
---
4+
5+
Streamable HTTP: answer an unknown or ended session ID with `404 Not Found` (carrying the request's `id` on a POST) instead of `400`; replay only the resumed stream's events after a `Last-Event-ID`, and refuse an unknown one; close every open session on shutdown.
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
// Unit tests for the Streamable HTTP event store (#4087), called directly
2+
// rather than over HTTP: which events a replay sends, and what an unknown event
3+
// id yields, are exact here, where streamable-http.test.ts can only observe
4+
// them through the SDK (which asks getStreamIdForEventId first and refuses an
5+
// unknown id before replaying).
6+
7+
import { describe, it, expect } from "vitest";
8+
import type { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js";
9+
import { InMemoryEventStore } from "../transports/in-memory-event-store.js";
10+
11+
const message = (method: string): JSONRPCMessage => ({
12+
jsonrpc: "2.0",
13+
method,
14+
});
15+
16+
describe("InMemoryEventStore", () => {
17+
it("replays only events from the same stream after the requested event", async () => {
18+
const eventStore = new InMemoryEventStore();
19+
const firstStreamEvent = await eventStore.storeEvent(
20+
"stream-a",
21+
message("notifications/stream-a/first"),
22+
);
23+
const otherStreamEvent = await eventStore.storeEvent(
24+
"stream-b",
25+
message("notifications/stream-b/first"),
26+
);
27+
const secondStreamEvent = await eventStore.storeEvent(
28+
"stream-a",
29+
message("notifications/stream-a/second"),
30+
);
31+
await eventStore.storeEvent(
32+
"stream-b",
33+
message("notifications/stream-b/second"),
34+
);
35+
36+
const replayedEvents: Array<{ eventId: string; message: JSONRPCMessage }> =
37+
[];
38+
const replayedStreamId = await eventStore.replayEventsAfter(
39+
firstStreamEvent,
40+
{
41+
send: async (eventId, replayedMessage) => {
42+
replayedEvents.push({ eventId, message: replayedMessage });
43+
},
44+
},
45+
);
46+
47+
expect(replayedStreamId).toBe("stream-a");
48+
expect(replayedEvents).toEqual([
49+
{
50+
eventId: secondStreamEvent,
51+
message: message("notifications/stream-a/second"),
52+
},
53+
]);
54+
expect(replayedEvents.map(({ eventId }) => eventId)).not.toContain(
55+
otherStreamEvent,
56+
);
57+
});
58+
59+
it("rejects an unknown event id without replaying anything", async () => {
60+
const eventStore = new InMemoryEventStore();
61+
await eventStore.storeEvent("stream-a", message("notifications/stream-a"));
62+
63+
const replayedEvents: Array<{ eventId: string; message: JSONRPCMessage }> =
64+
[];
65+
await expect(
66+
eventStore.replayEventsAfter("unknown-event-id", {
67+
send: async (eventId, replayedMessage) => {
68+
replayedEvents.push({ eventId, message: replayedMessage });
69+
},
70+
}),
71+
).rejects.toThrow("Unknown event ID: unknown-event-id");
72+
expect(replayedEvents).toEqual([]);
73+
});
74+
75+
it("looks up the stream id for a stored event id", async () => {
76+
const eventStore = new InMemoryEventStore();
77+
const eventId = await eventStore.storeEvent(
78+
"stream-a",
79+
message("notifications/stream-a"),
80+
);
81+
82+
await expect(eventStore.getStreamIdForEventId(eventId)).resolves.toBe(
83+
"stream-a",
84+
);
85+
await expect(
86+
eventStore.getStreamIdForEventId("unknown-event-id"),
87+
).resolves.toBeUndefined();
88+
});
89+
});

‎src/everything/__tests__/streamable-http.test.ts‎

Lines changed: 114 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
/**
22
* Characterizes the Streamable HTTP transport manager (#4854). `createApp()`
33
* is served on a free loopback port and driven by the SDK's Streamable HTTP
4-
* client, and by raw HTTP where the test pins the wire itself: the 400s for
5-
* missing or unknown sessions, the priming event on each SSE stream (#3267),
6-
* and the event store's replay of events from other streams (#4087). The
7-
* shutdown handler is called directly, and `startStreamableHttpServer()` is
4+
* client, and by raw HTTP where the test pins the wire itself: the 400 for a
5+
* missing session and the 404 for an unknown one (#4982), the priming event on
6+
* each SSE stream (#3267), and the event store's replay of the resumed stream
7+
* only (#4087). The shutdown handler is called directly (#4983), and
8+
* `startStreamableHttpServer()` is
89
* checked with `listenOrExit` stubbed, so no fixed port is ever bound.
910
*/
1011
import type { Server } from "node:http";
@@ -58,6 +59,12 @@ const BAD_SESSION = {
5859
error: { code: -32000, message: "Bad Request: No valid session ID provided" },
5960
};
6061

62+
const SESSION_NOT_FOUND = {
63+
jsonrpc: "2.0",
64+
error: { code: -32001, message: "Session not found" },
65+
id: null,
66+
};
67+
6168
type SseEvent = { id?: string; data: string };
6269

6370
/** Parse a complete SSE body into its events. */
@@ -111,22 +118,30 @@ async function rawInitialize() {
111118
return { sessionId, events };
112119
}
113120

114-
/** Read an open SSE response until `done(text)` holds, then abort it. */
115-
async function readUntil(
121+
/**
122+
* Read an open SSE response for `ms`, then abort it. A replay is written
123+
* before the response's headers are, so it has all arrived by then.
124+
*/
125+
async function readFor(
116126
response: Response,
117-
done: (text: string) => boolean,
127+
ms: number,
118128
controller: AbortController,
119129
): Promise<string> {
120130
const reader = response.body!.getReader();
121131
const decoder = new TextDecoder();
122132
let text = "";
123-
const deadline = Date.now() + 2000;
124-
while (!done(text) && Date.now() < deadline) {
125-
const { value, done: ended } = await reader.read();
126-
if (ended) break;
127-
text += decoder.decode(value);
133+
const timer = setTimeout(() => controller.abort(), ms);
134+
try {
135+
for (;;) {
136+
const { value, done } = await reader.read();
137+
if (done) break;
138+
text += decoder.decode(value);
139+
}
140+
} catch {
141+
// aborted: the read window is over
142+
} finally {
143+
clearTimeout(timer);
128144
}
129-
controller.abort();
130145
return text;
131146
}
132147

@@ -158,11 +173,10 @@ describe("Streamable HTTP transport", () => {
158173
});
159174
});
160175

161-
// KNOWN BUG #4087: pins current (wrong) behavior; the fix changes this assertion.
162-
it("replays events from other streams after a Last-Event-ID (#4087)", async () => {
163-
// Characterization of #4087: the in-memory event store replays every
164-
// event stored after the given one, whatever stream it belongs to, so a
165-
// GET resuming the initialize stream receives a later tool result.
176+
it("replays only the resumed stream's events after a Last-Event-ID (#4087)", async () => {
177+
// The initialize stream is resumed from its priming event: its own
178+
// response is replayed, and the tool result stored afterwards on another
179+
// stream is not.
166180
const { sessionId, events } = await rawInitialize();
167181
const echo = await post(
168182
{
@@ -173,45 +187,43 @@ describe("Streamable HTTP transport", () => {
173187
},
174188
sessionId,
175189
);
176-
await echo.text();
190+
expect(await echo.text()).toContain("Echo: from another stream");
177191

178192
const controller = new AbortController();
179193
const resumed = await fetch(mcp, {
180194
headers: {
181195
accept: "text/event-stream",
182196
"mcp-session-id": sessionId,
183197
"mcp-protocol-version": "2025-11-25",
184-
"last-event-id": events[1].id!,
198+
"last-event-id": events[0].id!,
185199
},
186200
signal: controller.signal,
187201
});
188202
expect(resumed.status).toBe(200);
189-
const text = await readUntil(
190-
resumed,
191-
(t) => t.includes("from another stream"),
192-
controller,
193-
);
194-
expect(text).toContain("Echo: from another stream");
203+
const replayed = parseSse(await readFor(resumed, 250, controller));
204+
expect(replayed).toEqual([{ id: events[1].id, data: events[1].data }]);
195205
expect(log).toHaveBeenCalledWith(
196-
`Client reconnecting with Last-Event-ID: ${events[1].id}`,
206+
`Client reconnecting with Last-Event-ID: ${events[0].id}`,
197207
);
198208
});
199209

200-
it("opens a standalone SSE stream, replaying nothing for an unknown Last-Event-ID", async () => {
210+
it("refuses a GET resuming from an unknown Last-Event-ID with a 400 (#4087)", async () => {
211+
// The event store reports no stream for the id, so the SDK refuses the
212+
// resume rather than mapping it to a stream that does not exist.
201213
const { sessionId } = await rawInitialize();
202-
const controller = new AbortController();
203214
const response = await fetch(mcp, {
204215
headers: {
205216
accept: "text/event-stream",
206217
"mcp-session-id": sessionId,
207218
"mcp-protocol-version": "2025-11-25",
208219
"last-event-id": "no-such-event",
209220
},
210-
signal: controller.signal,
211221
});
212-
expect(response.status).toBe(200);
213-
expect(response.headers.get("content-type")).toBe("text/event-stream");
214-
controller.abort();
222+
expect(response.status).toBe(400);
223+
expect(await response.json()).toMatchObject({
224+
jsonrpc: "2.0",
225+
error: { code: -32000, message: "Invalid event ID format" },
226+
});
215227
});
216228

217229
it("opens a standalone SSE stream without a Last-Event-ID", async () => {
@@ -241,31 +253,50 @@ describe("Streamable HTTP transport", () => {
241253
},
242254
);
243255

244-
// KNOWN BUG #4982: answers 400, not the 404 the spec requires, for an unknown or terminated session ID; the fix changes this assertion.
245256
it.each(["GET", "DELETE"])(
246-
"answers %s for an unknown session with a 400",
257+
"answers %s for an unknown session with a 404 (#4982)",
247258
async (method) => {
248259
const response = await fetch(mcp, {
249260
method,
250261
headers: { "mcp-session-id": "unknown" },
251262
});
252-
expect(response.status).toBe(400);
253-
expect(await response.json()).toEqual(BAD_SESSION);
263+
expect(response.status).toBe(404);
264+
expect(await response.json()).toEqual(SESSION_NOT_FOUND);
254265
},
255266
);
256267

257-
// KNOWN BUG #4982: answers 400, not the 404 the spec requires, for an unknown or terminated session ID, and the error omits the request id; the fix changes this assertion.
258-
it("answers a POST for an unknown session with a 400 that omits the request id", async () => {
259-
// Characterization: no body parser runs before this check, so
260-
// `req.body` is undefined and the error carries no `id`.
268+
it("answers a POST for an unknown session with a 404 that carries the request id (#4982)", async () => {
261269
const response = await post(
262270
{ jsonrpc: "2.0", id: 7, method: "ping" },
263271
"unknown",
264272
);
265-
expect(response.status).toBe(400);
266-
expect(await response.json()).toEqual(BAD_SESSION);
273+
expect(response.status).toBe(404);
274+
expect(await response.json()).toEqual({ ...SESSION_NOT_FOUND, id: 7 });
267275
});
268276

277+
it.each([
278+
["a notification", JSON.stringify({ jsonrpc: "2.0", method: "ping" })],
279+
["a batch", JSON.stringify([{ jsonrpc: "2.0", id: 8, method: "ping" }])],
280+
["a response", JSON.stringify({ jsonrpc: "2.0", id: 8, result: {} })],
281+
["an object that is not JSON-RPC", JSON.stringify({ id: 8 })],
282+
["malformed JSON", "{not json"],
283+
[
284+
"a body too large to read for its id",
285+
JSON.stringify({ jsonrpc: "2.0", id: 8, pad: "x".repeat(70 * 1024) }),
286+
],
287+
])(
288+
"answers a POST of %s for an unknown session with a 404 and a null id",
289+
async (_label, body) => {
290+
const response = await fetch(mcp, {
291+
method: "POST",
292+
headers: { ...JSON_HEADERS, "mcp-session-id": "unknown" },
293+
body,
294+
});
295+
expect(response.status).toBe(404);
296+
expect(await response.json()).toEqual(SESSION_NOT_FOUND);
297+
},
298+
);
299+
269300
it("creates a server for a session-less POST that is not initialize, which the SDK then rejects", async () => {
270301
const response = await post({ jsonrpc: "2.0", id: 1, method: "ping" });
271302
expect(response.status).toBe(400);
@@ -275,8 +306,7 @@ describe("Streamable HTTP transport", () => {
275306
});
276307
});
277308

278-
// KNOWN BUG #4982: answers 400, not the 404 the spec requires, for an unknown or terminated session ID; the fix changes this assertion.
279-
it("ends a session on DELETE, cleaning it up and refusing it afterwards", async () => {
309+
it("ends a session on DELETE, cleaning it up and refusing it afterwards with a 404 (#4982)", async () => {
280310
const { client, transport, sessionId } = await connectHttp();
281311
await transport.terminateSession();
282312
expect(log).toHaveBeenCalledWith(
@@ -291,7 +321,8 @@ describe("Streamable HTTP transport", () => {
291321
{ jsonrpc: "2.0", id: 9, method: "ping" },
292322
sessionId,
293323
);
294-
expect(after.status).toBe(400);
324+
expect(after.status).toBe(404);
325+
expect(await after.json()).toEqual({ ...SESSION_NOT_FOUND, id: 9 });
295326
await client.close();
296327
});
297328

@@ -378,29 +409,51 @@ describe("Streamable HTTP transport", () => {
378409
});
379410

380411
describe("shutdown", () => {
381-
// KNOWN BUG #4983: the SIGINT handler walks the session Map with for...in, so it never closes a session; the fix changes this assertion.
382-
it("logs and exits 0 without closing any session", async () => {
383-
// Characterization: the handler walks the session Map with `for...in`,
384-
// which visits no entries, so no transport is closed (#4854 baseline).
412+
it("closes every open session, then logs and exits 0 (#4983)", async () => {
385413
const exit = vi
386414
.spyOn(process, "exit")
387415
.mockImplementation(() => undefined as never);
388-
const { client } = await connectHttp();
416+
const first = await connectHttp();
417+
const second = await connectHttp();
389418
await app.shutdown();
390419
expect(log).toHaveBeenCalledWith("Shutting down server...");
420+
for (const { sessionId } of [first, second]) {
421+
expect(log).toHaveBeenCalledWith(
422+
`Closing transport for session ${sessionId}`,
423+
);
424+
expect(log).toHaveBeenCalledWith(
425+
`Transport closed for session ${sessionId}, removing from transports map`,
426+
);
427+
// The session is gone: the server answers it as unknown.
428+
const after = await post(
429+
{ jsonrpc: "2.0", id: 1, method: "ping" },
430+
sessionId,
431+
);
432+
expect(after.status).toBe(404);
433+
}
391434
expect(log).toHaveBeenCalledWith("Server shutdown complete");
392-
expect(log).not.toHaveBeenCalledWith(
393-
expect.stringMatching(/^Closing transport for session/),
435+
expect(exit).toHaveBeenCalledWith(0);
436+
await first.client.close();
437+
await second.client.close();
438+
});
439+
440+
it("logs a session that fails to close and still exits 0", async () => {
441+
const exit = vi
442+
.spyOn(process, "exit")
443+
.mockImplementation(() => undefined as never);
444+
const { client, sessionId } = await connectHttp();
445+
const failure = new Error("close failed");
446+
vi.spyOn(
447+
StreamableHTTPServerTransport.prototype,
448+
"close",
449+
).mockRejectedValueOnce(failure);
450+
await app.shutdown();
451+
expect(log).toHaveBeenCalledWith(
452+
`Error closing transport for session ${sessionId}:`,
453+
failure,
394454
);
455+
expect(log).toHaveBeenCalledWith("Server shutdown complete");
395456
expect(exit).toHaveBeenCalledWith(0);
396-
// The session still works.
397-
const result = await client.callTool({
398-
name: "echo",
399-
arguments: { message: "still here" },
400-
});
401-
expect(result.content).toEqual([
402-
{ type: "text", text: "Echo: still here" },
403-
]);
404457
await client.close();
405458
});
406459
});

0 commit comments

Comments
 (0)