mcp 1.9.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.
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "json"
4
4
  require "set"
5
+ require "timeout"
5
6
  require_relative "../../result_type"
6
7
  require_relative "../../transport"
7
8
 
@@ -144,8 +145,10 @@ module MCP
144
145
  # expiry. Not supported in stateless mode.
145
146
  # @param max_sessions [Integer, nil] cap on the concurrent session count in stateful mode; a new
146
147
  # `initialize` past the cap is rejected with HTTP 503, and `nil` disables the cap.
147
- # @param allowed_origins [Array<String>, nil] extra `Origin` values accepted in addition to
148
- # 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).
149
152
  # @param allowed_hosts [Array<String>, nil] extra `Host` values accepted beyond the loopback
150
153
  # defaults (`127.0.0.1`, `::1`, `localhost`); each entry matches a bare host name (any port)
151
154
  # or a full `host:port`.
@@ -188,6 +191,13 @@ module MCP
188
191
  # @param server_to_client_request_timeout [Numeric] seconds a server-to-client request waits for its
189
192
  # response before the transport stops waiting and raises `MCP::Server::RequestTimeoutError`.
190
193
  # Defaults to `DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT` (600); individual calls override it with `timeout:`.
194
+ # @param stream_write_timeout [Numeric, nil] seconds a notification, a server-to-client request, a listen
195
+ # acknowledgement or a keepalive may take to be written to an SSE stream before the stream is dropped as stalled.
196
+ # These writes are made on behalf of every stream in turn, so a peer that stops reading would otherwise hold
197
+ # the writer, and the streams after it, for as long as its buffers stay full. The response of a request is not bounded:
198
+ # it is written on that request's own thread and may be large. The bound is per stream, so several stalled streams delay
199
+ # a notification by the sum of their waits, once each. Closing a stream is given the same number of seconds, once.
200
+ # Defaults to `DEFAULT_STREAM_WRITE_TIMEOUT` (10); pass `nil` to wait without limit.
191
201
  # @param token_verifier [#verify, nil] enables built-in OAuth 2.1 bearer enforcement: anything responding to
192
202
  # `verify(token) -> MCP::Server::OAuth::AccessToken | nil` (see `MCP::Server::OAuth::TokenVerifier` for
193
203
  # the contract and the built-in JWT/introspection implementations). Every POST, GET, and DELETE is verified
@@ -210,6 +220,13 @@ module MCP
210
220
  # expiry closes the stream earlier when it comes first; the cap is what bounds a stream whose token reports no
211
221
  # expiry. `nil` removes the cap, leaving such a stream open until either side disconnects. Streams opened without
