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,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
380411describe ( "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 ( / ^ 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 / ) ,
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