mcp 1.11.0 → 1.13.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.
@@ -3,8 +3,10 @@
3
3
  require "json"
4
4
  require "set"
5
5
  require "timeout"
6
+ require_relative "../../duration"
6
7
  require_relative "../../result_type"
7
8
  require_relative "../../transport"
9
+ require_relative "../subscription_bus"
8
10
 
9
11
  # This file is autoloaded only when `StreamableHTTPTransport` is referenced,
10
12
  # so the `rack` dependency does not affect `StdioTransport` users.
@@ -135,6 +137,7 @@ module MCP
135
137
  DEFAULT_MAX_STREAM_LIFETIME = DEFAULT_SESSION_IDLE_TIMEOUT
136
138
 
137
139
  # Creates a Streamable HTTP transport that can be mounted as a Rack app.
140
+ # Timeouts and keepalive intervals take positive, finite durations in seconds. Optional bounds accept nil.
138
141
  #
139
142
  # @param server [MCP::Server] the server whose requests this transport dispatches.
140
143
  # @param stateless [Boolean] when `true`, no session is issued and each POST is self-contained.
@@ -142,7 +145,7 @@ module MCP
142
145
  # object instead of an SSE stream.
143
146
  # @param session_idle_timeout [Numeric, nil] seconds before an idle session is reaped; defaults
144
147
  # to `DEFAULT_SESSION_IDLE_TIMEOUT` (1800) in stateful mode, and an explicit `nil` disables
145
- # expiry. Not supported in stateless mode.
148
+ # expiry. A session is not idle while one of its requests is running. Not supported in stateless mode.
146
149
  # @param max_sessions [Integer, nil] cap on the concurrent session count in stateful mode; a new
147
150
  # `initialize` past the cap is rejected with HTTP 503, and `nil` disables the cap.
148
151
  # @param allowed_origins [Array<String>, :any, nil] extra `Origin` values accepted in addition to
@@ -188,6 +191,18 @@ module MCP
188
191
  # the method then answers 404 with JSON-RPC `-32601` like any unimplemented method,
189
192
  # and `Server#discover` stops advertising the `listChanged`/`subscribe` capability flags,
190
193
  # keeping the advertisement and the actual behavior in agreement. Defaults to `true`.
194
+ # @param stream_request_notifications [Boolean] whether a 2026-07-28 request that asks for progress
195
+ # (`_meta.progressToken` on a `tools/call`, `prompts/get` or `resources/read`) gets the notifications of its handler
196
+ # as they are emitted, on an SSE response held open until the result, instead of all at once after the handler returns.
197
+ # The handler then runs while the host writes the response body, so the host has to serve a streaming body,
198
+ # and an error of such a request is answered on the stream, under HTTP 200. A `tools/call` is streamed only when
199
+ # its tool is known ahead of the handler, which leaves out a server with a `tools_list_handler`.
200
+ # Keepalive comment frames are written every `listen_keepalive_interval` seconds. Defaults to `false`;
201
+ # cannot be combined with `serve_subscriptions_listen: false`.
202
+ # @param subscription_bus [#publish, #subscribe] the change-event bus feeding `subscriptions/listen` streams;
203
+ # defaults to an in-process `SubscriptionBus`. A multi-process deployment passes a bus backed by
204
+ # its own pub/sub system so changes published in one worker reach the streams the other workers hold.
205
+ # A `publish` that raises is reported through the exception reporter and does not fail the notifier.
191
206
  # @param server_to_client_request_timeout [Numeric] seconds a server-to-client request waits for its
192
207
  # response before the transport stops waiting and raises `MCP::Server::RequestTimeoutError`.
193
208
  # Defaults to `DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT` (600); individual calls override it with `timeout:`.
@@ -243,6 +258,8 @@ module MCP
243
258
  max_resource_subscription_bytes: DEFAULT_MAX_RESOURCE_SUBSCRIPTION_BYTES,
244
259
  listen_keepalive_interval: DEFAULT_LISTEN_KEEPALIVE_INTERVAL,
245
260
  serve_subscriptions_listen: true,
261
+ stream_request_notifications: false,
262
+ subscription_bus: nil,
246
263
  server_to_client_request_timeout: DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT,
247
264
  stream_write_timeout: DEFAULT_STREAM_WRITE_TIMEOUT,
248
265
  token_verifier: nil,
@@ -284,12 +301,15 @@ module MCP
284
301
  # unique only among that client's own in-flight requests, so it stamps `subscriptionId` but cannot serve as the key:
285
302
  # two clients may pick the same one. Whoever removes an entry signals `keepalive_wakeup` under `@mutex`,
286
303
  # so the stream's keepalive thread ends with its slot instead of sleeping out its interval.
287
- # In-process only; a multi-worker deployment needs an external event bus to fan notifications out across processes,
288
- # which is a follow-up.
304
+ # The registry is per-process (a stream is an open connection); cross-process fan-out goes through
305
+ # `@subscription_bus`.
289
306
  @listen_subscriptions = {}
290
307
 
291
308
  # Maps a modern request's ephemeral session id to the Array collecting the notifications its handler emits;
292
309
  # `handle_modern` registers the sink and flushes it as SSE frames ahead of the final response (SEP-2575).
310
+ # For a request served with `stream_request_notifications:` the sink is instead the open response stream,
311
+ # `{ stream: stream_object, session: ServerSession, write_mutex: Mutex, keepalive_wakeup: ConditionVariable }`,
312
+ # and each notification is written to it as it is emitted.
293
313
  @modern_request_sinks = {}
294
314
 
295
315
  # Resolve the idle timeout: an explicit value (including `nil` to opt out) wins; otherwise apply the secure default,
@@ -300,12 +320,13 @@ module MCP
300
320
  session_idle_timeout
301
321
  end
302
322
 
303
- if @session_idle_timeout
304
- if @stateless
305
- raise ArgumentError, "session_idle_timeout is not supported in stateless mode."
306
- elsif @session_idle_timeout <= 0
307
- raise ArgumentError, "session_idle_timeout must be a positive number."
323
+ # The value is checked ahead of the mode, so that an invalid one such as `false` is reported as what it is in stateless mode too.
324
+ unless @session_idle_timeout.nil?
325
+ unless Duration.positive_finite?(@session_idle_timeout)
326
+ raise ArgumentError, "session_idle_timeout must be a positive finite number, or nil to disable the timeout."
308
327
  end
328
+
329
+ raise ArgumentError, "session_idle_timeout is not supported in stateless mode." if @stateless
309
330
  end
310
331
 
311
332
  unless max_sessions.nil? || (max_sessions.is_a?(Integer) && max_sessions > 0)
@@ -340,21 +361,35 @@ module MCP
340
361
 
341
362
  @max_resource_subscription_bytes = max_resource_subscription_bytes
342
363
 
343
- if !listen_keepalive_interval.nil? && !(listen_keepalive_interval.is_a?(Numeric) && listen_keepalive_interval > 0)
344
- raise ArgumentError, "listen_keepalive_interval must be a positive number or nil"
364
+ unless listen_keepalive_interval.nil? || Duration.positive_finite?(listen_keepalive_interval)
365
+ raise ArgumentError, "listen_keepalive_interval must be a positive finite number or nil"
345
366
  end
346
367
 
347
368
  @listen_keepalive_interval = listen_keepalive_interval
348
369
  @serve_subscriptions_listen = serve_subscriptions_listen
349
370
 
