mcp 1.10.0 → 1.11.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.
@@ -145,8 +145,10 @@ module MCP
145
145
  # expiry. 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`.
@@ -218,6 +220,13 @@ module MCP
218
220
  # expiry closes the stream earlier when it comes first; the cap is what bounds a stream whose token reports no
219
221
  # expiry. `nil` removes the cap, leaving such a stream open until either side disconnects. Streams opened without
220
222
  # a token are never capped.
223
+ # @param event_store [MCP::Server::Transports::EventStore, nil] enables SSE stream resumability (MCP 2025-11-25,
224
+ # SEP-1699): every event is stored under the id the store assigns and written with it, each stream opens with
225
+ # a priming event, and a GET carrying `Last-Event-ID` replays the events of that stream the client missed and
226
+ # resumes it. The SDK ships no store; `examples/in_memory_event_store.rb` in its repository is one for
227
+ # a single process. Not supported in stateless mode, which has no sessions to resume.
228
+ # @param retry_interval [Integer, nil] milliseconds the SSE `retry` field of each priming event asks the client to
229
+ # wait before reconnecting; without it the client applies its own delay. Requires `event_store`.
221
230
  def initialize(
222
231
  server,
223
232
  stateless: false,
@@ -241,7 +250,9 @@ module MCP
241
250
  resource_metadata: nil,
242
251
  resource_metadata_url: nil,
243
252
  scope_matcher: nil,
244
- max_stream_lifetime: DEFAULT_MAX_STREAM_LIFETIME
253
+ max_stream_lifetime: DEFAULT_MAX_STREAM_LIFETIME,
254
+ event_store: nil,
255
+ retry_interval: nil
245
256
  )
246
257
  super(server)
247
258
  # Maps `session_id` to `{ get_sse_stream: stream_object, server_session: ServerSession, last_active_at: float_from_monotonic_clock, origin: origin_header }`.
@@ -253,9 +264,17 @@ module MCP
253
264
  @session_request_validator = session_request_validator
254
265
  @dns_rebinding_protection = dns_rebinding_protection
255
266
 
267
+ # A Symbol never equals an `Origin` value, so one other than `:any` would refuse every cross-origin request
268
+ # without a hint that it was mistyped.
269
+ if allowed_origins.is_a?(Symbol) && allowed_origins != :any
270
+ raise ArgumentError, "allowed_origins must be an Array of Origin values or :any (got #{allowed_origins.inspect}); " \
271
+ ":any turns Origin validation off, for a server that requires a bearer token on every request"
272
+ end
273
+
256
274
  # Host names are case-insensitive, so the allow lists are compared down-cased.
257
275
  @allowed_hosts = (DEFAULT_LOOPBACK_HOSTS + Array(allowed_hosts)).map(&:downcase).freeze
258
- @allowed_origins = Array(allowed_origins).map(&:downcase).freeze
276
+ @any_origin_allowed = allowed_origins == :any
277
+ @allowed_origins = (@any_origin_allowed ? [] : Array(allowed_origins)).map(&:downcase).freeze
259
278
  @pending_responses = {}
260
279
 
261
280
  # Maps a key the transport mints for each `subscriptions/listen` stream to
@@ -365,6 +384,27 @@ module MCP
365
384
 
366
385
  @max_stream_lifetime = max_stream_lifetime
367
386
 
387
+ if event_store
388
+ raise ArgumentError, "event_store is not supported in stateless mode." if @stateless
389
+
390
+ unless event_store.respond_to?(:store_event) && event_store.respond_to?(:events_after)
391
+ raise ArgumentError, "event_store must respond to store_event and events_after (see MCP::Server::Transports::EventStore)"
392
+ end
393
+ end
394
+
395
+ @event_store = event_store
396
+
397
+ if retry_interval
398
+ # A retry interval without a store would promise a resumable stream the transport cannot resume.
399
+ raise ArgumentError, "retry_interval requires event_store" unless event_store
400
+
401
+ unless retry_interval.is_a?(Integer) && retry_interval.positive?
402
+ raise ArgumentError, "retry_interval must be a positive Integer of milliseconds or nil"
403
+ end
404
+ end
405
+
406
+ @retry_interval = retry_interval
407
+
368
408
  # `close` sets the flag and signals the reaper under `@mutex`, so the reaper leaves its wait at once instead of
369
409
  # being killed in the middle of a reap.
370
410
  @closing = false
@@ -384,6 +424,17 @@ module MCP
384
424
  # A write blocks only once the peer's socket buffers are full, which takes a reader already hundreds of kilobytes behind;
385
425
  # one that still has not taken the frame after this long is dropped whether it stopped reading or is only that slow.
386
426
  DEFAULT_STREAM_WRITE_TIMEOUT = 10
