mcp 1.10.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -142,11 +142,13 @@ module MCP
142
142
  # object instead of an SSE stream.
143
143
  # @param session_idle_timeout [Numeric, nil] seconds before an idle session is reaped; defaults
144
144
  # to `DEFAULT_SESSION_IDLE_TIMEOUT` (1800) in stateful mode, and an explicit `nil` disables
145
- # expiry. Not supported in stateless mode.
145
+ # expiry. A session is not idle while one of its requests is running. Not supported in stateless mode.
146
146
  # @param max_sessions [Integer, nil] cap on the concurrent session count in stateful mode; a new
147
147
  # `initialize` past the cap is rejected with HTTP 503, and `nil` disables the cap.
148
- # @param allowed_origins [Array<String>, nil] extra `Origin` values accepted in addition to
149
- # same-origin requests, for DNS rebinding protection.
148
+ # @param allowed_origins [Array<String>, :any, nil] extra `Origin` values accepted in addition to
149
+ # same-origin requests, for DNS rebinding protection; `:any` accepts every `Origin` while
150
+ # the `Host` check stays on, for a server whose every request carries a credential the browser
151
+ # does not attach on its own (a bearer token, not a cookie).
150
152
  # @param allowed_hosts [Array<String>, nil] extra `Host` values accepted beyond the loopback
151
153
  # defaults (`127.0.0.1`, `::1`, `localhost`); each entry matches a bare host name (any port)
152
154
  # or a full `host:port`.
@@ -186,6 +188,14 @@ module MCP
186
188
  # the method then answers 404 with JSON-RPC `-32601` like any unimplemented method,
187
189
  # and `Server#discover` stops advertising the `listChanged`/`subscribe` capability flags,
188
190
  # keeping the advertisement and the actual behavior in agreement. Defaults to `true`.
191
+ # @param stream_request_notifications [Boolean] whether a 2026-07-28 request that asks for progress
192
+ # (`_meta.progressToken` on a `tools/call`, `prompts/get` or `resources/read`) gets the notifications of its handler
193
+ # as they are emitted, on an SSE response held open until the result, instead of all at once after the handler returns.
194
+ # The handler then runs while the host writes the response body, so the host has to serve a streaming body,
195
+ # and an error of such a request is answered on the stream, under HTTP 200. A `tools/call` is streamed only when
196
+ # its tool is known ahead of the handler, which leaves out a server with a `tools_list_handler`.
197
+ # Keepalive comment frames are written every `listen_keepalive_interval` seconds. Defaults to `false`;
198
+ # cannot be combined with `serve_subscriptions_listen: false`.
189
199
  # @param server_to_client_request_timeout [Numeric] seconds a server-to-client request waits for its
190
200
  # response before the transport stops waiting and raises `MCP::Server::RequestTimeoutError`.
191
201
  # Defaults to `DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT` (600); individual calls override it with `timeout:`.
@@ -218,6 +228,13 @@ module MCP
218
228
  # expiry closes the stream earlier when it comes first; the cap is what bounds a stream whose token reports no
219
229
  # expiry. `nil` removes the cap, leaving such a stream open until either side disconnects. Streams opened without
220
230
  # a token are never capped.
231
+ # @param event_store [MCP::Server::Transports::EventStore, nil] enables SSE stream resumability (MCP 2025-11-25,
232
+ # SEP-1699): every event is stored under the id the store assigns and written with it, each stream opens with
233
+ # a priming event, and a GET carrying `Last-Event-ID` replays the events of that stream the client missed and
234
+ # resumes it. The SDK ships no store; `examples/in_memory_event_store.rb` in its repository is one for
235
+ # a single process. Not supported in stateless mode, which has no sessions to resume.
236
+ # @param retry_interval [Integer, nil] milliseconds the SSE `retry` field of each priming event asks the client to
237
+ # wait before reconnecting; without it the client applies its own delay. Requires `event_store`.
221
238
  def initialize(
222
239
  server,
223
240
  stateless: false,
@@ -234,6 +251,7 @@ module MCP
234
251
  max_resource_subscription_bytes: DEFAULT_MAX_RESOURCE_SUBSCRIPTION_BYTES,
235
252
  listen_keepalive_interval: DEFAULT_LISTEN_KEEPALIVE_INTERVAL,
236
253
  serve_subscriptions_listen: true,
254
+ stream_request_notifications: false,
237
255
  server_to_client_request_timeout: DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT,
238
256
  stream_write_timeout: DEFAULT_STREAM_WRITE_TIMEOUT,
239
257
  token_verifier: nil,
@@ -241,7 +259,9 @@ module MCP
241
259
  resource_metadata: nil,
242
260
  resource_metadata_url: nil,
243
261
  scope_matcher: nil,
244
- max_stream_lifetime: DEFAULT_MAX_STREAM_LIFETIME
262
+ max_stream_lifetime: DEFAULT_MAX_STREAM_LIFETIME,
263
+ event_store: nil,
264
+ retry_interval: nil
245
265
  )
246
266
  super(server)
247
267
  # Maps `session_id` to `{ get_sse_stream: stream_object, server_session: ServerSession, last_active_at: float_from_monotonic_clock, origin: origin_header }`.
@@ -253,9 +273,17 @@ module MCP
253
273
  @session_request_validator = session_request_validator
254
274
  @dns_rebinding_protection = dns_rebinding_protection
255
275
 
276
+ # A Symbol never equals an `Origin` value, so one other than `:any` would refuse every cross-origin request
277
+ # without a hint that it was mistyped.
278
+ if allowed_origins.is_a?(Symbol) && allowed_origins != :any
279
+ raise ArgumentError, "allowed_origins must be an Array of Origin values or :any (got #{allowed_origins.inspect}); " \
280
+ ":any turns Origin validation off, for a server that requires a bearer token on every request"
281
+ end
282
+
256
283
  # Host names are case-insensitive, so the allow lists are compared down-cased.
257
284
  @allowed_hosts = (DEFAULT_LOOPBACK_HOSTS + Array(allowed_hosts)).map(&:downcase).freeze
258
- @allowed_origins = Array(allowed_origins).map(&:downcase).freeze
285
+ @any_origin_allowed = allowed_origins == :any
286
+ @allowed_origins = (@any_origin_allowed ? [] : Array(allowed_origins)).map(&:downcase).freeze
259
287
  @pending_responses = {}
260
288
 
261
289
  # Maps a key the transport mints for each `subscriptions/listen` stream to
@@ -271,6 +299,9 @@ module MCP
271
299
 
272
300
  # Maps a modern request's ephemeral session id to the Array collecting the notifications its handler emits;
273
301
  # `handle_modern` registers the sink and flushes it as SSE frames ahead of the final response (SEP-2575).
302
+ # For a request served with `stream_request_notifications:` the sink is instead the open response stream,
303
+ # `{ stream: stream_object, session: ServerSession, write_mutex: Mutex, keepalive_wakeup: ConditionVariable }`,
304
+ # and each notification is written to it as it is emitted.
274
305
  @modern_request_sinks = {}
275
306
 
276
307
  # Resolve the idle timeout: an explicit value (including `nil` to opt out) wins; otherwise apply the secure default,
@@ -328,6 +359,15 @@ module MCP
328
359
  @listen_keepalive_interval = listen_keepalive_interval
329
360
  @serve_subscriptions_listen = serve_subscriptions_listen
330
361
 
362
+ # `serve_subscriptions_listen: false` is how a host says it buffers responses, and a buffered response
363
+ # cannot carry a notification before its handler has returned.
364
+ if stream_request_notifications && !serve_subscriptions_listen
365
+ raise ArgumentError, "stream_request_notifications needs a host that serves streaming responses, " \
366
+ "so it cannot be combined with serve_subscriptions_listen: false"
367
+ end
368
+
369
+ @stream_request_notifications = stream_request_notifications
370
+
331
371
  unless server_to_client_request_timeout.is_a?(Numeric) && server_to_client_request_timeout.positive?
332
372
  raise ArgumentError, "server_to_client_request_timeout must be a positive number"
333
373
  end
@@ -365,6 +405,27 @@ module MCP
365
405
 
366
406
  @max_stream_lifetime = max_stream_lifetime
367
407
 
408
+ if event_store
409
+ raise ArgumentError, "event_store is not supported in stateless mode." if @stateless
410
+
411
+ unless event_store.respond_to?(:store_event) && event_store.respond_to?(:events_after)
412
+ raise ArgumentError, "event_store must respond to store_event and events_after (see MCP::Server::Transports::EventStore)"
413
+ end
414
+ end
415
+
416
+ @event_store = event_store
417
+
418
+ if retry_interval
419
+ # A retry interval without a store would promise a resumable stream the transport cannot resume.
420
+ raise ArgumentError, "retry_interval requires event_store" unless event_store
421
+
422
+ unless retry_interval.is_a?(Integer) && retry_interval.positive?
423
+ raise ArgumentError, "retry_interval must be a positive Integer of milliseconds or nil"
424
+ end
425
+ end
426
+
427
+ @retry_interval = retry_interval
428
+
368
429
  # `close` sets the flag and signals the reaper under `@mutex`, so the reaper leaves its wait at once instead of
369
430
  # being killed in the middle of a reap.
370
431
  @closing = false
@@ -384,19 +445,46 @@ module MCP
384
445
  # A write blocks only once the peer's socket buffers are full, which takes a reader already hundreds of kilobytes behind;
385
446
  # one that still has not taken the frame after this long is dropped whether it stopped reading or is only that slow.
386
447
  DEFAULT_STREAM_WRITE_TIMEOUT = 10
448
+
449
+ # How much of the response of a streamed request is written under one `stream_write_timeout:` deadline.
450
+ RESPONSE_FRAME_PIECE_BYTES = 64 * 1024
451
+ private_constant :RESPONSE_FRAME_PIECE_BYTES
452
+
453
+ # The first protocol version whose clients parse an SSE event with empty data, which the priming event of
454
+ # SEP-1699 resumability is. A session that negotiated an earlier version gets no priming event and is never
455
+ # asked to resume, since it would have no event id to come back with; its other events still carry ids.
456
+ RESUMABLE_PROTOCOL_VERSION = "2025-11-25"
457
+
458
+ # Replay passes a resume makes before it gives up attaching. Each pass takes the events stored since
459
+ # the previous one and a further pass follows whenever that batch was not empty, so a sender that stores
460
+ # at least one event during each write keeps the loop going; after this many passes that each found events,
461
+ # the connection is closed behind the last batch for the client to reconnect from.
462
+ REPLAY_PASS_LIMIT = 16
387
463
  SESSION_REAP_INTERVAL = 60