212
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`.
213
230
  def initialize(
214
231
  server,
215
232
  stateless: false,
@@ -227,12 +244,15 @@ module MCP
227
244
  listen_keepalive_interval: DEFAULT_LISTEN_KEEPALIVE_INTERVAL,
228
245
  serve_subscriptions_listen: true,
229
246
  server_to_client_request_timeout: DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT,
247
+ stream_write_timeout: DEFAULT_STREAM_WRITE_TIMEOUT,
230
248
  token_verifier: nil,
231
249
  required_scopes: [],
232
250
  resource_metadata: nil,
233
251
  resource_metadata_url: nil,
234
252
  scope_matcher: nil,
235
- max_stream_lifetime: DEFAULT_MAX_STREAM_LIFETIME
253
+ max_stream_lifetime: DEFAULT_MAX_STREAM_LIFETIME,
254
+ event_store: nil,
255
+ retry_interval: nil
236
256
  )
237
257
  super(server)
238
258
  # Maps `session_id` to `{ get_sse_stream: stream_object, server_session: ServerSession, last_active_at: float_from_monotonic_clock, origin: origin_header }`.
@@ -244,9 +264,17 @@ module MCP
244
264
  @session_request_validator = session_request_validator
245
265
  @dns_rebinding_protection = dns_rebinding_protection
246
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
+
247
274
  # Host names are case-insensitive, so the allow lists are compared down-cased.
248
275
  @allowed_hosts = (DEFAULT_LOOPBACK_HOSTS + Array(allowed_hosts)).map(&:downcase).freeze
249
- @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
250
278
  @pending_responses = {}
251
279
 
252
280
  # Maps a key the transport mints for each `subscriptions/listen` stream to
@@ -325,6 +353,15 @@ module MCP
325
353
 
326
354
  @server_to_client_request_timeout = server_to_client_request_timeout
327
355
 
356
+ unless stream_write_timeout.nil? || (stream_write_timeout.is_a?(Numeric) && stream_write_timeout.positive?)
357
+ raise ArgumentError, "stream_write_timeout must be a positive number or nil"
358
+ end
359
+
360
+ @stream_write_timeout = stream_write_timeout
361
+
362
+ # Keyed by identity and weak, so a stream is not kept alive for having been recorded here.
363
+ @streams_with_abandoned_close = ObjectSpace::WeakMap.new
364
+
328
365
  if token_verifier
329
366
  @oauth_authenticator = OAuth::Authenticator.new(
330
367
  token_verifier: token_verifier,
@@ -347,6 +384,27 @@ module MCP
347
384
 
348
385
  @max_stream_lifetime = max_stream_lifetime
349
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
+
350
408
  # `close` sets the flag and signals the reaper under `@mutex`, so the reaper leaves its wait at once instead of
351
409
  # being killed in the middle of a reap.
352
410
  @closing = false
@@ -358,6 +416,25 @@ module MCP
358
416
  REQUIRED_POST_ACCEPT_TYPES_JSON = ["application/json"].freeze
359
417
  REQUIRED_GET_ACCEPT_TYPES = ["text/event-stream"].freeze
360
418
  STREAM_WRITE_ERRORS = [IOError, Errno::EPIPE, Errno::ECONNRESET].freeze
419
+
420
+ # Raised from a write the transport pushes onto an SSE stream when it has not finished within `stream_write_timeout:` seconds.
421
+ # An `IOError`, so every path that drops a stream on a failed write drops this one the same way.
422
+ class StreamWriteTimeoutError < IOError; end
423
+
424
+ # A write blocks only once the peer's socket buffers are full, which takes a reader already hundreds of kilobytes behind;
425
+ # one that still has not taken the frame after this long is dropped whether it stopped reading or is only that slow.
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
361
438
  SESSION_REAP_INTERVAL = 60
362
439
  # Seconds `close` waits for a reap in progress to finish closing its streams before it kills the reaper.
363
440
  REAPER_JOIN_TIMEOUT = 5
@@ -509,6 +586,20 @@ module MCP
509
586
  end
510
587
  end
511
588
 
589
+ # Sessions a server-wide log broadcast is offered to, each applying its own level or the server default.
590
+ # Public only so that `Server#notify_log_message` can call it. Custom transports may implement this hook;
591
+ # returning `nil` keeps the server-wide filter.
592
+ #
593
+ # @api private
594
+ # @return [Array<ServerSession>]
595
+ def logging_sessions
596
+ @mutex.synchronize do
597
+ @sessions.values.filter_map do |session|
598
+ session[:server_session] if session[:get_sse_stream]
599
+ end
600
+ end
601
+ end
602
+
512
603
  def send_notification(method, params = nil, session_id: nil, related_request_id: nil)
513
604
  # `subscriptions/listen` streams (SEP-2575) receive matching change notifications regardless of the delivery below:
514
605
  # a resource updated by one session's tool call changed globally, so modern subscribers hear about it too.
@@ -562,44 +653,41 @@ module MCP
562
653
  return false if @enable_json_response && related_request_id
563
654
 
564
655
  streams_to_close = []
565
-
566
- # Resolve the target stream under the lock, then write outside it: a stalled SSE reader
567
- # must not block every other session that needs `@mutex`.
568
- stream = @mutex.synchronize do
569
- next unless (session = @sessions[session_id])
656
+ live = @mutex.synchronize do
657
+ next false unless (session = @sessions[session_id])
570
658
 
571
659
  if session_expired?(session)
572
660
  cleanup_and_collect_stream(session_id, streams_to_close)
573
- next
661
+ next false
574
662
  end
575
663
 
576
- active_stream(session, streams_to_close, related_request_id: related_request_id)
664
+ true
577
665
  end
578
666
 
579
667
  close_streams(streams_to_close)
580
- return false unless stream
668
+ return false unless live
581
669
 
582
- write_notification(stream, notification, session_id, related_request_id)
670
+ store_and_write(session_id, related_request_id, notification.to_json)
583
671
  end
584
672
 
585
673
  def deliver_broadcast_notification(notification)
586
674
  streams_to_close = []
587
675
 
588
- # 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.
589
679
  targets = @mutex.synchronize do
590
680
  expired_session_ids = []
