mcp 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -142,7 +142,7 @@ module MCP
142
142
  # object instead of an SSE stream.
143
143
  # @param session_idle_timeout [Numeric, nil] seconds before an idle session is reaped; defaults
144
144
  # to `DEFAULT_SESSION_IDLE_TIMEOUT` (1800) in stateful mode, and an explicit `nil` disables
145
- # expiry. Not supported in stateless mode.
145
+ # expiry. A session is not idle while one of its requests is running. Not supported in stateless mode.
146
146
  # @param max_sessions [Integer, nil] cap on the concurrent session count in stateful mode; a new
147
147
  # `initialize` past the cap is rejected with HTTP 503, and `nil` disables the cap.
148
148
  # @param allowed_origins [Array<String>, :any, nil] extra `Origin` values accepted in addition to
@@ -188,6 +188,14 @@ module MCP
188
188
  # the method then answers 404 with JSON-RPC `-32601` like any unimplemented method,
189
189
  # and `Server#discover` stops advertising the `listChanged`/`subscribe` capability flags,
190
190
  # keeping the advertisement and the actual behavior in agreement. Defaults to `true`.
191
+ # @param stream_request_notifications [Boolean] whether a 2026-07-28 request that asks for progress
192
+ # (`_meta.progressToken` on a `tools/call`, `prompts/get` or `resources/read`) gets the notifications of its handler
193
+ # as they are emitted, on an SSE response held open until the result, instead of all at once after the handler returns.
194
+ # The handler then runs while the host writes the response body, so the host has to serve a streaming body,
195
+ # and an error of such a request is answered on the stream, under HTTP 200. A `tools/call` is streamed only when
196
+ # its tool is known ahead of the handler, which leaves out a server with a `tools_list_handler`.
197
+ # Keepalive comment frames are written every `listen_keepalive_interval` seconds. Defaults to `false`;
198
+ # cannot be combined with `serve_subscriptions_listen: false`.
191
199
  # @param server_to_client_request_timeout [Numeric] seconds a server-to-client request waits for its
192
200
  # response before the transport stops waiting and raises `MCP::Server::RequestTimeoutError`.
193
201
  # Defaults to `DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT` (600); individual calls override it with `timeout:`.
@@ -243,6 +251,7 @@ module MCP
243
251
  max_resource_subscription_bytes: DEFAULT_MAX_RESOURCE_SUBSCRIPTION_BYTES,
244
252
  listen_keepalive_interval: DEFAULT_LISTEN_KEEPALIVE_INTERVAL,
245
253
  serve_subscriptions_listen: true,
254
+ stream_request_notifications: false,
246
255
  server_to_client_request_timeout: DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT,
247
256
  stream_write_timeout: DEFAULT_STREAM_WRITE_TIMEOUT,
248
257
  token_verifier: nil,
@@ -290,6 +299,9 @@ module MCP
290
299
 
291
300
  # Maps a modern request's ephemeral session id to the Array collecting the notifications its handler emits;
292
301
  # `handle_modern` registers the sink and flushes it as SSE frames ahead of the final response (SEP-2575).
302
+ # For a request served with `stream_request_notifications:` the sink is instead the open response stream,
303
+ # `{ stream: stream_object, session: ServerSession, write_mutex: Mutex, keepalive_wakeup: ConditionVariable }`,
304
+ # and each notification is written to it as it is emitted.
293
305
  @modern_request_sinks = {}
294
306
 
295
307
  # Resolve the idle timeout: an explicit value (including `nil` to opt out) wins; otherwise apply the secure default,
@@ -347,6 +359,15 @@ module MCP
347
359
  @listen_keepalive_interval = listen_keepalive_interval
348
360
  @serve_subscriptions_listen = serve_subscriptions_listen
349
361
 
362
+ # `serve_subscriptions_listen: false` is how a host says it buffers responses, and a buffered response
363
+ # cannot carry a notification before its handler has returned.
364
+ if stream_request_notifications && !serve_subscriptions_listen
365
+ raise ArgumentError, "stream_request_notifications needs a host that serves streaming responses, " \
366
+ "so it cannot be combined with serve_subscriptions_listen: false"
367
+ end
368
+
369
+ @stream_request_notifications = stream_request_notifications
370
+
350
371
  unless server_to_client_request_timeout.is_a?(Numeric) && server_to_client_request_timeout.positive?
351
372
  raise ArgumentError, "server_to_client_request_timeout must be a positive number"
352
373
  end
@@ -425,6 +446,10 @@ module MCP
425
446
  # one that still has not taken the frame after this long is dropped whether it stopped reading or is only that slow.
426
447
  DEFAULT_STREAM_WRITE_TIMEOUT = 10
427
448
 
449
+ # How much of the response of a streamed request is written under one `stream_write_timeout:` deadline.
450
+ RESPONSE_FRAME_PIECE_BYTES = 64 * 1024
451
+ private_constant :RESPONSE_FRAME_PIECE_BYTES
452
+
428
453
  # The first protocol version whose clients parse an SSE event with empty data, which the priming event of
429
454
  # SEP-1699 resumability is. A session that negotiated an earlier version gets no priming event and is never
430
455
  # asked to resume, since it would have no event id to come back with; its other events still carry ids.
@@ -441,13 +466,25 @@ module MCP
441
466
  # How long `close` waits in all for the closing results of the open `subscriptions/listen` streams
