mcp 1.12.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.
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../client_capabilities"
3
4
  require_relative "../methods"
4
5
  require_relative "../result_type"
5
6
 
@@ -116,9 +117,9 @@ module MCP
116
117
  # (symbol/string tolerant on the declared side).
117
118
  def missing_subtree(required, declared)
118
119
  required.each_with_object({}) do |(name, nested), missing|
119
- declared_value = read_key(declared, name)
120
+ declared_value = ClientCapabilities.value(declared, name)
120
121
 
121
- if declared_value.nil?
122
+ if !declared_value
122
123
  missing[name] = nested
123
124
  elsif nested.is_a?(Hash) && !nested.empty?
124
125
  nested_missing = missing_subtree(nested, declared_value)
@@ -134,21 +135,12 @@ module MCP
134
135
  elicitation_missing = missing[:elicitation]
135
136
  return missing unless elicitation_missing.is_a?(Hash) && elicitation_missing.key?(:form)
136
137
 
137
- declared_elicitation = read_key(declared, :elicitation)
138
- return missing unless declared_elicitation.is_a?(Hash)
139
- return missing unless read_key(declared_elicitation, :url).nil?
138
+ return missing unless ClientCapabilities.elicitation?(declared, :form)
140
139
 
141
140
  pruned = elicitation_missing.reject { |key, _| key == :form }
142
141
  pruned.empty? ? missing.reject { |key, _| key == :elicitation } : missing.merge(elicitation: pruned)
143
142
  end
144
143
 
145
- def read_key(hash, key)
146
- return unless hash.is_a?(Hash)
147
-
148
- value = hash[key.to_sym]
149
- value.nil? ? hash[key.to_s] : value
150
- end
151
-
152
144
  def deep_merge(left, right)
153
145
  left.merge(right) do |_key, left_value, right_value|
154
146
  if left_value.is_a?(Hash) && right_value.is_a?(Hash)
@@ -87,6 +87,12 @@ module MCP
87
87
  access_token
88
88
  end
89
89
 
90
+ # The default `inspect` would print the `client_secret` this verifier authenticates to the introspection endpoint with.
91
+ def inspect
92
+ "#<#{self.class.name} introspection_endpoint=#{@introspection_endpoint.inspect} client_id=#{@client_id.inspect} " \
93
+ "client_secret=#{@client_secret.nil? ? "nil" : "[present]"} client_auth_method=#{@client_auth_method.inspect}>"
94
+ end
95
+
90
96
  private
91
97
 
92
98
  def introspect(token)
@@ -118,6 +118,12 @@ module MCP
118
118
  raise InvalidTokenError, "Invalid token"
119
119
  end
120
120
 
121
+ # The default `inspect` would print the `key:`, which for HMAC algorithms is the shared secret itself.
122
+ def inspect
123
+ "#<#{self.class.name} issuer=#{@issuer.inspect} audience=#{@audience.inspect} jwks_uri=#{@jwks_uri.inspect} " \
124
+ "key=#{@key.nil? ? "nil" : "[present]"} algorithms=#{@algorithms.inspect}>"
125
+ end
126
+
121
127
  private
122
128
 
123
129
  def decode(token)
@@ -38,8 +38,8 @@ module MCP
38
38
  unless key.is_a?(String) && key.bytesize == KEY_BYTES
39
39
  raise ArgumentError, "key must be a #{KEY_BYTES}-byte String"
40
40
  end
41
- unless ttl.is_a?(Numeric) && ttl.positive?
42
- raise ArgumentError, "ttl must be a positive number of seconds"
41
+ unless ttl.is_a?(Numeric) && ttl.finite? && ttl.positive?
42
+ raise ArgumentError, "ttl must be a positive, finite number of seconds"
43
43
  end
44
44
 
45
45
  @key = key.dup.force_encoding(Encoding::BINARY).freeze
@@ -47,11 +47,17 @@ module MCP
47
47
  @audience = audience
48
48
  end
49
49
 
50
+ # The default `inspect` would print the `key:`, with which anyone can seal a state this server accepts.
51
+ def inspect
52
+ "#<#{self.class.name} ttl=#{@ttl.inspect} audience=#{@audience.inspect}>"
53
+ end
54
+
50
55
  # Seals a plaintext state into an opaque token bound to the originating request.