591
681
 
592
682
  collected = @sessions.filter_map do |session_id, session|
593
- next unless session[:get_sse_stream]
683
+ next unless session[:get_sse_stream] || (@event_store && session[:get_stream_opened])
594
684
 
595
685
  if session_expired?(session)
596
686
  expired_session_ids << session_id
597
687
  next
598
688
  end
599
689
 
600
- stream = active_stream(session, streams_to_close)
601
-
602
- [session_id, stream] if stream
690
+ session_id
603
691
  end
604
692
 
605
693
  expired_session_ids.each do |session_id|
@@ -611,22 +699,12 @@ module MCP
611
699
 
612
700
  close_streams(streams_to_close)
613
701
 
614
- targets.count do |session_id, stream|
615
- 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)
616
705
  end
617
706
  end
618
707
 
619
- # Writes a notification to an SSE stream without holding `@mutex`. On a write error,
620
- # drops the broken stream and returns false; on success returns true.
621
- def write_notification(stream, notification, session_id, related_request_id)
622
- send_to_stream(stream, notification)
623
- true
624
- rescue *STREAM_WRITE_ERRORS => e
625
- MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to send notification" })
626
- drop_broken_stream(session_id, stream, related_request_id)
627
- false
628
- end
629
-
630
708
  # Removes a stream that failed to accept a write. A request-scoped stream is dropped on its own;
631
709
  # a session-scoped (GET SSE) failure tears down the whole session. The `@sessions` mutation runs
632
710
  # under `@mutex`, and the affected streams are closed outside it.
@@ -635,6 +713,8 @@ module MCP
635
713
  # the lock that removes the session: the failed write may have been picked for a stream that was detached since,
636
714
  # because its token expired and the client reopened, and the stream opened in its place must stay. A failed
637
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.
638
718
  def drop_broken_stream(session_id, stream, related_request_id)
639
719
  streams_to_close = []
640
720
 
@@ -649,7 +729,11 @@ module MCP
649
729
 
650
730
  streams_to_close << stream
651
731
  elsif session && session[:get_sse_stream].equal?(stream)
652
- 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
653
737
  end
654
738
  end
655
739
 
@@ -704,39 +788,20 @@ module MCP
704
788
  request = { jsonrpc: "2.0", id: request_id, method: method }
705
789
  request[:params] = params if params
706
790
 
707
- # Register the pending response and resolve the stream under the lock, but perform
708
- # the write outside it so a stalled reader cannot block every other session on `@mutex`.
709
- streams_to_close = []
710
- stream = @mutex.synchronize do
711
- 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)
712
795
  raise "Session not found: #{session_id}."
713
796
  end
714
797
 
715
798
  @pending_responses[request_id] = { queue: pending_response, session_id: session_id }
716
-
717
- active_stream(session, streams_to_close, related_request_id: related_request_id)
718
799
  end
719
800
 
720
- close_streams(streams_to_close)
721
-
722
- sent = false
723
- if stream
724
- begin
725
- send_to_stream(stream, request)
726
- sent = true
727
- rescue *STREAM_WRITE_ERRORS
728
- drop_broken_stream(session_id, stream, related_request_id)
729
- end
730
- end
731
-
732
- # TODO: Replace with event store + replay when resumability is implemented.
733
- # Resumability is a separate MCP specification feature (SSE event IDs, Last-Event-ID replay,
734
- # event store management) independent of sampling.
735
- # See: https://modelcontextprotocol.io/specification/latest/basic/transports#resumability-and-redelivery
736
- #
737
- # The TypeScript and Python SDKs buffer messages and replay on reconnect.
738
- # Until then, raise to prevent queue.pop from blocking indefinitely.
739
- 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)
740
805
  raise "No active stream for #{method} request."
741
806
  end
742
807
 
@@ -817,6 +882,47 @@ module MCP
817
882
  end
818
883
  end
819
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
+
820
926
  private
821
927
 
822
928
  # The wait between reaps is a condition variable wait under `@mutex` rather than a sleep, so `close` can end it
@@ -855,9 +961,24 @@ module MCP
855
961
  end
856
962
  end
857
963
 
858
- 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)
859
966
  message = data.is_a?(String) ? data : data.to_json
860
- 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")
861
982
  stream.flush
862
983
  end
863
984
 
@@ -866,6 +987,41 @@ module MCP
866
987
  stream.flush
867
988
  end
868
989
 