442
467
  # before closing the streams still open without one.
443
468
  LISTEN_TEARDOWN_TIMEOUT = 5
469
+ # The reason the requests still in flight in a session are cancelled with when the session goes away: terminated by
470
+ # the client's DELETE, expired, torn down with its broken GET stream, or removed by `close`.
471
+ SESSION_TERMINATED_REASON = "Session terminated"
472
+ # The error message a request reusing the id of one in flight in its session is refused with.
473
+ REQUEST_ID_CONFLICT_MESSAGE = "Conflict: Request id is already in flight for this session"
444
474
 
445
475
  # Loopback hosts always accepted by DNS rebinding protection. A locally bound MCP server (the canonical pattern) is
446
476
  # protected out of the box; non-loopback deployments widen the list via `allowed_hosts:`.
447
477
  DEFAULT_LOOPBACK_HOSTS = ["127.0.0.1", "::1", "localhost"].freeze
448
478
 
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
479
+ # JSON-RPC methods whose target is mirrored into the `Mcp-Name` header (SEP-2575), with the `params` member
480
+ # that names it. The member is fixed per method: a `resources/read` is named by its `uri` whatever else
481
+ # its `params` carry, so a `name` added to them cannot stand in for the URI the header is checked against.
482
+ NAME_MEMBER_BY_METHOD = {
483
+ Methods::TOOLS_CALL => :name,
484
+ Methods::RESOURCES_READ => :uri,
485
+ Methods::PROMPTS_GET => :name,
486
+ }.freeze
487
+ NAME_BEARING_METHODS = NAME_MEMBER_BY_METHOD.keys.freeze
451
488
 
452
489
  # Maps broadcast notification methods to the `SubscriptionFilter` field that opts in to them on
453
490
  # a `subscriptions/listen` stream (SEP-2575). `notifications/resources/updated` is matched by URI
@@ -580,10 +617,7 @@ module MCP
580
617
  @sessions.each_key.filter_map { |session_id| cleanup_session_unsafe(session_id) }
581
618
  end
582
619
 
583
- removed_sessions.each do |session|
584
- close_stream_safely(session[:get_sse_stream])
585
- close_post_request_streams(session)
586
- end
620
+ release_sessions(removed_sessions)
587
621
  end
588
622
 
589
623
  # Sessions a server-wide log broadcast is offered to, each applying its own level or the server default.
@@ -620,16 +654,24 @@ module MCP
620
654
  # non-delivery (`false`), never handed to the legacy paths below. It holds each notification as JSON,
621
655
  # generated here so that one that cannot be generated is dropped on its own instead of failing
622
656
  # the whole response when the sink is flushed.
657
+ #
658
+ # A sink that is the open response stream (`stream_request_notifications:`) is written to at once and is not
659
+ # counted: each write waits for the peer, within `stream_write_timeout:`, so nothing accumulates here.
623
660
  sink = @mutex.synchronize { session_id && @modern_request_sinks[session_id] }
624
661
  if sink
625
- return false if sink.size >= MAX_MODERN_REQUEST_NOTIFICATIONS
662
+ return false if sink.is_a?(Array) && sink.size >= MAX_MODERN_REQUEST_NOTIFICATIONS
626
663
 
627
664
  begin
628
- sink << notification.to_json
665
+ notification_json = notification.to_json
629
666
  rescue JSON::GeneratorError => e
630
667
  MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to generate notification" })
631
668
  return false
632
669
  end
670
+
671
+ return write_to_request_stream(sink, notification_json) unless sink.is_a?(Array)
672
+
673
+ sink << notification_json
674
+
633
675
  return true
634
676
  end
635
677
 
@@ -652,26 +694,26 @@ module MCP
652
694
  # (e.g. `resources/updated`, `elicitation/complete`) still flow via GET SSE.
653
695
  return false if @enable_json_response && related_request_id
654
696
 
655
- streams_to_close = []
697
+ removed_sessions = []
656
698
  live = @mutex.synchronize do
657
699
  next false unless (session = @sessions[session_id])
658
700
 
659
701
  if session_expired?(session)
660
- cleanup_and_collect_stream(session_id, streams_to_close)
702
+ cleanup_and_collect_session(session_id, removed_sessions)
661
703
  next false
662
704
  end
663
705
 
664
706
  true
665
707
  end
666
708
 
667
- close_streams(streams_to_close)
709
+ release_sessions(removed_sessions)
668
710
  return false unless live
669
711
 
670
712
  store_and_write(session_id, related_request_id, notification.to_json)
671
713
  end
672
714
 
673
715
  def deliver_broadcast_notification(notification)
674
- streams_to_close = []
716
+ removed_sessions = []
675
717
 
676
718
  # Snapshot the sessions under the lock, then write to each outside it. A session whose GET stream is
677
719
  # closed at the moment still takes the notification when it has opened that stream before and an event
@@ -691,13 +733,13 @@ module MCP
691
733
  end
692
734
 
693
735
  expired_session_ids.each do |session_id|
694
- cleanup_and_collect_stream(session_id, streams_to_close)
736
+ cleanup_and_collect_session(session_id, removed_sessions)
695
737
  end
696
738
 
697
739
  collected
698
740
  end
699
741
 
700
- close_streams(streams_to_close)
742
+ release_sessions(removed_sessions)
701
743
 
702
744
  json = notification.to_json
703
745
  targets.count do |session_id|