388
464
  # Seconds `close` waits for a reap in progress to finish closing its streams before it kills the reaper.
389
465
  REAPER_JOIN_TIMEOUT = 5
390
466
  # How long `close` waits in all for the closing results of the open `subscriptions/listen` streams
391
467
  # before closing the streams still open without one.
392
468
  LISTEN_TEARDOWN_TIMEOUT = 5
469
+ # The reason the requests still in flight in a session are cancelled with when the session goes away: terminated by
470
+ # the client's DELETE, expired, torn down with its broken GET stream, or removed by `close`.
471
+ SESSION_TERMINATED_REASON = "Session terminated"
472
+ # The error message a request reusing the id of one in flight in its session is refused with.
473
+ REQUEST_ID_CONFLICT_MESSAGE = "Conflict: Request id is already in flight for this session"
393
474
 
394
475
  # Loopback hosts always accepted by DNS rebinding protection. A locally bound MCP server (the canonical pattern) is
395
476
  # protected out of the box; non-loopback deployments widen the list via `allowed_hosts:`.
396
477
  DEFAULT_LOOPBACK_HOSTS = ["127.0.0.1", "::1", "localhost"].freeze
397
478
 
398
- # JSON-RPC methods whose target name is mirrored into the `Mcp-Name` header (SEP-2575).
399
- NAME_BEARING_METHODS = [Methods::TOOLS_CALL, Methods::RESOURCES_READ, Methods::PROMPTS_GET].freeze
479
+ # JSON-RPC methods whose target is mirrored into the `Mcp-Name` header (SEP-2575), with the `params` member
480
+ # that names it. The member is fixed per method: a `resources/read` is named by its `uri` whatever else
481
+ # its `params` carry, so a `name` added to them cannot stand in for the URI the header is checked against.
482
+ NAME_MEMBER_BY_METHOD = {
483
+ Methods::TOOLS_CALL => :name,
484
+ Methods::RESOURCES_READ => :uri,
485
+ Methods::PROMPTS_GET => :name,
486
+ }.freeze
487
+ NAME_BEARING_METHODS = NAME_MEMBER_BY_METHOD.keys.freeze
400
488
 
401
489
  # Maps broadcast notification methods to the `SubscriptionFilter` field that opts in to them on
402
490
  # a `subscriptions/listen` stream (SEP-2575). `notifications/resources/updated` is matched by URI
@@ -529,10 +617,7 @@ module MCP
529
617
  @sessions.each_key.filter_map { |session_id| cleanup_session_unsafe(session_id) }
530
618
  end
531
619
 
532
- removed_sessions.each do |session|
533
- close_stream_safely(session[:get_sse_stream])
534
- close_post_request_streams(session)
535
- end
620
+ release_sessions(removed_sessions)
536
621
  end
537
622
 
538
623
  # Sessions a server-wide log broadcast is offered to, each applying its own level or the server default.
@@ -569,16 +654,24 @@ module MCP
569
654
  # non-delivery (`false`), never handed to the legacy paths below. It holds each notification as JSON,
570
655
  # generated here so that one that cannot be generated is dropped on its own instead of failing
571
656
  # the whole response when the sink is flushed.
657
+ #
658
+ # A sink that is the open response stream (`stream_request_notifications:`) is written to at once and is not
659
+ # counted: each write waits for the peer, within `stream_write_timeout:`, so nothing accumulates here.
572
660
  sink = @mutex.synchronize { session_id && @modern_request_sinks[session_id] }
573
661
  if sink
574
- return false if sink.size >= MAX_MODERN_REQUEST_NOTIFICATIONS
662
+ return false if sink.is_a?(Array) && sink.size >= MAX_MODERN_REQUEST_NOTIFICATIONS
575
663
 
576
664
  begin
577
- sink << notification.to_json
665
+ notification_json = notification.to_json
578
666
  rescue JSON::GeneratorError => e
579
667
  MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to generate notification" })
580
668
  return false
581
669
  end
670
+
671
+ return write_to_request_stream(sink, notification_json) unless sink.is_a?(Array)
672
+
673
+ sink << notification_json
674
+
582
675
  return true
583
676
  end
584
677
 
@@ -601,72 +694,59 @@ module MCP
601
694
  # (e.g. `resources/updated`, `elicitation/complete`) still flow via GET SSE.
602
695
  return false if @enable_json_response && related_request_id
603
696
 
604
- streams_to_close = []
605
-
606
- # Resolve the target stream under the lock, then write outside it: a stalled SSE reader
607
- # must not block every other session that needs `@mutex`.
608
- stream = @mutex.synchronize do
609
- next unless (session = @sessions[session_id])
697
+ removed_sessions = []
698
+ live = @mutex.synchronize do
699
+ next false unless (session = @sessions[session_id])
610
700
 
611
701
  if session_expired?(session)
612
- cleanup_and_collect_stream(session_id, streams_to_close)
613
- next
702
+ cleanup_and_collect_session(session_id, removed_sessions)
703
+ next false
614
704
  end
615
705
 
616
- active_stream(session, streams_to_close, related_request_id: related_request_id)
706
+ true
617
707
  end
618
708
 
619
- close_streams(streams_to_close)
620
- return false unless stream
709
+ release_sessions(removed_sessions)
710
+ return false unless live
621
711
 
622
- write_notification(stream, notification, session_id, related_request_id)
712
+ store_and_write(session_id, related_request_id, notification.to_json)
623
713
  end
624
714
 
625
715
  def deliver_broadcast_notification(notification)
626
- streams_to_close = []
716
+ removed_sessions = []
627
717
 
628
- # Snapshot the connected streams under the lock, then write to each outside it.
718
+ # Snapshot the sessions under the lock, then write to each outside it. A session whose GET stream is
719
+ # closed at the moment still takes the notification when it has opened that stream before and an event
720
+ # store keeps it for the reconnect; one that never opened the stream has no cursor to resume from.
629
721
  targets = @mutex.synchronize do
630
722
  expired_session_ids = []
631
723
 
632
724
  collected = @sessions.filter_map do |session_id, session|
633
- next unless session[:get_sse_stream]
725
+ next unless session[:get_sse_stream] || (@event_store && session[:get_stream_opened])
634
726
 
635
727
  if session_expired?(session)
636
728
  expired_session_ids << session_id
637
729
  next
638
730
  end
639
731
 
640
- stream = active_stream(session, streams_to_close)
641
-
642
- [session_id, stream] if stream
732
+ session_id
643
733
  end
644
734
 
645
735
  expired_session_ids.each do |session_id|
646
- cleanup_and_collect_stream(session_id, streams_to_close)
736
+ cleanup_and_collect_session(session_id, removed_sessions)
647
737
  end
648
738
 
649
739
  collected
650
740
  end
651
741
 
652
- close_streams(streams_to_close)
742
+ release_sessions(removed_sessions)
653
743
 
654
- targets.count do |session_id, stream|
655
- write_notification(stream, notification, session_id, nil)
744
+ json = notification.to_json
745
+ targets.count do |session_id|
746
+ store_and_write(session_id, nil, json)
656
747
  end
657
748
  end
658
749
 
659
- # Writes a notification to an SSE stream without holding `@mutex`. On a write error,
660
- # drops the broken stream and returns false; on success returns true.
661
- def write_notification(stream, notification, session_id, related_request_id)
662
- push_to_stream(stream, notification)
663
- true
664
- rescue *STREAM_WRITE_ERRORS => e
665
- MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to send notification" })
666
- drop_broken_stream(session_id, stream, related_request_id)
667
- false
668
- end
669
-
670
750
  # Removes a stream that failed to accept a write. A request-scoped stream is dropped on its own;
671
751
  # a session-scoped (GET SSE) failure tears down the whole session. The `@sessions` mutation runs
672
752
  # under `@mutex`, and the affected streams are closed outside it.
@@ -675,8 +755,11 @@ module MCP
675
755
  # the lock that removes the session: the failed write may have been picked for a stream that was detached since,
676
756
  # because its token expired and the client reopened, and the stream opened in its place must stay. A failed
677
757
  # stream the session no longer holds was closed by whichever path detached it, so there is nothing left to do.
758
+ # With an event store the GET stream is detached instead and the session kept: the client resumes the stream
759
+ # from its last event id (SEP-1699), and the events it misses meanwhile are stored for it.
678
760
  def drop_broken_stream(session_id, stream, related_request_id)
679
761
  streams_to_close = []
762
+ removed_sessions = []
680
763
 
681
764
  @mutex.synchronize do
682
765
  session = @sessions[session_id]
@@ -689,11 +772,16 @@ module MCP
689
772
 
690
773
  streams_to_close << stream
691
774
  elsif session && session[:get_sse_stream].equal?(stream)
692
- cleanup_and_collect_stream(session_id, streams_to_close)
775
+ if @event_store
776
+ streams_to_close << detach_get_stream(session)
777
+ else
778
+ cleanup_and_collect_session(session_id, removed_sessions)
779
+ end
693
780
  end
694
781
  end
695
782
 
696
783
  close_streams(streams_to_close)
784
+ release_sessions(removed_sessions)
697
785
  end
698
786
 
699
787
  def close_streams(streams)
@@ -744,39 +832,20 @@ module MCP
744
832
  request = { jsonrpc: "2.0", id: request_id, method: method }
745
833
  request[:params] = params if params
746
834
 
747
- # Register the pending response and resolve the stream under the lock, but perform
748
- # the write outside it so a stalled reader cannot block every other session on `@mutex`.
749
- streams_to_close = []
750
- stream = @mutex.synchronize do
751
- unless (session = @sessions[session_id])
835
+ # Register the pending response under the lock before the request is written, so a response arriving at once finds its entry;
836
+ # the write itself runs outside `@mutex`.
837
+ @mutex.synchronize do
838
+ unless @sessions.key?(session_id)
752
839
  raise "Session not found: #{session_id}."
753
840
  end
754
841
 
755
842
  @pending_responses[request_id] = { queue: pending_response, session_id: session_id }