990
+ # `send_to_stream` and `send_ping_to_stream` for the frames the transport pushes onto a stream on its own: a notification,
991
+ # a server-to-client request, a listen acknowledgement, a keepalive. One thread writes them to stream after stream,
992
+ # and a keepalive write holds its stream's write mutex, so a peer that stopped reading would stall the notifications of
993
+ # every other client, and each thread that sends one, for as long as its buffers stay full.
994
+ # The write is given `stream_write_timeout:` seconds; past that it fails as a write to a broken stream does, and the caller drops the stream.
995
+ #
996
+ # The deadline may cut a frame short, so the stream is closed here, before the error leaves: a listen stream is written under its write mutex,
997
+ # which the error releases on its way out, ahead of the caller's removal of the entry, and a writer waiting on that mutex would otherwise put
998
+ # its frame after the cut one. Closed first, every later write fails as on any closed stream. The entry of a listen stream, passed as `subscription`,
999
+ # is marked closed as well, still under its write mutex, so those writers skip it even when the close itself had to be abandoned.
1000
+ #
1001
+ #
1002
+ # The deadline interrupts the write with the exception `Timeout` raises on its own, which no `rescue` of an `IOError` or a `StandardError` inside
1003
+ # a stream implementation catches, and becomes `StreamWriteTimeoutError` only here, where it leaves the write.
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) }
1006
+ end
1007
+
1008
+ def push_ping_to_stream(stream, subscription: nil)
1009
+ within_stream_write_timeout(stream, subscription) { send_ping_to_stream(stream) }
1010
+ end
1011
+
1012
+ def within_stream_write_timeout(stream, subscription, &block)
1013
+ return yield unless @stream_write_timeout
1014
+
1015
+ begin
1016
+ Timeout.timeout(@stream_write_timeout, &block)
1017
+ rescue Timeout::Error
1018
+ subscription[:closed] = true if subscription
1019
+ close_stream_safely(stream)
1020
+
1021
+ raise StreamWriteTimeoutError, "SSE stream write did not finish within #{@stream_write_timeout} seconds"
1022
+ end
1023
+ end
1024
+
869
1025
  # Serves one request of the stateless modern lifecycle (MCP 2026-07-28, SEP-2575):
870
1026
  # a single POST/JSON exchange with no session. The modern path never consults
871
1027
  # `@stateless`, `@sessions`, or `@enable_json_response`, and never issues or accepts
@@ -895,6 +1051,8 @@ module MCP
895
1051
  return invalid_request_response("Invalid Request: JSON-RPC body must be a single request object")
896
1052
  end
897
1053
 
1054
+ return oversized_id_response if JsonRpcHandler.oversized_integer_id?(body[:id])
1055
+
898
1056
  # The version check precedes everything else that depends on request content,
899
1057
  # so a client probing with an unknown future version always receives the `-32022` signal
900
1058
  # (with the supported list to select from) rather than an incidental error.
@@ -905,9 +1063,9 @@ module MCP
905
1063
  message: "Unsupported protocol version",
906
1064
  data: {
907
1065
  supported: MCP::Configuration::SUPPORTED_MODERN_PROTOCOL_VERSIONS,
908
- requested: header_version,
1066
+ requested: printable_value(header_version),
909
1067
  },
910
- id: body[:id],
1068
+ id: echoable_id(body[:id]),
911
1069
  )
912
1070
  end
913
1071
 
@@ -916,13 +1074,20 @@ module MCP
916
1074
  status: 400,
917
1075
  code: JsonRpcHandler::ErrorCode::INVALID_REQUEST,
918
1076
  message: "Bad Request: Mcp-Session-Id is not accepted in the modern lifecycle",
919
- id: body[:id],
1077
+ id: echoable_id(body[:id]),
920
1078
  )
921
1079
  end
922
1080
 
923
1081
  mismatch_error = validate_modern_headers(request, body, header_version)
924
1082
  return mismatch_error if mismatch_error
925
1083
 
1084
+ # SEP-2243 custom headers: the `Mcp-Param-*` headers of a `tools/call` are checked against the body here,
1085
+ # before dispatch, so a disagreement is refused without the tool ever running.
1086
+ if body[:method] == Methods::TOOLS_CALL
1087
+ param_error = validate_mcp_param_headers(request, body)
1088
+ return param_error if param_error
1089
+ end
1090
+
926
1091
  # `subscriptions/listen` is a long-lived notification stream served at the transport layer;