@@ -717,6 +759,7 @@ module MCP
717
759
  # from its last event id (SEP-1699), and the events it misses meanwhile are stored for it.
718
760
  def drop_broken_stream(session_id, stream, related_request_id)
719
761
  streams_to_close = []
762
+ removed_sessions = []
720
763
 
721
764
  @mutex.synchronize do
722
765
  session = @sessions[session_id]
@@ -732,12 +775,13 @@ module MCP
732
775
  if @event_store
733
776
  streams_to_close << detach_get_stream(session)
734
777
  else
735
- cleanup_and_collect_stream(session_id, streams_to_close)
778
+ cleanup_and_collect_session(session_id, removed_sessions)
736
779
  end
737
780
  end
738
781
  end
739
782
 
740
783
  close_streams(streams_to_close)
784
+ release_sessions(removed_sessions)
741
785
  end
742
786
 
743
787
  def close_streams(streams)
@@ -955,19 +999,19 @@ module MCP
955
999
  end
956
1000
  end
957
1001
 
958
- removed_sessions.each do |session|
959
- close_stream_safely(session[:get_sse_stream])
960
- close_post_request_streams(session)
961
- end
1002
+ release_sessions(removed_sessions)
962
1003
  end
963
1004
 
964
1005
  # One `write` per frame, so the frames of concurrent writers cannot interleave in the middle of each other.
965
1006
  def send_to_stream(stream, data, event_id: nil)
1007
+ stream.write(sse_frame(data, event_id: event_id))
1008
+ stream.flush
1009
+ end
1010
+
1011
+ def sse_frame(data, event_id: nil)
966
1012
  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
1013
 
969
- stream.write(frame)
970
- stream.flush
1014
+ event_id ? "id: #{event_id}\ndata: #{message}\n\n" : "data: #{message}\n\n"
971
1015
  end
972
1016
 
973
1017
  # The priming event of SEP-1699: an id for the client to resume from, the `retry` field when configured, and
@@ -1081,13 +1125,6 @@ module MCP
1081
1125
  mismatch_error = validate_modern_headers(request, body, header_version)
1082
1126
  return mismatch_error if mismatch_error
1083
1127
 
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
1128
  # `subscriptions/listen` is a long-lived notification stream served at the transport layer;
1092
1129
  # it never dispatches through `Server#handle`. A transport constructed with
1093
1130
  # `serve_subscriptions_listen: false` skips the interception, so the method falls through
@@ -1097,32 +1134,39 @@ module MCP
1097
1134
  return handle_subscriptions_listen(body, auth_info: request.env[OAuth::ENV_KEY])
1098
1135
  end
1099
1136
 
1137
+ # SEP-2243 custom headers: the `Mcp-Param-*` headers of a `tools/call` are checked against the body by
1138
+ # the dispatcher, on the tool it resolved for this call, so a disagreement is refused without the tool ever running.
1139
+ # The refusal is answered from here, as a plain JSON 400 whatever the handler had emitted until then.
1140
+ header_mismatch = nil
1141
+ tool_call_check = lambda do |tool, params|
1142
+ header_mismatch = mcp_param_header_mismatch(tool, params, request)
1143
+ end
1144
+
1100
1145
  session = modern_session
1146
+ auth_info = request.env[OAuth::ENV_KEY]
1147
+ if stream_modern_request?(body, request)
1148
+ return streamed_modern_response(body, body_string, session, auth_info, tool_call_check)
1149
+ end
1150
+
1101
1151
  notifications = @mutex.synchronize { @modern_request_sinks[session.session_id] = [] }
1102
1152
  begin
1103
- response = @server.handle(body, session: session, auth_info: request.env[OAuth::ENV_KEY])
1153
+ response = @server.handle(body, session: session, auth_info: auth_info, tool_call_check: tool_call_check)
1104
1154
  ensure
1105
1155
  @mutex.synchronize { @modern_request_sinks.delete(session.session_id) }
1106
1156
  end
1107
1157
 
1158
+ return header_mismatch_response(header_mismatch, body[:id]) if header_mismatch
1159
+
1108
1160
  # `nil` covers notifications and cancellation-suppressed responses; ack with 202 like the legacy notification path.
1109
1161
  return handle_accepted if response.nil?
1110
1162
 
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
1163
+ response, response_json = modern_response_json(response)
1120
1164
 
1121
1165
  # Notifications a handler emitted during the request ride the request's own response stream as SSE frames ahead of
1122
1166
  # 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.
1167
+ # Delivery is buffered: frames flush after the handler returns, preserving order but not real-time interleaving,
1168
+ # and the sink grows with the handler's notification count. `stream_request_notifications:` delivers them as
1169
+ # they are emitted instead, for the requests `stream_modern_request?` selects.
1126
1170
  if notifications.empty?
1127
1171
  [modern_http_status(response), { "content-type" => "application/json" }, [response_json]]
1128
1172
  else
@@ -1139,10 +1183,211 @@ module MCP
1139
1183
  )
1140
1184
  end
1141
1185
 