427
+
428
+ # The first protocol version whose clients parse an SSE event with empty data, which the priming event of
429
+ # SEP-1699 resumability is. A session that negotiated an earlier version gets no priming event and is never
430
+ # asked to resume, since it would have no event id to come back with; its other events still carry ids.
431
+ RESUMABLE_PROTOCOL_VERSION = "2025-11-25"
432
+
433
+ # Replay passes a resume makes before it gives up attaching. Each pass takes the events stored since
434
+ # the previous one and a further pass follows whenever that batch was not empty, so a sender that stores
435
+ # at least one event during each write keeps the loop going; after this many passes that each found events,
436
+ # the connection is closed behind the last batch for the client to reconnect from.
437
+ REPLAY_PASS_LIMIT = 16
387
438
  SESSION_REAP_INTERVAL = 60
388
439
  # Seconds `close` waits for a reap in progress to finish closing its streams before it kills the reaper.
389
440
  REAPER_JOIN_TIMEOUT = 5
@@ -602,44 +653,41 @@ module MCP
602
653
  return false if @enable_json_response && related_request_id
603
654
 
604
655
  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])
656
+ live = @mutex.synchronize do
657
+ next false unless (session = @sessions[session_id])
610
658
 
611
659
  if session_expired?(session)
612
660
  cleanup_and_collect_stream(session_id, streams_to_close)
613
- next
661
+ next false
614
662
  end
615
663
 
616
- active_stream(session, streams_to_close, related_request_id: related_request_id)
664
+ true
617
665
  end
618
666
 
619
667
  close_streams(streams_to_close)
620
- return false unless stream
668
+ return false unless live
621
669
 
622
- write_notification(stream, notification, session_id, related_request_id)
670
+ store_and_write(session_id, related_request_id, notification.to_json)
623
671
  end
624
672
 
625
673
  def deliver_broadcast_notification(notification)
626
674
  streams_to_close = []
627
675
 
628
- # Snapshot the connected streams under the lock, then write to each outside it.
676
+ # Snapshot the sessions under the lock, then write to each outside it. A session whose GET stream is
677
+ # closed at the moment still takes the notification when it has opened that stream before and an event
678
+ # store keeps it for the reconnect; one that never opened the stream has no cursor to resume from.
629
679
  targets = @mutex.synchronize do
630
680
  expired_session_ids = []
631
681
 
632
682
  collected = @sessions.filter_map do |session_id, session|
633
- next unless session[:get_sse_stream]
683
+ next unless session[:get_sse_stream] || (@event_store && session[:get_stream_opened])
634
684
 
635
685
  if session_expired?(session)
636
686
  expired_session_ids << session_id
637
687
  next
638
688
  end
639
689
 
640
- stream = active_stream(session, streams_to_close)
641
-
642
- [session_id, stream] if stream
690
+ session_id
643
691
  end
644
692
 
645
693
  expired_session_ids.each do |session_id|
@@ -651,22 +699,12 @@ module MCP
651
699
 
652
700
  close_streams(streams_to_close)
653
701
 
654
- targets.count do |session_id, stream|
655
- write_notification(stream, notification, session_id, nil)
702
+ json = notification.to_json
703
+ targets.count do |session_id|
704
+ store_and_write(session_id, nil, json)
656
705
  end
657
706
  end
658
707
 
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
708
  # Removes a stream that failed to accept a write. A request-scoped stream is dropped on its own;
671
709
  # a session-scoped (GET SSE) failure tears down the whole session. The `@sessions` mutation runs
672
710
  # under `@mutex`, and the affected streams are closed outside it.
@@ -675,6 +713,8 @@ module MCP
675
713
  # the lock that removes the session: the failed write may have been picked for a stream that was detached since,
676
714
  # because its token expired and the client reopened, and the stream opened in its place must stay. A failed
677
715
  # stream the session no longer holds was closed by whichever path detached it, so there is nothing left to do.
716
+ # With an event store the GET stream is detached instead and the session kept: the client resumes the stream
717
+ # from its last event id (SEP-1699), and the events it misses meanwhile are stored for it.
678
718
  def drop_broken_stream(session_id, stream, related_request_id)
679
719
  streams_to_close = []
680
720
 
@@ -689,7 +729,11 @@ module MCP
689
729
 
690
730
  streams_to_close << stream
691
731
  elsif session && session[:get_sse_stream].equal?(stream)
692
- cleanup_and_collect_stream(session_id, streams_to_close)
732
+ if @event_store
733
+ streams_to_close << detach_get_stream(session)
734
+ else
735
+ cleanup_and_collect_stream(session_id, streams_to_close)
736
+ end
693
737
  end
694
738
  end
695
739
 
@@ -744,39 +788,20 @@ module MCP
744
788
  request = { jsonrpc: "2.0", id: request_id, method: method }
745
789
  request[:params] = params if params
746
790
 
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])
791
+ # Register the pending response under the lock before the request is written, so a response arriving at once finds its entry;
792
+ # the write itself runs outside `@mutex`.
793
+ @mutex.synchronize do
794
+ unless @sessions.key?(session_id)
752
795
  raise "Session not found: #{session_id}."
753
796
  end
754
797
 