927
1092
  # it never dispatches through `Server#handle`. A transport constructed with
928
1093
  # `serve_subscriptions_listen: false` skips the interception, so the method falls through
@@ -983,7 +1148,7 @@ module MCP
983
1148
  meta_version = params.is_a?(Hash) && params[:_meta].is_a?(Hash) ? params.dig(:_meta, :"io.modelcontextprotocol/protocolVersion") : nil
984
1149
  if meta_version && meta_version != header_version
985
1150
  return header_mismatch_response(
986
- "MCP-Protocol-Version header value '#{header_version}' does not match body value '#{meta_version}'",
1151
+ "MCP-Protocol-Version header value '#{printable_value(header_version)}' does not match body value '#{printable_value(meta_version)}'",
987
1152
  body[:id],
988
1153
  )
989
1154
  end
@@ -1002,7 +1167,7 @@ module MCP
1002
1167
  end
1003
1168
  if method_header != body[:method]
1004
1169
  return header_mismatch_response(
1005
- "Mcp-Method header value '#{method_header}' does not match body value '#{body[:method]}'",
1170
+ "Mcp-Method header value '#{printable_value(method_header)}' does not match body value '#{printable_value(body[:method])}'",
1006
1171
  body[:id],
1007
1172
  )
1008
1173
  end
@@ -1013,7 +1178,7 @@ module MCP
1013
1178
  if body_name
1014
1179
  if name_header.to_s.empty?
1015
1180
  return header_mismatch_response(
1016
- "Mcp-Name header is required for `#{body[:method]}`",
1181
+ "Mcp-Name header is required for `#{printable_value(body[:method])}`",
1017
1182
  body[:id],
1018
1183
  )
1019
1184
  end
@@ -1021,7 +1186,7 @@ module MCP
1021
1186
  decoded_name = decode_header_value(name_header)
1022
1187
  if decoded_name != body_name
1023
1188
  return header_mismatch_response(
1024
- "Mcp-Name header value '#{decoded_name}' does not match body value '#{body_name}'",
1189
+ "Mcp-Name header value '#{printable_value(decoded_name)}' does not match body value '#{printable_value(body_name)}'",
1025
1190
  body[:id],
1026
1191
  )
1027
1192
  end
@@ -1031,6 +1196,39 @@ module MCP
1031
1196
  nil
1032
1197
  end
1033
1198
 
1199
+ # Enforces the SEP-2243 server behavior for custom headers (`-32020`, HTTP 400) on a modern `tools/call`: each
1200
+ # `x-mcp-header` parameter of the called tool must have its `Mcp-Param-{Name}` header present exactly when the body
1201
+ # carries a value for it, agreeing with that value once a `=?base64?...?=` sentinel is decoded, and a malformed
1202
+ # sentinel is refused outright. The comparison runs before the tool does, on the schema the server itself serves
1203
+ # in `tools/list`, so the body a handler acts on is the one an intermediary routed on. A tool the server does not
1204
+ # know, or one whose declarations are invalid (a conforming client drops such a tool and sends no headers for it),
1205
+ # is left to the dispatcher, and headers for parameters no declaration names are ignored, as the spec asks of any
1206
+ # server that does not recognize them. The refusal names the header and the argument, not their values.
1207
+ #
1208
+ # Rack folds header names into `HTTP_` keys with `-` as `_`, so `Mcp-Param-Region-A` and `Mcp-Param-Region_A` land
1209
+ # on one key; a token that differs only in that way is the schema author's choice, and the value still has to
1210
+ # agree with the body.
1211
+ def validate_mcp_param_headers(request, body)
1212
+ params = body[:params]
1213
+ return unless params.is_a?(Hash)
1214
+
1215
+ tool = @server.tools[params[:name]]
1216
+ return unless tool
1217
+
1218
+ scan = McpParamHeaders.scan(tool.input_schema.to_h)
1219
+ return unless scan[:valid] && !scan[:declarations].empty?
1220
+
1221
+ arguments = params[:arguments] || {}
1222
+ return unless arguments.is_a?(Hash)
1223
+
1224
+ message = McpParamHeaders.mismatch(scan[:declarations], arguments) do |header_name|
1225
+ header_bytes(request, "HTTP_#{header_name.upcase.tr("-", "_")}")
1226
+ end
1227
+ return unless message
1228
+
1229
+ header_mismatch_response(message, body[:id])
1230
+ end
1231
+
1034
1232
  # Serves `subscriptions/listen` (SEP-2575): opens a long-lived SSE stream whose first message is