350
- unless server_to_client_request_timeout.is_a?(Numeric) && server_to_client_request_timeout.positive?
351
- raise ArgumentError, "server_to_client_request_timeout must be a positive number"
371
+ # `serve_subscriptions_listen: false` is how a host says it buffers responses, and a buffered response
372
+ # cannot carry a notification before its handler has returned.
373
+ if stream_request_notifications && !serve_subscriptions_listen
374
+ raise ArgumentError, "stream_request_notifications needs a host that serves streaming responses, " \
375
+ "so it cannot be combined with serve_subscriptions_listen: false"
376
+ end
377
+
378
+ @stream_request_notifications = stream_request_notifications
379
+
380
+ @subscription_bus = subscription_bus || SubscriptionBus.new
381
+ unless @subscription_bus.respond_to?(:publish) && @subscription_bus.respond_to?(:subscribe)
382
+ raise ArgumentError, "subscription_bus must respond to publish and subscribe"
383
+ end
384
+
385
+ unless Duration.positive_finite?(server_to_client_request_timeout)
386
+ raise ArgumentError, "server_to_client_request_timeout must be a positive finite number"
352
387
  end
353
388
 
354
389
  @server_to_client_request_timeout = server_to_client_request_timeout
355
390
 
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"
391
+ unless stream_write_timeout.nil? || Duration.positive_finite?(stream_write_timeout)
392
+ raise ArgumentError, "stream_write_timeout must be a positive finite number or nil"
358
393
  end
359
394
 
360
395
  @stream_write_timeout = stream_write_timeout
@@ -378,8 +413,8 @@ module MCP
378
413
  @oauth_authenticator = nil
379
414
  end
380
415
 
381
- unless max_stream_lifetime.nil? || (max_stream_lifetime.is_a?(Numeric) && max_stream_lifetime.positive?)
382
- raise ArgumentError, "max_stream_lifetime must be a positive number or nil"
416
+ unless max_stream_lifetime.nil? || Duration.positive_finite?(max_stream_lifetime)
417
+ raise ArgumentError, "max_stream_lifetime must be a positive finite number or nil"
383
418
  end
384
419
 
385
420
  @max_stream_lifetime = max_stream_lifetime
@@ -409,7 +444,36 @@ module MCP
409
444
  # being killed in the middle of a reap.
410
445
  @closing = false
411
446
  @reaper_wakeup = ConditionVariable.new
412
- start_reaper_thread if @session_idle_timeout
447
+
448
+ # Local listen streams are fed exclusively through the bus: the in-process default publishes back synchronously,
449
+ # and an external bus hands this listener the events other workers publish too, on the same arrival path.
450
+ # A bus asks its listeners not to raise, and this one may run on the reader thread of a broker, which an exception
451
+ # would end for good: a stream write can fail with an error the delivery does not expect, so it is reported here.
452
+ # The listener checks `@subscription_bus_detached` first, because the transport cannot always take it off the bus:
453
+ # a `subscribe` that raises after registering returns no callable, and the callable of a custom bus can raise.
454
+ # The listener the bus keeps then writes to no stream of a transport that was closed or never built.
455
+ @subscription_bus_detached = false
456
+ begin
457
+ @subscription_bus_unsubscribe = @subscription_bus.subscribe do |event|
458
+ next if @subscription_bus_detached
459
+
460
+ deliver_event_to_listen_subscriptions(event)
461
+ rescue => e
462
+ report_subscription_bus_failure(e, "Subscription bus delivery failed")
463
+ end
464
+ rescue StandardError
465
+ @subscription_bus_detached = true
466
+ raise
467
+ end
468
+
469
+ # The last step that can fail. A transport that was never built takes its listener off a shared bus,
470
+ # or leaves it inert there when the bus keeps it.
471
+ begin
472
+ start_reaper_thread if @session_idle_timeout
473
+ rescue StandardError
474
+ detach_from_subscription_bus
475
+ raise
476
+ end
413
477
  end
414
478
 
415
479
  REQUIRED_POST_ACCEPT_TYPES_SSE = ["application/json", "text/event-stream"].freeze
@@ -425,6 +489,10 @@ module MCP
425
489
  # one that still has not taken the frame after this long is dropped whether it stopped reading or is only that slow.
426
490
  DEFAULT_STREAM_WRITE_TIMEOUT = 10
427
491
 
492
+ # How much of the response of a streamed request is written under one `stream_write_timeout:` deadline.
493
+ RESPONSE_FRAME_PIECE_BYTES = 64 * 1024
494
+ private_constant :RESPONSE_FRAME_PIECE_BYTES
495
+
428
496
  # The first protocol version whose clients parse an SSE event with empty data, which the priming event of
429
497
  # SEP-1699 resumability is. A session that negotiated an earlier version gets no priming event and is never
430
498
  # asked to resume, since it would have no event id to come back with; its other events still carry ids.
@@ -441,13 +509,25 @@ module MCP
441
509
  # How long `close` waits in all for the closing results of the open `subscriptions/listen` streams
442
510
  # before closing the streams still open without one.
443
511
  LISTEN_TEARDOWN_TIMEOUT = 5
512
+ # The reason the requests still in flight in a session are cancelled with when the session goes away: terminated by
513
+ # the client's DELETE, expired, torn down with its broken GET stream, or removed by `close`.
514
+ SESSION_TERMINATED_REASON = "Session terminated"
515
+ # The error message a request reusing the id of one in flight in its session is refused with.
516
+ REQUEST_ID_CONFLICT_MESSAGE = "Conflict: Request id is already in flight for this session"
444
517
 
445
518
  # Loopback hosts always accepted by DNS rebinding protection. A locally bound MCP server (the canonical pattern) is
446
519
  # protected out of the box; non-loopback deployments widen the list via `allowed_hosts:`.
447
520
  DEFAULT_LOOPBACK_HOSTS = ["127.0.0.1", "::1", "localhost"].freeze
448
521
 
449
- # JSON-RPC methods whose target name is mirrored into the `Mcp-Name` header (SEP-2575).
450
- NAME_BEARING_METHODS = [Methods::TOOLS_CALL, Methods::RESOURCES_READ, Methods::PROMPTS_GET].freeze
522
+ # JSON-RPC methods whose target is mirrored into the `Mcp-Name` header (SEP-2575), with the `params` member
523
+ # that names it. The member is fixed per method: a `resources/read` is named by its `uri` whatever else
524
+ # its `params` carry, so a `name` added to them cannot stand in for the URI the header is checked against.
525
+ NAME_MEMBER_BY_METHOD = {
526
+ Methods::TOOLS_CALL => :name,
527
+ Methods::RESOURCES_READ => :uri,
528
+ Methods::PROMPTS_GET => :name,
529
+ }.freeze
530
+ NAME_BEARING_METHODS = NAME_MEMBER_BY_METHOD.keys.freeze
451
531
 
452
532
  # Maps broadcast notification methods to the `SubscriptionFilter` field that opts in to them on
453
533
  # a `subscriptions/listen` stream (SEP-2575). `notifications/resources/updated` is matched by URI
@@ -574,16 +654,19 @@ module MCP
574
654
  end
575
655
  @reaper_thread = nil
576
656
 
657
+ # Detach from the bus before tearing the streams down, so no new event is handed to this transport;
658
+ # a delivery already in flight is ordered against the teardown by each stream's write mutex and closed flag,
659
+ # not by the unsubscribe. The unsubscribe callable comes from a possibly custom bus;
660
+ # one that raises is reported and must not stop the teardown below.
661
+ detach_from_subscription_bus
662
+
577
663
  teardown_listen_subscriptions