1186
+ # A response that cannot be generated answers its request with Internal error, as `JsonRpcHandler.handle_json`
1187
+ # does on the legacy paths, instead of failing the whole exchange with a 500. Returns the response that was
1188
+ # generated along with its JSON.
1189
+ def modern_response_json(response)
1190
+ [response, response.to_json]
1191
+ rescue JSON::GeneratorError => e
1192
+ MCP.configuration.exception_reporter.call(e, { error: "Failed to generate response" })
1193
+ response = JsonRpcHandler.encodable_response(response)
1194
+
1195
+ [response, response.to_json]
1196
+ end
1197
+
1198
+ # The methods whose handlers report progress.
1199
+ STREAMED_MODERN_METHODS = [Methods::TOOLS_CALL, Methods::PROMPTS_GET, Methods::RESOURCES_READ].freeze
1200
+ private_constant :STREAMED_MODERN_METHODS
1201
+
1202
+ # Whether this request is answered on an open SSE stream (`stream_request_notifications:`): one that asks for progress,
1203
+ # of a method whose handler can report it. Opening the stream commits HTTP 200 before the handler runs,
1204
+ # so every other request keeps the buffered exchange and the status its answer maps to.
1205
+ #
1206
+ # The answers the spec ties to a status of their own are therefore ruled out here, ahead of the stream,
1207
+ # wherever they can be told without running the request: a request that is not valid JSON-RPC (400),
1208
+ # a method the server does not implement (404), an envelope that is missing or malformed (400),
1209
+ # and for a `tools/call` the header mismatch of SEP-2243 (400).
1210
+ # The headers are checked only on a tool that is known without running the request: with a `tools_list_handler`
1211
+ # the tool is the one the block returns for this very dispatch, which nothing ahead of the dispatch can stand in for.
1212
+ # A tool that is not found, a disagreement, or an error while looking leaves the request to the buffered exchange,
1213
+ # which answers it as it always has. What only the handler can decide, such as a client capability it finds missing,
1214
+ # is answered on the stream.
1215
+ def stream_modern_request?(body, request)
1216
+ return false unless @stream_request_notifications
1217
+ return false if body[:id].nil? || !STREAMED_MODERN_METHODS.include?(body[:method])
1218
+ return false unless JsonRpcHandler.valid_version?(body[:jsonrpc]) && JsonRpcHandler.valid_id?(body[:id])
1219
+
1220
+ params = body[:params]
1221
+ meta = params[:_meta] if params.is_a?(Hash)
1222
+ progress_token = meta[:progressToken] if meta.is_a?(Hash)
1223
+ return false unless progress_token.is_a?(String) || progress_token.is_a?(Integer)
1224
+ return false unless @server.implements_method?(body[:method])
1225
+ return false unless RequestEnvelope.modern?(params)
1226
+
1227
+ RequestEnvelope.parse!(params, request: params)
1228
+ return true unless body[:method] == Methods::TOOLS_CALL
1229
+
1230
+ tool = @server.tool_known_ahead_of_dispatch(params[:name])
1231
+
1232
+ !tool.nil? && mcp_param_header_mismatch(tool, params, request).nil?
1233
+ rescue StandardError
1234
+ false
1235
+ end
1236
+
1237
+ # The Rack streaming body of a request served with `stream_request_notifications:`. As `ListenStreamBody`,
1238
+ # it responds to `call` and not to `each`, and `first` turns the buffered-host mistake into guidance.
1239
+ class RequestStreamBody
1240
+ def initialize(&block)
1241
+ @block = block
1242
+ end
1243
+
1244
+ def call(stream)
1245
+ @block.call(stream)
1246
+ end
1247
+
1248
+ def first
1249
+ raise <<~MESSAGE
1250
+ The request was answered with a streaming SSE body, which cannot be buffered into a JSON response. \
1251
+ A host that cannot hold an SSE response open should construct the transport without `stream_request_notifications: true`.
1252
+ See the Rails (controller) section at https://ruby.sdk.modelcontextprotocol.io/server/transports/ for the hosting patterns.
1253
+ MESSAGE
1254
+ end
1255
+ end
1256
+ private_constant :RequestStreamBody
1257
+
1258
+ # Answers a request on an SSE stream that stays open while its handler runs. The handler runs inside the body,
1259
+ # on the thread the host writes the response from, not on one of the transport's own: an application keeps
1260
+ # its thread-bound state, and nothing outlives the response.
1261
+ #
1262
+ # The stream is the request's notification sink for as long as the handler runs, and the response is its last frame.
1263
+ # A request whose response is suppressed (it was cancelled) ends the stream without one.
1264
+ def streamed_modern_response(body, body_string, session, auth_info, tool_call_check)
1265
+ response_body = RequestStreamBody.new do |stream|
1266
+ sink = { stream: stream, session: session, write_mutex: Mutex.new, keepalive_wakeup: ConditionVariable.new }
1267
+
1268
+ begin
1269
+ @mutex.synchronize { @modern_request_sinks[session.session_id] = sink }
1270
+
1271
+ start_request_stream_keepalive_thread(session.session_id, sink)
1272
+
1273
+ response = @server.handle(body, session: session, auth_info: auth_info, tool_call_check: tool_call_check)
1274
+
1275
+ finish_request_stream(sink, response)
1276
+ rescue StandardError => e
1277
+ MCP.configuration.exception_reporter.call(e, { request: body_string })
1278
+
1279
+ finish_request_stream(sink, {
1280
+ jsonrpc: "2.0",
1281
+ id: echoable_id(body[:id]),
1282
+ error: { code: JsonRpcHandler::ErrorCode::INTERNAL_ERROR, message: "Internal server error" },
1283
+ })
1284
+ ensure
1285
+ @mutex.synchronize do
1286
+ @modern_request_sinks.delete(session.session_id)
1287
+ sink[:keepalive_wakeup].signal
1288
+ end
1289
+ sink[:write_mutex].synchronize { sink[:closed] = true }
1290
+
1291
+ close_stream_safely(stream)
1292
+ end
1293
+ end
1294
+
1295
+ [200, SSE_HEADERS.dup, response_body]
1296
+ end
1297
+
1298
+ # Writes one frame to the response stream of a streamed request, under its write mutex so that it cannot land
1299
+ # inside a keepalive or after the response. Returns whether the frame was written.
1300
+ #
1301
+ # A write that fails or stalls past `stream_write_timeout:` means the client is no longer reading. On this
1302
+ # lifecycle closing the response stream is how a client cancels its request, so the request is cancelled:
1303
+ # its handler observes it as it would `notifications/cancelled`, and nothing more is written.
1304
+ def write_to_request_stream(sink, data)
1305
+ guarded_request_stream_write(sink) { push_to_stream(sink[:stream], data, subscription: sink) }
1306
+ end
1307
+
1308
+ # The stream is marked closed before the write mutex is released, so a writer waiting on that mutex cannot put
1309
+ # its frame after one that failed part way. The cancellation runs outside the mutex: it calls the hooks of
1310
+ # the handler, which may themselves try to notify.
1311
+ def guarded_request_stream_write(sink)
1312
+ outcome = sink[:write_mutex].synchronize do
1313
+ next :skipped if sink[:closed]
1314
+
1315
+ begin
1316
+ yield
1317
+
1318
+ :written
1319
+ rescue *STREAM_WRITE_ERRORS
1320
+ sink[:closed] = true
1321
+
1322
+ :failed
1323
+ end
1324
+ end
1325
+
1326
+ sink[:session].cancel_all_incoming(reason: "The response stream was closed") if outcome == :failed
1327
+
1328
+ outcome == :written
1329
+ end
1330
+
1331
+ # The response may be large, so it is not held to one deadline as the frames above are: it is written in pieces,
1332
+ # each given `stream_write_timeout:` seconds. A client that takes each piece in that time receives all of it,
1333
+ # however long the whole takes, and one that does not is dropped. Nothing else would end this stream: it belongs
1334
+ # to no session, so until the write returns it holds the thread that serves the request and the keepalive waiting
1335
+ # on the mutex.
1336
+ def finish_request_stream(sink, response)
1337
+ return if response.nil?
1338
+
1339
+ _response, response_json = modern_response_json(response)
1340
+ frame = sse_frame(response_json)
1341
+
1342
+ sink[:write_mutex].synchronize do
1343
+ next if sink[:closed]
1344
+
1345
+ sink[:closed] = true
1346
+
1347
+ stream = sink[:stream]
1348
+ offset = 0
1349
+
1350
+ while offset < frame.bytesize
1351
+ piece = frame.byteslice(offset, RESPONSE_FRAME_PIECE_BYTES)
1352
+ within_stream_write_timeout(stream, sink) { stream.write(piece) }
1353
+ offset += piece.bytesize
1354
+ end
1355
+
1356
+ within_stream_write_timeout(stream, sink) { stream.flush }
1357
+ end
1358
+ rescue *STREAM_WRITE_ERRORS
1359
+ # The client went away before its response, or stopped reading it; there is no one left to answer.
1360
+ end
1361
+
1362
+ # Writes keepalive comment frames to the response stream of a streamed request while its handler is quiet, so
1363
+ # an intermediary does not time the response out and a client that went away is noticed, and its request cancelled,
1364
+ # without waiting for the next notification. Ends with the request: `streamed_modern_response` removes the sink and
1365
+ # signals the wait.
1366
+ def start_request_stream_keepalive_thread(session_id, sink)
1367
+ return unless @listen_keepalive_interval
1368
+
1369
+ Thread.new do
1370
+ loop do
1371
+ registered = @mutex.synchronize do
1372
+ next false unless @modern_request_sinks[session_id].equal?(sink)
1373
+
1374
+ sink[:keepalive_wakeup].wait(@mutex, @listen_keepalive_interval)
1375
+ @modern_request_sinks[session_id].equal?(sink)
1376
+ end
1377
+
1378
+ break unless registered
1379
+
1380
+ # A stream that is closed gets no more frames, so there is nothing left to keep alive.
1381
+ break unless guarded_request_stream_write(sink) { push_ping_to_stream(sink[:stream], subscription: sink) }
1382
+ end
1383
+ rescue StandardError => e
1384
+ MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Request stream keepalive failed" })
1385
+ end
1386
+ end
1387
+
1142
1388
  # 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.