755
798
  @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
799
  end
759
800
 
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
- end
771
-
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
801
+ # With an event store a request whose stream is disconnected is kept for replay, so the wait below can still
802
+ # be answered once the client resumes the stream (SEP-1699); without one there is nothing the client could
803
+ # come back to, so the wait is not started.
804
+ unless store_and_write(session_id, related_request_id, request.to_json)
780
805
  raise "No active stream for #{method} request."
781
806
  end
782
807
 
@@ -857,6 +882,47 @@ module MCP
857
882
  end
858
883
  end
859
884
 
885
+ # Closes the SSE connection of the request `request_id` without ending the request (SEP-1699), so the client reconnects with
886
+ # `Last-Event-ID` after the `retry_interval` and the handler's remaining messages, kept by the event store meanwhile,
887
+ # reach it through the resumed connection. Returns `false` when there is nothing to close: no `event_store:`,
888
+ # a client that negotiated a version before 2025-11-25 (it received no priming event to come back with),
889
+ # a connection whose priming event the store failed to take (the client holds no cursor for it either),
890
+ # an unknown session or request, or a connection already closed. Handlers reach this through `server_context.close_sse_stream`.
891
+ # @api private
892
+ def close_sse_stream(session_id, request_id)
893
+ stream = @mutex.synchronize do
894
+ session = session_id && @sessions[session_id]
895
+ next unless session && resumable_session?(session)
896
+
897
+ entry = session.dig(:post_stream_entries, request_id)
898
+ current = session.dig(:post_request_streams, request_id)
899
+ next unless entry && current && entry[:primed_stream].equal?(current)
900
+
901
+ session[:post_request_streams].delete(request_id)
902
+ end
903
+ return false unless stream
904
+
905
+ close_stream_safely(stream)
906
+
907
+ true
908
+ end
909
+
910
+ # Closes the session's standalone GET stream the same way, so the client polls for server-initiated messages.
911
+ # @api private
912
+ def close_standalone_sse_stream(session_id)
913
+ stream = @mutex.synchronize do
914
+ session = session_id && @sessions[session_id]
915
+ next unless session && resumable_session?(session)
916
+ next unless session[:get_sse_stream] && session[:get_primed_stream].equal?(session[:get_sse_stream])
917
+
918
+ detach_get_stream(session)
919
+ end
920
+ return false unless stream
921
+
922
+ close_stream_safely(stream)
923
+ true
924
+ end
925
+
860
926
  private
861
927
 
862
928
  # The wait between reaps is a condition variable wait under `@mutex` rather than a sleep, so `close` can end it
@@ -895,9 +961,24 @@ module MCP
895
961
  end
896
962
  end
897
963
 
898
- def send_to_stream(stream, data)
964
+ # One `write` per frame, so the frames of concurrent writers cannot interleave in the middle of each other.
965
+ def send_to_stream(stream, data, event_id: nil)
899
966
  message = data.is_a?(String) ? data : data.to_json
900
- stream.write("data: #{message}\n\n")
967
+ frame = event_id ? "id: #{event_id}\ndata: #{message}\n\n" : "data: #{message}\n\n"
968
+
969
+ stream.write(frame)
970
+ stream.flush
971
+ end
972
+
973
+ # The priming event of SEP-1699: an id for the client to resume from, the `retry` field when configured, and
974
+ # empty data. The `data:` line is what makes the event one the client dispatches (and so sees the id of);
975
+ # an id without it would only be noted.
976
+ def send_priming_event_to_stream(stream, event_id)
977
+ fields = ["id: #{event_id}"]
978
+ fields << "retry: #{@retry_interval}" if @retry_interval
979
+ fields << "data:"
980
+
981
+ stream.write("#{fields.join("\n")}\n\n")
901
982
  stream.flush
902
983
  end
903
984
 
@@ -920,8 +1001,8 @@ module MCP
920
1001
  #
921
1002
  # The deadline interrupts the write with the exception `Timeout` raises on its own, which no `rescue` of an `IOError` or a `StandardError` inside
922
1003
  # 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) }
1004
+ def push_to_stream(stream, data, event_id: nil, subscription: nil)
1005
+ within_stream_write_timeout(stream, subscription) { send_to_stream(stream, data, event_id: event_id) }
925
1006
  end
926
1007
 
927
1008
  def push_ping_to_stream(stream, subscription: nil)
@@ -970,6 +1051,8 @@ module MCP
970
1051
  return invalid_request_response("Invalid Request: JSON-RPC body must be a single request object")
971
1052
  end
972
1053
 
1054
+ return oversized_id_response if JsonRpcHandler.oversized_integer_id?(body[:id])
1055
+
973
1056
  # The version check precedes everything else that depends on request content,
974
1057
  # so a client probing with an unknown future version always receives the `-32022` signal
975
1058
  # (with the supported list to select from) rather than an incidental error.
@@ -1258,6 +1341,11 @@ module MCP
1258
1341
  nil
1259
1342
  end