51
56
  def seal(state, method:, target:, arguments_digest:)
52
57
  claims = {
53
58
  v: 1,
54
- exp: Time.now.to_i + @ttl,
59
+ # Whole seconds, as `verify!` requires: an `Integer` TTL keeps its exact value, a fractional one ends within the second it falls in.
60
+ exp: (Time.now + @ttl).to_i,
55
61
  m: method,
56
62
  t: target,
57
63
  a: arguments_digest,
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../subscriptions"
4
+
5
+ module MCP
6
+ class Server
7
+ # The change-event seam between notification publishers and open `subscriptions/listen` streams (SEP-2575).
8
+ # `StreamableHTTPTransport` publishes a typed event for every tools/prompts/resources change and
9
+ # delivers events arriving via `subscribe` to the matching streams it holds. This default bus is in-process:
10
+ # `publish` invokes the registered listeners synchronously, so a single-process deployment behaves exactly as if
11
+ # the transport wrote to its streams directly.
12
+ #
13
+ # In a multi-process deployment (such as Puma clustered mode), each worker holds only its own listen streams,
14
+ # so a change published in one worker must reach the streams the other workers hold. Pass a bus backed by an external
15
+ # pub/sub system (Redis, Postgres NOTIFY, and the like) via `StreamableHTTPTransport.new(server, subscription_bus: ...)`.
16
+ # A custom bus implements the same two methods:
17
+ #
18
+ # - `publish(event)` delivers the event to the listeners registered in every process, including the publishing one.
19
+ # - `subscribe { |event| ... }` registers a listener called once per arriving event and returns a callable that unregisters it.
20
+ #
21
+ # The bus carries the typed events of `MCP::Subscriptions` (`ToolsListChanged`, `PromptsListChanged`,
22
+ # `ResourcesListChanged`, and `ResourceUpdated`), never JSON-RPC: subscription-id stamping and per-stream filter
23
+ # matching stay in the transport, so a bus implementation can only move events between processes.
24
+ # Listeners are synchronous and must not raise; the wire encoding an external backend uses between processes
25
+ # is the implementation's own. The unregistering callable is idempotent (the transport calls it on `close`).
26
+ # Listeners run outside the bus's own locks, on whichever thread receives the event, and one already selected for
27
+ # delivery may still run after unregistering; the transport tolerates that through each stream's closed check.
28
+ # `publish` runs on the notifier's thread, so a broker round trip belongs behind a timeout; a `publish` that raises
29
+ # is reported by the transport without failing the notifier.
30
+ class SubscriptionBus
31
+ def initialize
32
+ @mutex = Mutex.new
33
+ @listeners = {}
34
+ end
35
+
36
+ # Delivers the event synchronously to every registered listener. A raising listener is
37
+ # reported through the configured exception reporter and does not stop delivery to the
38
+ # remaining listeners.
39
+ def publish(event)
40
+ listeners = @mutex.synchronize { @listeners.values }
41
+ listeners.each do |listener|
42
+ listener.call(event)
43
+ rescue => e
44
+ MCP.configuration.exception_reporter.call(e, { error: "SubscriptionBus listener failed" })
45
+ end
46
+ nil
47
+ end
48
+
49
+ # Registers a listener for published events and returns a callable that unregisters it.
50
+ def subscribe(&listener)
51
+ raise ArgumentError, "subscribe requires a block" unless listener
52
+
53
+ token = Object.new
54
+ @mutex.synchronize { @listeners[token] = listener }
55
+
56
+ proc do
57
+ @mutex.synchronize { @listeners.delete(token) }
58
+ nil
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
@@ -155,9 +155,11 @@ module MCP
155
155
  raise
156
156
  end
157
157
 
158
- if parsed[:id] == request_id && !parsed.key?(:method)
159
- if parsed[:error]
160
- raise StandardError, "Client returned an error for #{method} request (code: #{parsed[:error][:code]}): #{parsed[:error][:message]}"
158
+ # A frame that is not an object is not the response; it is answered like any other frame, as `open` does.
159
+ if parsed.is_a?(Hash) && parsed[:id] == request_id && !parsed.key?(:method)
160
+ if parsed.key?(:error)
161
+ error = parsed[:error].is_a?(Hash) ? parsed[:error] : {}
162
+ raise StandardError, "Client returned an error for #{method} request (code: #{error[:code]}): #{error[:message]}"
161
163
  end
162
164
 
163
165
  return parsed[:result]
@@ -3,8 +3,10 @@
3
3
  require "json"
4
4
  require "set"
5
5
  require "timeout"
6
+ require_relative "../../duration"
6
7
  require_relative "../../result_type"
7
8
  require_relative "../../transport"
9
+ require_relative "../subscription_bus"
8
10
 
9
11
  # This file is autoloaded only when `StreamableHTTPTransport` is referenced,
10
12
  # so the `rack` dependency does not affect `StdioTransport` users.
@@ -135,6 +137,7 @@ module MCP
135
137
  DEFAULT_MAX_STREAM_LIFETIME = DEFAULT_SESSION_IDLE_TIMEOUT
136
138
 
137
139
  # Creates a Streamable HTTP transport that can be mounted as a Rack app.
140
+ # Timeouts and keepalive intervals take positive, finite durations in seconds. Optional bounds accept nil.
138
141
  #
139
142
  # @param server [MCP::Server] the server whose requests this transport dispatches.
140
143
  # @param stateless [Boolean] when `true`, no session is issued and each POST is self-contained.
@@ -196,6 +199,10 @@ module MCP
196
199
  # its tool is known ahead of the handler, which leaves out a server with a `tools_list_handler`.
197
200
  # Keepalive comment frames are written every `listen_keepalive_interval` seconds. Defaults to `false`;
198
201
  # cannot be combined with `serve_subscriptions_listen: false`.
202
+ # @param subscription_bus [#publish, #subscribe] the change-event bus feeding `subscriptions/listen` streams;
203
+ # defaults to an in-process `SubscriptionBus`. A multi-process deployment passes a bus backed by
204
+ # its own pub/sub system so changes published in one worker reach the streams the other workers hold.
205
+ # A `publish` that raises is reported through the exception reporter and does not fail the notifier.
199
206
  # @param server_to_client_request_timeout [Numeric] seconds a server-to-client request waits for its
200
207
  # response before the transport stops waiting and raises `MCP::Server::RequestTimeoutError`.
201
208
  # Defaults to `DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT` (600); individual calls override it with `timeout:`.
@@ -252,6 +259,7 @@ module MCP
252
259
  listen_keepalive_interval: DEFAULT_LISTEN_KEEPALIVE_INTERVAL,
253
260
  serve_subscriptions_listen: true,
254
261
  stream_request_notifications: false,
262
+ subscription_bus: nil,
255
263
  server_to_client_request_timeout: DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT,
256
264
  stream_write_timeout: DEFAULT_STREAM_WRITE_TIMEOUT,
257
265
  token_verifier: nil,
@@ -293,8 +301,8 @@ module MCP
293
301
  # unique only among that client's own in-flight requests, so it stamps `subscriptionId` but cannot serve as the key:
294
302
  # two clients may pick the same one. Whoever removes an entry signals `keepalive_wakeup` under `@mutex`,
295
303
  # so the stream's keepalive thread ends with its slot instead of sleeping out its interval.
296
- # In-process only; a multi-worker deployment needs an external event bus to fan notifications out across processes,
297
- # which is a follow-up.
304
+ # The registry is per-process (a stream is an open connection); cross-process fan-out goes through
305
+ # `@subscription_bus`.
298
306
  @listen_subscriptions = {}
299
307
 
300
308
  # Maps a modern request's ephemeral session id to the Array collecting the notifications its handler emits;
@@ -312,12 +320,13 @@ module MCP
312
320
  session_idle_timeout
313
321
  end
314
322
 
315
- if @session_idle_timeout
316
- if @stateless
317
- raise ArgumentError, "session_idle_timeout is not supported in stateless mode."
318
- elsif @session_idle_timeout <= 0
319
- raise ArgumentError, "session_idle_timeout must be a positive number."
323
+ # The value is checked ahead of the mode, so that an invalid one such as `false` is reported as what it is in stateless mode too.
324
+ unless @session_idle_timeout.nil?
325
+ unless Duration.positive_finite?(@session_idle_timeout)
326
+ raise ArgumentError, "session_idle_timeout must be a positive finite number, or nil to disable the timeout."
320
327
  end
328
+
329
+ raise ArgumentError, "session_idle_timeout is not supported in stateless mode." if @stateless
321
330
  end
322
331
 
323
332
  unless max_sessions.nil? || (max_sessions.is_a?(Integer) && max_sessions > 0)
@@ -352,8 +361,8 @@ module MCP
352
361
 
353
362
  @max_resource_subscription_bytes = max_resource_subscription_bytes
354
363
 
355
- if !listen_keepalive_interval.nil? && !(listen_keepalive_interval.is_a?(Numeric) && listen_keepalive_interval > 0)
356
- raise ArgumentError, "listen_keepalive_interval must be a positive number or nil"
364
+ unless listen_keepalive_interval.nil? || Duration.positive_finite?(listen_keepalive_interval)
365
+ raise ArgumentError, "listen_keepalive_interval must be a positive finite number or nil"
357
366
  end
358
367
 
359
368
  @listen_keepalive_interval = listen_keepalive_interval
@@ -368,14 +377,19 @@ module MCP
368
377
 
369
378
  @stream_request_notifications = stream_request_notifications
370
379
 
371
- unless server_to_client_request_timeout.is_a?(Numeric) && server_to_client_request_timeout.positive?
372
- raise ArgumentError, "server_to_client_request_timeout must be a positive number"
380
+ @subscription_bus = subscription_bus || SubscriptionBus.new
381
+ unless @subscription_bus.respond_to?(:publish) && @subscription_bus.respond_to?(:subscribe)
382
+ raise ArgumentError, "subscription_bus must respond to publish and subscribe"
383
+ end
384
+
385
+ unless Duration.positive_finite?(server_to_client_request_timeout)
386
+ raise ArgumentError, "server_to_client_request_timeout must be a positive finite number"
373
387
  end
374
388
 
375
389
  @server_to_client_request_timeout = server_to_client_request_timeout
376
390
 
377
- unless stream_write_timeout.nil? || (stream_write_timeout.is_a?(Numeric) && stream_write_timeout.positive?)
378
- raise ArgumentError, "stream_write_timeout must be a positive number or nil"
391
+ unless stream_write_timeout.nil? || Duration.positive_finite?(stream_write_timeout)
392
+ raise ArgumentError, "stream_write_timeout must be a positive finite number or nil"
379
393
  end
380
394
 
381
395
  @stream_write_timeout = stream_write_timeout
@@ -399,8 +413,8 @@ module MCP
399
413
  @oauth_authenticator = nil
400
414
  end
401
415
 
402
- unless max_stream_lifetime.nil? || (max_stream_lifetime.is_a?(Numeric) && max_stream_lifetime.positive?)
403
- raise ArgumentError, "max_stream_lifetime must be a positive number or nil"
416
+ unless max_stream_lifetime.nil? || Duration.positive_finite?(max_stream_lifetime)
417
+ raise ArgumentError, "max_stream_lifetime must be a positive finite number or nil"
404
418
  end
405
419
 
406
420
  @max_stream_lifetime = max_stream_lifetime
@@ -430,7 +444,36 @@ module MCP
430
444
  # being killed in the middle of a reap.
431
445
  @closing = false
432
446
  @reaper_wakeup = ConditionVariable.new
433
- start_reaper_thread if @session_idle_timeout
447
+
448
+ # Local listen streams are fed exclusively through the bus: the in-process default publishes back synchronously,
449
+ # and an external bus hands this listener the events other workers publish too, on the same arrival path.
450
+ # A bus asks its listeners not to raise, and this one may run on the reader thread of a broker, which an exception
451
+ # would end for good: a stream write can fail with an error the delivery does not expect, so it is reported here.
452
+ # The listener checks `@subscription_bus_detached` first, because the transport cannot always take it off the bus:
453
+ # a `subscribe` that raises after registering returns no callable, and the callable of a custom bus can raise.
454
+ # The listener the bus keeps then writes to no stream of a transport that was closed or never built.
455
+ @subscription_bus_detached = false
456
+ begin
457
+ @subscription_bus_unsubscribe = @subscription_bus.subscribe do |event|
458
+ next if @subscription_bus_detached
459
+
460
+ deliver_event_to_listen_subscriptions(event)
461
+ rescue => e
462
+ report_subscription_bus_failure(e, "Subscription bus delivery failed")
463
+ end
464
+ rescue StandardError
465
+ @subscription_bus_detached = true
466
+ raise
467
+ end
468
+
469
+ # The last step that can fail. A transport that was never built takes its listener off a shared bus,
470
+ # or leaves it inert there when the bus keeps it.
471
+ begin
472
+ start_reaper_thread if @session_idle_timeout
473
+ rescue StandardError
474
+ detach_from_subscription_bus
475
+ raise
476
+ end
434
477
  end
435
478
 
436
479
  REQUIRED_POST_ACCEPT_TYPES_SSE = ["application/json", "text/event-stream"].freeze
@@ -611,6 +654,12 @@ module MCP
611
654
  end
612
655
  @reaper_thread = nil
613
656
 
657
+ # Detach from the bus before tearing the streams down, so no new event is handed to this transport;
658
+ # a delivery already in flight is ordered against the teardown by each stream's write mutex and closed flag,
659
+ # not by the unsubscribe. The unsubscribe callable comes from a possibly custom bus;
660
+ # one that raises is reported and must not stop the teardown below.
661
+ detach_from_subscription_bus
662
+
614
663
  teardown_listen_subscriptions
615
664
 
616
665
  removed_sessions = @mutex.synchronize do
@@ -639,7 +688,18 @@ module MCP
639
688
  # a resource updated by one session's tool call changed globally, so modern subscribers hear about it too.
640
689
  # Runs before the per-request sink and the stateless guard because the listen registry does not depend on sessions,
641
690
  # and a sink capturing the notification for its own response stream must not hide it from other subscriptions.
642
- deliver_to_listen_subscriptions(method, params)
691
+ # The change goes through the subscription bus rather than straight to the streams: the in-process default delivers
692
+ # back synchronously, while an external bus also carries it to the streams other workers hold.
693
+ # A custom bus that raises (a broker outage, say) is reported like a raising listener or unsubscribe,
694
+ # so the session and request deliveries below still run: whatever the failure cost the listen streams,
695
+ # the other streams of this worker should not lose the change as well.
696
+ if (event = subscription_event_for(method, params))
697
+ begin
698
+ @subscription_bus.publish(event)
699
+ rescue => e
700
+ report_subscription_bus_failure(e, "Subscription bus publish failed")
701
+ end
702
+ end
643
703
 
644
704
  notification = {
645
705
  jsonrpc: "2.0",
@@ -1847,6 +1907,46 @@ module MCP
1847
1907
  !!(value[flag] || value[flag.to_s])
1848
1908
  end
1849
1909
 
1910
+ # Maps a change notification onto its typed `MCP::Subscriptions` event, or `nil` for methods that do not
1911
+ # feed `subscriptions/listen` streams (progress, log, and the other request- or session-scoped notifications).
1912
+ def subscription_event_for(method, params)
1913
+ Subscriptions.event_from_wire(method, params)
1914
+ end
1915
+
1916
+ def detach_from_subscription_bus
1917
+ @subscription_bus_detached = true
1918
+ unsubscribe = @subscription_bus_unsubscribe
1919
+ @subscription_bus_unsubscribe = nil
1920
+ unsubscribe&.call
1921
+ rescue => e
1922
+ report_subscription_bus_failure(e, "Subscription bus unsubscribe failed")
1923
+ end
1924
+
1925
+ # A reporter that raises is ignored here, unlike elsewhere in the transport: these reports are made on the reader
1926
+ # thread of a broker, which the exception would end, inside `close`, whose teardown it would stop,
1927
+ # and ahead of the other deliveries of a change, which it would cost the streams of this worker.
1928
+ def report_subscription_bus_failure(exception, error)
1929
+ MCP.configuration.exception_reporter.call(exception, { error: error })
1930
+ rescue StandardError
1931
+ nil
1932
+ end
1933
+
1934
+ # Delivers a bus event (published locally or by another worker) to the matching listen streams.
1935
+ # An event kind this transport does not know is ignored, so a newer publisher sharing the bus
1936
+ # does not break an older worker.
1937
+ def deliver_event_to_listen_subscriptions(event)
1938
+ case event
1939
+ when Subscriptions::ToolsListChanged
1940
+ deliver_to_listen_subscriptions(Methods::NOTIFICATIONS_TOOLS_LIST_CHANGED, nil)
1941
+ when Subscriptions::PromptsListChanged
1942
+ deliver_to_listen_subscriptions(Methods::NOTIFICATIONS_PROMPTS_LIST_CHANGED, nil)
1943
+ when Subscriptions::ResourcesListChanged
1944
+ deliver_to_listen_subscriptions(Methods::NOTIFICATIONS_RESOURCES_LIST_CHANGED, nil)
1945
+ when Subscriptions::ResourceUpdated
1946
+ deliver_to_listen_subscriptions(Methods::NOTIFICATIONS_RESOURCES_UPDATED, { uri: event.uri })
1947
+ end
1948
+ end
1949
+
1850
1950
  # Fans a notification out to every `subscriptions/listen` stream whose honored filter opted in to it,
1851
1951
  # stamping the correlating `subscriptionId` into `_meta`. Matching against the honored filter
1852
1952
  # (not the requested one) enforces the MUST NOT-send-unrequested-types rule.
@@ -1900,10 +2000,8 @@ module MCP
1900
2000
  push_to_stream(subscription[:stream], notification, subscription: subscription)
1901
2001
  end
1902
2002
  rescue *STREAM_WRITE_ERRORS => e
1903
- MCP.configuration.exception_reporter.call(
1904
- e,
1905
- { subscription_id: subscription[:request_id], error: "Failed to send notification" },
1906
- )
2003
+ report_stream_write_failure(e, { subscription_id: subscription[:request_id], error: "Failed to send notification" })
2004
+
1907
2005
  # Closed only when the removal is this path's own, as every other removal path does: the keepalive loop,
1908
2006
  # a token expiry, or the teardown that removed the entry first closes the stream itself.
1909
2007
  close_removed_listen_stream(subscription) if remove_listen_subscription(subscription_key)
@@ -1911,6 +2009,14 @@ module MCP
1911
2009
  end
1912
2010
  end
1913
2011
 
2012
+ # Reports a write that failed on one stream of a delivery. A reporter that raises is ignored here, unlike elsewhere in the transport:
2013
+ # the exception would leave the failed stream registered and cost the streams the delivery has not reached yet the message.
2014
+ def report_stream_write_failure(exception, context)
2015
+ MCP.configuration.exception_reporter.call(exception, context)
2016
+ rescue StandardError
2017
+ nil
2018
+ end
2019
+
1914
2020
  def remove_listen_subscription(subscription_key)
1915
2021
  @mutex.synchronize do
1916
2022
  subscription = @listen_subscriptions.delete(subscription_key)
@@ -2640,7 +2746,9 @@ module MCP
2640
2746
  @mutex.synchronize do
2641
2747
  if (pending_response = @pending_responses[request_id]) && pending_response[:session_id] == session_id
2642
2748
  if body.key?(:error)
2643
- error = body[:error]
2749
+ # A malformed `error` member still answers the request as an error, rather than raising here and leaving
2750
+ # its `send_request` to wait out its timeout.
2751
+ error = body[:error].is_a?(Hash) ? body[:error] : {}
2644
2752
  pending_response[:queue].push(error: { code: error[:code], message: error[:message] })
2645
2753
  else
2646
2754
  pending_response[:queue].push(body[:result])
@@ -3356,7 +3464,7 @@ module MCP
3356
3464
 
3357
3465
  written = true
3358
3466
  rescue *STREAM_WRITE_ERRORS => e
3359
- MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to send message" })
3467
+ report_stream_write_failure(e, { session_id: session_id, error: "Failed to send message" })
3360
3468
 
3361
3469
  drop_broken_stream(session_id, stream, related_request_id)
3362
3470
  end
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
@@ -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
@@ -254,7 +255,13 @@ module MCP
254
255
  def create_form_elicitation(message:, requested_schema:, related_request_id: nil, timeout: nil)
255
256
  warn_unassociated_request(__method__, related_request_id)
256
257
 
257
- 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
+
258
265
  raise "Client does not support elicitation. " \
259
266
  "The client must declare the `elicitation` capability during initialization."
260
267
  end
@@ -276,7 +283,7 @@ module MCP
276
283
  def create_url_elicitation(message:, url:, elicitation_id:, related_request_id: nil, timeout: nil)
277
284
  warn_unassociated_request(__method__, related_request_id)
278
285
 
279
- unless client_capabilities&.dig(:elicitation, :url)
286
+ unless ClientCapabilities.elicitation?(client_capabilities, :url)
280
287
  raise "Client does not support URL mode elicitation. " \
281
288
  "The client must declare the `elicitation.url` capability during initialization."
282
289
  end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "methods"
4
+
5
+ module MCP
6
+ # The typed change-event vocabulary of `subscriptions/listen` (SEP-2575):
7
+ # `MCP::Server::SubscriptionBus` carries these events between processes. Each event maps onto exactly one
8
+ # change notification method; the wire shape itself never travels through these classes.
9
+ module Subscriptions
10
+ # Base for the payload-free list-changed events; equality is class identity.
11
+ class ListChangedEvent
12
+ def initialize
13
+ freeze
14
+ end
15
+
16
+ def ==(other)
17
+ other.instance_of?(self.class)
18
+ end
19
+ alias_method :eql?, :==
20
+
21
+ def hash
22
+ self.class.hash
23
+ end
24
+ end
25
+
26
+ # Announces `notifications/tools/list_changed`.
27
+ class ToolsListChanged < ListChangedEvent; end
28
+
29
+ # Announces `notifications/prompts/list_changed`.
30
+ class PromptsListChanged < ListChangedEvent; end
31
+
32
+ # Announces `notifications/resources/list_changed`.
33
+ class ResourcesListChanged < ListChangedEvent; end
34
+
35
+ # Announces `notifications/resources/updated` for one resource URI.
36
+ class ResourceUpdated
37
+ attr_reader :uri
38
+
39
+ def initialize(uri:)
40
+ raise ArgumentError, "uri must be a String" unless uri.is_a?(String)
41
+
42
+ @uri = -uri
43
+ freeze
44
+ end
45
+
46
+ def ==(other)
47
+ other.instance_of?(self.class) && other.uri == uri
48
+ end
49
+ alias_method :eql?, :==
50
+
51
+ def hash
52
+ [self.class, uri].hash
53
+ end
54
+ end
55
+
56
+ class << self
57
+ # Decodes a change notification into its typed event, or `nil` for any other method
58
+ # (progress, log, and the other request- or session-scoped notifications).
59
+ # Accepts symbol or string params keys, since parsed frames arrive in either form.
60
+ def event_from_wire(method, params)
61
+ case method
62
+ when Methods::NOTIFICATIONS_TOOLS_LIST_CHANGED
63
+ ToolsListChanged.new
64
+ when Methods::NOTIFICATIONS_PROMPTS_LIST_CHANGED
65
+ PromptsListChanged.new
66
+ when Methods::NOTIFICATIONS_RESOURCES_LIST_CHANGED
67
+ ResourcesListChanged.new
68
+ when Methods::NOTIFICATIONS_RESOURCES_UPDATED
69
+ uri = params.is_a?(Hash) ? params[:uri] || params["uri"] : nil
70
+ ResourceUpdated.new(uri: uri) if uri.is_a?(String)
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end
data/lib/mcp/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module MCP
4
- VERSION = "1.12.0"
4
+ VERSION = "1.13.0"
5
5
  end
data/lib/mcp.rb CHANGED
@@ -27,6 +27,7 @@ module MCP
27
27
  autoload :ServerContext, "mcp/server_context"
28
28
  autoload :ServerSession, "mcp/server_session"
29
29
  autoload :Skill, "mcp/skill"
30
+ autoload :Subscriptions, "mcp/subscriptions"
30
31
  autoload :Tool, "mcp/tool"
31
32
  autoload :TraceContext, "mcp/trace_context"
32
33