1389
+ # MUST match the `_meta`-carried version, and the `Mcp-Method` / `Mcp-Name` mirror headers MUST be present
1390
+ # and match the body.
1146
1391
  def validate_modern_headers(request, body, header_version)
1147
1392
  params = body[:params]
1148
1393
  meta_version = params.is_a?(Hash) && params[:_meta].is_a?(Hash) ? params.dig(:_meta, :"io.modelcontextprotocol/protocolVersion") : nil
@@ -1172,8 +1417,9 @@ module MCP
1172
1417
  )
1173
1418
  end
1174
1419
 
1175
- if NAME_BEARING_METHODS.include?(body[:method])
1176
- body_name = params.is_a?(Hash) ? params[:name] || params[:uri] : nil
1420
+ name_member = NAME_MEMBER_BY_METHOD[body[:method]]
1421
+ if name_member
1422
+ body_name = params.is_a?(Hash) ? params[name_member] : nil
1177
1423
  name_header = request.env["HTTP_MCP_NAME"]
1178
1424
  if body_name
1179
1425
  if name_header.to_s.empty?
@@ -1199,34 +1445,29 @@ module MCP
1199
1445
  # Enforces the SEP-2243 server behavior for custom headers (`-32020`, HTTP 400) on a modern `tools/call`: each
