mcp 1.8.2 → 1.10.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
@@ -180,16 +180,31 @@ module MCP
180
180
  Methods::RESOURCES_LIST,
181
181
  Methods::RESOURCES_TEMPLATES_LIST,
182
182
  Methods::RESOURCES_READ,
183
+ # Both Skills results extend `CacheableResult`, so both carry the hints at 2026-07-28 (SEP-2640).
184
+ Methods::SKILLS_LIST,
185
+ Methods::SKILLS_GET,
183
186
  ].freeze
184
187
 
185
- attr_accessor :description, :name, :title, :version, :website_url, :instructions, :tools, :prompts, :resource_templates, :server_context, :configuration, :capabilities, :transport, :logging_message_notification
186
- attr_reader :icons, :resources, :page_size, :client_capabilities, :ttl_ms, :cache_scope, :request_state_security
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
190
+ # The skills registered with `skills:` as a frozen Array (an empty one when only `skills_handlers` configured
191
+ # the extension), or nil when the server serves no skills.
192
+ attr_reader :skills
187
193
 
188
194
  # Replaces the icons advertised in `serverInfo`; a Hash is converted through `Icon.from`.
189
195
  def icons=(value)
190
196
  @icons = Icon.from_list(value)
191
197
  end
192
198
 
199
+ # Replaces the capabilities (a Hash or an `MCP::Server::Capabilities` builder). The Skills extension rules
200
+ # are checked before the value is taken, as at construction: the extension may be declared only when skills
201
+ # are configured, `resources` must be declared alongside it, and `directoryRead` is not served.
202
+ def capabilities=(value)
203
+ candidate = normalize_capabilities(value)
204
+ validate_skills_capabilities!(candidate)
205
+ @capabilities = candidate
206
+ end
207
+
193
208
  def initialize(
194
209
  description: nil,
195
210
  icons: [],
@@ -202,6 +217,7 @@ module MCP
202
217
  prompts: [],
203
218
  resources: [],
204
219
  resource_templates: [],
220
+ skills: nil,
205
221
  server_context: nil,
206
222
  configuration: nil,
207
223
  capabilities: nil,
@@ -224,6 +240,17 @@ module MCP
224
240
  @prompts = prompts.to_h { |p| [p.name_value, p] }
225
241
  @resources = resources
226
242
  @resource_templates = resource_templates
243
+ # Skills (SEP-2640): `nil`, whether omitted or supplied, means the extension is not served; an empty Array
244
+ # serves an empty catalog. The file map of directory-backed skills is built once here and never changes.
245
+ @skills_configured = !skills.nil?
246
+ @skills = skills.nil? ? nil : normalize_skills!(skills)
247
+ @skills_index = (@skills || []).to_h { |skill| [skill.uri, skill] }
248
+ @skill_files = Skill.file_map(@skills || [])
249
+ @skill_file_roots = Skill.file_roots(@skills || [])
250
+ @skills_list_handler = nil
251
+ @skills_get_handler = nil
252
+ @skills_methods_registered = false
253
+ ensure_no_skill_file_collision!(resources.map(&:uri))
227
254
  @resource_index = index_resources_by_uri(resources)
228
255
  @resources_list_handler = nil
229
256
  @server_context = server_context
@@ -240,15 +267,12 @@ module MCP
240
267
  @configuration = MCP.configuration.merge(configuration)
241
268
  @client = nil
242
269
  @client_protocol_version = nil
270
+ # Accept either a plain Hash or an `MCP::Server::Capabilities` builder, normalized before `validate!`
271
+ # so the Skills extension rules see the final Hash.
272
+ @capabilities = normalize_capabilities(capabilities)
243
273
 
244
274
  validate!
245
275
 
246
- # Accept either a plain Hash or an `MCP::Server::Capabilities` builder.
247
- @capabilities = if capabilities.is_a?(Capabilities)
248
- capabilities.to_h
249
- else
250
- capabilities || default_capabilities
251
- end
252
276
  @client_capabilities = nil
253
277
  @logging_message_notification = nil
254
278
 
@@ -274,6 +298,7 @@ module MCP
274
298
  # The protocol's own request methods, as opposed to the notifications above and to custom methods
275
299
  # registered later: these need a request id to be run.
276
300
  @protocol_request_methods = @handlers.keys.reject { |name| Methods.notification?(name) }.freeze
301
+ register_skills_handlers! if @skills_configured
277
302
  @transport = transport
278
303
  end
279
304
 
@@ -332,6 +357,7 @@ module MCP
332
357
  mime_type: mime_type, annotations: annotations, size: size, meta: meta,
333
358
  &block
334
359
  )
360
+ ensure_no_skill_file_collision!([resource.uri])
335
361
  @resources << resource
336
362
  @resource_index[resource.uri] = resource
337
363
 
@@ -350,6 +376,7 @@ module MCP
350
376
  end
351
377
 
352
378
  def resources=(resources)
379
+ ensure_no_skill_file_collision!(resources.map(&:uri))
353
380
  @resources = resources
354
381
  @resource_index = index_resources_by_uri(resources)
355
382
  end
@@ -420,6 +447,13 @@ module MCP
420
447
  # Use stderr or OpenTelemetry instead.
421
448
  def notify_log_message(data:, level:, logger: nil)
422
449
  return unless @transport