756
-
757
- active_stream(session, streams_to_close, related_request_id: related_request_id)
758
- end
759
-
760
- close_streams(streams_to_close)
761
-
762
- sent = false
763
- if stream
764
- begin
765
- push_to_stream(stream, request)
766
- sent = true
767
- rescue *STREAM_WRITE_ERRORS
768
- drop_broken_stream(session_id, stream, related_request_id)
769
- end
770
843
  end
771
844
 
772
- # TODO: Replace with event store + replay when resumability is implemented.
773
- # Resumability is a separate MCP specification feature (SSE event IDs, Last-Event-ID replay,
774
- # event store management) independent of sampling.
775
- # See: https://modelcontextprotocol.io/specification/latest/basic/transports#resumability-and-redelivery
776
- #
777
- # The TypeScript and Python SDKs buffer messages and replay on reconnect.
778
- # Until then, raise to prevent queue.pop from blocking indefinitely.
779
- unless sent
845
+ # With an event store a request whose stream is disconnected is kept for replay, so the wait below can still
846
+ # be answered once the client resumes the stream (SEP-1699); without one there is nothing the client could
847
+ # come back to, so the wait is not started.
848
+ unless store_and_write(session_id, related_request_id, request.to_json)
780
849
  raise "No active stream for #{method} request."
781
850
  end
782
851
 
@@ -857,6 +926,47 @@ module MCP
857
926
  end
858
927
  end
859
928
 
929
+ # Closes the SSE connection of the request `request_id` without ending the request (SEP-1699), so the client reconnects with
930
+ # `Last-Event-ID` after the `retry_interval` and the handler's remaining messages, kept by the event store meanwhile,
931
+ # reach it through the resumed connection. Returns `false` when there is nothing to close: no `event_store:`,
932
+ # a client that negotiated a version before 2025-11-25 (it received no priming event to come back with),
933
+ # a connection whose priming event the store failed to take (the client holds no cursor for it either),
934
+ # an unknown session or request, or a connection already closed. Handlers reach this through `server_context.close_sse_stream`.
935
+ # @api private
936
+ def close_sse_stream(session_id, request_id)
937
+ stream = @mutex.synchronize do
938
+ session = session_id && @sessions[session_id]
939
+ next unless session && resumable_session?(session)
940
+
941
+ entry = session.dig(:post_stream_entries, request_id)
942
+ current = session.dig(:post_request_streams, request_id)
943
+ next unless entry && current && entry[:primed_stream].equal?(current)
944
+
945
+ session[:post_request_streams].delete(request_id)
946
+ end
947
+ return false unless stream
948
+
949
+ close_stream_safely(stream)
950
+
951
+ true
952
+ end
953
+
954
+ # Closes the session's standalone GET stream the same way, so the client polls for server-initiated messages.
955
+ # @api private
956
+ def close_standalone_sse_stream(session_id)
957
+ stream = @mutex.synchronize do
958
+ session = session_id && @sessions[session_id]
959
+ next unless session && resumable_session?(session)
960
+ next unless session[:get_sse_stream] && session[:get_primed_stream].equal?(session[:get_sse_stream])
961
+
962
+ detach_get_stream(session)
963
+ end
964
+ return false unless stream
965
+
966
+ close_stream_safely(stream)
967
+ true
968
+ end
969
+
860
970
  private
861
971
 
862
972
  # The wait between reaps is a condition variable wait under `@mutex` rather than a sleep, so `close` can end it
@@ -889,15 +999,30 @@ module MCP
889
999
  end
890
1000
  end
891
1001
 
892
- removed_sessions.each do |session|
893
- close_stream_safely(session[:get_sse_stream])
894
- close_post_request_streams(session)
895
- end
1002
+ release_sessions(removed_sessions)
1003
+ end
1004
+
1005
+ # One `write` per frame, so the frames of concurrent writers cannot interleave in the middle of each other.
1006
+ def send_to_stream(stream, data, event_id: nil)
1007
+ stream.write(sse_frame(data, event_id: event_id))
1008
+ stream.flush
896
1009
  end
897
1010
 
898
- def send_to_stream(stream, data)
1011
+ def sse_frame(data, event_id: nil)
899
1012
  message = data.is_a?(String) ? data : data.to_json
900
- stream.write("data: #{message}\n\n")
1013
+
1014
+ event_id ? "id: #{event_id}\ndata: #{message}\n\n" : "data: #{message}\n\n"
1015
+ end
1016
+
1017
+ # The priming event of SEP-1699: an id for the client to resume from, the `retry` field when configured, and
1018
+ # empty data. The `data:` line is what makes the event one the client dispatches (and so sees the id of);
1019
+ # an id without it would only be noted.
1020
+ def send_priming_event_to_stream(stream, event_id)
1021
+ fields = ["id: #{event_id}"]
1022
+ fields << "retry: #{@retry_interval}" if @retry_interval
1023
+ fields << "data:"
1024
+
1025
+ stream.write("#{fields.join("\n")}\n\n")
901
1026
  stream.flush
902
1027
  end
903
1028
 
@@ -920,8 +1045,8 @@ module MCP
920
1045
  #
921
1046
  # The deadline interrupts the write with the exception `Timeout` raises on its own, which no `rescue` of an `IOError` or a `StandardError` inside
922
1047
  # a stream implementation catches, and becomes `StreamWriteTimeoutError` only here, where it leaves the write.
923
- def push_to_stream(stream, data, subscription: nil)
924
- within_stream_write_timeout(stream, subscription) { send_to_stream(stream, data) }
1048
+ def push_to_stream(stream, data, event_id: nil, subscription: nil)
1049
+ within_stream_write_timeout(stream, subscription) { send_to_stream(stream, data, event_id: event_id) }
925
1050
  end
926
1051
 
927
1052
  def push_ping_to_stream(stream, subscription: nil)
@@ -970,6 +1095,8 @@ module MCP
970
1095
  return invalid_request_response("Invalid Request: JSON-RPC body must be a single request object")
971
1096
  end
972
1097
 
1098
+ return oversized_id_response if JsonRpcHandler.oversized_integer_id?(body[:id])
1099
+
973
1100
  # The version check precedes everything else that depends on request content,
974
1101
  # so a client probing with an unknown future version always receives the `-32022` signal
975
1102
  # (with the supported list to select from) rather than an incidental error.
@@ -998,13 +1125,6 @@ module MCP
998
1125
  mismatch_error = validate_modern_headers(request, body, header_version)
999
1126
  return mismatch_error if mismatch_error
1000
1127
 
1001
- # SEP-2243 custom headers: the `Mcp-Param-*` headers of a `tools/call` are checked against the body here,
1002
- # before dispatch, so a disagreement is refused without the tool ever running.
1003
- if body[:method] == Methods::TOOLS_CALL
1004
- param_error = validate_mcp_param_headers(request, body)
1005
- return param_error if param_error
1006
- end
1007
-
1008
1128
  # `subscriptions/listen` is a long-lived notification stream served at the transport layer;
1009
1129
  # it never dispatches through `Server#handle`. A transport constructed with
1010
1130
  # `serve_subscriptions_listen: false` skips the interception, so the method falls through
@@ -1014,32 +1134,39 @@ module MCP
1014
1134
  return handle_subscriptions_listen(body, auth_info: request.env[OAuth::ENV_KEY])
1015
1135
  end
1016
1136
 
1137
+ # SEP-2243 custom headers: the `Mcp-Param-*` headers of a `tools/call` are checked against the body by
1138
+ # the dispatcher, on the tool it resolved for this call, so a disagreement is refused without the tool ever running.
1139
+ # The refusal is answered from here, as a plain JSON 400 whatever the handler had emitted until then.
1140
+ header_mismatch = nil
1141
+ tool_call_check = lambda do |tool, params|
1142
+ header_mismatch = mcp_param_header_mismatch(tool, params, request)
1143
+ end
1144
+
1017
1145
  session = modern_session
1146
+ auth_info = request.env[OAuth::ENV_KEY]
1147
+ if stream_modern_request?(body, request)
1148
+ return streamed_modern_response(body, body_string, session, auth_info, tool_call_check)
1149
+ end
1150
+
1018
1151
  notifications = @mutex.synchronize { @modern_request_sinks[session.session_id] = [] }
1019
1152
  begin
1020
- response = @server.handle(body, session: session, auth_info: request.env[OAuth::ENV_KEY])
1153
+ response = @server.handle(body, session: session, auth_info: auth_info, tool_call_check: tool_call_check)
1021
1154
  ensure
1022
1155
  @mutex.synchronize { @modern_request_sinks.delete(session.session_id) }
1023
1156
  end
1024
1157
 
1158
+ return header_mismatch_response(header_mismatch, body[:id]) if header_mismatch
1159
+
1025
1160
  # `nil` covers notifications and cancellation-suppressed responses; ack with 202 like the legacy notification path.
1026
1161
  return handle_accepted if response.nil?
1027
1162
 
1028
- # A response that cannot be generated answers its request with Internal error, as `JsonRpcHandler.handle_json`
1029
- # does on the legacy paths, instead of failing the whole exchange with a 500.
1030
- response_json = begin
1031
- response.to_json
1032
- rescue JSON::GeneratorError => e
1033
- MCP.configuration.exception_reporter.call(e, { error: "Failed to generate response" })
1034
- response = JsonRpcHandler.encodable_response(response)
1035
- response.to_json
1036
- end
1163
+ response, response_json = modern_response_json(response)
1037
1164
 
1038
1165
  # Notifications a handler emitted during the request ride the request's own response stream as SSE frames ahead of
1039
1166
  # the final response (SEP-2575); a request that emitted none keeps the single JSON exchange and its HTTP status ladder.
1040
- # Delivery is buffered: frames flush after the handler returns, preserving order but not real-time interleaving
1041
- # (the TypeScript and Python SDKs stream live), and the sink grows with the handler's notification count.
1042
- # Live streaming can follow without changing the wire shape.
1167
+ # Delivery is buffered: frames flush after the handler returns, preserving order but not real-time interleaving,
1168
+ # and the sink grows with the handler's notification count. `stream_request_notifications:` delivers them as
1169
+ # they are emitted instead, for the requests `stream_modern_request?` selects.
1043
1170
  if notifications.empty?
1044
1171
  [modern_http_status(response), { "content-type" => "application/json" }, [response_json]]
1045
1172
  else
@@ -1056,10 +1183,211 @@ module MCP
1056
1183
  )
1057
1184
  end
1058
1185
 