1260
1343
 
1344
+ # Answered before anything echoes the id: every refusal and response below writes it back.
1345
+ def oversized_id_response
1346
+ invalid_request_response("Invalid Request: id must be an integer of at most #{JsonRpcHandler::MAX_INTEGER_ID_BITS} bits")
1347
+ end
1348
+
1261
1349
  def listen_subscriptions_full?
1262
1350
  return false unless @max_listen_subscriptions
1263
1351
 
@@ -1777,6 +1865,8 @@ module MCP
1777
1865
  return invalid_request_response("Invalid Request: JSON-RPC body must be a single request object")
1778
1866
  end
1779
1867
 
1868
+ return oversized_id_response if JsonRpcHandler.oversized_integer_id?(body[:id])
1869
+
1780
1870
  # Header-primary routing sends sessionless modern traffic to `handle_modern` before this method runs,
1781
1871
  # so a body carrying the modern `_meta` triple (SEP-2575) arrives here in two shapes only.
1782
1872
  # Bound to a session under a dual-era header (2026-07-28), it is a lifecycle violation: the session
@@ -1900,6 +1990,14 @@ module MCP
1900
1990
  protocol_version_error = validate_protocol_version_header(request)
1901
1991
  return protocol_version_error if protocol_version_error
1902
1992
 
1993
+ # A reconnect naming the last event the client received resumes that stream (SEP-1699). Without an event store the header is ignored and
1994
+ # a plain stream is opened, since nothing was stored to replay.
1995
+ last_event_id = header_bytes(request, "HTTP_LAST_EVENT_ID")
1996
+
1997
+ if @event_store && last_event_id && !last_event_id.empty?
1998
+ return resume_sse_stream(session_id, last_event_id, request.env[OAuth::ENV_KEY])
1999
+ end
2000
+
1903
2001
  return session_already_connected_response if live_get_stream?(session_id)
1904
2002
 
1905
2003
  setup_sse_stream(session_id, request.env[OAuth::ENV_KEY])
@@ -2302,6 +2400,12 @@ module MCP
2302
2400
  auth_issuer: auth_info&.issuer,
2303
2401
  auth_subject: auth_info&.subject,
2304
2402
  auth_client_id: auth_info&.client_id,
2403
+ # Orders the session's event storage against a `Last-Event-ID` resume; see `store_and_write`.
2404
+ store_mutex: Mutex.new,
2405
+ # The stream id the events of the session's GET stream are stored under, fixed for the session's life
2406
+ # so a client resuming that stream finds everything it missed under one cursor however often
2407
+ # the connection was reopened. The response stream of each request gets its own id in `post_stream_entries`.
2408
+ get_stream_id: @event_store && mint_stream_id(session_id),
2305
2409
  }
2306
2410
  true
2307
2411
  end
@@ -2395,39 +2499,65 @@ module MCP
2395
2499
  # https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server
2396
2500
  def handle_request_with_sse_response(body_string, session_id, server_session, related_request_id: nil, auth_info: nil)
2397
2501
  body = proc do |stream|
2398
- @mutex.synchronize do
2502
+ # The stream id is kept with the request while it is in flight: it marks the request's events in
2503
+ # the event store and routes a `Last-Event-ID` resume back to the request (SEP-1699).
2504
+ # It is minted whether or not a store is configured, so the registration has one shape.
2505
+ stream_id = mint_stream_id(session_id)
2506
+ claimed = @mutex.synchronize do
2399
2507
  session = @sessions[session_id]
2400
- if session && related_request_id
2401
- session[:post_request_streams] ||= {}
2508
+ next false unless session && related_request_id
2402
2509
 
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
2510
+ session[:post_request_streams] ||= {}
2511
+ session[:post_stream_entries] ||= {}
2512
+
2513
+ # Claim the id only while it is free. `handle_regular_request` already refused the colliding request,
2514
+ # so reaching an occupied slot means a race got past that check; leaving the first stream in place keeps
2515
+ # its messages going where they belong.
2516
+ next false if session[:post_request_streams].key?(related_request_id) || session[:post_stream_entries].key?(related_request_id)
2517
+
2518
+ session[:post_request_streams][related_request_id] = stream
2519
+ session[:post_stream_entries][related_request_id] = { stream_id: stream_id, resumed: nil }
2520
+
2521
+ true
2408
2522
  end
2409
2523
 
2524
+ write_priming_event(session_id, related_request_id, stream) if claimed
2525
+
2410
2526
  begin
2411
2527
  response = dispatch_handle_json(body_string, server_session, auth_info: auth_info)
2412
2528
 
2413
- send_to_stream(stream, response) if response
2529
+ if response
2530
+ # Written through the registration rather than to `stream`: the response of a request whose connection was
2531
+ # closed and resumed meanwhile belongs on the resumed one, and is stored for a client still to reconnect.
2532
+ if claimed
2533
+ store_and_write(session_id, related_request_id, response, pushed: false)
2534
+ else
2535
+ send_to_stream(stream, response)
2536
+ end
2537
+ end
2414
2538
  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)