1200
1446
  # `x-mcp-header` parameter of the called tool must have its `Mcp-Param-{Name}` header present exactly when the body
1201
1447
  # 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.
1448
+ # sentinel is refused outright. The comparison runs before the tool does, on the schema the server serves this caller
1449
+ # in `tools/list`, so the body a handler acts on is the one an intermediary routed on: the dispatcher calls this
1450
+ # with the tool it resolved for the call, which with a `tools_list_handler` is the one the block returned.
1451
+ # A tool that is not found never reaches it, one whose declarations are invalid (a conforming client drops such
1452
+ # a tool and sends no headers for it) is not checked, and headers for parameters no declaration names are ignored,
1453
+ # as the spec asks of any server that does not recognize them. The message names the header and the argument,
1454
+ # not their values; `nil` means the headers agree.
1207
1455
  #
1208
1456
  # Rack folds header names into `HTTP_` keys with `-` as `_`, so `Mcp-Param-Region-A` and `Mcp-Param-Region_A` land
1209
1457
  # on one key; a token that differs only in that way is the schema author's choice, and the value still has to
1210
1458
  # agree with the body.
1211
- def validate_mcp_param_headers(request, body)
1212
- params = body[:params]
1459
+ def mcp_param_header_mismatch(tool, params, request)
1213
1460
  return unless params.is_a?(Hash)
1214
1461
 
1215
- tool = @server.tools[params[:name]]
1216
- return unless tool
1217
-
1218
1462
  scan = McpParamHeaders.scan(tool.input_schema.to_h)
1219
1463
  return unless scan[:valid] && !scan[:declarations].empty?
1220
1464
 
1221
1465
  arguments = params[:arguments] || {}
1222
1466
  return unless arguments.is_a?(Hash)
1223
1467
 
1224
- message = McpParamHeaders.mismatch(scan[:declarations], arguments) do |header_name|
1468
+ McpParamHeaders.mismatch(scan[:declarations], arguments) do |header_name|
1225
1469
  header_bytes(request, "HTTP_#{header_name.upcase.tr("-", "_")}")
1226
1470
  end
1227
- return unless message
1228
-
1229
- header_mismatch_response(message, body[:id])
1230
1471
  end
1231
1472
 
1232
1473
  # Serves `subscriptions/listen` (SEP-2575): opens a long-lived SSE stream whose first message is
@@ -1947,8 +2188,8 @@ module MCP
1947
2188
  # dispatching it against the shared `Server`. Mirrors the response and regular-request
1948
2189
  # branches; without it a custom notification handler could run without a live session.
1949
2190
  return session_not_found_response if !@stateless && !session_active?(session_id)
2191
+ return session_not_found_response unless dispatch_notification(body_string, session_id, auth_info: request.env[OAuth::ENV_KEY])
1950
2192
 
1951
- dispatch_notification(body_string, session_id, auth_info: request.env[OAuth::ENV_KEY])
1952
2193
  handle_accepted
1953
2194
  elsif response?(body)
1954
2195
  return session_not_found_response if !@stateless && !session_exists?(session_id)
@@ -2030,42 +2271,87 @@ module MCP
2030
2271
  success_response
2031
2272
  end
2032
2273
 
2033
- # Removes the session, closes its streams outside the lock, and returns the removed session, or nil when
2274
+ # Removes the session, releases it outside the lock, and returns the removed session, or nil when
2034
2275
  # there was none to remove.
2035
2276
  def cleanup_session(session_id)
2036
2277
  session = @mutex.synchronize do
2037
2278
  cleanup_session_unsafe(session_id)
2038
2279
  end
2039
2280
 
2040
- if session
2041
- close_stream_safely(session[:get_sse_stream])
2042
- close_post_request_streams(session)
2043
- end
2281
+ release_session(session) if session
2044
2282
 
2045
2283
  session
2046
2284
  end
2047
2285
 
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.
2286
+ # Removes a session from `@sessions` and returns it. Does not close the stream, cancel the in-flight requests, or wake
2287
+ # the threads waiting on the session's server-to-client requests: it collects those waits for `release_session`,
2288
+ # which callers must run outside the mutex to avoid holding the lock during potentially blocking I/O and
2289
+ # the requests' cancellation hooks. No wait is added once the session is gone, since `send_request` registers one
2290
+ # only for a session it finds under the lock.
2051
2291
  def cleanup_session_unsafe(session_id)
2052
- session = @sessions.delete(session_id)
2292
+ return unless (session = @sessions.delete(session_id))
2053
2293
 
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
2294
+ session[:pending_response_queues] = @pending_responses.each_value.filter_map do |pending_response|
2295
+ pending_response[:queue] if pending_response[:session_id] == session_id
2059
2296
  end
2060
2297
 
2061
2298
  session
2062
2299
  end
2063
2300
 