1186
+ # A response that cannot be generated answers its request with Internal error, as `JsonRpcHandler.handle_json`
1187
+ # does on the legacy paths, instead of failing the whole exchange with a 500. Returns the response that was
1188
+ # generated along with its JSON.
1189
+ def modern_response_json(response)
1190
+ [response, response.to_json]
1191
+ rescue JSON::GeneratorError => e
1192
+ MCP.configuration.exception_reporter.call(e, { error: "Failed to generate response" })
1193
+ response = JsonRpcHandler.encodable_response(response)
1194
+
1195
+ [response, response.to_json]
1196
+ end
1197
+
1198
+ # The methods whose handlers report progress.
1199
+ STREAMED_MODERN_METHODS = [Methods::TOOLS_CALL, Methods::PROMPTS_GET, Methods::RESOURCES_READ].freeze
1200
+ private_constant :STREAMED_MODERN_METHODS
1201
+
1202
+ # Whether this request is answered on an open SSE stream (`stream_request_notifications:`): one that asks for progress,
1203
+ # of a method whose handler can report it. Opening the stream commits HTTP 200 before the handler runs,
1204
+ # so every other request keeps the buffered exchange and the status its answer maps to.
1205
+ #
1206
+ # The answers the spec ties to a status of their own are therefore ruled out here, ahead of the stream,
1207
+ # wherever they can be told without running the request: a request that is not valid JSON-RPC (400),
1208
+ # a method the server does not implement (404), an envelope that is missing or malformed (400),
1209
+ # and for a `tools/call` the header mismatch of SEP-2243 (400).
1210
+ # The headers are checked only on a tool that is known without running the request: with a `tools_list_handler`
1211
+ # the tool is the one the block returns for this very dispatch, which nothing ahead of the dispatch can stand in for.
1212
+ # A tool that is not found, a disagreement, or an error while looking leaves the request to the buffered exchange,
1213
+ # which answers it as it always has. What only the handler can decide, such as a client capability it finds missing,
1214
+ # is answered on the stream.
1215
+ def stream_modern_request?(body, request)
1216
+ return false unless @stream_request_notifications
1217
+ return false if body[:id].nil? || !STREAMED_MODERN_METHODS.include?(body[:method])
1218
+ return false unless JsonRpcHandler.valid_version?(body[:jsonrpc]) && JsonRpcHandler.valid_id?(body[:id])
1219
+
1220
+ params = body[:params]
1221
+ meta = params[:_meta] if params.is_a?(Hash)
1222
+ progress_token = meta[:progressToken] if meta.is_a?(Hash)
1223
+ return false unless progress_token.is_a?(String) || progress_token.is_a?(Integer)
1224
+ return false unless @server.implements_method?(body[:method])
1225
+ return false unless RequestEnvelope.modern?(params)
1226
+
1227
+ RequestEnvelope.parse!(params, request: params)
1228
+ return true unless body[:method] == Methods::TOOLS_CALL
1229
+
1230
+ tool = @server.tool_known_ahead_of_dispatch(params[:name])
1231
+
1232
+ !tool.nil? && mcp_param_header_mismatch(tool, params, request).nil?
1233
+ rescue StandardError
1234
+ false
1235
+ end
1236
+
1237
+ # The Rack streaming body of a request served with `stream_request_notifications:`. As `ListenStreamBody`,
1238
+ # it responds to `call` and not to `each`, and `first` turns the buffered-host mistake into guidance.
1239
+ class RequestStreamBody
1240
+ def initialize(&block)
1241
+ @block = block
1242
+ end
1243
+
1244
+ def call(stream)
1245
+ @block.call(stream)
1246
+ end
1247
+
1248
+ def first
1249
+ raise <<~MESSAGE
1250
+ The request was answered with a streaming SSE body, which cannot be buffered into a JSON response. \
1251
+ A host that cannot hold an SSE response open should construct the transport without `stream_request_notifications: true`.
1252
+ See the Rails (controller) section at https://ruby.sdk.modelcontextprotocol.io/server/transports/ for the hosting patterns.
1253
+ MESSAGE
1254
+ end
1255
+ end
1256
+ private_constant :RequestStreamBody
1257
+
1258
+ # Answers a request on an SSE stream that stays open while its handler runs. The handler runs inside the body,
1259
+ # on the thread the host writes the response from, not on one of the transport's own: an application keeps
1260
+ # its thread-bound state, and nothing outlives the response.
1261
+ #
1262
+ # The stream is the request's notification sink for as long as the handler runs, and the response is its last frame.
1263
+ # A request whose response is suppressed (it was cancelled) ends the stream without one.
1264
+ def streamed_modern_response(body, body_string, session, auth_info, tool_call_check)
1265
+ response_body = RequestStreamBody.new do |stream|
1266
+ sink = { stream: stream, session: session, write_mutex: Mutex.new, keepalive_wakeup: ConditionVariable.new }
1267
+
1268
+ begin
1269
+ @mutex.synchronize { @modern_request_sinks[session.session_id] = sink }
1270
+
1271
+ start_request_stream_keepalive_thread(session.session_id, sink)
1272
+
1273
+ response = @server.handle(body, session: session, auth_info: auth_info, tool_call_check: tool_call_check)
1274
+
1275
+ finish_request_stream(sink, response)
1276
+ rescue StandardError => e
1277
+ MCP.configuration.exception_reporter.call(e, { request: body_string })
1278
+
1279
+ finish_request_stream(sink, {
1280
+ jsonrpc: "2.0",
1281
+ id: echoable_id(body[:id]),
1282
+ error: { code: JsonRpcHandler::ErrorCode::INTERNAL_ERROR, message: "Internal server error" },
1283
+ })
1284
+ ensure
1285
+ @mutex.synchronize do
1286
+ @modern_request_sinks.delete(session.session_id)
1287
+ sink[:keepalive_wakeup].signal
1288
+ end
1289
+ sink[:write_mutex].synchronize { sink[:closed] = true }
1290
+
1291
+ close_stream_safely(stream)
1292
+ end
1293
+ end
1294
+
1295
+ [200, SSE_HEADERS.dup, response_body]
1296
+ end
1297
+
1298
+ # Writes one frame to the response stream of a streamed request, under its write mutex so that it cannot land
1299
+ # inside a keepalive or after the response. Returns whether the frame was written.
1300
+ #
1301
+ # A write that fails or stalls past `stream_write_timeout:` means the client is no longer reading. On this
1302
+ # lifecycle closing the response stream is how a client cancels its request, so the request is cancelled:
1303
+ # its handler observes it as it would `notifications/cancelled`, and nothing more is written.
1304
+ def write_to_request_stream(sink, data)
1305
+ guarded_request_stream_write(sink) { push_to_stream(sink[:stream], data, subscription: sink) }
1306
+ end
1307
+
1308
+ # The stream is marked closed before the write mutex is released, so a writer waiting on that mutex cannot put
1309
+ # its frame after one that failed part way. The cancellation runs outside the mutex: it calls the hooks of
1310
+ # the handler, which may themselves try to notify.
1311
+ def guarded_request_stream_write(sink)
1312
+ outcome = sink[:write_mutex].synchronize do
1313
+ next :skipped if sink[:closed]
1314
+
1315
+ begin
1316
+ yield
1317
+
1318
+ :written
1319
+ rescue *STREAM_WRITE_ERRORS
1320
+ sink[:closed] = true
1321
+
1322
+ :failed
1323
+ end
1324
+ end
1325
+
1326
+ sink[:session].cancel_all_incoming(reason: "The response stream was closed") if outcome == :failed
1327
+
1328
+ outcome == :written
1329
+ end
1330
+
1331
+ # The response may be large, so it is not held to one deadline as the frames above are: it is written in pieces,
1332
+ # each given `stream_write_timeout:` seconds. A client that takes each piece in that time receives all of it,
1333
+ # however long the whole takes, and one that does not is dropped. Nothing else would end this stream: it belongs
1334
+ # to no session, so until the write returns it holds the thread that serves the request and the keepalive waiting
1335
+ # on the mutex.
1336
+ def finish_request_stream(sink, response)
1337
+ return if response.nil?
1338
+
1339
+ _response, response_json = modern_response_json(response)
1340
+ frame = sse_frame(response_json)
1341
+
1342
+ sink[:write_mutex].synchronize do
1343
+ next if sink[:closed]
1344
+
1345
+ sink[:closed] = true
1346
+
1347
+ stream = sink[:stream]
1348
+ offset = 0
1349
+
1350
+ while offset < frame.bytesize
1351
+ piece = frame.byteslice(offset, RESPONSE_FRAME_PIECE_BYTES)
1352
+ within_stream_write_timeout(stream, sink) { stream.write(piece) }
1353
+ offset += piece.bytesize
1354
+ end
1355
+
1356
+ within_stream_write_timeout(stream, sink) { stream.flush }
1357
+ end
1358
+ rescue *STREAM_WRITE_ERRORS
1359
+ # The client went away before its response, or stopped reading it; there is no one left to answer.
1360
+ end
1361
+
1362
+ # Writes keepalive comment frames to the response stream of a streamed request while its handler is quiet, so
1363
+ # an intermediary does not time the response out and a client that went away is noticed, and its request cancelled,
1364
+ # without waiting for the next notification. Ends with the request: `streamed_modern_response` removes the sink and
1365
+ # signals the wait.
1366
+ def start_request_stream_keepalive_thread(session_id, sink)
1367
+ return unless @listen_keepalive_interval
1368
+
1369
+ Thread.new do
1370
+ loop do
1371
+ registered = @mutex.synchronize do
1372
+ next false unless @modern_request_sinks[session_id].equal?(sink)
1373
+
1374
+ sink[:keepalive_wakeup].wait(@mutex, @listen_keepalive_interval)
1375
+ @modern_request_sinks[session_id].equal?(sink)
1376
+ end
1377
+
1378
+ break unless registered
1379
+
1380
+ # A stream that is closed gets no more frames, so there is nothing left to keep alive.
1381
+ break unless guarded_request_stream_write(sink) { push_ping_to_stream(sink[:stream], subscription: sink) }
1382
+ end
1383
+ rescue StandardError => e
1384
+ MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Request stream keepalive failed" })
1385
+ end
1386
+ end
1387
+
1059
1388
  # Enforces the SEP-2575 header/body match rules (`-32020`, HTTP 400): the `MCP-Protocol-Version` header