1035
1233
  # `notifications/subscriptions/acknowledged` with the subset of requested notification types
1036
1234
  # the server agreed to honor. Notifications delivered on the stream carry `io.modelcontextprotocol/subscriptionId`
@@ -1135,6 +1333,19 @@ module MCP
1135
1333
  false
1136
1334
  end
1137
1335
 
1336
+ # The id a refusal built here can echo: an Integer, or a String that is valid UTF-8. A String holding other
1337
+ # bytes would make the body's `to_json` raise, so the refusal carries no id, as for an id it could not read.
1338
+ def echoable_id(id)
1339
+ return id if id.is_a?(Integer) || (id.is_a?(String) && id.valid_encoding?)
1340
+
1341
+ nil
1342
+ end
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
+
1138
1349
  def listen_subscriptions_full?
1139
1350
  return false unless @max_listen_subscriptions
1140
1351
 
@@ -1222,7 +1433,7 @@ module MCP
1222
1433
  acknowledged = subscription[:write_mutex].synchronize do
1223
1434
  next false if subscription[:closed]
1224
1435
 
1225
- send_to_stream(stream, acknowledgement)
1436
+ push_to_stream(stream, acknowledgement, subscription: subscription)
1226
1437
 
1227
1438
  # Set on the entry itself, not through the registry: a concurrent close may already have cleared the registry
1228
1439
  # while its result write waits on this mutex, and that write must still find the stream acknowledged.
@@ -1303,7 +1514,7 @@ module MCP
1303
1514
  subscription[:write_mutex].synchronize do
1304
1515
  next if subscription[:closed]
1305
1516
 
1306
- send_ping_to_stream(subscription[:stream])
1517
+ push_ping_to_stream(subscription[:stream], subscription: subscription)
1307
1518
  end
1308
1519
  end
1309
1520
 
@@ -1445,7 +1656,7 @@ module MCP
1445
1656
  subscription[:write_mutex].synchronize do
1446
1657
  next if subscription[:closed]
1447
1658
 
1448
- send_to_stream(subscription[:stream], notification)
1659
+ push_to_stream(subscription[:stream], notification, subscription: subscription)
1449
1660
  end
1450
1661
  rescue *STREAM_WRITE_ERRORS => e
