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 */
1011import 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+
6168type 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,47 @@ 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+ [ "malformed JSON" , "{not json" ] ,
280+ [
281+ "a body too large to read for its id" ,
282+ JSON . stringify ( { jsonrpc : "2.0" , id : 8 , pad : "x" . repeat ( 70 * 1024 ) } ) ,
283+ ] ,
284+ ] ) (
285+ "answers a POST of %s for an unknown session with a 404 and a null id" ,
286+ async ( _label , body ) => {
287+ const response = await fetch ( mcp , {
288+ method : "POST" ,
289+ headers : { ...JSON_HEADERS , "mcp-session-id" : "unknown" } ,
290+ body,
291+ } ) ;
292+ expect ( response . status ) . toBe ( 404 ) ;
293+ expect ( await response . json ( ) ) . toEqual ( SESSION_NOT_FOUND ) ;
294+ } ,
295+ ) ;
296+
269297 it ( "creates a server for a session-less POST that is not initialize, which the SDK then rejects" , async ( ) => {
270298 const response = await post ( { jsonrpc : "2.0" , id : 1 , method : "ping" } ) ;
271299 expect ( response . status ) . toBe ( 400 ) ;
@@ -275,8 +303,7 @@ describe("Streamable HTTP transport", () => {
275303 } ) ;
276304 } ) ;
277305
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 ( ) => {
306+ it ( "ends a session on DELETE, cleaning it up and refusing it afterwards with a 404 (#4982)" , async ( ) => {
280307 const { client, transport, sessionId } = await connectHttp ( ) ;
281308 await transport . terminateSession ( ) ;
282309 expect ( log ) . toHaveBeenCalledWith (
@@ -291,7 +318,8 @@ describe("Streamable HTTP transport", () => {
291318 { jsonrpc : "2.0" , id : 9 , method : "ping" } ,
292319 sessionId ,
293320 ) ;
294- expect ( after . status ) . toBe ( 400 ) ;
321+ expect ( after . status ) . toBe ( 404 ) ;
322+ expect ( await after . json ( ) ) . toEqual ( { ...SESSION_NOT_FOUND , id : 9 } ) ;
295323 await client . close ( ) ;
296324 } ) ;
297325
@@ -378,29 +406,51 @@ describe("Streamable HTTP transport", () => {
378406} ) ;
379407
380408describe ( "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).
409+ it ( "closes every open session, then logs and exits 0 (#4983)" , async ( ) => {
385410 const exit = vi
386411 . spyOn ( process , "exit" )
387412 . mockImplementation ( ( ) => undefined as never ) ;
388- const { client } = await connectHttp ( ) ;
413+ const first = await connectHttp ( ) ;
414+ const second = await connectHttp ( ) ;
389415 await app . shutdown ( ) ;
390416 expect ( log ) . toHaveBeenCalledWith ( "Shutting down server..." ) ;
417+ for ( const { sessionId } of [ first , second ] ) {
418+ expect ( log ) . toHaveBeenCalledWith (
419+ `Closing transport for session ${ sessionId } ` ,
420+ ) ;
421+ expect ( log ) . toHaveBeenCalledWith (
422+ `Transport closed for session ${ sessionId } , removing from transports map` ,
423+ ) ;
424+ // The session is gone: the server answers it as unknown.
425+ const after = await post (
426+ { jsonrpc : "2.0" , id : 1 , method : "ping" } ,
427+ sessionId ,
428+ ) ;
429+ expect ( after . status ) . toBe ( 404 ) ;
430+ }
391431 expect ( log ) . toHaveBeenCalledWith ( "Server shutdown complete" ) ;
392- expect ( log ) . not . toHaveBeenCalledWith (
393- expect . stringMatching ( / ^ C l o s i n g t r a n s p o r t f o r s e s s i o n / ) ,
432+ expect ( exit ) . toHaveBeenCalledWith ( 0 ) ;
433+ await first . client . close ( ) ;
434+ await second . client . close ( ) ;
435+ } ) ;
436+
437+ it ( "logs a session that fails to close and still exits 0" , async ( ) => {
438+ const exit = vi
439+ . spyOn ( process , "exit" )
440+ . mockImplementation ( ( ) => undefined as never ) ;
441+ const { client, sessionId } = await connectHttp ( ) ;
442+ const failure = new Error ( "close failed" ) ;
443+ vi . spyOn (
444+ StreamableHTTPServerTransport . prototype ,
445+ "close" ,
446+ ) . mockRejectedValueOnce ( failure ) ;
447+ await app . shutdown ( ) ;
448+ expect ( log ) . toHaveBeenCalledWith (
449+ `Error closing transport for session ${ sessionId } :` ,
450+ failure ,
394451 ) ;
452+ expect ( log ) . toHaveBeenCalledWith ( "Server shutdown complete" ) ;
395453 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- ] ) ;
404454 await client . close ( ) ;
405455 } ) ;
406456} ) ;
0 commit comments