1060
- # MUST match the `_meta`-carried version, and the `Mcp-Method` / `Mcp-Name` mirror headers MUST match
1061
- # the body when sent. Absent mirror headers are tolerated for interoperability while other SDK serving stacks
1062
- # converge on enforcement.
1389
+ # MUST match the `_meta`-carried version, and the `Mcp-Method` / `Mcp-Name` mirror headers MUST be present
1390
+ # and match the body.
1063
1391
  def validate_modern_headers(request, body, header_version)
1064
1392
  params = body[:params]
1065
1393
  meta_version = params.is_a?(Hash) && params[:_meta].is_a?(Hash) ? params.dig(:_meta, :"io.modelcontextprotocol/protocolVersion") : nil
@@ -1089,8 +1417,9 @@ module MCP
1089
1417
  )
1090
1418
  end
1091
1419
 
1092
- if NAME_BEARING_METHODS.include?(body[:method])
1093
- body_name = params.is_a?(Hash) ? params[:name] || params[:uri] : nil
1420
+ name_member = NAME_MEMBER_BY_METHOD[body[:method]]
1421
+ if name_member
1422
+ body_name = params.is_a?(Hash) ? params[name_member] : nil
1094
1423
  name_header = request.env["HTTP_MCP_NAME"]
1095
1424
  if body_name
1096
1425
  if name_header.to_s.empty?
@@ -1116,34 +1445,29 @@ module MCP
1116
1445
  # Enforces the SEP-2243 server behavior for custom headers (`-32020`, HTTP 400) on a modern `tools/call`: each
1117
1446
  # `x-mcp-header` parameter of the called tool must have its `Mcp-Param-{Name}` header present exactly when the body
1118
1447
  # carries a value for it, agreeing with that value once a `=?base64?...?=` sentinel is decoded, and a malformed
1119
- # sentinel is refused outright. The comparison runs before the tool does, on the schema the server itself serves
1120
- # in `tools/list`, so the body a handler acts on is the one an intermediary routed on. A tool the server does not
1121
- # know, or one whose declarations are invalid (a conforming client drops such a tool and sends no headers for it),
1122
- # is left to the dispatcher, and headers for parameters no declaration names are ignored, as the spec asks of any
1123
- # server that does not recognize them. The refusal names the header and the argument, not their values.
1448
+ # sentinel is refused outright. The comparison runs before the tool does, on the schema the server serves this caller
1449
+ # in `tools/list`, so the body a handler acts on is the one an intermediary routed on: the dispatcher calls this
1450
+ # with the tool it resolved for the call, which with a `tools_list_handler` is the one the block returned.
1451
+ # A tool that is not found never reaches it, one whose declarations are invalid (a conforming client drops such
1452
+ # a tool and sends no headers for it) is not checked, and headers for parameters no declaration names are ignored,
1453
+ # as the spec asks of any server that does not recognize them. The message names the header and the argument,
1454
+ # not their values; `nil` means the headers agree.
1124
1455
  #
1125
1456
  # Rack folds header names into `HTTP_` keys with `-` as `_`, so `Mcp-Param-Region-A` and `Mcp-Param-Region_A` land
1126
1457
  # on one key; a token that differs only in that way is the schema author's choice, and the value still has to
1127
1458
  # agree with the body.
1128
- def validate_mcp_param_headers(request, body)
1129
- params = body[:params]
1459
+ def mcp_param_header_mismatch(tool, params, request)
1130
1460
  return unless params.is_a?(Hash)
1131
1461
 
1132
- tool = @server.tools[params[:name]]
1133
- return unless tool
1134
-
1135
1462
  scan = McpParamHeaders.scan(tool.input_schema.to_h)
1136
1463
  return unless scan[:valid] && !scan[:declarations].empty?
1137
1464
 
1138
1465
  arguments = params[:arguments] || {}
1139
1466
  return unless arguments.is_a?(Hash)
1140
1467
 
1141
- message = McpParamHeaders.mismatch(scan[:declarations], arguments) do |header_name|
1468
+ McpParamHeaders.mismatch(scan[:declarations], arguments) do |header_name|
1142
1469
  header_bytes(request, "HTTP_#{header_name.upcase.tr("-", "_")}")
1143
1470
  end
1144
- return unless message
1145
-
1146
- header_mismatch_response(message, body[:id])
1147
1471
  end
1148
1472
 
1149
1473
  # Serves `subscriptions/listen` (SEP-2575): opens a long-lived SSE stream whose first message is
@@ -1258,6 +1582,11 @@ module MCP
1258
1582
  nil
1259
1583
  end
1260
1584
 
1585
+ # Answered before anything echoes the id: every refusal and response below writes it back.
1586
+ def oversized_id_response
1587
+ invalid_request_response("Invalid Request: id must be an integer of at most #{JsonRpcHandler::MAX_INTEGER_ID_BITS} bits")
1588
+ end
1589
+
1261
1590
  def listen_subscriptions_full?
1262
1591
  return false unless @max_listen_subscriptions
1263
1592
 
@@ -1777,6 +2106,8 @@ module MCP
1777
2106
  return invalid_request_response("Invalid Request: JSON-RPC body must be a single request object")
1778
2107
  end
1779
2108
 
2109
+ return oversized_id_response if JsonRpcHandler.oversized_integer_id?(body[:id])
2110
+
1780
2111
  # Header-primary routing sends sessionless modern traffic to `handle_modern` before this method runs,
1781
2112
  # so a body carrying the modern `_meta` triple (SEP-2575) arrives here in two shapes only.
1782
2113
  # Bound to a session under a dual-era header (2026-07-28), it is a lifecycle violation: the session
@@ -1857,8 +2188,8 @@ module MCP
1857
2188
  # dispatching it against the shared `Server`. Mirrors the response and regular-request
1858
2189
  # branches; without it a custom notification handler could run without a live session.
1859
2190
  return session_not_found_response if !@stateless && !session_active?(session_id)
2191
+ return session_not_found_response unless dispatch_notification(body_string, session_id, auth_info: request.env[OAuth::ENV_KEY])
1860
2192
 
1861
- dispatch_notification(body_string, session_id, auth_info: request.env[OAuth::ENV_KEY])
1862
2193
  handle_accepted
1863
2194
  elsif response?(body)
1864
2195
  return session_not_found_response if !@stateless && !session_exists?(session_id)
@@ -1900,6 +2231,14 @@ module MCP
1900
2231
  protocol_version_error = validate_protocol_version_header(request)
1901
2232
  return protocol_version_error if protocol_version_error
1902
2233
 
2234
+ # A reconnect naming the last event the client received resumes that stream (SEP-1699). Without an event store the header is ignored and
2235
+ # a plain stream is opened, since nothing was stored to replay.
2236
+ last_event_id = header_bytes(request, "HTTP_LAST_EVENT_ID")
2237
+
2238
+ if @event_store && last_event_id && !last_event_id.empty?
2239
+ return resume_sse_stream(session_id, last_event_id, request.env[OAuth::ENV_KEY])
2240
+ end
2241
+
1903
2242
  return session_already_connected_response if live_get_stream?(session_id)
1904
2243
 
1905
2244
  setup_sse_stream(session_id, request.env[OAuth::ENV_KEY])
@@ -1932,42 +2271,87 @@ module MCP
1932
2271
  success_response
1933
2272
  end
1934
2273
 
1935
- # Removes the session, closes its streams outside the lock, and returns the removed session, or nil when
2274
+ # Removes the session, releases it outside the lock, and returns the removed session, or nil when
1936
2275
  # there was none to remove.
1937
2276
  def cleanup_session(session_id)
1938
2277
  session = @mutex.synchronize do
1939
2278
  cleanup_session_unsafe(session_id)
1940
2279
  end
1941
2280
 
1942
- if session
1943
- close_stream_safely(session[:get_sse_stream])
1944
- close_post_request_streams(session)
1945
- end
2281
+ release_session(session) if session
1946
2282
 
1947
2283
  session
1948
2284
  end
1949
2285
 
1950
- # Removes a session from `@sessions` and returns it. Does not close the stream.
1951
- # Callers must close the stream outside the mutex to avoid holding the lock during
1952
- # potentially blocking I/O.
2286
+ # Removes a session from `@sessions` and returns it. Does not close the stream, cancel the in-flight requests, or wake
2287
+ # the threads waiting on the session's server-to-client requests: it collects those waits for `release_session`,
2288
+ # which callers must run outside the mutex to avoid holding the lock during potentially blocking I/O and
2289
+ # the requests' cancellation hooks. No wait is added once the session is gone, since `send_request` registers one
2290
+ # only for a session it finds under the lock.
1953
2291
  def cleanup_session_unsafe(session_id)
1954
- session = @sessions.delete(session_id)
2292
+ return unless (session = @sessions.delete(session_id))
1955
2293
 
1956
- # Unblock threads waiting on pending responses for this session.
1957
- @pending_responses.each_value do |pending_response|
1958
- if pending_response[:session_id] == session_id
1959
- pending_response[:queue].push(:session_closed)
1960
- end
2294
+ session[:pending_response_queues] = @pending_responses.each_value.filter_map do |pending_response|
2295
+ pending_response[:queue] if pending_response[:session_id] == session_id
1961
2296
  end
1962
2297
 
1963
2298
  session
1964
2299
  end
1965
2300
 
1966
- def cleanup_and_collect_stream(session_id, streams_to_close)
2301
+ # Removes a session under `@mutex` and adds it to `removed_sessions`, for the caller to release once outside the lock.
2302
+ def cleanup_and_collect_session(session_id, removed_sessions)
1967
2303
  return unless (removed = cleanup_session_unsafe(session_id))
1968
2304
 