578
664
 
579
665
  removed_sessions = @mutex.synchronize do
580
666
  @sessions.each_key.filter_map { |session_id| cleanup_session_unsafe(session_id) }
581
667
  end
582
668
 
583
- removed_sessions.each do |session|
584
- close_stream_safely(session[:get_sse_stream])
585
- close_post_request_streams(session)
586
- end
669
+ release_sessions(removed_sessions)
587
670
  end
588
671
 
589
672
  # Sessions a server-wide log broadcast is offered to, each applying its own level or the server default.
@@ -605,7 +688,18 @@ module MCP
605
688
  # a resource updated by one session's tool call changed globally, so modern subscribers hear about it too.
606
689
  # Runs before the per-request sink and the stateless guard because the listen registry does not depend on sessions,
607
690
  # and a sink capturing the notification for its own response stream must not hide it from other subscriptions.
608
- deliver_to_listen_subscriptions(method, params)
691
+ # The change goes through the subscription bus rather than straight to the streams: the in-process default delivers
692
+ # back synchronously, while an external bus also carries it to the streams other workers hold.
693
+ # A custom bus that raises (a broker outage, say) is reported like a raising listener or unsubscribe,
694
+ # so the session and request deliveries below still run: whatever the failure cost the listen streams,
695
+ # the other streams of this worker should not lose the change as well.
696
+ if (event = subscription_event_for(method, params))
697
+ begin
698
+ @subscription_bus.publish(event)
699
+ rescue => e
700
+ report_subscription_bus_failure(e, "Subscription bus publish failed")
701
+ end
702
+ end
609
703
 
610
704
  notification = {
611
705
  jsonrpc: "2.0",
@@ -620,16 +714,24 @@ module MCP
620
714
  # non-delivery (`false`), never handed to the legacy paths below. It holds each notification as JSON,
621
715
  # generated here so that one that cannot be generated is dropped on its own instead of failing
622
716
  # the whole response when the sink is flushed.
717
+ #
718
+ # A sink that is the open response stream (`stream_request_notifications:`) is written to at once and is not
719
+ # counted: each write waits for the peer, within `stream_write_timeout:`, so nothing accumulates here.
623
720
  sink = @mutex.synchronize { session_id && @modern_request_sinks[session_id] }
624
721
  if sink
625
- return false if sink.size >= MAX_MODERN_REQUEST_NOTIFICATIONS
722
+ return false if sink.is_a?(Array) && sink.size >= MAX_MODERN_REQUEST_NOTIFICATIONS
626
723
 
627
724
  begin
628
- sink << notification.to_json
725
+ notification_json = notification.to_json
629
726
  rescue JSON::GeneratorError => e
630
727
  MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to generate notification" })
631
728
  return false
632
729
  end
730
+
731
+ return write_to_request_stream(sink, notification_json) unless sink.is_a?(Array)
732
+
733
+ sink << notification_json
734
+
633
735
  return true
634
736
  end
635
737
 
@@ -652,26 +754,26 @@ module MCP
652
754
  # (e.g. `resources/updated`, `elicitation/complete`) still flow via GET SSE.
653
755
  return false if @enable_json_response && related_request_id
654
756
 
655
- streams_to_close = []
757
+ removed_sessions = []
656
758
  live = @mutex.synchronize do
657
759
  next false unless (session = @sessions[session_id])
658
760
 
659
761
  if session_expired?(session)
660
- cleanup_and_collect_stream(session_id, streams_to_close)
762
+ cleanup_and_collect_session(session_id, removed_sessions)
661
763
  next false
662
764
  end
663
765
 
664
766
  true
665
767
  end
666
768
 
667
- close_streams(streams_to_close)
769
+ release_sessions(removed_sessions)
668
770
  return false unless live
669
771
 
670
772
  store_and_write(session_id, related_request_id, notification.to_json)
671
773
  end
672
774
 
673
775
  def deliver_broadcast_notification(notification)
674
- streams_to_close = []
776
+ removed_sessions = []
675
777
 
676
778
  # Snapshot the sessions under the lock, then write to each outside it. A session whose GET stream is
677
779
  # closed at the moment still takes the notification when it has opened that stream before and an event
@@ -691,13 +793,13 @@ module MCP
691
793
  end
692
794
 
693
795
  expired_session_ids.each do |session_id|
694
- cleanup_and_collect_stream(session_id, streams_to_close)
796
+ cleanup_and_collect_session(session_id, removed_sessions)
695
797
  end
696
798
 
697
799
  collected
698
800
  end
699
801
 
700
- close_streams(streams_to_close)
802
+ release_sessions(removed_sessions)
701
803
 
702
804
  json = notification.to_json
703
805
  targets.count do |session_id|
@@ -717,6 +819,7 @@ module MCP
717
819
  # from its last event id (SEP-1699), and the events it misses meanwhile are stored for it.
718
820
  def drop_broken_stream(session_id, stream, related_request_id)
719
821
  streams_to_close = []
822
+ removed_sessions = []
720
823
 
721
824
  @mutex.synchronize do
722
825
  session = @sessions[session_id]
@@ -732,12 +835,13 @@ module MCP
732
835
  if @event_store
733
836
  streams_to_close << detach_get_stream(session)
734
837
  else
735
- cleanup_and_collect_stream(session_id, streams_to_close)
838
+ cleanup_and_collect_session(session_id, removed_sessions)
736
839
  end
737
840
  end
738
841
  end
739
842
 
740
843
  close_streams(streams_to_close)
844
+ release_sessions(removed_sessions)
741
845
  end
742
846
 
743
847
  def close_streams(streams)
@@ -955,19 +1059,19 @@ module MCP
955
1059
  end
956
1060
  end
957
1061
 
958
- removed_sessions.each do |session|
959
- close_stream_safely(session[:get_sse_stream])
960
- close_post_request_streams(session)
961
- end
1062
+ release_sessions(removed_sessions)
962
1063
  end
963
1064
 
964
1065
  # One `write` per frame, so the frames of concurrent writers cannot interleave in the middle of each other.
965
1066
  def send_to_stream(stream, data, event_id: nil)
1067
+ stream.write(sse_frame(data, event_id: event_id))
1068
+ stream.flush
1069
+ end
1070
+
1071
+ def sse_frame(data, event_id: nil)
966
1072
  message = data.is_a?(String) ? data : data.to_json
967
- frame = event_id ? "id: #{event_id}\ndata: #{message}\n\n" : "data: #{message}\n\n"
968
1073
 
969
- stream.write(frame)
970
- stream.flush
1074
+ event_id ? "id: #{event_id}\ndata: #{message}\n\n" : "data: #{message}\n\n"
971
1075
  end
972
1076
 
973
1077
  # The priming event of SEP-1699: an id for the client to resume from, the `retry` field when configured, and
@@ -1081,13 +1185,6 @@ module MCP
1081
1185
  mismatch_error = validate_modern_headers(request, body, header_version)
1082
1186
  return mismatch_error if mismatch_error
1083
1187
 
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
-
1091
1188
  # `subscriptions/listen` is a long-lived notification stream served at the transport layer;
1092
1189
  # it never dispatches through `Server#handle`. A transport constructed with
1093
1190
  # `serve_subscriptions_listen: false` skips the interception, so the method falls through
@@ -1097,32 +1194,39 @@ module MCP
1097
1194
  return handle_subscriptions_listen(body, auth_info: request.env[OAuth::ENV_KEY])
1098
1195
  end
1099
1196
 
1197
+ # SEP-2243 custom headers: the `Mcp-Param-*` headers of a `tools/call` are checked against the body by
1198
+ # the dispatcher, on the tool it resolved for this call, so a disagreement is refused without the tool ever running.
1199
+ # The refusal is answered from here, as a plain JSON 400 whatever the handler had emitted until then.
1200
+ header_mismatch = nil
1201
+ tool_call_check = lambda do |tool, params|
1202
+ header_mismatch = mcp_param_header_mismatch(tool, params, request)
1203
+ end
1204
+
1100
1205
  session = modern_session
1206
+ auth_info = request.env[OAuth::ENV_KEY]
1207
+ if stream_modern_request?(body, request)
1208
+ return streamed_modern_response(body, body_string, session, auth_info, tool_call_check)
1209
+ end
1210
+
1101
1211
  notifications = @mutex.synchronize { @modern_request_sinks[session.session_id] = [] }
1102
1212
  begin
1103
- response = @server.handle(body, session: session, auth_info: request.env[OAuth::ENV_KEY])
1213
+ response = @server.handle(body, session: session, auth_info: auth_info, tool_call_check: tool_call_check)
1104
1214
  ensure
1105
1215
  @mutex.synchronize { @modern_request_sinks.delete(session.session_id) }
1106
1216
  end
1107
1217
 
1218
+ return header_mismatch_response(header_mismatch, body[:id]) if header_mismatch
1219
+
1108
1220
  # `nil` covers notifications and cancellation-suppressed responses; ack with 202 like the legacy notification path.
1109
1221
  return handle_accepted if response.nil?
1110
1222
 
1111
- # A response that cannot be generated answers its request with Internal error, as `JsonRpcHandler.handle_json`
1112
- # does on the legacy paths, instead of failing the whole exchange with a 500.
1113
- response_json = begin
1114
- response.to_json
1115
- rescue JSON::GeneratorError => e
1116
- MCP.configuration.exception_reporter.call(e, { error: "Failed to generate response" })
1117
- response = JsonRpcHandler.encodable_response(response)
1118
- response.to_json
1119
- end
1223
+ response, response_json = modern_response_json(response)
1120
1224
 
1121
1225
  # Notifications a handler emitted during the request ride the request's own response stream as SSE frames ahead of
1122
1226
  # the final response (SEP-2575); a request that emitted none keeps the single JSON exchange and its HTTP status ladder.
1123
- # Delivery is buffered: frames flush after the handler returns, preserving order but not real-time interleaving
1124
- # (the TypeScript and Python SDKs stream live), and the sink grows with the handler's notification count.
1125
- # Live streaming can follow without changing the wire shape.
1227
+ # Delivery is buffered: frames flush after the handler returns, preserving order but not real-time interleaving,
1228
+ # and the sink grows with the handler's notification count. `stream_request_notifications:` delivers them as
1229
+ # they are emitted instead, for the requests `stream_modern_request?` selects.
1126
1230
  if notifications.empty?
1127
1231
  [modern_http_status(response), { "content-type" => "application/json" }, [response_json]]
1128
1232
  else
@@ -1139,10 +1243,211 @@ module MCP
1139
1243
  )