2539
+ resumed = nil
2421
2540
 
2422
- session[:post_request_streams].delete(related_request_id) if registered.equal?(stream)
2541
+ if claimed
2542
+ resumed = @mutex.synchronize do
2543
+ session = @sessions[session_id]
2544
+ entry = session&.dig(:post_stream_entries, related_request_id)
2545
+ # Only retire our own registration: one whose claim has already been replaced must not unregister
2546
+ # the stream that owns it. The live stream is this request's own when it is the one opened here or
2547
+ # the one a resume put in its place.
2548
+ next unless entry && entry[:stream_id] == stream_id
2549
+
2550
+ session[:post_stream_entries].delete(related_request_id)
2551
+ registered = session[:post_request_streams][related_request_id]
2552
+ if registered.equal?(stream) || (entry[:resumed] && registered.equal?(entry[:resumed]))
2553
+ session[:post_request_streams].delete(related_request_id)
2554
+ end
2555
+ entry[:resumed]
2423
2556
  end
2424
2557
  end
2425
2558
 
2426
- begin
2427
- stream.close
2428
- rescue StandardError
2429
- # Ignore close-related errors from already closed/broken streams.
2430
- end
2559
+ close_stream_safely(resumed) if resumed
2560
+ close_stream_safely(stream)
2431
2561
  end
2432
2562
  end
2433
2563
 
@@ -2570,7 +2700,7 @@ module MCP
2570
2700
  # to prevent DNS rebinding attacks against locally bound MCP servers. Protection is on by default;
2571
2701
  # pass `dns_rebinding_protection: false` to disable it (e.g. when an upstream proxy or middleware already
2572
2702
  # 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:`.
2703
+ # and the `Origin` header, when present, must be same-origin or in `allowed_origins:`, unless that is `:any`.
2574
2704
  def validate_dns_rebinding(request)
2575
2705
  return unless @dns_rebinding_protection
2576
2706
 
@@ -2602,7 +2732,14 @@ module MCP
2602
2732
 
2603
2733
  # A request without an `Origin` header (typical for non-browser MCP clients) is allowed. A browser cross-origin request is
2604
2734
  # rejected unless the origin is same-origin or explicitly allow-listed via `allowed_origins:`.
2735
+ #
2736
+ # `allowed_origins: :any` skips this check alone. A rebound request names the attacker's host in `Host` and, when it carries one,
2737
+ # 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
2738
+ # that relies on what the browser attaches by itself, which a server requiring a bearer token does not accept.
2739
+ # The `Origin` a session was created with still binds its later requests (`session_request_rejection`).
2605
2740
  def validate_origin(request)
2741
+ return if @any_origin_allowed
2742
+
2606
2743
  origin = header_bytes(request, "HTTP_ORIGIN")
2607
2744
  return if origin.nil?
2608
2745
  return if same_origin?(origin, request)
@@ -2706,7 +2843,10 @@ module MCP
2706
2843
  def create_sse_body(session_id, auth_info = nil)
2707
2844
  proc do |stream|
2708
2845
  stored = store_stream_for_session(session_id, stream, auth_info)
2709
- start_keepalive_thread(session_id, stream) if stored
2846
+ next unless stored
2847
+
2848
+ write_priming_event(session_id, nil, stream)
2849
+ start_keepalive_thread(session_id, stream)
2710
2850
  end
2711
2851
  end
2712
2852
 
@@ -2719,6 +2859,9 @@ module MCP
2719
2859
 
2720
2860
  session[:get_sse_stream] = stream
2721
2861
  session[:get_sse_stream_expires_at] = stream_token_expiry(auth_info)
2862
+ # From here on the session's GET stream events are stored, since the client now has the cursor to
2863
+ # resume them from.
2864
+ session[:get_stream_opened] = true
2722
2865
  true
2723
2866
  end
2724
2867
 
@@ -2737,7 +2880,8 @@ module MCP
2737
2880
  # stream at a delivery once its token expired and the client may have opened a new one since, which gets
2738
2881
  # a keepalive thread of its own. The loop therefore ends as soon as the session no longer holds this stream,
2739
2882
  # 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.
2883
+ # `drop_broken_stream`, which tears the session down only while it still holds that stream, as before,
2884
+ # or detaches the stream alone when an event store lets the client resume it.
2741
2885
  def start_keepalive_thread(session_id, stream)
2742
2886
  Thread.new do
2743
2887
  ended = false
@@ -2820,6 +2964,307 @@ module MCP
2820
2964
 
2821
2965
  Process.clock_gettime(Process::CLOCK_MONOTONIC) - session[:last_active_at] > @session_idle_timeout
2822
2966
  end