1969
- streams_to_close << removed[:get_sse_stream]
1970
- removed[:post_request_streams]&.each_value { |stream| streams_to_close << stream }
2305
+ removed_sessions << removed
2306
+ end
2307
+
2308
+ # Ends what a removed session still has running: cancels its in-flight requests, whose handlers observe
2309
+ # the termination through `server_context.cancelled?` and whose responses are suppressed as for `notifications/cancelled`,
2310
+ # wakes the threads still waiting on its server-to-client requests, and closes its streams. Runs outside `@mutex`:
2311
+ # a close can block, and a cancellation fires the request's `on_cancel` hooks synchronously, which may call back into
2312
+ # the transport.
2313
+ #
2314
+ # The cancellation comes first. A close can block for up to `stream_write_timeout:` on a stalled peer, and until
2315
+ # the cancellation runs, a request the session still receives is admitted and run as usual. Waking the waits first
2316
+ # would likewise tell a request waiting on a nested request only that the session closed, before its own token is
2317
+ # cancelled. Cancelling first wakes that wait through the request's cancellation hook, so the request ends cancelled;
2318
+ # `:session_closed` then wakes the waits that belong to no request of the session.
2319
+ def release_session(session)
2320
+ release_sessions([session])
2321
+ end
2322
+
2323
+ # Sessions that end together (`close`, the reaper) are all cancelled before the streams of any of them are closed:
2324
+ # released one after the other, each session would wait for the closes of those ahead of it, as its own cancellation
2325
+ # once waited for its own.
2326
+ #
2327
+ # A cancellation runs application hooks and can raise (a hook that fails, reported by an exception reporter that fails as well).
2328
+ # The sessions are removed from the registry by then, so nothing would come back for what is left:
2329
+ # every session is still cancelled and every stream closed, and the first error is raised once that is done.
2330
+ def release_sessions(sessions)
2331
+ first_error = nil
2332
+
2333
+ sessions.each do |session|
2334
+ end_session_requests(session)
2335
+ rescue StandardError => e
2336
+ first_error ||= e
2337
+ end
2338
+
2339
+ raise first_error if first_error
2340
+ ensure
2341
+ sessions.each do |session|
2342
+ close_session_streams(session)
2343
+ end
2344
+ end
2345
+
2346
+ def end_session_requests(session)
2347
+ session[:server_session]&.cancel_all_incoming(reason: SESSION_TERMINATED_REASON)
2348
+ ensure
2349
+ session[:pending_response_queues]&.each { |queue| queue.push(:session_closed) }
2350
+ end
2351
+
2352
+ def close_session_streams(session)
2353
+ close_stream_safely(session[:get_sse_stream])
2354
+ close_post_request_streams(session)
1971
2355
  end
1972
2356
 
1973
2357
  # A close can block on the same full buffers a write does (a TLS stream writes its closing alert, a buffered one flushes),
@@ -2227,20 +2611,22 @@ module MCP
2227
2611
 
2228
2612
  # Dispatches a client-originated notification (e.g. `notifications/cancelled`,
2229
2613
  # `notifications/initialized`) through the server so it can update session state.
2614
+ # Returns false, without dispatching, when the session was removed after the caller checked it,
2615
+ # and true otherwise, including when the dispatch raised.
2230
2616
  def dispatch_notification(body_string, session_id, auth_info: nil)
2231
2617
  server_session = nil
2232
2618
  if @stateless
2233
2619
  server_session = ephemeral_session
2234
2620
  elsif session_id
2235
- @mutex.synchronize do
2236
- session = @sessions[session_id]
2237
- server_session = session[:server_session] if session
2238
- end
2621
+ server_session = @mutex.synchronize { @sessions[session_id]&.dig(:server_session) }
2622
+ return false unless server_session
2239
2623
  end
2240
2624
 
2241
2625
  dispatch_handle_json(body_string, server_session, auth_info: auth_info)
2626
+ true
2242
2627
  rescue => e
2243
2628
  MCP.configuration.exception_reporter.call(e, { error: "Failed to dispatch notification" })
2629
+ true
2244
2630
  end
2245
2631
 
2246
2632
  def response?(body)
@@ -2283,7 +2669,7 @@ module MCP
2283
2669
  # so the cap rejects only when genuinely full rather than up to a reaper interval after sessions expired.
2284
2670
  if @max_sessions && @sessions.size >= @max_sessions
2285
2671
  @sessions.each_key.select { |id| session_expired?(@sessions[id]) }.each do |id|
2286
- cleanup_and_collect_stream(id, reclaimed)
2672
+ cleanup_and_collect_session(id, reclaimed)
2287
2673
  end
2288
2674
  end
2289
2675
 
@@ -2302,11 +2688,17 @@ module MCP
2302
2688
  auth_issuer: auth_info&.issuer,
2303
2689
  auth_subject: auth_info&.subject,
2304
2690
  auth_client_id: auth_info&.client_id,
2691
+ # Orders the session's event storage against a `Last-Event-ID` resume; see `store_and_write`.
2692
+ store_mutex: Mutex.new,
2693
+ # The stream id the events of the session's GET stream are stored under, fixed for the session's life
2694
+ # so a client resuming that stream finds everything it missed under one cursor however often
2695
+ # the connection was reopened. The response stream of each request gets its own id in `post_stream_entries`.
2696
+ get_stream_id: @event_store && mint_stream_id(session_id),
2305
2697
  }
2306
2698
  true
2307
2699
  end
2308
2700
 
2309
- reclaimed.each { |stream| close_stream_safely(stream) }
2701
+ release_sessions(reclaimed)
2310
2702
  return too_many_sessions_response unless inserted
2311
2703
  end
2312
2704
 
@@ -2362,10 +2754,11 @@ module MCP
2362
2754
  error_response = validate_and_touch_session(session_id)
2363
2755
  return error_response if error_response
2364
2756
 
2365
- @mutex.synchronize do
2366
- session = @sessions[session_id]
2367
- server_session = session[:server_session] if session
2368
- end
2757
+ server_session = @mutex.synchronize { @sessions[session_id]&.dig(:server_session) }
2758
+ # The session may have been removed since the check above, by a `DELETE` from another connection or by `close`.
2759
+ # The request is refused as one naming an unknown session: dispatched without one, it would run against
2760
+ # the shared `Server`, outside the session whose termination cancels it.
2761
+ return session_not_found_response unless server_session
2369
2762
  end
2370
2763
 
2371
2764
  # `Server` refuses a duplicate id as well, but only once the request reaches it. The SSE branch below
@@ -2395,39 +2788,71 @@ module MCP
2395
2788
  # https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server
2396
2789
  def handle_request_with_sse_response(body_string, session_id, server_session, related_request_id: nil, auth_info: nil)
2397
2790
  body = proc do |stream|
2398
- @mutex.synchronize do
2791
+ # The stream id is kept with the request while it is in flight: it marks the request's events in
2792
+ # the event store and routes a `Last-Event-ID` resume back to the request (SEP-1699).
2793
+ # It is minted whether or not a store is configured, so the registration has one shape.
2794
+ stream_id = mint_stream_id(session_id)
2795
+ claim = @mutex.synchronize do
2399
2796
  session = @sessions[session_id]
2400
- if session && related_request_id
2401
- session[:post_request_streams] ||= {}
2797
+ next unless session && related_request_id
2402
2798
 
2403
- # Claim the id only while it is free. `handle_regular_request` already refused the colliding request,
2404
- # so reaching an occupied slot means a race got past that check; leaving the first stream in place keeps
2405
- # its messages going where they belong.
2406
- session[:post_request_streams][related_request_id] ||= stream
2407
- end
2799
+ session[:post_request_streams] ||= {}
2800
+ session[:post_stream_entries] ||= {}
2801
+
2802
+ # Claim the id only while it is free. `handle_regular_request` already refused the colliding request,
2803
+ # so reaching an occupied slot means a race got past that check; leaving the first stream in place keeps
2804
+ # its messages going where they belong, and the request that lost the claim is refused below without
2805
+ # running, since it could otherwise register the id before the owner does.
2806
+ next :taken if session[:post_request_streams].key?(related_request_id) || session[:post_stream_entries].key?(related_request_id)
2807
+
2808
+ session[:post_request_streams][related_request_id] = stream
2809
+ session[:post_stream_entries][related_request_id] = { stream_id: stream_id, resumed: nil }
2810
+
2811
+ :claimed
2408
2812
  end
2813
+ claimed = claim == :claimed
2814
+
2815
+ write_priming_event(session_id, related_request_id, stream) if claimed
2409
2816
 
2410
2817
  begin
2411
- response = dispatch_handle_json(body_string, server_session, auth_info: auth_info)
2818
+ response = if claim == :taken
2819
+ request_id_conflict_message(related_request_id)
2820
+ else
2821
+ dispatch_handle_json(body_string, server_session, auth_info: auth_info)
2822
+ end
2412
2823
 
2413
- send_to_stream(stream, response) if response
2824
+ if response
2825
+ # Written through the registration rather than to `stream`: the response of a request whose connection was
2826
+ # closed and resumed meanwhile belongs on the resumed one, and is stored for a client still to reconnect.
2827
+ if claimed
2828
+ store_and_write(session_id, related_request_id, response, pushed: false)
2829
+ else
2830
+ send_to_stream(stream, response)
2831
+ end
2832
+ end
2414
2833
  ensure
2415
- if related_request_id
2416
- @mutex.synchronize do
2417
- session = @sessions[session_id]
2418
- # Only retire our own registration: a request that never claimed the id, or one whose claim has
2419
- # already been replaced, must not unregister the stream that owns it.
2420
- registered = session&.dig(:post_request_streams, related_request_id)
2834
+ resumed = nil
2421
2835
 
2422
- session[:post_request_streams].delete(related_request_id) if registered.equal?(stream)
2836
+ if claimed
2837
+ resumed = @mutex.synchronize do
2838
+ session = @sessions[session_id]
2839
+ entry = session&.dig(:post_stream_entries, related_request_id)
2840
+ # Only retire our own registration: one whose claim has already been replaced must not unregister
2841
+ # the stream that owns it. The live stream is this request's own when it is the one opened here or
2842
+ # the one a resume put in its place.
2843
+ next unless entry && entry[:stream_id] == stream_id
2844
+
2845
+ session[:post_stream_entries].delete(related_request_id)
2846
+ registered = session[:post_request_streams][related_request_id]
2847
+ if registered.equal?(stream) || (entry[:resumed] && registered.equal?(entry[:resumed]))
2848
+ session[:post_request_streams].delete(related_request_id)
2849
+ end
2850
+ entry[:resumed]
2423
2851
  end
2424
2852
  end
2425
2853
 
2426
- begin
2427
- stream.close
2428
- rescue StandardError
2429
- # Ignore close-related errors from already closed/broken streams.
2430
- end
2854
+ close_stream_safely(resumed) if resumed
2855
+ close_stream_safely(stream)
2431
2856
  end
2432
2857
  end
2433
2858
 
@@ -2476,13 +2901,7 @@ module MCP
2476
2901
  nil
2477
2902
  end
2478
2903
 
2479
- if removed
2480
- close_stream_safely(removed[:get_sse_stream])
2481
-
2482
- removed[:post_request_streams]&.each_value do |stream|
2483
- close_stream_safely(stream)
2484
- end
2485
- end
2904
+ release_session(removed) if removed
2486
2905
 
