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.
data/lib/mcp/server.rb CHANGED
@@ -17,6 +17,7 @@ require_relative "server/oauth"
17
17
  require_relative "server/pagination"
18
18
  require_relative "server/pending_response"
19
19
  require_relative "server/request_state_security"
20
+ require_relative "server/subscription_bus"
20
21
  require_relative "server/transports"
21
22
 
22
23
  module MCP
@@ -185,8 +186,8 @@ module MCP
185
186
  Methods::SKILLS_GET,
186
187
  ].freeze
187
188
 
188
- attr_accessor :description, :name, :title, :version, :website_url, :instructions, :tools, :prompts, :resource_templates, :server_context, :configuration, :transport, :logging_message_notification
189
- attr_reader :icons, :resources, :page_size, :client_capabilities, :ttl_ms, :cache_scope, :request_state_security, :capabilities
189
+ attr_accessor :description, :name, :title, :version, :website_url, :instructions, :tools, :prompts, :server_context, :configuration, :transport, :logging_message_notification
190
+ attr_reader :icons, :resources, :resource_templates, :page_size, :client_capabilities, :ttl_ms, :cache_scope, :request_state_security, :capabilities
190
191
  # The skills registered with `skills:` as a frozen Array (an empty one when only `skills_handlers` configured
191
192
  # the extension), or nil when the server serves no skills.
192
193
  attr_reader :skills
@@ -250,9 +251,12 @@ module MCP
250
251
  @skills_list_handler = nil
251
252
  @skills_get_handler = nil
252
253
  @skills_methods_registered = false
254
+ ensure_required_members!(resources, :uri, :name)
255
+ ensure_required_members!(resource_templates, :uriTemplate, :name)
253
256
  ensure_no_skill_file_collision!(resources.map(&:uri))
254
257
  @resource_index = index_resources_by_uri(resources)
255
258
  @resources_list_handler = nil
259
+ @tools_list_handler = nil
256
260
  @server_context = server_context
257
261
  self.page_size = page_size
258
262
  self.ttl_ms = ttl_ms
@@ -311,10 +315,14 @@ module MCP
311
315
  # @param auth_info [Server::OAuth::AccessToken, nil] The verified access token
312
316
  # for the current request, passed by the transport layer and exposed to
313
317
  # handlers as `server_context.auth_info`.
318
+ # @param tool_call_check [#call, nil] For a transport that has to compare a `tools/call` with the schema of
319
+ # its tool (the custom header check of the streamable HTTP transport): called with the tool the call resolved to
320
+ # and the request params, after the tool is found and before its arguments are examined. A message it returns
321
+ # refuses the call with `-32020` Header mismatch, and the tool does not run. Not part of the public API.
314
322
  # @return [Hash, nil] The JSON-RPC response, or `nil` for notifications.
315
- def handle(request, session: nil, auth_info: nil)
323
+ def handle(request, session: nil, auth_info: nil, tool_call_check: nil)
316
324
  JsonRpcHandler.handle(request, id_validation_pattern: nil) do |method, request_id|
317
- handle_request(request, method, session: session, related_request_id: request_id, auth_info: auth_info)
325
+ handle_request(request, method, session: session, related_request_id: request_id, auth_info: auth_info, tool_call_check: tool_call_check)
318
326
  end
319
327
  end
320
328
 
@@ -357,6 +365,7 @@ module MCP
357
365
  mime_type: mime_type, annotations: annotations, size: size, meta: meta,
358
366
  &block
359
367
  )
368
+ ensure_required_members!([resource], :uri, :name)
360
369
  ensure_no_skill_file_collision!([resource.uri])
361
370
  @resources << resource
362
371
  @resource_index[resource.uri] = resource
@@ -370,12 +379,19 @@ module MCP
370
379
  mime_type: mime_type, annotations: annotations, meta: meta,
371
380
  &block
372
381
  )
382
+ ensure_required_members!([resource_template], :uriTemplate, :name)
373
383
  @resource_templates << resource_template
374
384
 
375
385
  validate!
376
386
  end
377
387
 
388
+ def resource_templates=(resource_templates)
389
+ ensure_required_members!(resource_templates, :uriTemplate, :name)
390
+ @resource_templates = resource_templates
391
+ end
392
+
378
393
  def resources=(resources)