450
+
451
+ if @transport.respond_to?(:logging_sessions) && (sessions = @transport.logging_sessions)
452
+ sessions.each do |session|
453
+ session.notify_log_message(data: data, level: level, logger: logger)
454
+ end
455
+ return
456
+ end
423
457
  return unless logging_message_notification&.should_notify?(level)
424
458
 
425
459
  params = { "data" => data, "level" => level }
@@ -468,6 +502,48 @@ module MCP
468
502
  @handlers[Methods::RESOURCES_READ] = block
469
503
  end
470
504
 
505
+ # Serves the Skills extension (SEP-2640) from per-request handlers instead of the `skills:` registry, for
506
+ # catalogs that depend on the caller. Both handlers are required because a server declaring the extension
507
+ # MUST answer `skills/get` for every skill it serves, listed or not.
508
+ #
509
+ # `list` receives the request params (and `server_context:` when it declares the keyword) and returns
510
+ # the whole collection of `MCP::Skill` in a stable order; the server paginates it. `get` returns the `MCP::Skill`
511
+ # for `params[:uri]`, or nil for `-32602`. A result that is not what these contracts describe is answered
512
+ # with `-32603`.
513
+ #
514
+ # A server serves skills from the `skills:` registry or from handlers, never both: a registered skill,
515
+ # its `SKILL.md` entry in `resources/list`, and its files are served to every caller, which a catalog that
516
+ # hides a skill from some callers must not inherit, so handlers are refused while the registry holds skills.
517
+ # With handlers the application serves the files itself and applies the same rule there, for example from
518
+ # `resources_read_handler` with `MCP::Skill.read_file(skills_for(server_context), params[:uri])`.
519
+ # A skill nested in the directory of another is served through the enclosing skill as well, whose manifest
520
+ # lists its files, so hiding it from a caller means withholding the enclosing skill too.
521
+ # What the handlers answer is never stamped `cacheScope: "public"`: where the `cache_scope` of the server
522
+ # would make it so, the result says `"private"`.
523
+ # Every check runs before anything is assigned, so a failure leaves the previous configuration in place.
524
+ def skills_handlers(list:, get:)
525
+ unless list.respond_to?(:call) && get.respond_to?(:call)
526
+ raise ArgumentError, "skills_handlers requires callable list: and get: handlers."
527
+ end
528
+ if @skills && !@skills.empty?
529
+ raise ArgumentError, "skills_handlers cannot be combined with skills in the skills: registry, which are served " \
530
+ "to every caller, files included. Return the skills from the handlers and serve their files yourself."
531
+ end
532
+
533
+ validate_skills_capabilities!(@capabilities, configured: true)
534
+ unless @skills_methods_registered
535
+ [Methods::SKILLS_LIST, Methods::SKILLS_GET].each do |method_name|
536
+ raise MethodAlreadyDefinedError, method_name if @handlers.key?(method_name)
537
+ end
538
+ end
539
+
540
+ @skills_list_handler = list
541
+ @skills_get_handler = get
542
+ @skills ||= [].freeze
543
+ @skills_configured = true
544
+ register_skills_handlers!
545
+ end
546
+
471
547
  # Sets a custom handler for `completion/complete` requests.
472
548
  # The block receives the parsed request params and should return completion values.
473
549
  #
@@ -574,6 +650,7 @@ module MCP
574
650
 
575
651
  def validate!
576
652
  validate_tool_name!
653
+ validate_skills_capabilities!(@capabilities)
577
654
 
578
655
  # NOTE: The draft protocol version is the next version after 2025-11-25.
579
656
  if @configuration.protocol_version <= "2025-06-18"
@@ -663,9 +740,9 @@ module MCP
663
740
 
664
741
  handler = @handlers[method]
665
742
  unless handler
666
- instrument_call("unsupported_method", server_context: { request: request }) do
743
+ instrument_call("unsupported_method", server_context: { request: request }) do |instrumentation_data|
667
744
  client = session&.client || @client
668
- add_instrumentation_data(client: client) if client
745
+ instrumentation_data.merge!(client: client) if client
669
746
  end
670
747
  return
671
748
  end
@@ -683,7 +760,8 @@ module MCP
683
760
  end
684
761
 
685
762
  begin
686
- Methods.ensure_capability!(method, capabilities)
763
+ # The same snapshot `initialize` and `server/discover` advertise, so dispatch cannot disagree with it.
764
+ Methods.ensure_capability!(method, effective_capabilities)
687
765
  rescue Methods::MissingRequiredCapabilityError => e
688
766
  # A method of a capability the server does not declare is one the server does not implement, so it is answered as Method not found,
689
767
  # which the TypeScript and Python servers return for a handler they never registered, and which the Streamable HTTP transport maps to
@@ -727,7 +805,8 @@ module MCP
727
805
  method,
728
806
  server_context: { request: request },
729
807
  exception_already_reported: ->(e) { reported_exception.equal?(e) },
730
- ) do
808
+ ) do |instrumentation_data|
809
+ refuse_non_object_meta!(params)
731
810
  envelope = lift_request_envelope(params, method: method, session: session)
732
811
 
733
812
  # The envelope's `logLevel` member replaces `logging/setLevel` in the modern lifecycle:
@@ -745,7 +824,7 @@ module MCP
745
824
  when Methods::INITIALIZE
746
825
  init(params, session: session)
747
826
  when Methods::RESOURCES_READ