2487
2906
  response
2488
2907
  end
@@ -2537,10 +2956,7 @@ module MCP
2537
2956
  true
2538
2957
  end
2539
2958
 
2540
- if removed
2541
- close_stream_safely(removed[:get_sse_stream])
2542
- close_post_request_streams(removed)
2543
- end
2959
+ release_session(removed) if removed
2544
2960
 
2545
2961
  active
2546
2962
  end
@@ -2570,7 +2986,7 @@ module MCP
2570
2986
  # to prevent DNS rebinding attacks against locally bound MCP servers. Protection is on by default;
2571
2987
  # pass `dns_rebinding_protection: false` to disable it (e.g. when an upstream proxy or middleware already
2572
2988
  # performs the check). The `Host` header is validated against the loopback defaults plus `allowed_hosts:`,
2573
- # and the `Origin` header, when present, must be same-origin or in `allowed_origins:`.
2989
+ # and the `Origin` header, when present, must be same-origin or in `allowed_origins:`, unless that is `:any`.
2574
2990
  def validate_dns_rebinding(request)
2575
2991
  return unless @dns_rebinding_protection
2576
2992
 
@@ -2602,7 +3018,14 @@ module MCP
2602
3018
 
2603
3019
  # A request without an `Origin` header (typical for non-browser MCP clients) is allowed. A browser cross-origin request is
2604
3020
  # rejected unless the origin is same-origin or explicitly allow-listed via `allowed_origins:`.
3021
+ #
3022
+ # `allowed_origins: :any` skips this check alone. A rebound request names the attacker's host in `Host` and, when it carries one,
3023
+ # in `Origin`, so it is same-origin here and `validate_host` is what refuses it; what this check adds is refusing a page on another site
3024
+ # that relies on what the browser attaches by itself, which a server requiring a bearer token does not accept.
3025
+ # The `Origin` a session was created with still binds its later requests (`session_request_rejection`).
2605
3026
  def validate_origin(request)
3027
+ return if @any_origin_allowed
3028
+
2606
3029
  origin = header_bytes(request, "HTTP_ORIGIN")
2607
3030
  return if origin.nil?
2608
3031
  return if same_origin?(origin, request)
@@ -2693,10 +3116,15 @@ module MCP
2693
3116
  json_rpc_error_response(
2694
3117
  status: 409,
2695
3118
  code: JsonRpcHandler::ErrorCode::INVALID_REQUEST,
2696
- message: "Conflict: Request id is already in flight for this session",
3119
+ message: REQUEST_ID_CONFLICT_MESSAGE,
2697
3120
  )
2698
3121
  end
2699
3122
 
3123
+ # The same refusal, for a request whose SSE response has already started.
3124
+ def request_id_conflict_message(request_id)
3125
+ { jsonrpc: "2.0", id: request_id, error: { code: JsonRpcHandler::ErrorCode::INVALID_REQUEST, message: REQUEST_ID_CONFLICT_MESSAGE } }.to_json
3126
+ end
3127
+
2700
3128
  def setup_sse_stream(session_id, auth_info = nil)
2701
3129
  body = create_sse_body(session_id, auth_info)
2702
3130
 
@@ -2706,7 +3134,10 @@ module MCP
2706
3134
  def create_sse_body(session_id, auth_info = nil)
2707
3135
  proc do |stream|
2708
3136
  stored = store_stream_for_session(session_id, stream, auth_info)
2709
- start_keepalive_thread(session_id, stream) if stored
3137
+ next unless stored
3138
+
3139
+ write_priming_event(session_id, nil, stream)
3140
+ start_keepalive_thread(session_id, stream)
2710
3141
  end
2711
3142
  end
2712
3143
 
@@ -2719,6 +3150,9 @@ module MCP
2719
3150
 
2720
3151
  session[:get_sse_stream] = stream
2721
3152
  session[:get_sse_stream_expires_at] = stream_token_expiry(auth_info)
3153
+ # From here on the session's GET stream events are stored, since the client now has the cursor to
3154
+ # resume them from.
3155
+ session[:get_stream_opened] = true
2722
3156
  true
2723
3157
  end
2724
3158
 
@@ -2737,7 +3171,8 @@ module MCP
2737
3171
  # stream at a delivery once its token expired and the client may have opened a new one since, which gets
2738
3172
  # a keepalive thread of its own. The loop therefore ends as soon as the session no longer holds this stream,
2739
3173
  # and a loop that did not run to its end (a failed ping, or any other abnormal exit) drops the stream through
2740
- # `drop_broken_stream`, which tears the session down only while it still holds that stream, as before.
3174
+ # `drop_broken_stream`, which tears the session down only while it still holds that stream, as before,
3175
+ # or detaches the stream alone when an event store lets the client resume it.
2741
3176
  def start_keepalive_thread(session_id, stream)
2742
3177
  Thread.new do
2743
3178
  ended = false
@@ -2815,10 +3250,319 @@ module MCP
2815
3250
  raise # Re-raise to exit the keepalive loop
2816
3251
  end
2817
3252
 
3253
+ # A session is idle only while none of its requests is running, and its idle time counts from the later of
3254
+ # the last activity that touched it and the end of its last request. `last_active_at` alone is the start of
3255
+ # the latest request, so a request longer than the timeout would lose its session, and with it its response,
3256
+ # while the client is still waiting for it.
2818
3257
  def session_expired?(session)
2819
3258
  return false unless @session_idle_timeout
2820
3259
 
