Skip to content

Commit f7af617

Browse files
cliffhallclaude
andcommitted
fix(everything): answer unknown and duplicate SSE sessions
The HTTP+SSE transport left POST /message for an unknown session and a second GET /sse for a live session unanswered, and GET /sse with an unknown sessionId threw a TypeError that Express turned into a 500. Each now gets a prompt JSON-RPC error response: 404 for an unknown session (POST or GET), 400 for a POST with no sessionId, and 409 for a GET /sse naming a session that already has its stream. A rejected GET /sse no longer builds a server it never connects. The pinning tests in sse.test.ts now assert these responses, and their KNOWN BUG modelcontextprotocol#4981 markers are removed. Closes modelcontextprotocol#4981 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 571e2b3 commit f7af617

3 files changed

Lines changed: 125 additions & 67 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+
The HTTP+SSE transport now answers requests for sessions it cannot serve instead of leaving them hanging or failing with a 500: `POST /message` for an unknown session returns `404` (and `400` with no `sessionId`), and `GET /sse?sessionId=…` returns `409` for a session that already has its stream and `404` for an unknown one. Each carries a JSON-RPC error body.

‎src/everything/__tests__/sse.test.ts‎

Lines changed: 71 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -43,17 +43,6 @@ async function connectSse() {
4343
return { client, sessionId };
4444
}
4545

46-
/** Whether `request` gets any response within `ms`. */
47-
async function respondsWithin(url: string, init: RequestInit, ms = 300) {
48-
try {
49-
await fetch(url, { ...init, signal: AbortSignal.timeout(ms) });
50-
return true;
51-
} catch (e) {
52-
if (e instanceof Error && e.name === "TimeoutError") return false;
53-
throw e;
54-
}
55-
}
56-
5746
describe("SSE transport", () => {
5847
it("serves the protocol: GET /sse opens the stream, POST /message carries requests", async () => {
5948
const { client, sessionId } = await connectSse();
@@ -83,58 +72,99 @@ describe("SSE transport", () => {
8372
await Promise.all([a.client.close(), b.client.close()]);
8473
});
8574

86-
// KNOWN BUG #4981: POST /message for an unknown session is never answered; the fix changes this assertion.
8775
it("forgets the session and cleans up when the stream closes", async () => {
8876
const { client, sessionId } = await connectSse();
8977
await client.close();
9078
await vi.waitFor(() =>
9179
expect(error).toHaveBeenCalledWith("Client Disconnected: ", sessionId),
9280
);
93-
// A message for the closed session finds no transport and gets no answer.
94-
const answered = await respondsWithin(
95-
`${base}/message?sessionId=${sessionId}`,
96-
{
97-
method: "POST",
98-
headers: { "content-type": "application/json" },
99-
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }),
100-
},
101-
);
102-
expect(answered).toBe(false);
81+
// A message for the closed session finds no transport and is answered 404.
82+
const response = await fetch(`${base}/message?sessionId=${sessionId}`, {
83+
method: "POST",
84+
headers: { "content-type": "application/json" },
85+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }),
86+
signal: AbortSignal.timeout(2000),
87+
});
88+
expect(response.status).toBe(404);
10389
expect(error).toHaveBeenCalledWith(
10490
`No transport found for sessionId ${sessionId}`,
10591
);
10692
});
10793