1451
1662
  MCP.configuration.exception_reporter.call(
@@ -1535,6 +1746,10 @@ module MCP
1535
1746
  # The stream is left open for the caller to close.
1536
1747
  def write_listen_closing_result(subscription)
1537
1748
  subscription[:write_mutex].synchronize do
1749
+ # Already marked by a write that ran into its deadline: the last frame on the stream may be cut short,
1750
+ # and the stream may still be open because its close was abandoned, so the result must not follow it.
1751
+ next if subscription[:closed]
1752
+
1538
1753
  subscription[:closed] = true
1539
1754
 
1540
1755
  # A stream whose acknowledgement was never written gets no result either: SEP-2575 makes
@@ -1571,12 +1786,21 @@ module MCP
1571
1786
  end
1572
1787
  end
1573
1788
 
1789
+ # A client-supplied value for an error message or `data` member. A header value reaches the transport as
1790
+ # ASCII-8BIT from a Rack server, or tagged UTF-8 from a test request or a framework, and a body value comes
1791
+ # out of the JSON parser; a value holding bytes that are not valid UTF-8 would make the response's `to_json`
1792
+ # raise and turn the intended 400 into a 500 with an exception report. Such bytes are replaced with U+FFFD;
1793
+ # a valid value comes through unchanged.
1794
+ def printable_value(value)
1795
+ value.to_s.dup.force_encoding(Encoding::UTF_8).scrub
1796
+ end
1797
+
1574
1798
  def header_mismatch_response(message, id)
1575
1799
  json_rpc_error_response(
1576
1800
  status: 400,
1577
1801
  code: ErrorCodes::HEADER_MISMATCH,
1578
1802
  message: "Header mismatch: #{message}",
1579
- id: id,
1803
+ id: echoable_id(id),
1580
1804
  )
1581
1805
  end
1582
1806
 
@@ -1641,6 +1865,8 @@ module MCP
1641
1865
  return invalid_request_response("Invalid Request: JSON-RPC body must be a single request object")
1642
1866
  end
1643
1867
 
1868
+ return oversized_id_response if JsonRpcHandler.oversized_integer_id?(body[:id])
1869
+
1644
1870
  # Header-primary routing sends sessionless modern traffic to `handle_modern` before this method runs,
1645
1871
  # so a body carrying the modern `_meta` triple (SEP-2575) arrives here in two shapes only.
1646
1872
  # Bound to a session under a dual-era header (2026-07-28), it is a lifecycle violation: the session
@@ -1653,7 +1879,7 @@ module MCP
1653
1879
  if header_version && MCP::Configuration.modern_protocol_version?(header_version)
1654
1880
  return invalid_request_response(
1655
1881
  "Invalid Request: the session already negotiated the legacy lifecycle via `initialize`",
1656
- request_id: body[:id],
1882
+ request_id: echoable_id(body[:id]),
1657
1883
  )
1658
1884
  end
1659
1885
 
@@ -1699,7 +1925,7 @@ module MCP
1699
1925
  session = @mutex.synchronize { @sessions[session_id] }
1700
1926
  return session_not_found_response unless session && session_principal_matches?(session, request)
1701
1927
 
1702
- return already_initialized_response(body[:id])
1928
+ return already_initialized_response(echoable_id(body[:id]))
1703
1929
  end
1704
1930
 
1705
1931
  return session_not_found_response
@@ -1764,6 +1990,14 @@ module MCP
1764
1990
  protocol_version_error = validate_protocol_version_header(request)
1765
1991
  return protocol_version_error if protocol_version_error
1766
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
+
1767
2001
  return session_already_connected_response if live_get_stream?(session_id)
1768
2002
 
1769
2003
  setup_sse_stream(session_id, request.env[OAuth::ENV_KEY])
@@ -1834,8 +2068,21 @@ module MCP
1834
2068
  removed[:post_request_streams]&.each_value { |stream| streams_to_close << stream }
1835
2069
  end
1836
2070
 
2071
+ # A close can block on the same full buffers a write does (a TLS stream writes its closing alert, a buffered one flushes),
2072
+ # and it runs on the threads that deliver to every stream, in places under a stream's write mutex,
2073
+ # so it gets `stream_write_timeout:` seconds as well. One that has not finished by then is abandoned,
2074
+ # and not tried again: the path that drops a stream after its write timed out closes it a second time,
2075
+ # which would wait out the same block once more.
1837
2076
  def close_stream_safely(stream)
1838
- stream&.close
2077
+ return unless stream
2078
+ return stream.close unless @stream_write_timeout
2079
+ return if @streams_with_abandoned_close.key?(stream)
2080
+
2081
+ begin
2082
+ Timeout.timeout(@stream_write_timeout) { stream.close }
2083
+ rescue Timeout::Error
2084
+ @streams_with_abandoned_close[stream] = true
2085
+ end
1839
2086
  rescue StandardError
1840
2087
  # Ignore close-related errors from already closed/broken streams.
1841
2088
  end
@@ -1966,7 +2213,7 @@ module MCP
1966
2213
  status: 413,
1967
2214
  code: JsonRpcHandler::ErrorCode::INVALID_REQUEST,
1968
2215
  message: "Payload too large: initialize request #{reason}",
1969
- id: request_id,
2216
+ id: echoable_id(request_id),
1970
2217
  )
1971
2218
  end
1972
2219
 
@@ -2055,7 +2302,7 @@ module MCP
2055
2302
  json_rpc_error_response(
2056
2303
  status: 400,
2057
2304
  code: JsonRpcHandler::ErrorCode::INVALID_REQUEST,
2058
- message: "Bad Request: Unsupported protocol version: #{header_value}. Supported versions: #{supported}",
2305
+ message: "Bad Request: Unsupported protocol version: #{printable_value(header_value)}. Supported versions: #{supported}",
2059
2306
  )
2060
2307
  end
2061
2308
 
@@ -2153,6 +2400,12 @@ module MCP
2153
2400
  auth_issuer: auth_info&.issuer,
2154
2401
  auth_subject: auth_info&.subject,
2155
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),
2156
2409
  }
2157
2410
  true
2158
2411
  end
@@ -2246,39 +2499,65 @@ module MCP
2246
2499
  # https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server
2247
2500
  def handle_request_with_sse_response(body_string, session_id, server_session, related_request_id: nil, auth_info: nil)
2248
2501
  body = proc do |stream|
2249
- @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
2250
2507
  session = @sessions[session_id]