1140
1244
  end
1141
1245
 
1246
+ # A response that cannot be generated answers its request with Internal error, as `JsonRpcHandler.handle_json`
1247
+ # does on the legacy paths, instead of failing the whole exchange with a 500. Returns the response that was
1248
+ # generated along with its JSON.
1249
+ def modern_response_json(response)
1250
+ [response, response.to_json]
1251
+ rescue JSON::GeneratorError => e
1252
+ MCP.configuration.exception_reporter.call(e, { error: "Failed to generate response" })
1253
+ response = JsonRpcHandler.encodable_response(response)
1254
+
1255
+ [response, response.to_json]
1256
+ end
1257
+
1258
+ # The methods whose handlers report progress.
1259
+ STREAMED_MODERN_METHODS = [Methods::TOOLS_CALL, Methods::PROMPTS_GET, Methods::RESOURCES_READ].freeze
1260
+ private_constant :STREAMED_MODERN_METHODS
1261
+
1262
+ # Whether this request is answered on an open SSE stream (`stream_request_notifications:`): one that asks for progress,
1263
+ # of a method whose handler can report it. Opening the stream commits HTTP 200 before the handler runs,
1264
+ # so every other request keeps the buffered exchange and the status its answer maps to.
1265
+ #
1266
+ # The answers the spec ties to a status of their own are therefore ruled out here, ahead of the stream,
1267
+ # wherever they can be told without running the request: a request that is not valid JSON-RPC (400),
1268
+ # a method the server does not implement (404), an envelope that is missing or malformed (400),
1269
+ # and for a `tools/call` the header mismatch of SEP-2243 (400).
1270
+ # The headers are checked only on a tool that is known without running the request: with a `tools_list_handler`
1271
+ # the tool is the one the block returns for this very dispatch, which nothing ahead of the dispatch can stand in for.
1272
+ # A tool that is not found, a disagreement, or an error while looking leaves the request to the buffered exchange,
1273
+ # which answers it as it always has. What only the handler can decide, such as a client capability it finds missing,
1274
+ # is answered on the stream.
1275
+ def stream_modern_request?(body, request)
1276
+ return false unless @stream_request_notifications
1277
+ return false if body[:id].nil? || !STREAMED_MODERN_METHODS.include?(body[:method])
1278
+ return false unless JsonRpcHandler.valid_version?(body[:jsonrpc]) && JsonRpcHandler.valid_id?(body[:id])
1279
+
1280
+ params = body[:params]
1281
+ meta = params[:_meta] if params.is_a?(Hash)
1282
+ progress_token = meta[:progressToken] if meta.is_a?(Hash)
1283
+ return false unless progress_token.is_a?(String) || progress_token.is_a?(Integer)
1284
+ return false unless @server.implements_method?(body[:method])
1285
+ return false unless RequestEnvelope.modern?(params)
1286
+
1287
+ RequestEnvelope.parse!(params, request: params)
1288
+ return true unless body[:method] == Methods::TOOLS_CALL
1289
+
1290
+ tool = @server.tool_known_ahead_of_dispatch(params[:name])
1291
+
1292
+ !tool.nil? && mcp_param_header_mismatch(tool, params, request).nil?
1293
+ rescue StandardError
1294
+ false
1295
+ end
1296
+
1297
+ # The Rack streaming body of a request served with `stream_request_notifications:`. As `ListenStreamBody`,
1298
+ # it responds to `call` and not to `each`, and `first` turns the buffered-host mistake into guidance.
1299
+ class RequestStreamBody
1300
+ def initialize(&block)
1301
+ @block = block
1302
+ end
1303
+
1304
+ def call(stream)
1305
+ @block.call(stream)
1306
+ end
1307
+
1308
+ def first
1309
+ raise <<~MESSAGE
1310
+ The request was answered with a streaming SSE body, which cannot be buffered into a JSON response. \
1311
+ A host that cannot hold an SSE response open should construct the transport without `stream_request_notifications: true`.
1312
+ See the Rails (controller) section at https://ruby.sdk.modelcontextprotocol.io/server/transports/ for the hosting patterns.
1313
+ MESSAGE
1314
+ end
1315
+ end
1316
+ private_constant :RequestStreamBody
1317
+
1318
+ # Answers a request on an SSE stream that stays open while its handler runs. The handler runs inside the body,
1319
+ # on the thread the host writes the response from, not on one of the transport's own: an application keeps
1320
+ # its thread-bound state, and nothing outlives the response.
1321
+ #
1322
+ # The stream is the request's notification sink for as long as the handler runs, and the response is its last frame.
1323
+ # A request whose response is suppressed (it was cancelled) ends the stream without one.
1324
+ def streamed_modern_response(body, body_string, session, auth_info, tool_call_check)
1325
+ response_body = RequestStreamBody.new do |stream|
1326
+ sink = { stream: stream, session: session, write_mutex: Mutex.new, keepalive_wakeup: ConditionVariable.new }
1327
+
1328
+ begin
1329
+ @mutex.synchronize { @modern_request_sinks[session.session_id] = sink }
1330
+
1331
+ start_request_stream_keepalive_thread(session.session_id, sink)
1332
+
1333
+ response = @server.handle(body, session: session, auth_info: auth_info, tool_call_check: tool_call_check)
1334
+
1335
+ finish_request_stream(sink, response)
1336
+ rescue StandardError => e
1337
+ MCP.configuration.exception_reporter.call(e, { request: body_string })
1338
+
1339
+ finish_request_stream(sink, {
1340
+ jsonrpc: "2.0",
1341
+ id: echoable_id(body[:id]),
1342
+ error: { code: JsonRpcHandler::ErrorCode::INTERNAL_ERROR, message: "Internal server error" },
1343
+ })
1344
+ ensure
1345
+ @mutex.synchronize do
1346
+ @modern_request_sinks.delete(session.session_id)
1347
+ sink[:keepalive_wakeup].signal
1348
+ end
1349
+ sink[:write_mutex].synchronize { sink[:closed] = true }
1350
+
1351
+ close_stream_safely(stream)
1352
+ end
1353
+ end
1354
+
1355
+ [200, SSE_HEADERS.dup, response_body]
1356
+ end
1357
+
1358
+ # Writes one frame to the response stream of a streamed request, under its write mutex so that it cannot land
1359
+ # inside a keepalive or after the response. Returns whether the frame was written.
1360
+ #
1361
+ # A write that fails or stalls past `stream_write_timeout:` means the client is no longer reading. On this
1362
+ # lifecycle closing the response stream is how a client cancels its request, so the request is cancelled:
1363
+ # its handler observes it as it would `notifications/cancelled`, and nothing more is written.
1364
+ def write_to_request_stream(sink, data)
1365
+ guarded_request_stream_write(sink) { push_to_stream(sink[:stream], data, subscription: sink) }
1366
+ end
1367
+
1368
+ # The stream is marked closed before the write mutex is released, so a writer waiting on that mutex cannot put
1369
+ # its frame after one that failed part way. The cancellation runs outside the mutex: it calls the hooks of
1370
+ # the handler, which may themselves try to notify.
1371
+ def guarded_request_stream_write(sink)
1372
+ outcome = sink[:write_mutex].synchronize do
1373
+ next :skipped if sink[:closed]
1374
+
1375
+ begin
1376
+ yield
1377
+
1378
+ :written
1379
+ rescue *STREAM_WRITE_ERRORS
1380
+ sink[:closed] = true
1381
+
1382
+ :failed
1383
+ end
1384
+ end
1385
+
1386
+ sink[:session].cancel_all_incoming(reason: "The response stream was closed") if outcome == :failed
1387
+
1388
+ outcome == :written
1389
+ end
1390
+
1391
+ # The response may be large, so it is not held to one deadline as the frames above are: it is written in pieces,
1392
+ # each given `stream_write_timeout:` seconds. A client that takes each piece in that time receives all of it,
1393
+ # however long the whole takes, and one that does not is dropped. Nothing else would end this stream: it belongs
1394
+ # to no session, so until the write returns it holds the thread that serves the request and the keepalive waiting
1395
+ # on the mutex.
1396
+ def finish_request_stream(sink, response)
1397
+ return if response.nil?
1398
+
1399
+ _response, response_json = modern_response_json(response)
1400
+ frame = sse_frame(response_json)
1401
+
1402
+ sink[:write_mutex].synchronize do
1403
+ next if sink[:closed]
1404
+
1405
+ sink[:closed] = true
1406
+
1407
+ stream = sink[:stream]
1408
+ offset = 0
1409
+
1410
+ while offset < frame.bytesize
1411
+ piece = frame.byteslice(offset, RESPONSE_FRAME_PIECE_BYTES)
1412
+ within_stream_write_timeout(stream, sink) { stream.write(piece) }
1413
+ offset += piece.bytesize
1414
+ end
1415
+
1416
+ within_stream_write_timeout(stream, sink) { stream.flush }
1417
+ end
1418
+ rescue *STREAM_WRITE_ERRORS
1419
+ # The client went away before its response, or stopped reading it; there is no one left to answer.
1420
+ end
1421
+
1422
+ # Writes keepalive comment frames to the response stream of a streamed request while its handler is quiet, so
1423
+ # an intermediary does not time the response out and a client that went away is noticed, and its request cancelled,
1424
+ # without waiting for the next notification. Ends with the request: `streamed_modern_response` removes the sink and
1425
+ # signals the wait.
1426
+ def start_request_stream_keepalive_thread(session_id, sink)
1427
+ return unless @listen_keepalive_interval
1428
+
1429
+ Thread.new do
1430
+ loop do
1431
+ registered = @mutex.synchronize do
1432
+ next false unless @modern_request_sinks[session_id].equal?(sink)
1433
+
1434
+ sink[:keepalive_wakeup].wait(@mutex, @listen_keepalive_interval)
1435
+ @modern_request_sinks[session_id].equal?(sink)
1436
+ end
1437
+
1438
+ break unless registered
1439
+
1440
+ # A stream that is closed gets no more frames, so there is nothing left to keep alive.
1441
+ break unless guarded_request_stream_write(sink) { push_ping_to_stream(sink[:stream], subscription: sink) }
1442
+ end
1443
+ rescue StandardError => e
1444
+ MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Request stream keepalive failed" })
1445
+ end
1446
+ end
1447
+
1142
1448
  # Enforces the SEP-2575 header/body match rules (`-32020`, HTTP 400): the `MCP-Protocol-Version` header