2064
- def cleanup_and_collect_stream(session_id, streams_to_close)
2301
+ # Removes a session under `@mutex` and adds it to `removed_sessions`, for the caller to release once outside the lock.
2302
+ def cleanup_and_collect_session(session_id, removed_sessions)
2065
2303
  return unless (removed = cleanup_session_unsafe(session_id))
2066
2304
 
2067
- streams_to_close << removed[:get_sse_stream]
2068
- removed[:post_request_streams]&.each_value { |stream| streams_to_close << stream }
2305
+ removed_sessions << removed
2306
+ end
2307
+
2308
+ # Ends what a removed session still has running: cancels its in-flight requests, whose handlers observe
2309
+ # the termination through `server_context.cancelled?` and whose responses are suppressed as for `notifications/cancelled`,
2310
+ # wakes the threads still waiting on its server-to-client requests, and closes its streams. Runs outside `@mutex`:
2311
+ # a close can block, and a cancellation fires the request's `on_cancel` hooks synchronously, which may call back into
2312
+ # the transport.
2313
+ #
2314
+ # The cancellation comes first. A close can block for up to `stream_write_timeout:` on a stalled peer, and until
2315
+ # the cancellation runs, a request the session still receives is admitted and run as usual. Waking the waits first
2316
+ # would likewise tell a request waiting on a nested request only that the session closed, before its own token is
2317
+ # cancelled. Cancelling first wakes that wait through the request's cancellation hook, so the request ends cancelled;
2318
+ # `:session_closed` then wakes the waits that belong to no request of the session.
2319
+ def release_session(session)
2320
+ release_sessions([session])
2321
+ end
2322
+
2323
+ # Sessions that end together (`close`, the reaper) are all cancelled before the streams of any of them are closed:
2324
+ # released one after the other, each session would wait for the closes of those ahead of it, as its own cancellation
2325
+ # once waited for its own.
2326
+ #
2327
+ # A cancellation runs application hooks and can raise (a hook that fails, reported by an exception reporter that fails as well).
2328
+ # The sessions are removed from the registry by then, so nothing would come back for what is left:
2329
+ # every session is still cancelled and every stream closed, and the first error is raised once that is done.
2330
+ def release_sessions(sessions)
2331
+ first_error = nil
2332
+
2333
+ sessions.each do |session|
2334
+ end_session_requests(session)
2335
+ rescue StandardError => e
2336
+ first_error ||= e
2337
+ end
2338
+
2339
+ raise first_error if first_error
2340
+ ensure
2341
+ sessions.each do |session|
2342
+ close_session_streams(session)
2343
+ end
2344
+ end
2345
+
2346
+ def end_session_requests(session)
2347
+ session[:server_session]&.cancel_all_incoming(reason: SESSION_TERMINATED_REASON)
2348
+ ensure
2349
+ session[:pending_response_queues]&.each { |queue| queue.push(:session_closed) }
2350
+ end
2351
+
2352
+ def close_session_streams(session)
2353
+ close_stream_safely(session[:get_sse_stream])
2354
+ close_post_request_streams(session)
2069
2355
  end
2070
2356
 
2071
2357
  # 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 +2611,22 @@ module MCP
2325
2611
 
2326
2612
  # Dispatches a client-originated notification (e.g. `notifications/cancelled`,
2327
2613
  # `notifications/initialized`) through the server so it can update session state.
2614
+ # Returns false, without dispatching, when the session was removed after the caller checked it,
2615
+ # and true otherwise, including when the dispatch raised.
2328
2616
  def dispatch_notification(body_string, session_id, auth_info: nil)
2329
2617
  server_session = nil
2330
2618
  if @stateless
2331
2619
  server_session = ephemeral_session
2332
2620
  elsif session_id
2333
- @mutex.synchronize do
2334
- session = @sessions[session_id]
2335
- server_session = session[:server_session] if session
2336
- end
2621
+ server_session = @mutex.synchronize { @sessions[session_id]&.dig(:server_session) }
2622
+ return false unless server_session
2337
2623
  end
2338
2624
 
2339
2625
  dispatch_handle_json(body_string, server_session, auth_info: auth_info)
2626
+ true
2340
2627
  rescue => e
2341
2628
  MCP.configuration.exception_reporter.call(e, { error: "Failed to dispatch notification" })
2629
+ true
2342
2630
  end
2343
2631
 
2344
2632
  def response?(body)
@@ -2381,7 +2669,7 @@ module MCP
2381
2669
  # so the cap rejects only when genuinely full rather than up to a reaper interval after sessions expired.
2382
2670
  if @max_sessions && @sessions.size >= @max_sessions
2383
2671
  @sessions.each_key.select { |id| session_expired?(@sessions[id]) }.each do |id|
2384
- cleanup_and_collect_stream(id, reclaimed)
2672
+ cleanup_and_collect_session(id, reclaimed)
2385
2673
  end
2386
2674
  end
2387
2675
 
@@ -2410,7 +2698,7 @@ module MCP
2410
2698
  true
2411
2699
  end
2412
2700
 
2413
- reclaimed.each { |stream| close_stream_safely(stream) }
2701
+ release_sessions(reclaimed)
2414
2702
  return too_many_sessions_response unless inserted
2415
2703
  end
2416
2704
 
@@ -2466,10 +2754,11 @@ module MCP
2466
2754
  error_response = validate_and_touch_session(session_id)
2467
2755
  return error_response if error_response
2468
2756
 