108-
// KNOWN BUG #4981: POST /message for an unknown session is never answered; the fix changes this assertion.
109-
it("never answers a POST for an unknown session", async () => {
110-
expect(
111-
await respondsWithin(`${base}/message?sessionId=nope`, {
112-
method: "POST",
113-
body: "{}",
114-
}),
115-
).toBe(false);
94+
it("answers a POST for an unknown session with a 404", async () => {
95+
const response = await fetch(`${base}/message?sessionId=nope`, {
96+
method: "POST",
97+
body: "{}",
98+
signal: AbortSignal.timeout(2000),
99+
});
100+
expect(response.status).toBe(404);
101+
expect(await response.json()).toEqual({
102+
jsonrpc: "2.0",
103+
error: { code: -32000, message: "Session not found" },
104+
id: null,
105+
});
116106
expect(error).toHaveBeenCalledWith("No transport found for sessionId nope");
117107
});
118108

119-
// KNOWN BUG #4981: a second GET /sse for an existing session is never answered; the fix changes this assertion.
120-
it("never answers a second GET /sse for an existing session, and only logs it", async () => {
109+
it("answers a POST with no session id with a 400", async () => {
110+
const response = await fetch(`${base}/message`, {
111+
method: "POST",
112+
body: "{}",
113+
signal: AbortSignal.timeout(2000),
114+
});
115+
expect(response.status).toBe(400);
116+
expect(await response.json()).toEqual({
117+
jsonrpc: "2.0",
118+
error: {
119+
code: -32000,
120+
message: "Bad Request: sessionId query parameter is required",
121+
},
122+
id: null,
123+
});
124+
});
125+
126+
it("answers a second GET /sse for an existing session with a 409, and keeps the first stream", async () => {
121127
const { client, sessionId } = await connectSse();
122-
expect(await respondsWithin(`${base}/sse?sessionId=${sessionId}`, {})).toBe(
123-
false,
124-
);
128+
const response = await fetch(`${base}/sse?sessionId=${sessionId}`, {
129+
signal: AbortSignal.timeout(2000),
130+
});
131+
expect(response.status).toBe(409);
132+
expect(await response.json()).toEqual({
133+
jsonrpc: "2.0",
134+
error: {
135+
code: -32000,
136+
message: "Conflict: this session already has an SSE stream",
137+
},
138+
id: null,
139+
});
125140
expect(error).toHaveBeenCalledWith(
126141
"Client Reconnecting? This shouldn't happen; when client has a sessionId, GET /sse should not be called again.",
127142
sessionId,
128143
);
144+
// The original session is untouched and still serves requests.
145+
const result = await client.callTool({
146+
name: "echo",
147+
arguments: { message: "still here" },
148+
});
149+
expect(result.content).toEqual([
150+
{ type: "text", text: "Echo: still here" },
151+
]);
129152
await client.close();
130153
});
131154

132-
// KNOWN BUG #4981: GET /sse?sessionId=<unknown> throws a TypeError that surfaces as a 500; the fix changes this assertion.
133-
it("fails a GET /sse for an unknown session id with a 500", async () => {
134-
// Characterization: the reconnect branch reads `.sessionId` of a missing
135-
// transport, and Express turns the TypeError into a 500.
136-
const response = await fetch(`${base}/sse?sessionId=unknown`);
137-
expect(response.status).toBe(500);
155+
it("answers a GET /sse for an unknown session id with a 404", async () => {
156+
const response = await fetch(`${base}/sse?sessionId=unknown`, {
157+
signal: AbortSignal.timeout(2000),
158+
});
159+
expect(response.status).toBe(404);
160+
expect(await response.json()).toEqual({
161+
jsonrpc: "2.0",
162+
error: { code: -32000, message: "Session not found" },
163+
id: null,
164+
});
165+
expect(error).toHaveBeenCalledWith(
166+
"No transport found for sessionId unknown",
167+
);
138168
});
139169

140170
it("answers a CORS preflight for any origin", async () => {

‎src/everything/transports/sse.ts‎

Lines changed: 49 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,24 @@
66
// app has its own session map. `startSseServer()` is what the launcher runs.
77

88
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
9-
import express, { type Express } from "express";
9+
import express, { type Express, type Response } from "express";
1010
import type { Server } from "node:http";
1111
import { createServer } from "../server/index.js";
1212
import cors from "cors";
1313
import { listenOrExit } from "./listen.js";
1414

15+
/**
16+
* Answer a request the transport cannot serve with a JSON-RPC error body, as
17+
* the Streamable HTTP transport does, so the client is not left waiting.
18+
*/
19+
function sendError(res: Response, status: number, message: string): void {
20+
res.status(status).json({
21+
jsonrpc: "2.0",
22+
error: { code: -32000, message },
23+
id: null,
24+
});
25+
}
26+
1527
/**
1628
* Build the SSE transport's Express app: CORS, `GET /sse` and `POST /message`,
1729
* and the map from session id to transport that they share.
@@ -36,35 +48,41 @@ export function createApp(): Express {
3648

3749
// Handle GET requests for new SSE streams
3850
app.get("/sse", async (req, res) => {
39-
let transport: SSEServerTransport;
51+
// Session Id should not exist for GET /sse requests: each stream is a new
52+
// session. Answer one that names a session rather than leaving it hanging
53+
// (#4981): 409 if that session already has its stream, 404 if it is unknown.
54+
if (req?.query?.sessionId) {
55+
const sessionId = String(req.query.sessionId);
56+
if (transports.has(sessionId)) {
57+
console.error(
58+
"Client Reconnecting? This shouldn't happen; when client has a sessionId, GET /sse should not be called again.",
59+
sessionId,
60+
);
61+
sendError(res, 409, "Conflict: this session already has an SSE stream");
62+
} else {
63+
console.error(`No transport found for sessionId ${sessionId}`);
64+
sendError(res, 404, "Session not found");
65+
}
66+
return;
67+
}
68+
69+
// Create and store transport for the new session
4070
const { server, cleanup } = createServer();
71+
const transport = new SSEServerTransport("/message", res);
72+
transports.set(transport.sessionId, transport);
4173

42-
// Session Id should not exist for GET /sse requests
43-
if (req?.query?.sessionId) {
44-
const sessionId = req?.query?.sessionId as string;
45-
transport = transports.get(sessionId) as SSEServerTransport;
46-
console.error(
47-
"Client Reconnecting? This shouldn't happen; when client has a sessionId, GET /sse should not be called again.",
48-
transport.sessionId,
49-
);
50-
} else {
51-
// Create and store transport for the new session
52-
transport = new SSEServerTransport("/message", res);
53-
transports.set(transport.sessionId, transport);
74+
// Connect server to transport
75+
await server.connect(transport);
76+
const sessionId = transport.sessionId;
77+
console.error("Client Connected: ", sessionId);
5478

55-
// Connect server to transport
56-
await server.connect(transport);
79+
// Handle close of connection
80+
server.server.onclose = async () => {
5781
const sessionId = transport.sessionId;
58-
console.error("Client Connected: ", sessionId);
59-
60-
// Handle close of connection
61-
server.server.onclose = async () => {
62-
const sessionId = transport.sessionId;
63-
console.error("Client Disconnected: ", sessionId);
64-
transports.delete(sessionId);
65-
cleanup(sessionId);
66-
};
67-
}
82+
console.error("Client Disconnected: ", sessionId);
83+
transports.delete(sessionId);
84+
cleanup(sessionId);
85+
};
6886
});
6987

7088
// Handle POST requests for client messages
@@ -77,8 +95,13 @@ export function createApp(): Express {
7795
if (transport) {
7896
console.error("Client Message from", sessionId);
7997
await transport.handlePostMessage(req, res);
98+
} else if (!sessionId) {
99+
// Answer rather than leave the request hanging (#4981)
100+
console.error("No sessionId in POST /message");
101+
sendError(res, 400, "Bad Request: sessionId query parameter is required");
80102
} else {
81103
console.error(`No transport found for sessionId ${sessionId}`);
104+
sendError(res, 404, "Session not found");
82105
}
83106
});
84107

0 commit comments

Comments
 (0)