1143
- # MUST match the `_meta`-carried version, and the `Mcp-Method` / `Mcp-Name` mirror headers MUST match
1144
- # the body when sent. Absent mirror headers are tolerated for interoperability while other SDK serving stacks
1145
- # converge on enforcement.
1449
+ # MUST match the `_meta`-carried version, and the `Mcp-Method` / `Mcp-Name` mirror headers MUST be present
1450
+ # and match the body.
1146
1451
  def validate_modern_headers(request, body, header_version)
1147
1452
  params = body[:params]
1148
1453
  meta_version = params.is_a?(Hash) && params[:_meta].is_a?(Hash) ? params.dig(:_meta, :"io.modelcontextprotocol/protocolVersion") : nil
@@ -1172,8 +1477,9 @@ module MCP
1172
1477
  )
1173
1478
  end
1174
1479
 
1175
- if NAME_BEARING_METHODS.include?(body[:method])
1176
- body_name = params.is_a?(Hash) ? params[:name] || params[:uri] : nil
1480
+ name_member = NAME_MEMBER_BY_METHOD[body[:method]]
1481
+ if name_member
1482
+ body_name = params.is_a?(Hash) ? params[name_member] : nil
1177
1483
  name_header = request.env["HTTP_MCP_NAME"]
1178
1484
  if body_name