394
+ ensure_required_members!(resources, :uri, :name)
379
395
  ensure_no_skill_file_collision!(resources.map(&:uri))
380
396
  @resources = resources
381
397
  @resource_index = index_resources_by_uri(resources)
@@ -476,6 +492,50 @@ module MCP
476
492
  @handlers[Methods::NOTIFICATIONS_ROOTS_LIST_CHANGED] = block
477
493
  end
478
494
 
495
+ # Sets a custom handler for the tools visible to a request, letting them depend on request context such as
496
+ # the authenticated principal or granted scope. The block returns the tool collection for the request;
497
+ # the framework paginates it for `tools/list` and stamps the same cache hints it applies to the registered tools,
498
+ # so the block returns only the array, not the paginated result.
499
+ # A block that declares a `server_context:` keyword receives an `MCP::ServerContext`. When no handler is set,
500
+ # the registered tools are used unchanged.
501
+ #
502
+ # The returned collection is both what `tools/list` advertises and what `tools/call` resolves against:
503
+ # a tool the block leaves out is refused as not found, and a tool it returns is callable
504
+ # whether or not it is registered on the server.
505
+ #
506
+ # The block is invoked once per `tools/list` page and once per `tools/call`, so it should be cheap and
507
+ # must return a stable ordering across the pages of one logical query; the cursor is a positional offset
508
+ # into the returned collection.
509
+ #
510
+ # @yield [params, server_context:] The `tools/list` or `tools/call` request params,
511
+ # and an `MCP::ServerContext` when declared.
512
+ # @yieldreturn [Array<MCP::Tool>] The tools visible to the request.
513
+ def tools_list_handler(&block)
514
+ @tools_list_handler = block
515
+ end
516
+
517
+ # The tool a `tools/call` naming `name` resolves to when that can be told before the request is dispatched:
518
+ # `nil` for a name that is not registered, and always with a `tools_list_handler`, whose answer belongs to
519
+ # the dispatch that asks for it.
520
+ #
521
+ # @api private
522
+ def tool_known_ahead_of_dispatch(name)
523
+ tools[name] unless @tools_list_handler
524
+ end
525
+
526
+ # Whether a request for `method` reaches a handler, by the two checks the dispatch makes first: a handler is registered,
527
+ # and the capability the method belongs to is declared.
528
+ #
529
+ # @api private
530
+ def implements_method?(method)
531
+ return false unless @handlers[method]
532
+
533
+ Methods.ensure_capability!(method, effective_capabilities)
534
+ true
535
+ rescue Methods::MissingRequiredCapabilityError
536
+ false
537
+ end
538
+
479
539
  # Sets a custom handler for `resources/list` requests, letting the visible list depend on request context such as
480
540
  # the authenticated principal or granted scope. The block returns the resource collection to serve;
481
541
  # the framework paginates it and stamps SEP-2549 cache hints exactly as it does for the constructor-provided resources,
@@ -717,7 +777,7 @@ module MCP
717
777
  end
718
778
  end
719
779
 
720
- def handle_request(request, method, session: nil, related_request_id: nil, auth_info: nil)
780
+ def handle_request(request, method, session: nil, related_request_id: nil, auth_info: nil, tool_call_check: nil)
721
781
  # A well-formed notification carries no JSON-RPC id and receives no response.
722
782
  # If a client erroneously sends a notification-only method with an id, the message
723
783
  # is framed as a request; since notification methods have no request handler,
@@ -799,13 +859,19 @@ module MCP
799
859
  end
800
860
  end
801
861
 