748
- contents = read_resource_contents(params, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
827
+ contents = read_resource_contents(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
749
828
 
750
829
  # An SEP-2322 `input_required` result must not be wrapped as `contents` or stamped with SEP-2549 cache hints.
751
830
  contents.is_a?(InputRequiredResult) ? contents : build_read_resource_result(contents)
@@ -755,9 +834,9 @@ module MCP
755
834
 
756
835
  subscription_result(handler_result)
757
836
  when Methods::TOOLS_CALL
758
- call_tool(params, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
837
+ call_tool(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
759
838
  when Methods::PROMPTS_GET
760
- get_prompt(params, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
839
+ get_prompt(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
761
840
  when Methods::COMPLETION_COMPLETE
762
841
  complete(params, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
763
842
  when Methods::LOGGING_SET_LEVEL
@@ -766,10 +845,10 @@ module MCP
766
845
  dispatch_optional_context_handler(@handlers[method], params, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info)
767
846
  end
768
847
  client = session&.client || @client
769
- add_instrumentation_data(client: client) if client
848
+ instrumentation_data.merge!(client: client) if client
770
849
 
771
850
  if cancellation&.cancelled?
772
- add_instrumentation_data(cancelled: true, cancellation_reason: cancellation.reason)
851
+ instrumentation_data.merge!(cancelled: true, cancellation_reason: cancellation.reason)
773
852
  next JsonRpcHandler::NO_RESPONSE
774
853
  end
775
854
 
@@ -779,6 +858,7 @@ module MCP
779
858
  result = if envelope.nil? && @input_required_legacy_shim && session
780
859
  run_legacy_input_required_shim(
781
860
  result,
861
+ instrumentation_data: instrumentation_data,
782
862
  method: method,
783
863
  params: params,
784
864
  session: session,
@@ -786,7 +866,7 @@ module MCP
786
866
  cancellation: cancellation,
787
867
  )
788
868
  else
789
- serialize_input_required_result(result, envelope: envelope, request: params, method: method)
869
+ serialize_input_required_result(result, instrumentation_data: instrumentation_data, envelope: envelope, request: params, method: method)
790
870
  end
791
871
  end
792
872
 
@@ -812,25 +892,25 @@ module MCP
812
892
 
813
893
  result
814
894
  rescue CancelledError => e
815
- add_instrumentation_data(cancelled: true, cancellation_reason: e.reason)
895
+ instrumentation_data.merge!(cancelled: true, cancellation_reason: e.reason)
816
896
  next JsonRpcHandler::NO_RESPONSE
817
897
  rescue OAuth::InsufficientScopeError => e
818
898
  # A handler's `require_scopes!` failure is a client authorization error, not a server fault:
819
899
  # surface it as an invalid-request JSON-RPC error whose message names the missing scopes.
820
900
  # HTTP-level 403 challenges remain the transport `required_scopes` gate's job.
821
901
  report_exception(e, { request: request })
822
- add_instrumentation_data(error: :insufficient_scope)
902
+ instrumentation_data.merge!(error: :insufficient_scope)
823
903
  converted = RequestHandlerError.new(e.message, request, error_type: :invalid_request, original_error: e)
824
904
  reported_exception = converted
825
905
  raise converted
826
906
  rescue RequestHandlerError => e
827
907
  report_exception(e.original_error || e, { request: request })
828
- add_instrumentation_data(error: e.error_type)
908
+ instrumentation_data.merge!(error: e.error_type)
829
909
  reported_exception = e
830
910
  raise e
831
911
  rescue => e
832
912
  report_exception(e, { request: request })
833
- add_instrumentation_data(error: :internal_error)
913
+ instrumentation_data.merge!(error: :internal_error)
834
914
  wrapped = RequestHandlerError.new("Internal error handling #{method} request", request, original_error: e)
835
915
  reported_exception = wrapped
836
916
  raise wrapped
@@ -860,6 +940,26 @@ module MCP
860
940
  RequestEnvelope.modern?(request.is_a?(Hash) ? request[:params] : nil)
861
941
  end
862
942
 
943
+ # `_meta` is an object on every request (`MetaObject`); a String, Array, or number there carries no envelope,
944
+ # no progress token, and no trace context, and the TypeScript and Python servers refuse it as invalid params on
945
+ # both lifecycles. Refused before the envelope is read and before any handler can meet it in `server_context`.
946
+ # `null` reads as absent, as it does for the Python server.
947
+ def refuse_non_object_meta!(params)
948
+ return unless params.is_a?(Hash)
949
+
950
+ # Read as `RequestEnvelope` reads it, so the two cannot disagree on a Hash holding both key spellings.
951
+ meta = params[:_meta]
952
+ meta = params["_meta"] if meta.nil?
953
+ return if meta.nil? || meta.is_a?(Hash)
954
+
955
+ raise RequestHandlerError.new(
956
+ "Invalid params: _meta must be an object",
957
+ params,
958
+ error_type: :invalid_params,
959
+ error_code: JsonRpcHandler::ErrorCode::INVALID_PARAMS,
960
+ )
961
+ end
962
+
863
963
  # Lifts the SEP-2575 per-request `_meta` envelope for modern requests. Only a request whose `_meta` carries
864
964
  # the full required triple is classified as modern; a partial triple keeps flowing through the legacy path untouched.
865
965
  # Notifications carry no envelope (their `_meta` is a `NotificationMetaObject`), and `server/discover` is
@@ -906,7 +1006,7 @@ module MCP
906
1006
  # a final result. The capability gate enforces the SEP-2575 rule that servers MUST NOT rely on
907
1007
  # (or embed requests for) capabilities the client did not declare, and reports every missing capability at
908
1008
  # once so the client sees the full set.
909
- def serialize_input_required_result(result, envelope:, request:, method:)
1009
+ def serialize_input_required_result(result, instrumentation_data:, envelope:, request:, method:)
910
1010
  if envelope.nil?
911
1011
  raise RequestHandlerError.new(
912
1012
  "input_required results require the 2026-07-28 stateless lifecycle (SEP-2322)",
@@ -918,7 +1018,7 @@ module MCP
918
1018
  missing = result.missing_client_capabilities(envelope.client_capabilities)
919
1019
  raise MissingRequiredClientCapabilityError.new(missing, request) unless missing.empty?
920
1020
 
921
- add_instrumentation_data(input_required: true)
1021
+ instrumentation_data.merge!(input_required: true)
922
1022
  serialized = result.to_h
923
1023
 
924
1024
  if @request_state_security && serialized[:requestState]
@@ -947,7 +1047,7 @@ module MCP
947
1047
  # re-runs with `inputResponses`/`requestState` merged into the original params - the same deterministic replay
948
1048
  # contract the modern client driver follows. The `requestState` round-trips in-process as the raw value
949
1049
  # the handler wrote; `RequestStateSecurity` sealing is wire hardening and does not apply.
950
- def run_legacy_input_required_shim(result, method:, params:, session:, related_request_id:, cancellation:)
1050
+ def run_legacy_input_required_shim(result, instrumentation_data:, method:, params:, session:, related_request_id:, cancellation:)
951
1051
  rounds = 0
952
1052
 
953
1053
  loop do
@@ -979,6 +1079,7 @@ module MCP
979
1079
  result = redispatch_mrtr_method(
980
1080
  method,
981
1081
  retry_params,
1082
+ instrumentation_data: instrumentation_data,
982
1083
  session: session,
983
1084
  related_request_id: related_request_id,
984
1085
  cancellation: cancellation,
@@ -1012,14 +1113,14 @@ module MCP
1012
1113
 
1013
1114
  # Re-runs the handler of one of the three MRTR-capable methods for
1014
1115
  # the legacy shim. Legacy wire, so no envelope is threaded.
1015
- def redispatch_mrtr_method(method, params, session:, related_request_id:, cancellation:)
1116
+ def redispatch_mrtr_method(method, params, instrumentation_data:, session:, related_request_id:, cancellation:)
1016
1117
  case method
1017
1118
  when Methods::TOOLS_CALL
1018
- call_tool(params, session: session, related_request_id: related_request_id, cancellation: cancellation)
1119
+ call_tool(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation)
1019
1120
  when Methods::PROMPTS_GET
1020
- get_prompt(params, session: session, related_request_id: related_request_id, cancellation: cancellation)
1121
+ get_prompt(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation)
1021
1122
  when Methods::RESOURCES_READ
1022
- contents = read_resource_contents(params, session: session, related_request_id: related_request_id, cancellation: cancellation)
1123
+ contents = read_resource_contents(params, instrumentation_data: instrumentation_data, session: session, related_request_id: related_request_id, cancellation: cancellation)
1023
1124
  contents.is_a?(InputRequiredResult) ? contents : build_read_resource_result(contents)
1024
1125
  else
1025
1126
  raise RequestHandlerError.new(
@@ -1254,18 +1355,20 @@ module MCP
1254
1355
  # promise delivery over `subscriptions/listen` streams, so they are stripped when the transport does not serve that RPC
1255
1356
  # (e.g. stdio), matching the Python SDK's era-aware capability derivation.
1256
1357
  def discover_capabilities
1257
- return capabilities if @transport.respond_to?(:serves_subscriptions_listen?) && @transport.serves_subscriptions_listen?
1358
+ advertised = effective_capabilities
1359
+ return advertised if @transport.respond_to?(:serves_subscriptions_listen?) && @transport.serves_subscriptions_listen?
1258
1360
 
1259
- without_notification_flags(capabilities)
1361
+ without_notification_flags(advertised)
1260
1362
  end
1261
1363
 
1262
1364
  # Capabilities as advertised by `initialize`. A transport that delivers no notifications to its sessions
1263
1365
  # (stateless Streamable HTTP) cannot keep the promise the `listChanged` and `subscribe` flags make, so they are
1264
1366
  # left out, as `server/discover` leaves them out when `subscriptions/listen` is not served.
1265
1367
  def handshake_capabilities
1266
- return capabilities unless @transport.respond_to?(:delivers_notifications?) && !@transport.delivers_notifications?
1368
+ advertised = effective_capabilities
1369
+ return advertised unless @transport.respond_to?(:delivers_notifications?) && !@transport.delivers_notifications?
1267
1370
 
1268
- without_notification_flags(capabilities)
1371
+ without_notification_flags(advertised)
1269
1372
  end
1270
1373
 
1271
1374
  def without_notification_flags(capabilities)
@@ -1288,8 +1391,11 @@ module MCP
1288
1391
  raise RequestHandlerError.new("Invalid log level #{request[:level]}", request, error_type: :invalid_params)
1289
1392
  end
1290
1393
 
1291
- session&.configure_logging(logging_message_notification)
1292
- @logging_message_notification = logging_message_notification
1394
+ if session
1395
+ session.configure_logging(logging_message_notification)
1396
+ else
1397
+ @logging_message_notification = logging_message_notification
1398
+ end
1293
1399
 
1294
1400
  {}
1295
1401
  end
@@ -1300,21 +1406,21 @@ module MCP
1300
1406
  apply_cache_metadata({ tools: page[:items], nextCursor: page[:next_cursor] }.compact)
1301
1407
  end
1302
1408
 
1303
- def call_tool(request, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil)
1409
+ def call_tool(request, instrumentation_data:, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil)
1304
1410
  tool_name = request[:name]
1305
1411
 
1306
1412
  tool = tools[tool_name]
1307
1413
  unless tool
1308
- add_instrumentation_data(tool_name: tool_name, error: :tool_not_found)
1414
+ instrumentation_data.merge!(tool_name: tool_name, error: :tool_not_found)
1309
1415
 
1310
1416
  raise RequestHandlerError.new("Tool not found: #{tool_name}", request, error_type: :invalid_params)
1311
1417
  end
1312
1418
 
1313
1419
  arguments = request[:arguments] || {}
1314
- add_instrumentation_data(tool_name: tool_name, tool_arguments: arguments)
1420
+ instrumentation_data.merge!(tool_name: tool_name, tool_arguments: arguments)
1315
1421
 
1316
1422
  if tool.input_schema&.missing_required_arguments?(arguments)
1317
- add_instrumentation_data(error: :missing_required_arguments)
1423
+ instrumentation_data.merge!(error: :missing_required_arguments)
1318
1424
 
1319
1425
  missing = tool.input_schema.missing_required_arguments(arguments).join(", ")
1320
1426
  return error_tool_response("Missing required arguments: #{missing}")
@@ -1324,13 +1430,13 @@ module MCP
1324
1430
  begin
1325
1431
  tool.input_schema.validate_arguments(arguments)
1326
1432
  rescue Tool::InputSchema::ValidationError => e
1327
- add_instrumentation_data(error: :invalid_schema)
1433
+ instrumentation_data.merge!(error: :invalid_schema)
1328
1434
 
1329
1435
  return error_tool_response(e.message)
1330
1436
  end
1331
1437
  end
1332
1438
 
1333
- progress_token = request.dig(:_meta, :progressToken)
1439
+ progress_token = request.dig(:_meta, :progressToken) if request[:_meta].is_a?(Hash)
1334
1440
 
1335
1441
  response = call_tool_with_args(
1336
1442
  tool,
@@ -1379,11 +1485,11 @@ module MCP
1379
1485
  apply_cache_metadata({ prompts: page[:items], nextCursor: page[:next_cursor] }.compact)
1380
1486
  end
1381
1487
 
1382
- def get_prompt(request, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil)
1488
+ def get_prompt(request, instrumentation_data:, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil)
1383
1489
  prompt_name = request[:name]
1384
1490
  prompt = @prompts[prompt_name]
1385
1491
  unless prompt
1386
- add_instrumentation_data(error: :prompt_not_found)
1492
+ instrumentation_data.merge!(error: :prompt_not_found)
1387
1493
  # The explicit `error_code` maps an unknown prompt to Invalid Params (-32602) rather than
1388
1494
  # the default Internal Error (-32603), matching the `tools/call`, `resources/read`, and
1389
1495
  # `completion/complete` siblings for the same not-found condition, while `error_type:
@@ -1396,7 +1502,7 @@ module MCP
1396
1502
  )
1397
1503
  end
1398
1504
 
1399
- add_instrumentation_data(prompt_name: prompt_name)
1505
+ instrumentation_data.merge!(prompt_name: prompt_name)
1400
1506
 
1401
1507
  prompt_args = request[:arguments]
1402
1508
  prompt.validate_arguments!(prompt_args)
@@ -1417,7 +1523,7 @@ module MCP
1417
1523
  resources = if @resources_list_handler
1418
1524
  invoke_resources_list_handler(request, server_context)
1419
1525
  else
1420
- @resources
1526
+ @resources + skill_manifest_resources
1421
1527
  end
1422
1528
 
1423
1529
  page = paginate(resources, cursor: cursor_from(request), page_size: @page_size, request: request, &:to_h)
@@ -1425,6 +1531,17 @@ module MCP
1425
1531
  apply_cache_metadata({ resources: page[:items], nextCursor: page[:next_cursor] }.compact)
1426
1532
  end
1427
1533
 
1534
+ # The `SKILL.md` of every registered skill as a resource entry, with `name` and `description` taken from
1535
+ # the frontmatter and `text/markdown`, as the Skills extension asks of a `SKILL.md` resource; a resource
1536
+ # the application registered at that URI takes its place.
1537
+ def skill_manifest_resources
1538
+ return [] if @skills.nil? || @skills.empty?
1539
+
1540
+ @skills.reject { |skill| @resource_index.key?(skill.uri) }.map do |skill|
1541
+ Resource.new(uri: skill.uri, name: skill.name, description: skill.frontmatter["description"], mime_type: "text/markdown")
1542
+ end
1543
+ end
1544
+
1428
1545
  # Calls the `resources_list_handler` block, forwarding `server_context:` only when the block opts in
1429
1546
  # by declaring the keyword (the same rule `dispatch_optional_context_handler` applies).
1430
1547
  def invoke_resources_list_handler(request, server_context)
@@ -1435,25 +1552,265 @@ module MCP
1435
1552
  end
1436
1553
  end
1437
1554
 
1555
+ # `skills/list` (SEP-2640): the registry, or the `list` handler's collection, paginated like `resources/list`.
1556
+ def list_skills(request, server_context: nil)
1557
+ skills = if @skills_list_handler
1558
+ result = invoke_skills_handler(@skills_list_handler, request, server_context)
1559
+ problem = skills_problem(result)
1560
+ raise invalid_skills_result(request, problem) if problem
1561
+
1562
+ result
1563
+ else
1564
+ @skills
1565
+ end
1566
+
1567
+ page = paginate(skills, cursor: cursor_from(request), page_size: @page_size, request: request, &:to_h)
1568
+
1569
+ apply_skills_cache_metadata({ skills: page[:items], nextCursor: page[:next_cursor] }.compact, @skills_list_handler)
1570
+ end
1571
+
1572
+ # `skills/get` (SEP-2640): answers for every skill the server serves, listed or not. The URI shape is checked
1573
+ # before any handler runs; a `get` handler's result must be the skill for exactly that URI.
1574
+ def get_skill(request, server_context: nil)
1575
+ # Absent, null, or Array params reach here through the generic JSON-RPC validation.
1576
+ uri = request.is_a?(Hash) ? request[:uri] : nil
1577
+ unless Skill::Uri.manifest_uri?(uri)
1578
+ raise RequestHandlerError.new(
1579
+ "Invalid params: uri is not a skill SKILL.md URI",
1580
+ request,
1581
+ error_type: :invalid_params,
1582
+ error_code: JsonRpcHandler::ErrorCode::INVALID_PARAMS,
1583
+ error_data: refused_uri_data(uri),
1584
+ )
1585
+ end
1586
+
1587
+ skill = if @skills_get_handler
1588
+ result = invoke_skills_handler(@skills_get_handler, request, server_context)
1589
+ unless result.nil?
1590
+ raise invalid_skills_result(request, "skills/get returned #{result.class}") unless result.is_a?(Skill)
1591
+ raise invalid_skills_result(request, "skills/get returned #{result.uri.dump} for #{uri.dump}") unless result.uri == uri
1592
+
1593
+ problem = skills_problem([result])
1594
+ raise invalid_skills_result(request, problem) if problem
1595
+ end
1596
+ result
1597
+ else
1598
+ @skills_index[uri]
1599
+ end
1600
+
1601
+ if skill.nil?
1602
+ raise RequestHandlerError.new(
1603
+ "Skill not found: #{uri.dump}",
1604
+ request,
1605
+ error_type: :invalid_params,
1606
+ error_code: JsonRpcHandler::ErrorCode::INVALID_PARAMS,
1607
+ error_data: refused_uri_data(uri),
1608
+ )
1609
+ end
1610
+
1611
+ apply_skills_cache_metadata({ skill: skill.to_h }, @skills_get_handler)
1612
+ end
1613
+
1614
+ # A handler answers per caller and, returning skills, has no result of its own to carry a scope in,
1615
+ # so what it answered is never marked for shared caches, whatever scope the server was configured with.
1616
+ def apply_skills_cache_metadata(result, handler)
1617
+ stamped = apply_cache_metadata(result)
1618
+ return stamped unless handler && stamped[:cacheScope] == "public"
1619
+
1620
+ stamped.merge(cacheScope: "private")
1621
+ end
1622
+
1623
+ def invoke_skills_handler(handler, request, server_context)
1624
+ if handler_declares_server_context?(handler)
1625
+ handler.call(request, server_context: server_context)
1626
+ else
1627
+ handler.call(request)
1628
+ end
1629
+ end
1630
+
1631
+ # The wire sees one fixed message; what was wrong goes to the exception reporter only.
1632
+ def invalid_skills_result(request, problem)
1633
+ RequestHandlerError.new(
1634
+ "Skills handler returned an invalid result",
1635
+ request,
1636
+ error_type: :internal_error,
1637
+ error_code: JsonRpcHandler::ErrorCode::INTERNAL_ERROR,
1638
+ original_error: StandardError.new(problem),
1639
+ )
1640
+ end
1641
+
1642
+ # Describes the first problem in a set of skills served together, or returns nil: every element
1643
+ # an `MCP::Skill` and URIs unique. A skill may list any file under its own root, a nested skill's files
1644
+ # included, because the specification wants the enclosing manifest complete.
1645
+ def skills_problem(skills)
1646
+ unless skills.is_a?(Array) && skills.all? { |skill| skill.is_a?(Skill) }
1647
+ return "skills must be an Array of MCP::Skill (got #{skills.class})"
1648
+ end
1649
+
1650
+ registered = {}
1651
+ skills.each do |skill|
1652
+ return "skill #{skill.uri} is listed twice" if registered.key?(skill.uri)
1653
+
1654
+ registered[skill.uri] = true
1655
+ end
1656
+
1657
+ nil
1658
+ end
1659
+
1660
+ def normalize_skills!(skills)
1661
+ problem = skills_problem(skills)
1662
+ raise ArgumentError, "skills: #{problem}." if problem
1663
+
1664
+ skills.dup.freeze
1665
+ end
1666
+
1667
+ def register_skills_handlers!
1668
+ return if @skills_methods_registered
1669
+
1670
+ [Methods::SKILLS_LIST, Methods::SKILLS_GET].each do |method_name|
1671
+ raise MethodAlreadyDefinedError, method_name if @handlers.key?(method_name)
1672
+ end
1673
+ @handlers[Methods::SKILLS_LIST] = method(:list_skills)
1674
+ @handlers[Methods::SKILLS_GET] = method(:get_skill)
1675
+ # Request methods of the extension, so like the protocol's own they are not run without an id; added here
1676
+ # rather than at construction because `skills_handlers` registers them later.
1677
+ @protocol_request_methods = (@protocol_request_methods + [Methods::SKILLS_LIST, Methods::SKILLS_GET]).freeze
1678
+ @skills_methods_registered = true
1679
+ end
1680
+
1681
+ # A file of a directory-backed skill is served ahead of any resource with the same URI, so registering such
1682
+ # a resource would be silently shadowed; it is refused before anything is committed.
1683
+ def ensure_no_skill_file_collision!(uris)
1684
+ uris.each do |uri|
1685
+ next unless @skill_files.key?(uri)
1686
+
1687
+ raise ArgumentError, "Resource URI #{uri} is a file of a directory-backed skill and cannot be registered as a resource."
1688
+ end
1689
+ end
1690
+
1691
+ def normalize_capabilities(value)
1692
+ case value
1693
+ when Capabilities then value.to_h
1694
+ when nil then default_capabilities
1695
+ when Hash then value
1696
+ else raise ArgumentError, "capabilities must be a Hash or an MCP::Server::Capabilities (got #{value.class})."
1697
+ end
1698
+ end
1699
+
1700
+ # The capabilities a client sees in `initialize` and `server/discover`, and that dispatch gates on. The Skills
1701
+ # entry is computed from the configured state rather than read from the stored Hash, which the public reader
1702
+ # exposes for in-place mutation: when skills are configured the extension is advertised with `directoryRead`
1703
+ # removed (nothing serves it) and `resources` is ensured, when they are not it is absent. Only the nested
1704
+ # structures being modified are copied; the stored Hash is left as it is.
1705
+ def effective_capabilities
1706
+ base = @capabilities
1707
+ extensions = declared_extensions(base)
1708
+ declared_keys = skills_extension_keys(extensions)
1709
+ unless @skills_configured
1710
+ return base if declared_keys.empty?
1711
+
1712
+ stripped = extensions.reject { |key, _| declared_keys.include?(key) }
1713
+ snapshot = base.dup
1714
+ snapshot.delete(:extensions)
1715
+ snapshot.delete("extensions")
1716
+ snapshot[:extensions] = stripped unless stripped.empty?
1717
+ return snapshot
1718
+ end
1719
+
1720
+ settings = declared_keys.map { |key| extensions[key] }.find { |value| value.is_a?(Hash) } || {}
1721
+ settings = settings.reject { |key, _| key.to_s == "directoryRead" }
1722
+ others = extensions.reject { |key, _| declared_keys.include?(key) }
1723
+ snapshot = base.dup
1724
+ snapshot.delete("extensions")
1725
+ snapshot[:extensions] = others.merge(Skill::EXTENSION_ID => settings)
1726
+ # One `resources` key, so a second spelling cannot serialize after it and undo the declaration.
1727
+ resources = capability_member(snapshot, :resources)
1728
+ snapshot.delete("resources")
1729
+ snapshot[:resources] = resources.is_a?(Hash) ? resources : {}
1730
+ snapshot
1731
+ end
1732
+
1733
+ # The Skills extension rules for an explicitly supplied capabilities Hash (SEP-2640): the extension is declared
1734
+ # only when skills are configured, its settings are a Hash without `directoryRead`, and `resources` is declared
1735
+ # alongside it. Both key spellings are read, because JSON serialization erases the difference between
1736
+ # `:extensions` and `"extensions"` or between a Symbol and a String extension identifier.
1737
+ # Checked at construction, on `capabilities=`, and when handlers are installed.
1738
+ def validate_skills_capabilities!(caps, configured: @skills_configured)
1739
+ extensions = declared_extensions(caps)
1740
+ declared_keys = skills_extension_keys(extensions)
1741
+
1742
+ if !declared_keys.empty? && !configured
1743
+ raise ArgumentError, "capabilities declare #{Skill::EXTENSION_ID} but no skills are configured; " \
1744
+ "pass skills: (an empty Array serves an empty catalog) or call skills_handlers."
1745
+ end
1746
+
1747
+ declared_keys.each do |key|
1748
+ settings = extensions[key]
1749
+ unless settings.is_a?(Hash)
1750
+ raise ArgumentError, "The #{Skill::EXTENSION_ID} capability must be a Hash (got #{settings.class})."
1751
+ end
1752
+ if settings.any? { |name, value| name.to_s == "directoryRead" && value }
1753
+ raise ArgumentError, "directoryRead is not served by this release; do not declare it under #{Skill::EXTENSION_ID}."
1754
+ end
1755
+ end
1756
+
1757
+ if configured && !capability_member(caps, :resources).is_a?(Hash)
1758
+ raise ArgumentError, "SEP-2640 requires the resources capability alongside #{Skill::EXTENSION_ID}; declare resources too."
1759
+ end
1760
+ end
1761
+
1762
+ def capability_member(caps, name)
1763
+ value = caps[name]
1764
+ value.nil? ? caps[name.to_s] : value
1765
+ end
1766
+
1767
+ # The `extensions` declarations under both key spellings merged into one Hash (empty when there are none),
1768
+ # so a Skills declaration is found whichever spelling holds it and the other extensions survive the rewrite.
1769
+ def declared_extensions(caps)
1770
+ [caps[:extensions], caps["extensions"]].grep(Hash).reduce({}, :merge)
1771
+ end
1772
+
1773
+ # Every key of an `extensions` Hash that spells the Skills extension identifier, as a String or a Symbol.
1774
+ def skills_extension_keys(extensions)
1775
+ extensions.keys.select { |key| key.to_s == Skill::EXTENSION_ID }
1776
+ end
1777
+
1438
1778
  # Default `resources/read` handler: routes to class-based resources and resource templates.
1439
1779
  # Fully replaced when `resources_read_handler` is set. When no class-based resource or template is registered,
1440
1780
  # unknown URIs keep the historical no-op `[]` response instead of raising.
1441
- def read_resource(request, server_context: nil)
1781
+ def read_resource(request, instrumentation_data:, server_context: nil)
1442
1782
  uri = request[:uri]
1443
- add_instrumentation_data(resource_uri: uri)
1783
+ instrumentation_data.merge!(resource_uri: uri)
1784
+
1785
+ # Files of directory-backed skills are looked up by exact string equality in a map built at construction,
1786
+ # so request data never reaches the filesystem; a miss falls through to the routing below.
1787
+ record = @skill_files[uri]
1788
+ return Skill.read_record(record, request) if record
1444
1789
 
1445
1790
  resource = @resource_index[uri]
1446
1791
  if resource.is_a?(Class)
1447
1792
  return normalize_resource_contents(call_resource_contents(resource, server_context))
1448
1793
  end
1449
1794
 
1795
+ # A URI under a directory-backed skill that names none of its files: the manifest is complete, so the file
1796
+ # is not served, and the Skills extension asks for `-32602` where the base reader keeps its `[]`.
1797
+ if resource.nil? && uri.is_a?(String) && @skill_file_roots.any? { |root| Skill::Uri.under?(uri, root) }
1798
+ raise RequestHandlerError.new(
1799
+ "Skill file not found: #{uri.dump}",
1800
+ request,
1801
+ error_type: :invalid_params,
1802
+ error_code: JsonRpcHandler::ErrorCode::INVALID_PARAMS,
1803
+ error_data: refused_uri_data(uri),
1804
+ )
1805
+ end
1806
+
1450
1807
  @resource_templates.each do |template|
1451
1808
  next unless template.is_a?(Class)
1452
1809
 
1453
1810
  params = template.match_uri(uri)
1454
1811
  next unless params
1455
1812
 
1456
- add_instrumentation_data(resource_template: template.uri_template)
1813
+ instrumentation_data.merge!(resource_template: template.uri_template)
1457
1814
  return normalize_resource_contents(call_template_contents(template, params, server_context))
1458
1815
  end
1459
1816
 
@@ -1539,9 +1896,22 @@ module MCP
1539
1896
  # Invokes `resources/read` via the registered handler. If the handler block opts in to `server_context:`,
1540
1897
  # pass an `MCP::ServerContext` so the handler can observe cancellation via `server_context.cancelled?` or
1541
1898
  # `server_context.raise_if_cancelled!`.
1542
- def read_resource_contents(request, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil)
1899
+ def read_resource_contents(request, instrumentation_data:, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil)
1900
+ handler = @handlers[Methods::RESOURCES_READ]
1901
+ if handler == method(:read_resource)
1902
+ server_context = build_server_context(
1903
+ request: request,
1904
+ session: session,
1905
+ related_request_id: related_request_id,
1906
+ cancellation: cancellation,
1907
+ envelope: envelope,
1908
+ auth_info: auth_info,
1909
+ )
1910
+ return read_resource(request, instrumentation_data: instrumentation_data, server_context: server_context)
1911
+ end
1912
+
1543
1913
  dispatch_optional_context_handler(
1544
- @handlers[Methods::RESOURCES_READ],
1914
+ handler,
1545
1915
  request,
1546
1916
  session: session,
1547
1917
  related_request_id: related_request_id,
@@ -1591,7 +1961,7 @@ module MCP
1591
1961
  # (progress, cancellation, nested server-to-client requests).
1592
1962
  def build_server_context(request:, session:, related_request_id:, cancellation:, envelope: nil, auth_info: nil)
1593
1963
  meta_source = request.is_a?(Hash) ? request : {}
1594
- progress_token = meta_source.dig(:_meta, :progressToken)
1964
+ progress_token = meta_source.dig(:_meta, :progressToken) if meta_source[:_meta].is_a?(Hash)
1595
1965
  progress = Progress.new(notification_target: session, progress_token: progress_token, related_request_id: related_request_id)
1596
1966
  retry_fields = mrtr_retry_fields(meta_source)
1597
1967
  ServerContext.new(
@@ -1765,5 +2135,15 @@ module MCP
1765
2135
 
1766
2136
  { completion: { values: values, total: total, hasMore: has_more }.compact }
1767
2137
  end
2138
+
2139
+ # The error data of a Skills refusal: the request URI when it is a String, read as UTF-8 with its invalid bytes
2140
+ # replaced, so that the response can be generated whatever bytes the request held; nothing for another value,
2141
+ # which could hold such bytes anywhere, so the data falls back to the message. The messages quote the URI with
2142
+ # `dump` for the same reason, and so that the exception reporter gets one printable line.
2143
+ def refused_uri_data(uri)
2144
+ return unless uri.is_a?(String)
2145
+
2146
+ { uri: uri.dup.force_encoding(Encoding::UTF_8).scrub }
2147
+ end
1768
2148
  end
1769
2149
  end