1179
1485
  if name_header.to_s.empty?
@@ -1199,34 +1505,29 @@ module MCP
1199
1505
  # Enforces the SEP-2243 server behavior for custom headers (`-32020`, HTTP 400) on a modern `tools/call`: each
1200
1506
  # `x-mcp-header` parameter of the called tool must have its `Mcp-Param-{Name}` header present exactly when the body
1201
1507
  # 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.
1508
+ # sentinel is refused outright. The comparison runs before the tool does, on the schema the server serves this caller
1509
+ # in `tools/list`, so the body a handler acts on is the one an intermediary routed on: the dispatcher calls this
1510
+ # with the tool it resolved for the call, which with a `tools_list_handler` is the one the block returned.
1511
+ # A tool that is not found never reaches it, one whose declarations are invalid (a conforming client drops such
1512
+ # a tool and sends no headers for it) is not checked, and headers for parameters no declaration names are ignored,
1513
+ # as the spec asks of any server that does not recognize them. The message names the header and the argument,
1514
+ # not their values; `nil` means the headers agree.
1207
1515
  #
1208
1516
  # Rack folds header names into `HTTP_` keys with `-` as `_`, so `Mcp-Param-Region-A` and `Mcp-Param-Region_A` land
1209
1517
  # on one key; a token that differs only in that way is the schema author's choice, and the value still has to
1210
1518
  # agree with the body.
1211
- def validate_mcp_param_headers(request, body)
1212
- params = body[:params]
1519
+ def mcp_param_header_mismatch(tool, params, request)
1213
1520
  return unless params.is_a?(Hash)
1214
1521
 
1215
- tool = @server.tools[params[:name]]
1216
- return unless tool
1217
-
1218
1522
  scan = McpParamHeaders.scan(tool.input_schema.to_h)
1219
1523
  return unless scan[:valid] && !scan[:declarations].empty?
1220
1524
 
1221
1525
  arguments = params[:arguments] || {}
1222
1526
  return unless arguments.is_a?(Hash)
1223
1527
 
1224
- message = McpParamHeaders.mismatch(scan[:declarations], arguments) do |header_name|
1528
+ McpParamHeaders.mismatch(scan[:declarations], arguments) do |header_name|
1225
1529
  header_bytes(request, "HTTP_#{header_name.upcase.tr("-", "_")}")
1226
1530
  end
1227
- return unless message
1228
-
1229
- header_mismatch_response(message, body[:id])
1230
1531
  end
1231
1532
 
1232
1533
  # Serves `subscriptions/listen` (SEP-2575): opens a long-lived SSE stream whose first message is
@@ -1606,6 +1907,46 @@ module MCP
1606
1907
  !!(value[flag] || value[flag.to_s])
1607
1908
  end
1608
1909
 
1910
+ # Maps a change notification onto its typed `MCP::Subscriptions` event, or `nil` for methods that do not
1911
+ # feed `subscriptions/listen` streams (progress, log, and the other request- or session-scoped notifications).
1912
+ def subscription_event_for(method, params)
1913
+ Subscriptions.event_from_wire(method, params)
1914
+ end
1915
+
1916
+ def detach_from_subscription_bus
1917
+ @subscription_bus_detached = true
1918
+ unsubscribe = @subscription_bus_unsubscribe
1919
+ @subscription_bus_unsubscribe = nil
1920
+ unsubscribe&.call
1921
+ rescue => e
1922
+ report_subscription_bus_failure(e, "Subscription bus unsubscribe failed")
1923
+ end
1924
+
1925
+ # A reporter that raises is ignored here, unlike elsewhere in the transport: these reports are made on the reader
1926
+ # thread of a broker, which the exception would end, inside `close`, whose teardown it would stop,
1927
+ # and ahead of the other deliveries of a change, which it would cost the streams of this worker.
1928
+ def report_subscription_bus_failure(exception, error)
1929
+ MCP.configuration.exception_reporter.call(exception, { error: error })
1930
+ rescue StandardError
1931
+ nil
1932
+ end
1933
+
1934
+ # Delivers a bus event (published locally or by another worker) to the matching listen streams.
1935
+ # An event kind this transport does not know is ignored, so a newer publisher sharing the bus
1936
+ # does not break an older worker.
1937
+ def deliver_event_to_listen_subscriptions(event)
1938
+ case event
1939
+ when Subscriptions::ToolsListChanged
1940
+ deliver_to_listen_subscriptions(Methods::NOTIFICATIONS_TOOLS_LIST_CHANGED, nil)
1941
+ when Subscriptions::PromptsListChanged
1942
+ deliver_to_listen_subscriptions(Methods::NOTIFICATIONS_PROMPTS_LIST_CHANGED, nil)
1943
+ when Subscriptions::ResourcesListChanged
1944
+ deliver_to_listen_subscriptions(Methods::NOTIFICATIONS_RESOURCES_LIST_CHANGED, nil)
1945
+ when Subscriptions::ResourceUpdated
1946
+ deliver_to_listen_subscriptions(Methods::NOTIFICATIONS_RESOURCES_UPDATED, { uri: event.uri })
1947
+ end
1948
+ end
1949
+
1609
1950
  # Fans a notification out to every `subscriptions/listen` stream whose honored filter opted in to it,
1610
1951
  # stamping the correlating `subscriptionId` into `_meta`. Matching against the honored filter
1611
1952
  # (not the requested one) enforces the MUST NOT-send-unrequested-types rule.
@@ -1659,10 +2000,8 @@ module MCP
1659
2000
  push_to_stream(subscription[:stream], notification, subscription: subscription)
1660
2001
  end
1661
2002
  rescue *STREAM_WRITE_ERRORS => e
1662
- MCP.configuration.exception_reporter.call(
1663
- e,
1664
- { subscription_id: subscription[:request_id], error: "Failed to send notification" },
1665
- )
2003
+ report_stream_write_failure(e, { subscription_id: subscription[:request_id], error: "Failed to send notification" })
2004
+
1666
2005
  # Closed only when the removal is this path's own, as every other removal path does: the keepalive loop,
1667
2006
  # a token expiry, or the teardown that removed the entry first closes the stream itself.
1668
2007
  close_removed_listen_stream(subscription) if remove_listen_subscription(subscription_key)
@@ -1670,6 +2009,14 @@ module MCP
1670
2009
  end
1671
2010
  end
1672
2011
 
2012
+ # Reports a write that failed on one stream of a delivery. A reporter that raises is ignored here, unlike elsewhere in the transport:
2013
+ # the exception would leave the failed stream registered and cost the streams the delivery has not reached yet the message.
2014
+ def report_stream_write_failure(exception, context)
2015
+ MCP.configuration.exception_reporter.call(exception, context)
2016
+ rescue StandardError
2017
+ nil
2018
+ end
2019
+
1673
2020
  def remove_listen_subscription(subscription_key)
1674
2021
  @mutex.synchronize do
1675
2022
  subscription = @listen_subscriptions.delete(subscription_key)
@@ -1947,8 +2294,8 @@ module MCP
1947
2294
  # dispatching it against the shared `Server`. Mirrors the response and regular-request
1948
2295
  # branches; without it a custom notification handler could run without a live session.