802
- ->(params) {
862
+ ->(params) do
803
863
  reported_exception = nil
804
864
  instrument_call(
805
865
  method,
806
866
  server_context: { request: request },
807
867
  exception_already_reported: ->(e) { reported_exception.equal?(e) },
808
868
  ) do |instrumentation_data|
869
+ # Cancelled before its handler starts, as a request is when its session ended while it was being admitted.
870
+ if cancellation&.cancelled?
871
+ instrumentation_data.merge!(cancelled: true, cancellation_reason: cancellation.reason)
872
+ next JsonRpcHandler::NO_RESPONSE
873
+ end
874
+
809
875
  refuse_non_object_meta!(params)
810
876
  envelope = lift_request_envelope(params, method: method, session: session)
811
877
 
@@ -835,12 +901,15 @@ module MCP
835
901
 
836
902
  subscription_result(handler_result)
837
903
  when Methods::TOOLS_CALL
838
- call_tool(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
904
+ validate_object_params!(params)
905
+ call_tool(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info, tool_call_check: tool_call_check)
839
906
  when Methods::PROMPTS_GET
907
+ validate_object_params!(params)
840
908
  get_prompt(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
841
909
  when Methods::COMPLETION_COMPLETE
842
910
  complete(params, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
843
911
  when Methods::LOGGING_SET_LEVEL
912
+ validate_object_params!(params)
844
913
  configure_logging_level(params, session: session)
845
914
  else
846
915
  dispatch_optional_context_handler(@handlers[method], params, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
@@ -865,6 +934,7 @@ module MCP
865
934
  session: session,
866
935
  related_request_id: related_request_id,
867
936
  cancellation: cancellation,
937
+ auth_info: auth_info,
868
938
  )
869
939
  else
870
940
  serialize_input_required_result(result, instrumentation_data: instrumentation_data, envelope: envelope, request: params, method: method)
@@ -901,27 +971,35 @@ module MCP
901
971
  # HTTP-level 403 challenges remain the transport `required_scopes` gate's job.
902
972
  report_exception(e, { request: request })
903
973
  instrumentation_data.merge!(error: :insufficient_scope)
974
+ next cancelled_response(cancellation, instrumentation_data) if cancellation&.cancelled?
975
+
904
976
  converted = RequestHandlerError.new(e.message, request, error_type: :invalid_request, original_error: e)
905
977
  reported_exception = converted
906
978
  raise converted
907
979
  rescue RequestHandlerError => e
908
980
  report_exception(e.original_error || e, { request: request })
909
981
  instrumentation_data.merge!(error: e.error_type)
982
+ next cancelled_response(cancellation, instrumentation_data) if cancellation&.cancelled?
983
+
910
984
  reported_exception = e
911
985
  raise e
912
986
  rescue => e
913
987
  report_exception(e, { request: request })
914
988
  instrumentation_data.merge!(error: :internal_error)
989
+ next cancelled_response(cancellation, instrumentation_data) if cancellation&.cancelled?
990
+
915
991
  wrapped = RequestHandlerError.new("Internal error handling #{method} request", request, original_error: e)
916
992
  reported_exception = wrapped
917
993
  raise wrapped
918
- ensure
919
- # `cancellation` is non-nil exactly when this request claimed the id above, so this also keeps `initialize`
920
- # (which never registers) from evicting an in-flight registration under a reused id when the duplicate-`initialize`
921
- # refusal raises out of the handler.
922
- session&.unregister_in_flight(related_request_id, cancellation: cancellation) if related_request_id && cancellation
923
994
  end
924
- }
995
+ ensure
996
+ # Outside the instrumented block, which `configuration.around_request` may never run.
997
+ #
998
+ # `cancellation` is non-nil exactly when this request claimed the id above, so this also keeps `initialize`
999
+ # (which never registers) from evicting an in-flight registration under a reused id when the duplicate-`initialize`
1000
+ # refusal raises out of the handler.
1001
+ session&.unregister_in_flight(related_request_id, cancellation: cancellation) if related_request_id && cancellation
1002
+ end
925
1003
  end
926
1004
 
927
1005
  # Whether this request belongs to the modern lifecycle, used to refuse the RPCs SEP-2575 removed from it.
@@ -1026,7 +1104,7 @@ module MCP
1026
1104
  serialized = serialized.merge(requestState: @request_state_security.seal(
1027
1105
  serialized[:requestState],
1028
1106
  method: method,
1029
- target: mrtr_target(request),
1107
+ target: mrtr_target(request, method: method),
1030
1108
  arguments_digest: mrtr_arguments_digest(request),
1031
1109
  ))
1032
1110
  end
@@ -1048,7 +1126,7 @@ module MCP
1048
1126
  # re-runs with `inputResponses`/`requestState` merged into the original params - the same deterministic replay
1049
1127
  # contract the modern client driver follows. The `requestState` round-trips in-process as the raw value
1050
1128
  # the handler wrote; `RequestStateSecurity` sealing is wire hardening and does not apply.
1051
- def run_legacy_input_required_shim(result, instrumentation_data:, method:, params:, session:, related_request_id:, cancellation:)
1129
+ def run_legacy_input_required_shim(result, instrumentation_data:, method:, params:, session:, related_request_id:, cancellation:, auth_info:)
1052
1130
  rounds = 0
1053
1131
 
1054
1132
  loop do
@@ -1065,7 +1143,12 @@ module MCP
1065
1143
  )
1066
1144
  end
1067
1145
 
1146
+ # `handle_request` checks for cancellation only before the shim starts, so the shim checks again before each leg,
1147
+ # before re-running the handler, and before returning its result: a client's `notifications/cancelled` can arrive
1148
+ # after it answered a leg or while the handler re-runs. `CancelledError` reaches the rescue a cancelled nested
1149
+ # request does, which suppresses the response.
1068
1150
  responses = (result.input_requests || {}).each_with_object({}) do |(key, entry), collected|
1151
+ cancellation&.raise_if_cancelled!
1069
1152
  collected[key] = session.fulfill_input_request(
1070
1153
  entry[:method],
1071
1154
  legacy_leg_params(entry),
@@ -1077,6 +1160,7 @@ module MCP
1077
1160
  retry_params[:inputResponses] = responses unless responses.empty?
1078
1161
  retry_params[:requestState] = result.request_state if result.request_state
1079
1162
 
1163
+ cancellation&.raise_if_cancelled!
1080
1164
  result = redispatch_mrtr_method(
1081
1165
  method,
1082
1166
  retry_params,
@@ -1084,7 +1168,9 @@ module MCP
1084
1168
  session: session,
1085
1169
  related_request_id: related_request_id,
1086
1170
  cancellation: cancellation,
1171
+ auth_info: auth_info,
1087
1172
  )
1173
+ cancellation&.raise_if_cancelled!
1088
1174
  return result unless result.is_a?(InputRequiredResult)
1089
1175
 
1090
1176
  rounds += 1
@@ -1113,15 +1199,16 @@ module MCP
1113
1199
  end
1114
1200
 
1115
1201
  # Re-runs the handler of one of the three MRTR-capable methods for
1116
- # the legacy shim. Legacy wire, so no envelope is threaded.
1117
- def redispatch_mrtr_method(method, params, instrumentation_data:, session:, related_request_id:, cancellation:)
1202
+ # the legacy shim. Legacy wire, so no envelope is threaded. The access token is threaded: every round belongs to
1203
+ # the one authenticated request, so the handler sees the same `auth_info` on each.
1204
+ def redispatch_mrtr_method(method, params, instrumentation_data:, session:, related_request_id:, cancellation:, auth_info:)
1118
1205
  case method
1119
1206
  when Methods::TOOLS_CALL
1120
- call_tool(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation)
1207
+ call_tool(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, auth_info: auth_info)
1121
1208
  when Methods::PROMPTS_GET
1122
- get_prompt(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation)
1209
+ get_prompt(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, auth_info: auth_info)
1123
1210
  when Methods::RESOURCES_READ
1124
- contents = read_resource_contents(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation)
1211
+ contents = read_resource_contents(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, auth_info: auth_info)
1125
1212
  contents.is_a?(InputRequiredResult) ? contents : build_read_resource_result(contents)
1126
1213
  else
1127
1214
  raise RequestHandlerError.new(
@@ -1145,7 +1232,7 @@ module MCP
1145
1232
  plaintext = @request_state_security.unseal(
1146
1233
  sealed,
1147
1234
  method: method,
1148
- target: mrtr_target(params),
1235
+ target: mrtr_target(params, method: method),
1149
1236
  arguments_digest: mrtr_arguments_digest(params),
1150
1237
  )
1151
1238
  key = params.key?("requestState") ? "requestState" : :requestState
@@ -1160,10 +1247,14 @@ module MCP
1160
1247
  )
1161
1248
  end
1162
1249
 
1163
- def mrtr_target(params)
1250
+ # What a sealed state is bound to besides the method and the arguments: the resource URI of a `resources/read`,
1251
+ # the tool or prompt name otherwise. The member is fixed per method, so a `name` added to the `params` of
1252
+ # a `resources/read` cannot stand in for the URI and carry a state over to another resource.
1253
+ def mrtr_target(params, method:)
1164
1254
  return "" unless params.is_a?(Hash)
1165
1255
 
1166
- params[:name] || params["name"] || params[:uri] || params["uri"] || ""
1256
+ member = method == Methods::RESOURCES_READ ? "uri" : "name"
1257
+ params[member.to_sym] || params[member] || ""
1167
1258
  end
1168
1259
 
1169
1260
  # Digest of the originating arguments, binding a sealed state to retries of
@@ -1311,6 +1402,15 @@ module MCP
1311
1402
  meta.is_a?(Hash) ? { _meta: meta } : {}
1312
1403
  end
1313
1404
 
1405
+ # `tools/call`, `prompts/get` and `logging/setLevel` read named members of `params`. JSON-RPC also allows
1406
+ # an array there, and a request may leave `params` out, so neither is refused before it gets here;
1407
+ # without this check the first read raised and the client was answered Internal error for its own mistake.
1408
+ def validate_object_params!(params)
1409
+ return if params.is_a?(Hash)
1410
+
1411
+ raise RequestHandlerError.new("Invalid params", params, error_type: :invalid_params)
1412
+ end
1413
+
1314
1414
  def validate_initialize_params!(params)
1315
1415
  unless params.is_a?(Hash)
1316
1416
  raise RequestHandlerError.new("Invalid params", params, error_type: :invalid_params)
@@ -1407,23 +1507,79 @@ module MCP
1407
1507
  {}
1408
1508
  end
1409
1509
 
1410
- def list_tools(request)
1411
- page = paginate(@tools.values, cursor: cursor_from(request), page_size: @page_size, request: request, &:to_h)
1510
+ def list_tools(request, server_context: nil)
1511
+ tools = if @tools_list_handler
1512
+ invoke_tools_list_handler(request, server_context)
1513
+ else
1514
+ @tools.values
1515
+ end
1516
+
1517
+ page = paginate(tools, cursor: cursor_from(request), page_size: @page_size, request: request, &:to_h)
1412
1518
 
1413
1519
  apply_cache_metadata({ tools: page[:items], nextCursor: page[:next_cursor] }.compact)
1414
1520
  end
1415
1521
 
1416
- def call_tool(request, instrumentation_data:, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil)
1522
+ # Calls the `tools_list_handler` block, forwarding `server_context:` only when the block opts in
1523
+ # by declaring the keyword (the same rule `dispatch_optional_context_handler` applies).
1524
+ def invoke_tools_list_handler(request, server_context)
1525
+ if handler_declares_server_context?(@tools_list_handler)
1526
+ @tools_list_handler.call(request, server_context: server_context)
1527
+ else
1528
+ @tools_list_handler.call(request)
1529
+ end
1530
+ end
1531
+
1532
+ def resolve_tool(request, session:, related_request_id:, cancellation:, envelope:, auth_info:)
1533
+ return tools[request[:name]] unless @tools_list_handler
1534
+
1535
+ server_context = if handler_declares_server_context?(@tools_list_handler)
1536
+ build_server_context(
1537
+ request: request,
1538
+ session: session,
1539
+ related_request_id: related_request_id,
1540
+ cancellation: cancellation,
1541
+ envelope: envelope,
1542
+ auth_info: auth_info,
1543
+ )
1544
+ end
1545
+
1546
+ invoke_tools_list_handler(request, server_context).find { |tool| tool.name_value == request[:name] }
1547
+ end
1548
+
1549
+ def call_tool(request, instrumentation_data:, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil, tool_call_check: nil)
1417
1550
  tool_name = request[:name]
1418
1551
 
1419
- tool = tools[tool_name]
1552
+ tool = resolve_tool(request, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
1420
1553
  unless tool
1421
1554
  instrumentation_data.merge!(tool_name: tool_name, error: :tool_not_found)
1422
1555
 
1423
1556
  raise RequestHandlerError.new("Tool not found: #{tool_name}", request, error_type: :invalid_params)
1424
1557
  end
1425
1558
 
1426
- arguments = request[:arguments] || {}
1559
+ # The transport's check runs here, on the tool this very call resolved to, rather than on a lookup of its own:
1560
+ # with a `tools_list_handler`, a second resolution could see another context and answer for a schema the caller
1561
+ # was not served, or for a tool the caller cannot see. It comes after the lookup, so a tool that is not found
1562
+ # answers the same whatever the request carries, and before the arguments are examined or the tool runs.
1563
+ if tool_call_check && (mismatch = tool_call_check.call(tool, request))
1564
+ instrumentation_data.merge!(tool_name: tool_name)
1565
+
1566
+ raise RequestHandlerError.new(
1567
+ "Header mismatch: #{mismatch}",
1568
+ request,
1569
+ error_type: :invalid_request,
1570
+ error_code: ErrorCodes::HEADER_MISMATCH,
1571
+ )
1572
+ end
1573
+
1574
+ arguments = request[:arguments]
1575
+ unless arguments.nil? || arguments.is_a?(Hash)
1576
+ instrumentation_data.merge!(tool_name: tool_name, error: :invalid_params)
1577
+
1578
+ raise RequestHandlerError.new("Invalid arguments: expected an object", request, error_type: :invalid_params)
1579
+ end
1580
+
1581
+ arguments ||= {}
1582
+
1427
1583
  instrumentation_data.merge!(tool_name: tool_name, tool_arguments: arguments)
1428
1584
 
1429
1585
  if tool.input_schema&.missing_required_arguments?(arguments)
@@ -1512,6 +1668,12 @@ module MCP
1512
1668
  instrumentation_data.merge!(prompt_name: prompt_name)
1513
1669
 
1514
1670
  prompt_args = request[:arguments]
1671
+ unless prompt_args.nil? || prompt_args.is_a?(Hash)
1672
+ instrumentation_data.merge!(error: :invalid_params)
1673
+
1674
+ raise RequestHandlerError.new("Invalid arguments: expected an object", request, error_type: :invalid_params)
1675
+ end
1676
+
1515
1677
  prompt.validate_arguments!(prompt_args)
1516
1678
 
1517
1679
  server_context = build_server_context(
@@ -1988,10 +2150,33 @@ module MCP
1988
2150
  configuration.exception_reporter.call(exception, server_context)
1989
2151
  end
1990
2152
 
2153
+ # A cancelled request gets no response, so an error it raises once cancelled is reported but not answered.
2154
+ def cancelled_response(cancellation, instrumentation_data)
2155
+ instrumentation_data.merge!(cancelled: true, cancellation_reason: cancellation.reason)
2156
+ JsonRpcHandler::NO_RESPONSE
2157
+ end
2158
+
1991
2159
  def index_resources_by_uri(resources)
1992
2160
  resources.to_h { |resource| [resource.uri, resource] }
1993
2161
  end
1994
2162
 
2163
+ # A resource or a resource template serializes without the members it was not given, so one registered without
2164
+ # a member the spec requires would be listed without it, in a result a client has every reason to reject whole.
2165
+ # Refused where it is registered instead, and named by what it does have.
2166
+ def ensure_required_members!(definitions, *members)
2167
+ definitions.each do |definition|
2168
+ serialized = definition.to_h
2169
+ missing = members.select { |member| serialized[member].nil? }
2170
+ next if missing.empty?
2171
+
2172
+ kind = members.include?(:uriTemplate) ? "resource template" : "resource"
2173
+ known = serialized.slice(*members).values.first
2174
+ verb = missing.size == 1 ? "is" : "are"
2175
+
2176
+ raise ArgumentError, "A #{kind} must have #{members.join(" and ")}#{" (#{known})" if known}: #{missing.join(", ")} #{verb} missing."
2177
+ end
2178
+ end
2179
+
1995
2180
  def error_tool_response(text)
1996
2181
  Tool::Response.new(
1997
2182
  [{
@@ -2098,12 +2283,12 @@ module MCP
2098
2283
  end
2099
2284
 
2100
2285
  ref = params[:ref]
2101
- if ref.nil? || ref[:type].nil?
2286
+ if !ref.is_a?(Hash) || ref[:type].nil?
2102
2287
  raise RequestHandlerError.new("Missing or invalid ref", params, error_type: :invalid_params)
2103
2288
  end
2104
2289
 
2105
2290
  argument = params[:argument]
2106
- if argument.nil? || argument[:name].nil? || !argument.key?(:value)
2291
+ if !argument.is_a?(Hash) || argument[:name].nil? || !argument.key?(:value)
2107
2292
  raise RequestHandlerError.new("Missing argument name or value", params, error_type: :invalid_params)
2108
2293
  end
2109
2294
 
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "client_capabilities"
4
+
3
5
  module MCP
4
6
  class ServerContext
5
7
  attr_reader :cancellation
@@ -77,17 +79,16 @@ module MCP
77
79
  # Guards the current request on a declared client capability (SEP-2575). `path` names nested capability keys,
78
80
  # e.g. `require_client_capability!(:elicitation, :form)`. Raises `Server::MissingRequiredClientCapabilityError`
79
81
  # (JSON-RPC error `-32021` with `data: { requiredCapabilities: ... }`) when the capability was not declared.
82
+ # An elicitation mode is read as everywhere else: a declaration that names no mode, such as `elicitation: {}`, is form mode.
80
83
  def require_client_capability!(*path)
81
84
  raise ArgumentError, "at least one capability key is required" if path.empty?
82
85
 
83
- declared = client_capabilities
84
- value = path.reduce(declared) do |acc, key|
85
- break unless acc.is_a?(Hash)
86
-
87
- symbol_value = acc[key.to_sym]
88
- symbol_value.nil? ? acc[key.to_s] : symbol_value
86
+ declared = if path.size == 2 && path.first.to_sym == :elicitation
87
+ ClientCapabilities.elicitation?(client_capabilities, path.last.to_sym)
88
+ else
89
+ path.reduce(client_capabilities) { |capabilities, key| ClientCapabilities.value(capabilities, key) }
89
90
  end
90
- return unless value.nil?
91
+ return if declared
91
92
 
92
93
  required = path.reverse.inject({}) { |acc, key| { key.to_sym => acc } }
93
94
  raise Server::MissingRequiredClientCapabilityError, required
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "cancellation"
4
+ require_relative "client_capabilities"
4
5
  require_relative "methods"
5
6
 
6
7
  module MCP
@@ -27,8 +28,11 @@ module MCP
27
28
  @client_capabilities = nil
28
29
  @logging_message_notification = nil
29
30
  @protocol_version = nil
31
+ @incoming_cancelled = false
32
+ @incoming_cancel_reason = nil
30
33
  @in_flight = {}
31
34
  @in_flight_mutex = Mutex.new
35
+ @last_request_finished_at = nil
32
36
  @initialized = false
33
37
  end
34
38
 
@@ -63,18 +67,28 @@ module MCP
63
67
  # and `notifications/cancelled` back to the request that caused them, so a second live request under the same id
64
68
  # has no destination of its own. Rather than let the newcomer displace the registration, report the collision
65
69
  # and leave the first request intact; the caller turns that into an Invalid Request.
70
+ #
71
+ # Once `cancel_all_incoming` has run, the token comes back already cancelled with its reason and is not tracked:
72
+ # a transport can hand a request to a session it is ending, and that request must not outlive the session.
66
73
  def register_in_flight(request_id)
67
74
  return if request_id.nil?
68
75
 
69
76
  cancellation = Cancellation.new(request_id: request_id)
70
- registered = @in_flight_mutex.synchronize do
71
- next false if @in_flight.key?(request_id)
72
-
73
- @in_flight[request_id] = cancellation
74
- true
77
+ cancel_reason = nil
78
+ admission = @in_flight_mutex.synchronize do
79
+ if @incoming_cancelled
80
+ cancel_reason = @incoming_cancel_reason
81
+ :cancelled
82
+ elsif @in_flight.key?(request_id)
83
+ nil
84
+ else
85
+ @in_flight[request_id] = cancellation
86
+ :registered
87
+ end
75
88
  end
76
89
 
77
- registered ? cancellation : nil
90
+ cancellation.cancel(reason: cancel_reason) if admission == :cancelled
91
+ cancellation if admission
78
92
  end
79
93
 
80
94
  # Removes an in-flight registration. Passing the `Cancellation` that `register_in_flight` returned removes
@@ -85,10 +99,19 @@ module MCP
85
99
  @in_flight_mutex.synchronize do
86
100
  next if cancellation && !@in_flight[request_id].equal?(cancellation)
87
101
 
88
- @in_flight.delete(request_id)
102
+ @last_request_finished_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) if @in_flight.delete(request_id)
89
103
  end
90
104
  end
91
105
 
106
+ # What a transport needs to tell whether the session is idle, read in one step so the two cannot disagree:
107
+ # whether a request is still in flight, and the monotonic clock reading at which the last one finished
108
+ # (`nil` when none has).
109
+ #
110
+ # @api private
111
+ def in_flight_activity
112
+ @in_flight_mutex.synchronize { [!@in_flight.empty?, @last_request_finished_at] }
113
+ end
114
+
92
115
  # Whether `request_id` is currently in flight, so a transport can refuse a colliding request
93
116
  # before registering any state of its own for it.
94
117
  def in_flight?(request_id)
@@ -106,6 +129,29 @@ module MCP
106
129
  cancellation&.cancel(reason: reason)
107
130
  end
108
131
 
132
+ # Flips the `Cancellation` of every request still in flight, for a transport ending the session they belong to:
133
+ # their handlers observe it as they would `notifications/cancelled`, and their responses are suppressed the same way.
134
+ # Requests registered afterwards are cancelled as they register. The cancellations run outside the registry lock,
135
+ # since each fires its `on_cancel` hooks synchronously. One that raises does not keep the rest from being cancelled:
136
+ # the first error is raised once all of them are.
137
+ def cancel_all_incoming(reason: nil)
138
+ cancellations = @in_flight_mutex.synchronize do
139
+ @incoming_cancelled = true
140
+ @incoming_cancel_reason = reason
141
+ @in_flight.values
142
+ end
143
+
144
+ first_error = nil
145
+
146
+ cancellations.each do |cancellation|
147
+ cancellation.cancel(reason: reason)
148
+ rescue StandardError => e
149
+ first_error ||= e
150
+ end
151
+
152
+ raise first_error if first_error
153
+ end
154
+
109
155
  # Sends `notifications/cancelled` to the peer for a previously-issued request.
110
156
  # Also unblocks any transport-level `send_request` waiting on a response for `request_id`.
111
157
  def cancel_request(request_id:, reason: nil)
@@ -209,7 +255,13 @@ module MCP
209
255
  def create_form_elicitation(message:, requested_schema:, related_request_id: nil, timeout: nil)
210
256
  warn_unassociated_request(__method__, related_request_id)
211
257
 
212
- unless client_capabilities&.dig(:elicitation)
258
+ unless ClientCapabilities.elicitation?(client_capabilities, :form)
259
+ # A client that declared the capability without form mode is told which mode is missing.
260
+ if ClientCapabilities.value(client_capabilities, :elicitation).is_a?(Hash)
261
+ raise "Client does not support form mode elicitation. " \
262
+ "The client must declare the `elicitation.form` capability, or `elicitation` without a mode, during initialization."
263
+ end
264
+
213
265
  raise "Client does not support elicitation. " \
214
266
  "The client must declare the `elicitation` capability during initialization."
215
267
  end
@@ -231,7 +283,7 @@ module MCP
231
283
  def create_url_elicitation(message:, url:, elicitation_id:, related_request_id: nil, timeout: nil)
232
284
  warn_unassociated_request(__method__, related_request_id)
233
285
 
234
- unless client_capabilities&.dig(:elicitation, :url)
286
+ unless ClientCapabilities.elicitation?(client_capabilities, :url)
235
287
  raise "Client does not support URL mode elicitation. " \
236
288
  "The client must declare the `elicitation.url` capability during initialization."
237
289
  end