2821
- Process.clock_gettime(Process::CLOCK_MONOTONIC) - session[:last_active_at] > @session_idle_timeout
3260
+ busy, last_request_finished_at = session[:server_session]&.in_flight_activity
3261
+ return false if busy
3262
+
3263
+ idle_since = [session[:last_active_at], last_request_finished_at].compact.max
3264
+ Process.clock_gettime(Process::CLOCK_MONOTONIC) - idle_since > @session_idle_timeout
3265
+ end
3266
+
3267
+ # Stream ids carry the session id, so a `Last-Event-ID` is matched to the session presenting it with
3268
+ # a string check, however long ago the request that opened the stream finished.
3269
+ def mint_stream_id(session_id)
3270
+ "#{session_id}:#{SecureRandom.uuid}"
3271
+ end
3272
+
3273
+ def owned_stream_id?(session_id, stream_id)
3274
+ stream_id.is_a?(String) && stream_id.start_with?("#{session_id}:")
3275
+ end
3276
+
3277
+ def resumable_session?(session)
3278
+ !@event_store.nil? && resumable_protocol_version?(session[:server_session].protocol_version)
3279
+ end
3280
+
3281
+ # Membership in the supported list keeps an unknown future version out: `initialize` only ever records
3282
+ # a negotiated handshake version, so this is belt and braces, as in the TypeScript SDK.
3283
+ def resumable_protocol_version?(version)
3284
+ version.is_a?(String) &&
3285
+ MCP::Configuration::SUPPORTED_STABLE_PROTOCOL_VERSIONS.include?(version) &&
3286
+ version >= RESUMABLE_PROTOCOL_VERSION
3287
+ end
3288
+
3289
+ # The event store stream the messages for `related_request_id` belong to (the GET stream for `nil`), or `nil`
3290
+ # when nothing is to be stored: no store, a request not in flight, or a GET stream the client has not opened
3291
+ # yet and so has no cursor into.
3292
+ def resolve_stream_id(session, related_request_id)
3293
+ return unless @event_store
3294
+
3295
+ if related_request_id
3296
+ session.dig(:post_stream_entries, related_request_id, :stream_id)
3297
+ elsif session[:get_stream_opened]
3298
+ session[:get_stream_id]
3299
+ end
3300
+ end
3301
+
3302
+ # Runs the block under the session's store lock, which orders the storing of a message and the choice of its
3303
+ # stream against a replay pass and the attachment of a resumed stream (see `store_and_write`); `false` when
3304
+ # the session is gone. The lock is created on first use, so a session built before this transport kept one is
3305
+ # served too. It is held across store calls but never across a stream write, so a stalled reader stalls nobody.
3306
+ def with_session_store_lock(session_id)
3307
+ lock = @mutex.synchronize do
3308
+ session = @sessions[session_id]
3309
+ session && (session[:store_mutex] ||= Mutex.new)
3310
+ end
3311
+ return false unless lock
3312
+
3313
+ lock.synchronize { yield }
3314
+ true
3315
+ end
3316
+
3317
+ # Delivers `json`, a JSON-RPC message, on the session's stream for `related_request_id` (the GET stream for `nil`).
3318
+ # With an event store the message is stored first and written with the id the store assigned, so one written while
3319
+ # the stream is disconnected is replayed when the client resumes. The store and the choice of the stream share one hold of
3320
+ # the session's store lock, which `replay_and_attach` holds across each replay pass and the attachment of the resumed stream:
3321
+ # a message is therefore either in a set that replay writes to the resumed stream or written to that stream by
3322
+ # its own sender afterwards, never missed by both or written to it twice. The write itself runs outside every lock.
3323
+ # Returns `true` when the message reached a live stream or was stored for the reconnect, `false` otherwise.
3324
+ #
3325
+ # A message the transport pushes on its own (a notification, a server-to-client request) is written under `stream_write_timeout:`,
3326
+ # since its sender writes to stream after stream. `pushed: false` is for the response of a request,
3327
+ # written on that request's own thread, which waits for its reader as it did before.
3328
+ def store_and_write(session_id, related_request_id, json, pushed: true)
3329
+ event_id = nil
3330
+ stream = nil
3331
+ streams_to_close = []
3332
+ locked = with_session_store_lock(session_id) do
3333
+ stream_id = @mutex.synchronize do
3334
+ session = @sessions[session_id]
3335
+ session && resolve_stream_id(session, related_request_id)
3336
+ end
3337
+ event_id = stream_id && safe_store_event(stream_id, json)
3338
+
3339
+ stream = @mutex.synchronize do
3340
+ session = @sessions[session_id]
3341
+ session && active_stream(session, streams_to_close, related_request_id: related_request_id)
3342
+ end
3343
+ end
3344
+
3345
+ close_streams(streams_to_close)
3346
+ return false unless locked
3347
+
3348
+ written = false
3349
+ if stream
3350
+ begin
3351
+ if pushed
3352
+ push_to_stream(stream, json, event_id: event_id)
3353
+ else
3354
+ send_to_stream(stream, json, event_id: event_id)
3355
+ end
3356
+
3357
+ written = true
3358
+ rescue *STREAM_WRITE_ERRORS => e
3359
+ MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to send message" })
3360
+
3361
+ drop_broken_stream(session_id, stream, related_request_id)
3362
+ end
3363
+ end
3364
+
3365
+ written || !event_id.nil?
3366
+ end
3367
+
3368
+ # Opens `stream`, the connection the caller has just put in place for `related_request_id`, with the priming event,
3369
+ # stored first so its id is a cursor in the stream like any other. Only for sessions that negotiated
3370
+ # `RESUMABLE_PROTOCOL_VERSION` or later.
3371
+ #
3372
+ # The write has no deadline, since it is made on the thread of the request that opened or resumed the connection,
3373
+ # so it goes to that connection and no other: when a later resume has taken its place in the meantime,
3374
+ # nothing is written, and that resume primes the connection it attached.
3375
+ def write_priming_event(session_id, related_request_id, stream)
3376
+ event_id = nil
3377
+ streams_to_close = []
3378
+ with_session_store_lock(session_id) do
3379
+ stream_id = @mutex.synchronize do
3380
+ session = @sessions[session_id]
3381
+ next unless session && resumable_session?(session)
3382
+ next unless active_stream(session, streams_to_close, related_request_id: related_request_id).equal?(stream)
3383
+
3384
+ resolve_stream_id(session, related_request_id)
3385
+ end
3386
+ event_id = stream_id && safe_store_event(stream_id, nil)
3387
+ end
3388
+ close_streams(streams_to_close)
3389
+ return unless event_id
3390
+
3391
+ send_priming_event_to_stream(stream, event_id)
3392
+ mark_primed(session_id, related_request_id, stream)
3393
+ rescue *STREAM_WRITE_ERRORS => e
3394
+ MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to send message" })
3395
+ drop_broken_stream(session_id, stream, related_request_id)
3396
+ end
3397
+
3398
+ # Records that `stream` received its priming event, which `close_sse_stream` and `close_standalone_sse_stream`
3399
+ # require before they close it on purpose: a connection without one has given the client no cursor to come
3400
+ # back with. Compared by identity, so a connection opened in the stream's place starts unprimed.
3401
+ def mark_primed(session_id, related_request_id, stream)
3402
+ @mutex.synchronize do
3403
+ session = @sessions[session_id]
3404
+ next unless session
3405
+
3406
+ if related_request_id
3407
+ entry = session.dig(:post_stream_entries, related_request_id)
3408
+ entry[:primed_stream] = stream if entry && session.dig(:post_request_streams, related_request_id).equal?(stream)
3409
+ elsif session[:get_sse_stream].equal?(stream)
3410
+ session[:get_primed_stream] = stream
3411
+ end
3412
+ end
3413
+ end
3414
+
3415
+ # A failing store must not take the request or the session down with it: the frame is written without an id
3416
+ # (the client's cursor stays at the previous event, which costs it this one event on resume) and the failure
3417
+ # is reported. An id with a line break would end the SSE frame early, so it is refused the same way.
3418
+ def safe_store_event(stream_id, message)
3419
+ event_id = @event_store.store_event(stream_id, message)
3420
+ return event_id if valid_event_id?(event_id)
3421
+
3422
+ report_event_store_failure(ArgumentError.new("event store returned an invalid event id"), stream_id)
3423
+ nil
3424
+ rescue StandardError => e
3425
+ report_event_store_failure(e, stream_id)
3426
+ nil
3427
+ end
3428
+
3429
+ def safe_events_after(last_event_id)
3430
+ replay = @event_store.events_after(last_event_id)
3431
+ return unless replay.is_a?(Array) && replay.size == 2 && replay[0].is_a?(String) && replay[1].is_a?(Array)
3432
+
3433
+ replay
3434
+ rescue StandardError => e
3435
+ report_event_store_failure(e, nil)
3436
+ nil
3437
+ end
3438
+
3439
+ def valid_event_id?(event_id)
3440
+ event_id.is_a?(String) && !event_id.empty? && !event_id.match?(/[\r\n]/)
3441
+ end
3442
+
3443
+ def report_event_store_failure(error, stream_id)
3444
+ MCP.configuration.exception_reporter.call(error, { stream_id: stream_id, error: "Event store failure" })
3445
+ end
3446
+
3447
+ # Serves a GET carrying `Last-Event-ID` (SEP-1699): the stream the event belongs to is replayed from that event and,
3448
+ # when it is still open on the server side (the session's GET stream, or the response stream of a request still in flight),
3449
+ # the new connection takes the old one's place. The stream must belong to this session: an id of another session,
3450
+ # or one the store no longer knows, is answered 400 without replaying anything, and the two cases are not told apart.
3451
+ def resume_sse_stream(session_id, last_event_id, auth_info)
3452
+ replay = safe_events_after(last_event_id)
3453
+ return unknown_last_event_id_response unless replay && owned_stream_id?(session_id, replay[0])
3454
+
3455
+ body = proc do |stream|
3456
+ replay_and_attach(session_id, last_event_id, stream, auth_info)
3457
+ end
3458
+
3459
+ [200, SSE_HEADERS.dup, body]
3460
+ end
3461
+
3462
+ # The value is not echoed: it is client-supplied and nothing about it needs confirming.
3463
+ def unknown_last_event_id_response
3464
+ json_rpc_error_response(
3465
+ status: 400,
3466
+ code: JsonRpcHandler::ErrorCode::INVALID_REQUEST,
3467
+ message: "Bad Request: Unknown Last-Event-ID",
3468
+ )
3469
+ end
3470
+
3471
+ # Writes the events stored on the stream after `last_event_id` to `stream`, then puts `stream` in place of the connection
3472
+ # that stream was last carried by. Each pass takes the events stored since the cursor under the session's store lock
3473
+ # and writes them outside it; the pass that finds none left attaches the stream under the same hold, so a message stored
3474
+ # between the last replayed event and the attachment is impossible: it is either replayed by a further pass or written to
3475
+ # the attached stream by its own sender. A resume whose `REPLAY_PASS_LIMIT` passes all found events is closed behind
3476
+ # the last batch instead of attached, so no connection replays without end and the lock is still never held across a write;
3477
+ # the client reconnects from its new cursor after `retry`, as after any disconnect.
3478
+ def replay_and_attach(session_id, last_event_id, stream, auth_info)
3479
+ cursor = last_event_id
3480
+ attachment = nil
3481
+ passes = 0
3482
+
3483
+ until attachment
3484
+ events = []
3485
+ passes += 1
3486
+ locked = with_session_store_lock(session_id) do
3487
+ replay = safe_events_after(cursor)
3488
+ stream_id = replay && replay[0]
3489
+ if stream_id && owned_stream_id?(session_id, stream_id)
3490
+ events = replay[1]
3491
+ attachment = attach_resumed_stream(session_id, stream_id, stream, auth_info) if events.empty?
3492
+ else
3493
+ attachment = :refused
3494
+ end
3495
+ end
3496
+ attachment = :refused unless locked
3497
+ attachment ||= :behind if passes >= REPLAY_PASS_LIMIT
3498
+
3499
+ events.each do |event_id, message|
3500
+ cursor = event_id
3501
+ next unless message.is_a?(String)
3502
+
3503
+ send_to_stream(stream, message, event_id: valid_event_id?(event_id) ? event_id : nil)
3504
+ end
3505
+ end
3506
+
3507
+ finish_resumed_stream(session_id, stream, attachment)
3508
+ rescue *STREAM_WRITE_ERRORS => e
3509
+ MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to replay events" })
3510
+
3511
+ close_stream_safely(stream)
3512
+ end
3513
+
3514
+ # Puts `stream` in place of the connection `stream_id` was last carried by, the session's GET stream or
3515
+ # the response stream of a request still in flight, and says which; `:retired` for the stream of a request already answered,
3516
+ # `:gone` for a session that no longer exists. A connection still attached there is handed back as `replaced` for closing:
3517
+ # the client presenting the id of its last event is the one that held it. Called under the session's store lock.
3518
+ def attach_resumed_stream(session_id, stream_id, stream, auth_info)
3519
+ @mutex.synchronize do
3520
+ session = @sessions[session_id]
3521
+ next :gone unless session
3522
+
3523
+ if stream_id == session[:get_stream_id]
3524
+ replaced = detach_get_stream(session)
3525
+ session[:get_sse_stream] = stream
3526
+ session[:get_sse_stream_expires_at] = stream_token_expiry(auth_info)
3527
+ session[:get_stream_opened] = true
3528
+ { kind: :get, replaced: replaced }
3529
+ elsif (request_id = request_id_of_stream(session, stream_id))
3530
+ replaced = session[:post_request_streams][request_id]
3531
+ session[:post_request_streams][request_id] = stream
3532
+ session[:post_stream_entries][request_id][:resumed] = stream
3533
+ { kind: :post, request_id: request_id, replaced: replaced }
3534
+ else
3535
+ :retired
3536
+ end
3537
+ end
3538
+ end
3539
+
3540
+ # The stream of a request already answered has nothing more to carry once replayed, so that connection is
3541
+ # closed, as the spec asks after the response, and so is one that found events on each of its `REPLAY_PASS_LIMIT`
3542
+ # passes, which the client reconnects from its new cursor. An attached stream is primed, giving the client a cursor and
3543
+ # the `retry` field again, and a GET stream gets its keepalive.
3544
+ def finish_resumed_stream(session_id, stream, attachment)
3545
+ unless attachment.is_a?(Hash)
3546
+ close_stream_safely(stream)
3547
+ return
3548
+ end
3549
+
3550
+ close_stream_safely(attachment[:replaced]) if attachment[:replaced]
3551
+
3552
+ if attachment[:kind] == :get
3553
+ write_priming_event(session_id, nil, stream)
3554
+ start_keepalive_thread(session_id, stream)
3555
+ else
3556
+ write_priming_event(session_id, attachment[:request_id], stream)
3557
+ end
3558
+ end
3559
+
3560
+ def request_id_of_stream(session, stream_id)
3561
+ entries = session[:post_stream_entries]
3562
+ return unless entries
3563
+
3564
+ request_id, = entries.find { |_request_id, entry| entry[:stream_id] == stream_id }
3565
+ request_id
2822
3566
  end
2823
3567
  end
2824
3568
  end