2251
- if session && related_request_id
2252
- session[:post_request_streams] ||= {}
2508
+ next false unless session && related_request_id
2253
2509
 
2254
- # Claim the id only while it is free. `handle_regular_request` already refused the colliding request,
2255
- # so reaching an occupied slot means a race got past that check; leaving the first stream in place keeps
2256
- # its messages going where they belong.
2257
- session[:post_request_streams][related_request_id] ||= stream
2258
- 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
2259
2522
  end
2260
2523
 
2524
+ write_priming_event(session_id, related_request_id, stream) if claimed
2525
+
2261
2526
  begin
2262
2527
  response = dispatch_handle_json(body_string, server_session, auth_info: auth_info)
2263
2528
 
2264
- 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
2265
2538
  ensure
2266
- if related_request_id
2267
- @mutex.synchronize do
2268
- session = @sessions[session_id]
2269
- # Only retire our own registration: a request that never claimed the id, or one whose claim has
2270
- # already been replaced, must not unregister the stream that owns it.
2271
- registered = session&.dig(:post_request_streams, related_request_id)
2539
+ resumed = nil
2272
2540
 
2273
- 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]
2274
2556
  end
2275
2557
  end
2276
2558
 
2277
- begin
2278
- stream.close
2279
- rescue StandardError
2280
- # Ignore close-related errors from already closed/broken streams.
2281
- end
2559
+ close_stream_safely(resumed) if resumed
2560
+ close_stream_safely(stream)
2282
2561
  end
2283
2562
  end
2284
2563
 
@@ -2421,7 +2700,7 @@ module MCP
2421
2700
  # to prevent DNS rebinding attacks against locally bound MCP servers. Protection is on by default;
2422
2701
  # pass `dns_rebinding_protection: false` to disable it (e.g. when an upstream proxy or middleware already
2423
2702
  # performs the check). The `Host` header is validated against the loopback defaults plus `allowed_hosts:`,
2424
- # 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`.
2425
2704
  def validate_dns_rebinding(request)
2426
2705
  return unless @dns_rebinding_protection
2427
2706
 
@@ -2453,7 +2732,14 @@ module MCP
2453
2732
 
2454
2733
  # A request without an `Origin` header (typical for non-browser MCP clients) is allowed. A browser cross-origin request is
2455
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`).
2456
2740
  def validate_origin(request)
2741
+ return if @any_origin_allowed
2742
+
2457
2743
  origin = header_bytes(request, "HTTP_ORIGIN")
2458
2744
  return if origin.nil?
2459
2745
  return if same_origin?(origin, request)
@@ -2557,7 +2843,10 @@ module MCP
2557
2843
  def create_sse_body(session_id, auth_info = nil)
2558
2844
  proc do |stream|
2559
2845
  stored = store_stream_for_session(session_id, stream, auth_info)
2560
- 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)
2561
2850
  end
2562
2851
  end
2563
2852
 
@@ -2570,6 +2859,9 @@ module MCP
2570
2859
 
2571
2860
  session[:get_sse_stream] = stream
2572
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
2573
2865
  true
2574
2866
  end
2575
2867
 
@@ -2588,7 +2880,8 @@ module MCP
2588
2880
  # stream at a delivery once its token expired and the client may have opened a new one since, which gets
2589
2881
  # a keepalive thread of its own. The loop therefore ends as soon as the session no longer holds this stream,
2590
2882
  # and a loop that did not run to its end (a failed ping, or any other abnormal exit) drops the stream through
2591
- # `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.
2592
2885
  def start_keepalive_thread(session_id, stream)
2593
2886
  Thread.new do
2594
2887
  ended = false
@@ -2657,7 +2950,7 @@ module MCP
2657
2950
  def send_keepalive_ping(session_id, stream)
2658
2951
  return unless session_holds_stream?(session_id, stream)
2659
2952
 
2660
- send_ping_to_stream(stream)
2953
+ push_ping_to_stream(stream)
2661
2954
  rescue *STREAM_WRITE_ERRORS => e
2662
2955
  MCP.configuration.exception_reporter.call(
2663
2956
  e,
@@ -2671,6 +2964,307 @@ module MCP
2671
2964
 
2672
2965
  Process.clock_gettime(Process::CLOCK_MONOTONIC) - session[:last_active_at] > @session_idle_timeout
2673
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
2674
3268
  end
2675
3269
  end
2676
3270
  end