2469
- @mutex.synchronize do
2470
- session = @sessions[session_id]
2471
- server_session = session[:server_session] if session
2472
- end
2757
+ server_session = @mutex.synchronize { @sessions[session_id]&.dig(:server_session) }
2758
+ # The session may have been removed since the check above, by a `DELETE` from another connection or by `close`.
2759
+ # The request is refused as one naming an unknown session: dispatched without one, it would run against
2760
+ # the shared `Server`, outside the session whose termination cancels it.
2761
+ return session_not_found_response unless server_session
2473
2762
  end
2474
2763
 
2475
2764
  # `Server` refuses a duplicate id as well, but only once the request reaches it. The SSE branch below
@@ -2503,28 +2792,34 @@ module MCP
2503
2792
  # the event store and routes a `Last-Event-ID` resume back to the request (SEP-1699).
2504
2793
  # It is minted whether or not a store is configured, so the registration has one shape.
2505
2794
  stream_id = mint_stream_id(session_id)
2506
- claimed = @mutex.synchronize do
2795
+ claim = @mutex.synchronize do
2507
2796
  session = @sessions[session_id]
2508
- next false unless session && related_request_id
2797
+ next unless session && related_request_id
2509
2798
 
2510
2799
  session[:post_request_streams] ||= {}
2511
2800
  session[:post_stream_entries] ||= {}
2512
2801
 
2513
2802
  # Claim the id only while it is free. `handle_regular_request` already refused the colliding request,
2514
2803
  # 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)
2804
+ # its messages going where they belong, and the request that lost the claim is refused below without
2805
+ # running, since it could otherwise register the id before the owner does.
2806
+ next :taken if session[:post_request_streams].key?(related_request_id) || session[:post_stream_entries].key?(related_request_id)
2517
2807
 
2518
2808
  session[:post_request_streams][related_request_id] = stream
2519
2809
  session[:post_stream_entries][related_request_id] = { stream_id: stream_id, resumed: nil }
2520
2810
 
2521
- true
2811
+ :claimed
2522
2812
  end
2813
+ claimed = claim == :claimed
2523
2814
 
2524
2815
  write_priming_event(session_id, related_request_id, stream) if claimed
2525
2816
 
2526
2817
  begin
2527
- response = dispatch_handle_json(body_string, server_session, auth_info: auth_info)
2818
+ response = if claim == :taken
2819
+ request_id_conflict_message(related_request_id)
2820
+ else
2821
+ dispatch_handle_json(body_string, server_session, auth_info: auth_info)
2822
+ end
2528
2823
 
2529
2824
  if response
2530
2825
  # Written through the registration rather than to `stream`: the response of a request whose connection was
@@ -2606,13 +2901,7 @@ module MCP
2606
2901
  nil
2607
2902
  end
2608
2903
 
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
2904
+ release_session(removed) if removed
2616
2905
 
2617
2906
  response
2618
2907
  end
@@ -2667,10 +2956,7 @@ module MCP
2667
2956
  true
2668
2957
  end
2669
2958
 
2670
- if removed
2671
- close_stream_safely(removed[:get_sse_stream])
2672
- close_post_request_streams(removed)
2673
- end
2959
+ release_session(removed) if removed
2674
2960
 
2675
2961
  active
2676
2962
  end
@@ -2830,10 +3116,15 @@ module MCP
2830
3116
  json_rpc_error_response(
2831
3117
  status: 409,
2832
3118
  code: JsonRpcHandler::ErrorCode::INVALID_REQUEST,
2833
- message: "Conflict: Request id is already in flight for this session",
3119
+ message: REQUEST_ID_CONFLICT_MESSAGE,
2834
3120
  )
2835
3121
  end
2836
3122
 
3123
+ # The same refusal, for a request whose SSE response has already started.
3124
+ def request_id_conflict_message(request_id)
3125
+ { jsonrpc: "2.0", id: request_id, error: { code: JsonRpcHandler::ErrorCode::INVALID_REQUEST, message: REQUEST_ID_CONFLICT_MESSAGE } }.to_json
3126
+ end
3127
+
2837
3128
  def setup_sse_stream(session_id, auth_info = nil)
2838
3129
  body = create_sse_body(session_id, auth_info)
2839
3130
 
@@ -2959,10 +3250,18 @@ module MCP
2959
3250
  raise # Re-raise to exit the keepalive loop
2960
3251
  end
2961
3252
 
3253
+ # A session is idle only while none of its requests is running, and its idle time counts from the later of
3254
+ # the last activity that touched it and the end of its last request. `last_active_at` alone is the start of
3255
+ # the latest request, so a request longer than the timeout would lose its session, and with it its response,
3256
+ # while the client is still waiting for it.
2962
3257
  def session_expired?(session)
2963
3258
  return false unless @session_idle_timeout
2964
3259
 
2965
- Process.clock_gettime(Process::CLOCK_MONOTONIC) - session[:last_active_at] > @session_idle_timeout
3260
+ busy, last_request_finished_at = session[:server_session]&.in_flight_activity
3261
+ return false if busy
3262
+
3263
+ idle_since = [session[:last_active_at], last_request_finished_at].compact.max
3264
+ Process.clock_gettime(Process::CLOCK_MONOTONIC) - idle_since > @session_idle_timeout
2966
3265
  end
2967
3266
 
2968
3267
  # Stream ids carry the session id, so a `Last-Event-ID` is matched to the session presenting it with