2967
+
2968
+ # Stream ids carry the session id, so a `Last-Event-ID` is matched to the session presenting it with
2969
+ # a string check, however long ago the request that opened the stream finished.
2970
+ def mint_stream_id(session_id)
2971
+ "#{session_id}:#{SecureRandom.uuid}"
2972
+ end
2973
+
2974
+ def owned_stream_id?(session_id, stream_id)
2975
+ stream_id.is_a?(String) && stream_id.start_with?("#{session_id}:")
2976
+ end
2977
+
2978
+ def resumable_session?(session)
2979
+ !@event_store.nil? && resumable_protocol_version?(session[:server_session].protocol_version)
2980
+ end
2981
+
2982
+ # Membership in the supported list keeps an unknown future version out: `initialize` only ever records
2983
+ # a negotiated handshake version, so this is belt and braces, as in the TypeScript SDK.
2984
+ def resumable_protocol_version?(version)
2985
+ version.is_a?(String) &&
2986
+ MCP::Configuration::SUPPORTED_STABLE_PROTOCOL_VERSIONS.include?(version) &&
2987
+ version >= RESUMABLE_PROTOCOL_VERSION
2988
+ end
2989
+
2990
+ # The event store stream the messages for `related_request_id` belong to (the GET stream for `nil`), or `nil`
2991
+ # when nothing is to be stored: no store, a request not in flight, or a GET stream the client has not opened
2992
+ # yet and so has no cursor into.
2993
+ def resolve_stream_id(session, related_request_id)
2994
+ return unless @event_store
2995
+
2996
+ if related_request_id
2997
+ session.dig(:post_stream_entries, related_request_id, :stream_id)
2998
+ elsif session[:get_stream_opened]
2999
+ session[:get_stream_id]
3000
+ end
3001
+ end
3002
+
3003
+ # Runs the block under the session's store lock, which orders the storing of a message and the choice of its
3004
+ # stream against a replay pass and the attachment of a resumed stream (see `store_and_write`); `false` when
3005
+ # the session is gone. The lock is created on first use, so a session built before this transport kept one is
3006
+ # served too. It is held across store calls but never across a stream write, so a stalled reader stalls nobody.
3007
+ def with_session_store_lock(session_id)
3008
+ lock = @mutex.synchronize do
3009
+ session = @sessions[session_id]
3010
+ session && (session[:store_mutex] ||= Mutex.new)
3011
+ end
3012
+ return false unless lock
3013
+
3014
+ lock.synchronize { yield }
3015
+ true
3016
+ end
3017
+
3018
+ # Delivers `json`, a JSON-RPC message, on the session's stream for `related_request_id` (the GET stream for `nil`).
3019
+ # With an event store the message is stored first and written with the id the store assigned, so one written while
3020
+ # the stream is disconnected is replayed when the client resumes. The store and the choice of the stream share one hold of
3021
+ # the session's store lock, which `replay_and_attach` holds across each replay pass and the attachment of the resumed stream:
3022
+ # a message is therefore either in a set that replay writes to the resumed stream or written to that stream by
3023
+ # its own sender afterwards, never missed by both or written to it twice. The write itself runs outside every lock.
3024
+ # Returns `true` when the message reached a live stream or was stored for the reconnect, `false` otherwise.
3025
+ #
3026
+ # A message the transport pushes on its own (a notification, a server-to-client request) is written under `stream_write_timeout:`,
3027
+ # since its sender writes to stream after stream. `pushed: false` is for the response of a request,
3028
+ # written on that request's own thread, which waits for its reader as it did before.
3029
+ def store_and_write(session_id, related_request_id, json, pushed: true)
3030
+ event_id = nil
3031
+ stream = nil
3032
+ streams_to_close = []
3033
+ locked = with_session_store_lock(session_id) do
3034
+ stream_id = @mutex.synchronize do
3035
+ session = @sessions[session_id]
3036
+ session && resolve_stream_id(session, related_request_id)
3037
+ end
3038
+ event_id = stream_id && safe_store_event(stream_id, json)
3039
+
3040
+ stream = @mutex.synchronize do
3041
+ session = @sessions[session_id]
3042
+ session && active_stream(session, streams_to_close, related_request_id: related_request_id)
3043
+ end
3044
+ end
3045
+
3046
+ close_streams(streams_to_close)
3047
+ return false unless locked
3048
+
3049
+ written = false
3050
+ if stream
3051
+ begin
3052
+ if pushed
3053
+ push_to_stream(stream, json, event_id: event_id)
3054
+ else
3055
+ send_to_stream(stream, json, event_id: event_id)
3056
+ end
3057
+
3058
+ written = true
3059
+ rescue *STREAM_WRITE_ERRORS => e
3060
+ MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to send message" })
3061
+
3062
+ drop_broken_stream(session_id, stream, related_request_id)
3063
+ end
3064
+ end
3065
+
3066
+ written || !event_id.nil?
3067
+ end
3068
+
3069
+ # Opens `stream`, the connection the caller has just put in place for `related_request_id`, with the priming event,
3070
+ # stored first so its id is a cursor in the stream like any other. Only for sessions that negotiated
3071
+ # `RESUMABLE_PROTOCOL_VERSION` or later.
3072
+ #
3073
+ # The write has no deadline, since it is made on the thread of the request that opened or resumed the connection,
3074
+ # so it goes to that connection and no other: when a later resume has taken its place in the meantime,
3075
+ # nothing is written, and that resume primes the connection it attached.
3076
+ def write_priming_event(session_id, related_request_id, stream)
3077
+ event_id = nil
3078
+ streams_to_close = []
3079
+ with_session_store_lock(session_id) do
3080
+ stream_id = @mutex.synchronize do
3081
+ session = @sessions[session_id]
3082
+ next unless session && resumable_session?(session)
3083
+ next unless active_stream(session, streams_to_close, related_request_id: related_request_id).equal?(stream)
3084
+
3085
+ resolve_stream_id(session, related_request_id)
3086
+ end
3087
+ event_id = stream_id && safe_store_event(stream_id, nil)
3088
+ end
3089
+ close_streams(streams_to_close)
3090
+ return unless event_id
3091
+
3092
+ send_priming_event_to_stream(stream, event_id)
3093
+ mark_primed(session_id, related_request_id, stream)
3094
+ rescue *STREAM_WRITE_ERRORS => e
3095
+ MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to send message" })
3096
+ drop_broken_stream(session_id, stream, related_request_id)
3097
+ end
3098
+
3099
+ # Records that `stream` received its priming event, which `close_sse_stream` and `close_standalone_sse_stream`
3100
+ # require before they close it on purpose: a connection without one has given the client no cursor to come
3101
+ # back with. Compared by identity, so a connection opened in the stream's place starts unprimed.
3102
+ def mark_primed(session_id, related_request_id, stream)
3103
+ @mutex.synchronize do
3104
+ session = @sessions[session_id]
3105
+ next unless session
3106
+
3107
+ if related_request_id
3108
+ entry = session.dig(:post_stream_entries, related_request_id)
3109
+ entry[:primed_stream] = stream if entry && session.dig(:post_request_streams, related_request_id).equal?(stream)
3110
+ elsif session[:get_sse_stream].equal?(stream)
3111
+ session[:get_primed_stream] = stream
3112
+ end
3113
+ end
3114
+ end
3115
+
3116
+ # A failing store must not take the request or the session down with it: the frame is written without an id
3117
+ # (the client's cursor stays at the previous event, which costs it this one event on resume) and the failure
3118
+ # is reported. An id with a line break would end the SSE frame early, so it is refused the same way.
3119
+ def safe_store_event(stream_id, message)
3120
+ event_id = @event_store.store_event(stream_id, message)
3121
+ return event_id if valid_event_id?(event_id)
3122
+
3123
+ report_event_store_failure(ArgumentError.new("event store returned an invalid event id"), stream_id)
3124
+ nil
3125
+ rescue StandardError => e
3126
+ report_event_store_failure(e, stream_id)
3127
+ nil
3128
+ end
3129
+
3130
+ def safe_events_after(last_event_id)
3131
+ replay = @event_store.events_after(last_event_id)
3132
+ return unless replay.is_a?(Array) && replay.size == 2 && replay[0].is_a?(String) && replay[1].is_a?(Array)
3133
+
3134
+ replay
3135
+ rescue StandardError => e
3136
+ report_event_store_failure(e, nil)
3137
+ nil
3138
+ end
3139
+
3140
+ def valid_event_id?(event_id)
3141
+ event_id.is_a?(String) && !event_id.empty? && !event_id.match?(/[\r\n]/)
3142
+ end
3143
+
3144
+ def report_event_store_failure(error, stream_id)
3145
+ MCP.configuration.exception_reporter.call(error, { stream_id: stream_id, error: "Event store failure" })
3146
+ end
3147
+
3148
+ # Serves a GET carrying `Last-Event-ID` (SEP-1699): the stream the event belongs to is replayed from that event and,
3149
+ # when it is still open on the server side (the session's GET stream, or the response stream of a request still in flight),
3150
+ # the new connection takes the old one's place. The stream must belong to this session: an id of another session,
3151
+ # or one the store no longer knows, is answered 400 without replaying anything, and the two cases are not told apart.
3152
+ def resume_sse_stream(session_id, last_event_id, auth_info)
3153
+ replay = safe_events_after(last_event_id)
3154
+ return unknown_last_event_id_response unless replay && owned_stream_id?(session_id, replay[0])
3155
+
3156
+ body = proc do |stream|
3157
+ replay_and_attach(session_id, last_event_id, stream, auth_info)
3158
+ end
3159
+
3160
+ [200, SSE_HEADERS.dup, body]
3161
+ end
3162
+
3163
+ # The value is not echoed: it is client-supplied and nothing about it needs confirming.
3164
+ def unknown_last_event_id_response
3165
+ json_rpc_error_response(
3166
+ status: 400,
3167
+ code: JsonRpcHandler::ErrorCode::INVALID_REQUEST,
3168
+ message: "Bad Request: Unknown Last-Event-ID",
3169
+ )
3170
+ end
3171
+
3172
+ # Writes the events stored on the stream after `last_event_id` to `stream`, then puts `stream` in place of the connection
3173
+ # that stream was last carried by. Each pass takes the events stored since the cursor under the session's store lock
3174
+ # and writes them outside it; the pass that finds none left attaches the stream under the same hold, so a message stored
3175
+ # between the last replayed event and the attachment is impossible: it is either replayed by a further pass or written to
3176
+ # the attached stream by its own sender. A resume whose `REPLAY_PASS_LIMIT` passes all found events is closed behind
3177
+ # the last batch instead of attached, so no connection replays without end and the lock is still never held across a write;
3178
+ # the client reconnects from its new cursor after `retry`, as after any disconnect.
3179
+ def replay_and_attach(session_id, last_event_id, stream, auth_info)
3180
+ cursor = last_event_id
3181
+ attachment = nil
3182
+ passes = 0
3183
+
3184
+ until attachment
3185
+ events = []
3186
+ passes += 1
3187
+ locked = with_session_store_lock(session_id) do
3188
+ replay = safe_events_after(cursor)
3189
+ stream_id = replay && replay[0]
3190
+ if stream_id && owned_stream_id?(session_id, stream_id)
3191
+ events = replay[1]
3192
+ attachment = attach_resumed_stream(session_id, stream_id, stream, auth_info) if events.empty?
3193
+ else
3194
+ attachment = :refused
3195
+ end
3196
+ end
3197
+ attachment = :refused unless locked
3198
+ attachment ||= :behind if passes >= REPLAY_PASS_LIMIT
3199
+
3200
+ events.each do |event_id, message|
3201
+ cursor = event_id
3202
+ next unless message.is_a?(String)
3203
+
3204
+ send_to_stream(stream, message, event_id: valid_event_id?(event_id) ? event_id : nil)
3205
+ end
3206
+ end
3207
+
3208
+ finish_resumed_stream(session_id, stream, attachment)
3209
+ rescue *STREAM_WRITE_ERRORS => e
3210
+ MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to replay events" })
3211
+
3212
+ close_stream_safely(stream)
3213
+ end
3214
+
3215
+ # Puts `stream` in place of the connection `stream_id` was last carried by, the session's GET stream or
3216
+ # the response stream of a request still in flight, and says which; `:retired` for the stream of a request already answered,
3217
+ # `:gone` for a session that no longer exists. A connection still attached there is handed back as `replaced` for closing:
3218
+ # the client presenting the id of its last event is the one that held it. Called under the session's store lock.
3219
+ def attach_resumed_stream(session_id, stream_id, stream, auth_info)
3220
+ @mutex.synchronize do
3221
+ session = @sessions[session_id]
3222
+ next :gone unless session
3223
+
3224
+ if stream_id == session[:get_stream_id]
3225
+ replaced = detach_get_stream(session)
3226
+ session[:get_sse_stream] = stream
3227
+ session[:get_sse_stream_expires_at] = stream_token_expiry(auth_info)
3228
+ session[:get_stream_opened] = true
3229
+ { kind: :get, replaced: replaced }
3230
+ elsif (request_id = request_id_of_stream(session, stream_id))
3231
+ replaced = session[:post_request_streams][request_id]
3232
+ session[:post_request_streams][request_id] = stream
3233
+ session[:post_stream_entries][request_id][:resumed] = stream
3234
+ { kind: :post, request_id: request_id, replaced: replaced }
3235
+ else
3236
+ :retired
3237
+ end
3238
+ end
3239
+ end
3240
+
3241
+ # The stream of a request already answered has nothing more to carry once replayed, so that connection is
3242
+ # closed, as the spec asks after the response, and so is one that found events on each of its `REPLAY_PASS_LIMIT`
3243
+ # passes, which the client reconnects from its new cursor. An attached stream is primed, giving the client a cursor and
3244
+ # the `retry` field again, and a GET stream gets its keepalive.
3245
+ def finish_resumed_stream(session_id, stream, attachment)
3246
+ unless attachment.is_a?(Hash)
3247
+ close_stream_safely(stream)
3248
+ return
3249
+ end
3250
+
3251
+ close_stream_safely(attachment[:replaced]) if attachment[:replaced]
3252
+
3253
+ if attachment[:kind] == :get
3254
+ write_priming_event(session_id, nil, stream)
3255
+ start_keepalive_thread(session_id, stream)
3256
+ else
3257
+ write_priming_event(session_id, attachment[:request_id], stream)
3258
+ end
3259
+ end
3260
+
3261
+ def request_id_of_stream(session, stream_id)
3262
+ entries = session[:post_stream_entries]
3263
+ return unless entries
3264
+
3265
+ request_id, = entries.find { |_request_id, entry| entry[:stream_id] == stream_id }
3266
+ request_id
3267
+ end
2823
3268
  end
2824
3269
  end
2825
3270
  end