1949
2296
  return session_not_found_response if !@stateless && !session_active?(session_id)
2297
+ return session_not_found_response unless dispatch_notification(body_string, session_id, auth_info: request.env[OAuth::ENV_KEY])
1950
2298
 
1951
- dispatch_notification(body_string, session_id, auth_info: request.env[OAuth::ENV_KEY])
1952
2299
  handle_accepted
1953
2300
  elsif response?(body)
1954
2301
  return session_not_found_response if !@stateless && !session_exists?(session_id)
@@ -2030,42 +2377,87 @@ module MCP
2030
2377
  success_response
2031
2378
  end
2032
2379
 
2033
- # Removes the session, closes its streams outside the lock, and returns the removed session, or nil when
2380
+ # Removes the session, releases it outside the lock, and returns the removed session, or nil when
2034
2381
  # there was none to remove.
2035
2382
  def cleanup_session(session_id)
2036
2383
  session = @mutex.synchronize do
2037
2384
  cleanup_session_unsafe(session_id)
2038
2385
  end
2039
2386
 
2040
- if session
2041
- close_stream_safely(session[:get_sse_stream])
2042
- close_post_request_streams(session)
2043
- end
2387
+ release_session(session) if session
2044
2388
 
2045
2389
  session
2046
2390
  end
2047
2391
 
2048
- # Removes a session from `@sessions` and returns it. Does not close the stream.
2049
- # Callers must close the stream outside the mutex to avoid holding the lock during
2050
- # potentially blocking I/O.
2392
+ # Removes a session from `@sessions` and returns it. Does not close the stream, cancel the in-flight requests, or wake
2393
+ # the threads waiting on the session's server-to-client requests: it collects those waits for `release_session`,
2394
+ # which callers must run outside the mutex to avoid holding the lock during potentially blocking I/O and
2395
+ # the requests' cancellation hooks. No wait is added once the session is gone, since `send_request` registers one
2396
+ # only for a session it finds under the lock.
2051
2397
  def cleanup_session_unsafe(session_id)
2052
- session = @sessions.delete(session_id)
2398
+ return unless (session = @sessions.delete(session_id))
2053
2399
 
2054
- # Unblock threads waiting on pending responses for this session.
2055
- @pending_responses.each_value do |pending_response|
2056
- if pending_response[:session_id] == session_id
2057
- pending_response[:queue].push(:session_closed)
2058
- end
2400
+ session[:pending_response_queues] = @pending_responses.each_value.filter_map do |pending_response|
2401
+ pending_response[:queue] if pending_response[:session_id] == session_id
2059
2402
  end
2060
2403
 
2061
2404
  session
2062
2405
  end
2063
2406
 
2064
- def cleanup_and_collect_stream(session_id, streams_to_close)
2407
+ # Removes a session under `@mutex` and adds it to `removed_sessions`, for the caller to release once outside the lock.
2408
+ def cleanup_and_collect_session(session_id, removed_sessions)
2065
2409
  return unless (removed = cleanup_session_unsafe(session_id))
2066
2410
 
2067
- streams_to_close << removed[:get_sse_stream]
2068
- removed[:post_request_streams]&.each_value { |stream| streams_to_close << stream }
2411
+ removed_sessions << removed
2412
+ end
2413
+
2414
+ # Ends what a removed session still has running: cancels its in-flight requests, whose handlers observe
2415
+ # the termination through `server_context.cancelled?` and whose responses are suppressed as for `notifications/cancelled`,
2416
+ # wakes the threads still waiting on its server-to-client requests, and closes its streams. Runs outside `@mutex`:
2417
+ # a close can block, and a cancellation fires the request's `on_cancel` hooks synchronously, which may call back into
2418
+ # the transport.
2419
+ #
2420
+ # The cancellation comes first. A close can block for up to `stream_write_timeout:` on a stalled peer, and until
2421
+ # the cancellation runs, a request the session still receives is admitted and run as usual. Waking the waits first
2422
+ # would likewise tell a request waiting on a nested request only that the session closed, before its own token is
2423
+ # cancelled. Cancelling first wakes that wait through the request's cancellation hook, so the request ends cancelled;
2424
+ # `:session_closed` then wakes the waits that belong to no request of the session.
2425
+ def release_session(session)
2426
+ release_sessions([session])
2427
+ end
2428
+
2429
+ # Sessions that end together (`close`, the reaper) are all cancelled before the streams of any of them are closed:
2430
+ # released one after the other, each session would wait for the closes of those ahead of it, as its own cancellation
2431
+ # once waited for its own.
2432
+ #
2433
+ # A cancellation runs application hooks and can raise (a hook that fails, reported by an exception reporter that fails as well).
2434
+ # The sessions are removed from the registry by then, so nothing would come back for what is left:
2435
+ # every session is still cancelled and every stream closed, and the first error is raised once that is done.
2436
+ def release_sessions(sessions)
2437
+ first_error = nil
2438
+
2439
+ sessions.each do |session|
2440
+ end_session_requests(session)
2441
+ rescue StandardError => e
2442
+ first_error ||= e
2443
+ end
2444
+
2445
+ raise first_error if first_error
2446
+ ensure
2447
+ sessions.each do |session|
2448
+ close_session_streams(session)
2449
+ end
2450
+ end
2451
+
2452
+ def end_session_requests(session)
2453
+ session[:server_session]&.cancel_all_incoming(reason: SESSION_TERMINATED_REASON)
2454
+ ensure
2455
+ session[:pending_response_queues]&.each { |queue| queue.push(:session_closed) }
2456
+ end
2457
+
2458
+ def close_session_streams(session)
2459
+ close_stream_safely(session[:get_sse_stream])
2460
+ close_post_request_streams(session)
2069
2461
  end
2070
2462
 
2071
2463
  # A close can block on the same full buffers a write does (a TLS stream writes its closing alert, a buffered one flushes),
@@ -2325,20 +2717,22 @@ module MCP
2325
2717
 
2326
2718
  # Dispatches a client-originated notification (e.g. `notifications/cancelled`,
2327
2719
  # `notifications/initialized`) through the server so it can update session state.
2720
+ # Returns false, without dispatching, when the session was removed after the caller checked it,
2721
+ # and true otherwise, including when the dispatch raised.
2328
2722
  def dispatch_notification(body_string, session_id, auth_info: nil)
2329
2723
  server_session = nil
2330
2724
  if @stateless
2331
2725
  server_session = ephemeral_session
2332
2726
  elsif session_id
2333
- @mutex.synchronize do
2334
- session = @sessions[session_id]
2335
- server_session = session[:server_session] if session
2336
- end
2727
+ server_session = @mutex.synchronize { @sessions[session_id]&.dig(:server_session) }
2728
+ return false unless server_session
2337
2729
  end
2338
2730
 
2339
2731
  dispatch_handle_json(body_string, server_session, auth_info: auth_info)
2732
+ true
2340
2733
  rescue => e
2341
2734
  MCP.configuration.exception_reporter.call(e, { error: "Failed to dispatch notification" })
2735
+ true
2342
2736
  end
2343
2737
 
2344
2738
  def response?(body)
@@ -2352,7 +2746,9 @@ module MCP
2352
2746
  @mutex.synchronize do
2353
2747
  if (pending_response = @pending_responses[request_id]) && pending_response[:session_id] == session_id
2354
2748
  if body.key?(:error)
2355
- error = body[:error]
2749
+ # A malformed `error` member still answers the request as an error, rather than raising here and leaving
2750
+ # its `send_request` to wait out its timeout.
2751
+ error = body[:error].is_a?(Hash) ? body[:error] : {}
2356
2752
  pending_response[:queue].push(error: { code: error[:code], message: error[:message] })
2357
2753
  else
2358
2754
  pending_response[:queue].push(body[:result])
@@ -2381,7 +2777,7 @@ module MCP
2381
2777
  # so the cap rejects only when genuinely full rather than up to a reaper interval after sessions expired.
2382
2778
  if @max_sessions && @sessions.size >= @max_sessions
2383
2779
  @sessions.each_key.select { |id| session_expired?(@sessions[id]) }.each do |id|
2384
- cleanup_and_collect_stream(id, reclaimed)
2780
+ cleanup_and_collect_session(id, reclaimed)
2385
2781
  end
2386
2782
  end
2387
2783
 
@@ -2410,7 +2806,7 @@ module MCP
2410
2806
  true
2411
2807
  end
2412
2808
 
2413
- reclaimed.each { |stream| close_stream_safely(stream) }
2809
+ release_sessions(reclaimed)
2414
2810
  return too_many_sessions_response unless inserted
2415
2811
  end
2416
2812
 
@@ -2466,10 +2862,11 @@ module MCP
2466
2862
  error_response = validate_and_touch_session(session_id)
2467
2863
  return error_response if error_response
2468
2864
 
2469
- @mutex.synchronize do
2470
- session = @sessions[session_id]
2471
- server_session = session[:server_session] if session
2472
- end
2865
+ server_session = @mutex.synchronize { @sessions[session_id]&.dig(:server_session) }
2866
+ # The session may have been removed since the check above, by a `DELETE` from another connection or by `close`.
2867
+ # The request is refused as one naming an unknown session: dispatched without one, it would run against
2868
+ # the shared `Server`, outside the session whose termination cancels it.
2869
+ return session_not_found_response unless server_session
2473
2870
  end
2474
2871
 
2475
2872
  # `Server` refuses a duplicate id as well, but only once the request reaches it. The SSE branch below
@@ -2503,28 +2900,34 @@ module MCP
2503
2900
  # the event store and routes a `Last-Event-ID` resume back to the request (SEP-1699).
2504
2901
  # It is minted whether or not a store is configured, so the registration has one shape.
2505
2902
  stream_id = mint_stream_id(session_id)
2506
- claimed = @mutex.synchronize do
2903
+ claim = @mutex.synchronize do
2507
2904
  session = @sessions[session_id]
2508
- next false unless session && related_request_id
2905
+ next unless session && related_request_id
2509
2906
 
2510
2907
  session[:post_request_streams] ||= {}
2511
2908
  session[:post_stream_entries] ||= {}
2512
2909
 
2513
2910
  # Claim the id only while it is free. `handle_regular_request` already refused the colliding request,
2514
2911
  # 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)
2912
+ # its messages going where they belong, and the request that lost the claim is refused below without
2913
+ # running, since it could otherwise register the id before the owner does.
2914
+ next :taken if session[:post_request_streams].key?(related_request_id) || session[:post_stream_entries].key?(related_request_id)
2517
2915
 
2518
2916
  session[:post_request_streams][related_request_id] = stream
2519
2917
  session[:post_stream_entries][related_request_id] = { stream_id: stream_id, resumed: nil }
2520
2918
 
2521
- true
2919
+ :claimed
2522
2920
  end
2921
+ claimed = claim == :claimed
2523
2922
 
2524
2923
  write_priming_event(session_id, related_request_id, stream) if claimed
2525
2924
 
2526
2925
  begin
2527
- response = dispatch_handle_json(body_string, server_session, auth_info: auth_info)
2926
+ response = if claim == :taken
2927
+ request_id_conflict_message(related_request_id)
2928
+ else
2929
+ dispatch_handle_json(body_string, server_session, auth_info: auth_info)
2930
+ end
2528
2931
 
2529
2932
  if response
2530
2933
  # Written through the registration rather than to `stream`: the response of a request whose connection was
@@ -2606,13 +3009,7 @@ module MCP
2606
3009
  nil
2607
3010
  end
2608
3011
 
2609
- if removed
2610
- close_stream_safely(removed[:get_sse_stream])
2611
-
2612
- removed[:post_request_streams]&.each_value do |stream|
2613
- close_stream_safely(stream)
2614
- end
2615
- end
3012
+ release_session(removed) if removed
2616
3013
 
2617
3014
  response
2618
3015
  end
@@ -2667,10 +3064,7 @@ module MCP
2667
3064
  true
2668
3065
  end
2669
3066
 
2670
- if removed
2671
- close_stream_safely(removed[:get_sse_stream])
2672
- close_post_request_streams(removed)
2673
- end
3067
+ release_session(removed) if removed
2674
3068
 
2675
3069
  active
2676
3070
  end
@@ -2830,10 +3224,15 @@ module MCP
2830
3224
  json_rpc_error_response(
2831
3225
  status: 409,
2832
3226
  code: JsonRpcHandler::ErrorCode::INVALID_REQUEST,
2833
- message: "Conflict: Request id is already in flight for this session",
3227
+ message: REQUEST_ID_CONFLICT_MESSAGE,
2834
3228
  )
2835
3229
  end
2836
3230
 
3231
+ # The same refusal, for a request whose SSE response has already started.
3232
+ def request_id_conflict_message(request_id)
3233
+ { jsonrpc: "2.0", id: request_id, error: { code: JsonRpcHandler::ErrorCode::INVALID_REQUEST, message: REQUEST_ID_CONFLICT_MESSAGE } }.to_json
3234
+ end
3235
+
2837
3236
  def setup_sse_stream(session_id, auth_info = nil)
2838
3237
  body = create_sse_body(session_id, auth_info)
2839
3238
 
@@ -2959,10 +3358,18 @@ module MCP
2959
3358
  raise # Re-raise to exit the keepalive loop
2960
3359
  end
2961
3360
 
3361
+ # A session is idle only while none of its requests is running, and its idle time counts from the later of
3362
+ # the last activity that touched it and the end of its last request. `last_active_at` alone is the start of
3363
+ # the latest request, so a request longer than the timeout would lose its session, and with it its response,
3364
+ # while the client is still waiting for it.
2962
3365
  def session_expired?(session)
2963
3366
  return false unless @session_idle_timeout
2964
3367
 
2965
- Process.clock_gettime(Process::CLOCK_MONOTONIC) - session[:last_active_at] > @session_idle_timeout
3368
+ busy, last_request_finished_at = session[:server_session]&.in_flight_activity
3369
+ return false if busy
3370
+
3371
+ idle_since = [session[:last_active_at], last_request_finished_at].compact.max
3372
+ Process.clock_gettime(Process::CLOCK_MONOTONIC) - idle_since > @session_idle_timeout
2966
3373
  end
2967
3374
 
2968
3375
  # Stream ids carry the session id, so a `Last-Event-ID` is matched to the session presenting it with
@@ -3057,7 +3464,7 @@ module MCP
3057
3464
 
3058
3465
  written = true
3059
3466
  rescue *STREAM_WRITE_ERRORS => e
3060
- MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to send message" })
3467
+ report_stream_write_failure(e, { session_id: session_id, error: "Failed to send message" })
3061
3468
 
3062
3469
  drop_broken_stream(session_id, stream, related_request_id)
3063
3470
  end