From dbafe21ed929c9f97b3cbe7f2c821850fda2bf27 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Mon, 31 Aug 2026 01:38:06 +0900 Subject: [PATCH] Add a pluggable subscription bus for `subscriptions/listen` streams ## Motivation and Context The `subscriptions/listen` registry is per-process: a stream lives in the worker that accepted it, so a change published in another worker (Puma clustered mode, or several instances behind a load balancer) never reached it. This was the one remaining piece of cross-process state on the modern lifecycle; sessions, SSE resumability, and server-initiated requests are gone as of MCP 2026-07-28, and the MRTR pattern is specified to work "without requiring a shared storage layer across server instances". Both reference SDKs close the gap with the same seam - the Python SDK's `SubscriptionBus` protocol and the TypeScript SDK's `ServerEventBus` interface, each with an in-memory default and user-supplied brokers - and this ports that seam. `MCP::Server::SubscriptionBus` carries the four typed change events of `MCP::Subscriptions` (`ToolsListChanged`, `PromptsListChanged`, `ResourcesListChanged`, and `ResourceUpdated` with its URI), never JSON-RPC: acknowledgements, per-stream filter matching, and subscriptionId stamping stay in the transport, so a bus implementation can only move events between processes. `StreamableHTTPTransport` publishes every change through the bus and feeds its local streams from a bus listener registered at construction, making the arrival path identical for local and remote events; the in-process default publishes back synchronously, preserving the single-process delivery behavior. A multi-process deployment passes `subscription_bus:` backed by its own pub/sub system; the docs show a Redis sketch, and no broker adapter is bundled, matching both reference SDKs. `MCP::Subscriptions` is registered in the autoload list of `mcp.rb` like every other public constant, so a custom bus that rebuilds events from its broker at boot resolves the classes before any transport exists. A `publish` that raises, a broker outage, say, is reported through the exception reporter the way a raising listener or unsubscribe already is, so the legacy streams and modern sinks of the publishing worker still receive the change; the change senders rescue on their own, so what such a failure used to cost was that local delivery. The typed round trip carries only what the specification's params hold, the event kind and the resource URI, so an extension member a caller adds to one of the four change notifications reaches the legacy streams and modern sinks but not the listen streams, as in the Python SDK. The docs state that the default bus belongs to one transport, and the Redis sketch rescues per listener, like the default bus, with a separate rescue for a message the worker cannot decode. The page also states the contract a custom bus honors (an idempotent unregistering callable, listeners run outside the bus's locks on the receiving thread, and one already selected may still run after unregistering, which each stream's closed check absorbs), that with the default bus delivery is synchronous on the calling thread, so a stalled stream delays the notifier and a broker round trip in `publish` belongs behind a timeout, that the broker needs the same trust as the server processes, and what a production adapter adds to the sketch: waiting for the subscription before serving traffic, supervising the reader, stopping it on close, and building the bus after the fork. The class comment carries the same contract, and the `close` comment attributes the teardown ordering to each stream's write mutex and closed flag rather than to the unsubscribe. The transport does not depend on a custom bus honoring that contract. Its listener does nothing once the transport is closed or could not be built, so a listener left on the bus by an unregistering callable that raises, or by a `subscribe` that raises after registering, writes to no stream. An exception reporter that raises while one of the bus failures is reported is ignored, since the exception would end the reader thread of a broker, stop `close`, or cost the other streams of the worker the change. ## How Has This Been Tested? With the new bus unit tests and transport tests (including two transports sharing one bus standing in for two workers), the full suite, RuboCop, and the conformance suite, all green; the docs preview builds with every internal link and anchor check passing. A subprocess test resolves `MCP::Subscriptions` right after `require "mcp"`, and a bus whose `publish` raises is reported under its own context while a legacy GET stream still receives the change; both fail against the previous tree. Six more tests keep a listener on a bus whose unregistering callable or `subscribe` raises and report through a reporter that raises; each fails without the guard it covers. ## Breaking Changes None. The bus is a new optional keyword argument, and the in-process default preserves the existing single-process delivery behavior, apart from the extension members noted above, which no longer reach the listen streams. --- docs/_server/subscriptions.md | 98 +++++ docs/_server/transports.md | 3 +- lib/mcp.rb | 1 + lib/mcp/server.rb | 1 + lib/mcp/server/subscription_bus.rb | 63 ++++ .../transports/streamable_http_transport.rb | 105 +++++- lib/mcp/subscriptions.rb | 75 ++++ test/mcp/server/subscription_bus_test.rb | 58 +++ .../streamable_http_transport_test.rb | 352 ++++++++++++++++++ test/mcp/subscriptions_test.rb | 59 +++ 10 files changed, 810 insertions(+), 5 deletions(-) create mode 100644 lib/mcp/server/subscription_bus.rb create mode 100644 lib/mcp/subscriptions.rb create mode 100644 test/mcp/server/subscription_bus_test.rb create mode 100644 test/mcp/subscriptions_test.rb diff --git a/docs/_server/subscriptions.md b/docs/_server/subscriptions.md index 8d197d99..d271bc01 100644 --- a/docs/_server/subscriptions.md +++ b/docs/_server/subscriptions.md @@ -128,4 +128,102 @@ each open stream receives its `subscriptions/listen` response before closing. `close` waits at most 5 seconds in all for those responses to be written: a stream whose client stopped reading is closed without one when that time is up, and the client re-sends its `subscriptions/listen` request. +## Scaling Past One Process + +Changes travel from the notifying code to the open streams over a subscription bus. +The default bus is in-process and belongs to one transport: it delivers to the streams that transport holds, which is the right answer for +a single-process server (two transports in one process share a bus only when handed the same instance). +In a multi-process deployment (Puma clustered mode, or several instances behind a load balancer), each worker holds only +the streams it accepted, so a change published in one worker reaches the others only through an external pub/sub system. + +Pass a custom bus via `subscription_bus:`. A bus implements two methods: `publish(event)` delivers the event to the listeners registered in every process, +including the publishing one, and `subscribe { |event| ... }` registers a listener and returns a callable that unregisters it. +The bus carries typed events (`MCP::Subscriptions::ToolsListChanged`, `PromptsListChanged`, `ResourcesListChanged`, and `ResourceUpdated` with its `uri`), +never JSON-RPC: acknowledgements, per-stream filtering, and `subscriptionId` stamping stay in the transport, so a bus implementation +can only move events between processes. + +The contract a custom bus honors is small. The unregistering callable is idempotent, since the transport calls it on `close` +and a second call must be harmless. Listeners run outside the bus's own locks, on whichever thread receives the event +(the broker reader's, typically), and a listener already selected for delivery may still run after the callable returns; +the transport tolerates that, because every stream write checks the stream's closed flag under the stream's own mutex. +The callable has to remove the listener as well: a closed transport ignores the events a listener left on the bus still receives, +but the bus keeps that transport in memory for as long as it keeps the listener. + +The transport writes to every matching stream before its listener returns, so a stalled stream delays the listeners after it. +With the default bus that happens on the thread that emitted the change, which waits for it as well. +With an external bus the streams are typically written on the thread that receives the event, within `stream_write_timeout:` per write, +and `publish` still runs on the thread that emitted the change, so a broker round trip belongs behind a timeout rather than an unbounded wait. +A `publish` that raises is reported through the exception reporter without failing the code that emitted the change. +Nothing then delivers the change to the `subscriptions/listen` streams in place of the bus, those of the publishing worker included, +while that worker's other deliveries of the notification still run. +Whatever can publish to the broker can put change events in front of every matching stream in every worker, +so the broker needs the same trust as the server processes themselves. + +A Redis-backed sketch (the SDK bundles no broker adapter; `encode` and `decode` are the implementation's own, +for example JSON with an event-kind field mapped back to the typed classes): + +```ruby +class RedisSubscriptionBus + def initialize(redis_config) + @mutex = Mutex.new + @listeners = {} + @redis = Redis.new(redis_config) + + # Each worker runs one reader: decode arriving messages and hand them to every listener. + Thread.new do + Redis.new(redis_config).subscribe("mcp-events") do |on| + on.message do |_channel, message| + event = decode(message) + + # Snapshot under the lock, deliver outside it: a listener may subscribe or + # unsubscribe without deadlocking, and a slow listener does not hold the lock. + listeners = @mutex.synchronize { @listeners.values } + + listeners.each do |listener| + listener.call(event) + rescue => e + # A raising listener must not kill the reader thread, which would silently stop cross-worker + # delivery for this worker, nor cost the remaining listeners their delivery, as in the default bus. + MCP.configuration.exception_reporter.call(e, { error: "subscription bus listener failed" }) + end + rescue => e + # A message this worker cannot decode is reported and skipped; the reader keeps running. + MCP.configuration.exception_reporter.call(e, { error: "subscription bus message rejected" }) + end + end + end + end + + def publish(event) + @redis.publish("mcp-events", encode(event)) + end + + def subscribe(&listener) + token = Object.new + + @mutex.synchronize do + @listeners[token] = listener + end + + proc do + @mutex.synchronize { @listeners.delete(token) } + end + end +end + +transport = MCP::Server::Transports::StreamableHTTPTransport.new( + server, subscription_bus: RedisSubscriptionBus.new(url: ENV["REDIS_URL"]) +) +``` + +Note that `publish` does not call the local listeners itself: the publishing worker receives its own message back through Redis, +so every worker delivers a message it receives through the same arrival path, once. Nothing is queued for a worker +whose reader is not subscribed at that moment; the changes published meanwhile never reach its streams. + +The sketch leaves out what a production adapter needs beyond it: wait for the subscription to be established +(`on.subscribe` in redis-rb) before the worker serves traffic, or the changes published in the meantime miss its streams; +supervise the reader, since a lost connection ends the `subscribe` call and the rescue in the sketch covers one message only; +stop the reader when the transport closes; and build the bus after the process forks, +so each Puma worker opens its own connection and reader instead of sharing one across the fork. + See [Notifications](/server/notifications/) for the notification types themselves and their session scoping. diff --git a/docs/_server/transports.md b/docs/_server/transports.md index 2c9ef846..974dcbe2 100644 --- a/docs/_server/transports.md +++ b/docs/_server/transports.md @@ -78,7 +78,8 @@ The following examples show two common integration styles in Rails. > Stateless mode (`stateless: true`) does not use sessions and works with any server configuration. > Requests of the [modern lifecycle](/server/discover/#the-stateless-modern-lifecycle) (MCP 2026-07-28) are likewise sessionless single exchanges and work > with any configuration, with two caveats: a [`subscriptions/listen`](/server/subscriptions/) stream -> is held in memory by the process that accepted it, so only notifications emitted in that process reach it, +> is held in memory by the process that accepted it, so notifications emitted in other workers reach it +> only through a shared [subscription bus](/server/subscriptions/#scaling-past-one-process), > and the [multi round-trip](/server/mrtr/) `requestState` crosses workers only when they > share a `RequestStateSecurity` key. diff --git a/lib/mcp.rb b/lib/mcp.rb index af3ec3c7..48130104 100644 --- a/lib/mcp.rb +++ b/lib/mcp.rb @@ -27,6 +27,7 @@ module MCP autoload :ServerContext, "mcp/server_context" autoload :ServerSession, "mcp/server_session" autoload :Skill, "mcp/skill" + autoload :Subscriptions, "mcp/subscriptions" autoload :Tool, "mcp/tool" autoload :TraceContext, "mcp/trace_context" diff --git a/lib/mcp/server.rb b/lib/mcp/server.rb index 8a20d125..d7db143e 100644 --- a/lib/mcp/server.rb +++ b/lib/mcp/server.rb @@ -17,6 +17,7 @@ require_relative "server/pagination" require_relative "server/pending_response" require_relative "server/request_state_security" +require_relative "server/subscription_bus" require_relative "server/transports" module MCP diff --git a/lib/mcp/server/subscription_bus.rb b/lib/mcp/server/subscription_bus.rb new file mode 100644 index 00000000..079650cd --- /dev/null +++ b/lib/mcp/server/subscription_bus.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true + +require_relative "../subscriptions" + +module MCP + class Server + # The change-event seam between notification publishers and open `subscriptions/listen` streams (SEP-2575). + # `StreamableHTTPTransport` publishes a typed event for every tools/prompts/resources change and + # delivers events arriving via `subscribe` to the matching streams it holds. This default bus is in-process: + # `publish` invokes the registered listeners synchronously, so a single-process deployment behaves exactly as if + # the transport wrote to its streams directly. + # + # In a multi-process deployment (such as Puma clustered mode), each worker holds only its own listen streams, + # so a change published in one worker must reach the streams the other workers hold. Pass a bus backed by an external + # pub/sub system (Redis, Postgres NOTIFY, and the like) via `StreamableHTTPTransport.new(server, subscription_bus: ...)`. + # A custom bus implements the same two methods: + # + # - `publish(event)` delivers the event to the listeners registered in every process, including the publishing one. + # - `subscribe { |event| ... }` registers a listener called once per arriving event and returns a callable that unregisters it. + # + # The bus carries the typed events of `MCP::Subscriptions` (`ToolsListChanged`, `PromptsListChanged`, + # `ResourcesListChanged`, and `ResourceUpdated`), never JSON-RPC: subscription-id stamping and per-stream filter + # matching stay in the transport, so a bus implementation can only move events between processes. + # Listeners are synchronous and must not raise; the wire encoding an external backend uses between processes + # is the implementation's own. The unregistering callable is idempotent (the transport calls it on `close`). + # Listeners run outside the bus's own locks, on whichever thread receives the event, and one already selected for + # delivery may still run after unregistering; the transport tolerates that through each stream's closed check. + # `publish` runs on the notifier's thread, so a broker round trip belongs behind a timeout; a `publish` that raises + # is reported by the transport without failing the notifier. + class SubscriptionBus + def initialize + @mutex = Mutex.new + @listeners = {} + end + + # Delivers the event synchronously to every registered listener. A raising listener is + # reported through the configured exception reporter and does not stop delivery to the + # remaining listeners. + def publish(event) + listeners = @mutex.synchronize { @listeners.values } + listeners.each do |listener| + listener.call(event) + rescue => e + MCP.configuration.exception_reporter.call(e, { error: "SubscriptionBus listener failed" }) + end + nil + end + + # Registers a listener for published events and returns a callable that unregisters it. + def subscribe(&listener) + raise ArgumentError, "subscribe requires a block" unless listener + + token = Object.new + @mutex.synchronize { @listeners[token] = listener } + + proc do + @mutex.synchronize { @listeners.delete(token) } + nil + end + end + end + end +end diff --git a/lib/mcp/server/transports/streamable_http_transport.rb b/lib/mcp/server/transports/streamable_http_transport.rb index 19c33187..74d15b1b 100644 --- a/lib/mcp/server/transports/streamable_http_transport.rb +++ b/lib/mcp/server/transports/streamable_http_transport.rb @@ -6,6 +6,7 @@ require_relative "../../duration" require_relative "../../result_type" require_relative "../../transport" +require_relative "../subscription_bus" # This file is autoloaded only when `StreamableHTTPTransport` is referenced, # so the `rack` dependency does not affect `StdioTransport` users. @@ -198,6 +199,10 @@ class InvalidJsonError < StandardError; end # its tool is known ahead of the handler, which leaves out a server with a `tools_list_handler`. # Keepalive comment frames are written every `listen_keepalive_interval` seconds. Defaults to `false`; # cannot be combined with `serve_subscriptions_listen: false`. + # @param subscription_bus [#publish, #subscribe] the change-event bus feeding `subscriptions/listen` streams; + # defaults to an in-process `SubscriptionBus`. A multi-process deployment passes a bus backed by + # its own pub/sub system so changes published in one worker reach the streams the other workers hold. + # A `publish` that raises is reported through the exception reporter and does not fail the notifier. # @param server_to_client_request_timeout [Numeric] seconds a server-to-client request waits for its # response before the transport stops waiting and raises `MCP::Server::RequestTimeoutError`. # Defaults to `DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT` (600); individual calls override it with `timeout:`. @@ -254,6 +259,7 @@ def initialize( listen_keepalive_interval: DEFAULT_LISTEN_KEEPALIVE_INTERVAL, serve_subscriptions_listen: true, stream_request_notifications: false, + subscription_bus: nil, server_to_client_request_timeout: DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT, stream_write_timeout: DEFAULT_STREAM_WRITE_TIMEOUT, token_verifier: nil, @@ -295,8 +301,8 @@ def initialize( # unique only among that client's own in-flight requests, so it stamps `subscriptionId` but cannot serve as the key: # two clients may pick the same one. Whoever removes an entry signals `keepalive_wakeup` under `@mutex`, # so the stream's keepalive thread ends with its slot instead of sleeping out its interval. - # In-process only; a multi-worker deployment needs an external event bus to fan notifications out across processes, - # which is a follow-up. + # The registry is per-process (a stream is an open connection); cross-process fan-out goes through + # `@subscription_bus`. @listen_subscriptions = {} # Maps a modern request's ephemeral session id to the Array collecting the notifications its handler emits; @@ -371,6 +377,11 @@ def initialize( @stream_request_notifications = stream_request_notifications + @subscription_bus = subscription_bus || SubscriptionBus.new + unless @subscription_bus.respond_to?(:publish) && @subscription_bus.respond_to?(:subscribe) + raise ArgumentError, "subscription_bus must respond to publish and subscribe" + end + unless Duration.positive_finite?(server_to_client_request_timeout) raise ArgumentError, "server_to_client_request_timeout must be a positive finite number" end @@ -433,7 +444,36 @@ def initialize( # being killed in the middle of a reap. @closing = false @reaper_wakeup = ConditionVariable.new - start_reaper_thread if @session_idle_timeout + + # Local listen streams are fed exclusively through the bus: the in-process default publishes back synchronously, + # and an external bus hands this listener the events other workers publish too, on the same arrival path. + # A bus asks its listeners not to raise, and this one may run on the reader thread of a broker, which an exception + # would end for good: a stream write can fail with an error the delivery does not expect, so it is reported here. + # The listener checks `@subscription_bus_detached` first, because the transport cannot always take it off the bus: + # a `subscribe` that raises after registering returns no callable, and the callable of a custom bus can raise. + # The listener the bus keeps then writes to no stream of a transport that was closed or never built. + @subscription_bus_detached = false + begin + @subscription_bus_unsubscribe = @subscription_bus.subscribe do |event| + next if @subscription_bus_detached + + deliver_event_to_listen_subscriptions(event) + rescue => e + report_subscription_bus_failure(e, "Subscription bus delivery failed") + end + rescue StandardError + @subscription_bus_detached = true + raise + end + + # The last step that can fail. A transport that was never built takes its listener off a shared bus, + # or leaves it inert there when the bus keeps it. + begin + start_reaper_thread if @session_idle_timeout + rescue StandardError + detach_from_subscription_bus + raise + end end REQUIRED_POST_ACCEPT_TYPES_SSE = ["application/json", "text/event-stream"].freeze @@ -614,6 +654,12 @@ def close end @reaper_thread = nil + # Detach from the bus before tearing the streams down, so no new event is handed to this transport; + # a delivery already in flight is ordered against the teardown by each stream's write mutex and closed flag, + # not by the unsubscribe. The unsubscribe callable comes from a possibly custom bus; + # one that raises is reported and must not stop the teardown below. + detach_from_subscription_bus + teardown_listen_subscriptions removed_sessions = @mutex.synchronize do @@ -642,7 +688,18 @@ def send_notification(method, params = nil, session_id: nil, related_request_id: # a resource updated by one session's tool call changed globally, so modern subscribers hear about it too. # Runs before the per-request sink and the stateless guard because the listen registry does not depend on sessions, # and a sink capturing the notification for its own response stream must not hide it from other subscriptions. - deliver_to_listen_subscriptions(method, params) + # The change goes through the subscription bus rather than straight to the streams: the in-process default delivers + # back synchronously, while an external bus also carries it to the streams other workers hold. + # A custom bus that raises (a broker outage, say) is reported like a raising listener or unsubscribe, + # so the session and request deliveries below still run: whatever the failure cost the listen streams, + # the other streams of this worker should not lose the change as well. + if (event = subscription_event_for(method, params)) + begin + @subscription_bus.publish(event) + rescue => e + report_subscription_bus_failure(e, "Subscription bus publish failed") + end + end notification = { jsonrpc: "2.0", @@ -1850,6 +1907,46 @@ def capability_flag?(capabilities, name, flag) !!(value[flag] || value[flag.to_s]) end + # Maps a change notification onto its typed `MCP::Subscriptions` event, or `nil` for methods that do not + # feed `subscriptions/listen` streams (progress, log, and the other request- or session-scoped notifications). + def subscription_event_for(method, params) + Subscriptions.event_from_wire(method, params) + end + + def detach_from_subscription_bus + @subscription_bus_detached = true + unsubscribe = @subscription_bus_unsubscribe + @subscription_bus_unsubscribe = nil + unsubscribe&.call + rescue => e + report_subscription_bus_failure(e, "Subscription bus unsubscribe failed") + end + + # A reporter that raises is ignored here, unlike elsewhere in the transport: these reports are made on the reader + # thread of a broker, which the exception would end, inside `close`, whose teardown it would stop, + # and ahead of the other deliveries of a change, which it would cost the streams of this worker. + def report_subscription_bus_failure(exception, error) + MCP.configuration.exception_reporter.call(exception, { error: error }) + rescue StandardError + nil + end + + # Delivers a bus event (published locally or by another worker) to the matching listen streams. + # An event kind this transport does not know is ignored, so a newer publisher sharing the bus + # does not break an older worker. + def deliver_event_to_listen_subscriptions(event) + case event + when Subscriptions::ToolsListChanged + deliver_to_listen_subscriptions(Methods::NOTIFICATIONS_TOOLS_LIST_CHANGED, nil) + when Subscriptions::PromptsListChanged + deliver_to_listen_subscriptions(Methods::NOTIFICATIONS_PROMPTS_LIST_CHANGED, nil) + when Subscriptions::ResourcesListChanged + deliver_to_listen_subscriptions(Methods::NOTIFICATIONS_RESOURCES_LIST_CHANGED, nil) + when Subscriptions::ResourceUpdated + deliver_to_listen_subscriptions(Methods::NOTIFICATIONS_RESOURCES_UPDATED, { uri: event.uri }) + end + end + # Fans a notification out to every `subscriptions/listen` stream whose honored filter opted in to it, # stamping the correlating `subscriptionId` into `_meta`. Matching against the honored filter # (not the requested one) enforces the MUST NOT-send-unrequested-types rule. diff --git a/lib/mcp/subscriptions.rb b/lib/mcp/subscriptions.rb new file mode 100644 index 00000000..50fd1791 --- /dev/null +++ b/lib/mcp/subscriptions.rb @@ -0,0 +1,75 @@ +# frozen_string_literal: true + +require_relative "methods" + +module MCP + # The typed change-event vocabulary of `subscriptions/listen` (SEP-2575): + # `MCP::Server::SubscriptionBus` carries these events between processes. Each event maps onto exactly one + # change notification method; the wire shape itself never travels through these classes. + module Subscriptions + # Base for the payload-free list-changed events; equality is class identity. + class ListChangedEvent + def initialize + freeze + end + + def ==(other) + other.instance_of?(self.class) + end + alias_method :eql?, :== + + def hash + self.class.hash + end + end + + # Announces `notifications/tools/list_changed`. + class ToolsListChanged < ListChangedEvent; end + + # Announces `notifications/prompts/list_changed`. + class PromptsListChanged < ListChangedEvent; end + + # Announces `notifications/resources/list_changed`. + class ResourcesListChanged < ListChangedEvent; end + + # Announces `notifications/resources/updated` for one resource URI. + class ResourceUpdated + attr_reader :uri + + def initialize(uri:) + raise ArgumentError, "uri must be a String" unless uri.is_a?(String) + + @uri = -uri + freeze + end + + def ==(other) + other.instance_of?(self.class) && other.uri == uri + end + alias_method :eql?, :== + + def hash + [self.class, uri].hash + end + end + + class << self + # Decodes a change notification into its typed event, or `nil` for any other method + # (progress, log, and the other request- or session-scoped notifications). + # Accepts symbol or string params keys, since parsed frames arrive in either form. + def event_from_wire(method, params) + case method + when Methods::NOTIFICATIONS_TOOLS_LIST_CHANGED + ToolsListChanged.new + when Methods::NOTIFICATIONS_PROMPTS_LIST_CHANGED + PromptsListChanged.new + when Methods::NOTIFICATIONS_RESOURCES_LIST_CHANGED + ResourcesListChanged.new + when Methods::NOTIFICATIONS_RESOURCES_UPDATED + uri = params.is_a?(Hash) ? params[:uri] || params["uri"] : nil + ResourceUpdated.new(uri: uri) if uri.is_a?(String) + end + end + end + end +end diff --git a/test/mcp/server/subscription_bus_test.rb b/test/mcp/server/subscription_bus_test.rb new file mode 100644 index 00000000..ce05e534 --- /dev/null +++ b/test/mcp/server/subscription_bus_test.rb @@ -0,0 +1,58 @@ +# frozen_string_literal: true + +require "test_helper" + +module MCP + class Server + class SubscriptionBusTest < ActiveSupport::TestCase + test "publish delivers the event to every registered listener" do + bus = SubscriptionBus.new + received = [] + bus.subscribe { |event| received << [:first, event] } + bus.subscribe { |event| received << [:second, event] } + + event = Subscriptions::ToolsListChanged.new + bus.publish(event) + + assert_equal [[:first, event], [:second, event]], received + end + + test "the callable returned by subscribe unregisters the listener and is idempotent" do + bus = SubscriptionBus.new + received = [] + unsubscribe = bus.subscribe { |event| received << event } + + unsubscribe.call + unsubscribe.call + bus.publish(Subscriptions::ToolsListChanged.new) + + assert_empty received + end + + test "subscribe requires a block" do + assert_raises(ArgumentError) { SubscriptionBus.new.subscribe } + end + + test "a raising listener is reported and does not stop delivery to the remaining listeners" do + bus = SubscriptionBus.new + received = [] + bus.subscribe { raise "listener boom" } + bus.subscribe { |event| received << event } + + reported = [] + original_reporter = MCP.configuration.exception_reporter + MCP.configuration.exception_reporter = ->(error, context) { reported << [error, context] } + begin + event = Subscriptions::PromptsListChanged.new + bus.publish(event) + ensure + MCP.configuration.exception_reporter = original_reporter + end + + assert_equal [event], received + assert_equal 1, reported.size + assert_equal "listener boom", reported[0][0].message + end + end + end +end diff --git a/test/mcp/server/transports/streamable_http_transport_test.rb b/test/mcp/server/transports/streamable_http_transport_test.rb index 2ea899d4..53ddcec3 100644 --- a/test/mcp/server/transports/streamable_http_transport_test.rb +++ b/test/mcp/server/transports/streamable_http_transport_test.rb @@ -8692,6 +8692,358 @@ def wait_until_blocked_or_done(thread) end end + # A bus that records publishes and never delivers, proving the transport's listen delivery + # goes through the bus rather than straight to its streams. + class BlackHoleBus + attr_reader :published + + def initialize + @published = [] + end + + def publish(event) + @published << event + end + + def subscribe(&_listener) + proc {} + end + end + + # A bus that records whether the transport called the unsubscribe callable. + class UnsubscribeTrackingBus + attr_reader :unsubscribed + + def initialize + @unsubscribed = false + end + + def publish(_event); end + + def subscribe(&_listener) + proc { @unsubscribed = true } + end + end + + # A bus whose unsubscribe callable raises, proving close still tears the streams down. + class RaisingUnsubscribeBus + def publish(_event); end + + def subscribe(&_listener) + proc { raise "unsubscribe boom" } + end + end + + # A bus whose publish raises, standing in for a broker outage. + class RaisingPublishBus + def publish(_event) + raise "publish boom" + end + + def subscribe(&_listener) + proc {} + end + end + + test "subscriptions/listen delivery goes through the subscription bus" do + bus = BlackHoleBus.new + server = Server.new(name: "listen_test", capabilities: { tools: { listChanged: true } }) + transport = StreamableHTTPTransport.new(server, subscription_bus: bus) + + io = open_listen_stream(id: "listen-1", notifications: { toolsListChanged: true }, transport: transport) + server.notify_tools_list_changed + + # The bus swallowed the event, so nothing reached the stream beyond the acknowledgement. + assert_equal 1, sse_events(io).size + assert_equal [Subscriptions::ToolsListChanged.new], bus.published + ensure + transport.close + end + + test "events published on the subscription bus reach matching listen streams" do + bus = SubscriptionBus.new + server = Server.new( + name: "listen_test", + capabilities: { tools: { listChanged: true }, resources: { listChanged: true, subscribe: true } }, + ) + transport = StreamableHTTPTransport.new(server, subscription_bus: bus) + + tools_io = open_listen_stream(id: "listen-1", notifications: { toolsListChanged: true }, transport: transport) + resource_io = open_listen_stream( + id: "listen-2", + notifications: { resourceSubscriptions: ["file:///subscribed.txt"] }, + transport: transport, + ) + + # Publishing directly on the bus stands in for a change announced by another worker. + bus.publish(Subscriptions::ToolsListChanged.new) + bus.publish(Subscriptions::ResourceUpdated.new(uri: "file:///subscribed.txt")) + bus.publish(Subscriptions::ResourceUpdated.new(uri: "file:///other.txt")) + + tools_events = sse_events(tools_io) + assert_equal 2, tools_events.size + assert_equal "notifications/tools/list_changed", tools_events[1]["method"] + assert_equal "listen-1", tools_events[1].dig("params", "_meta", "io.modelcontextprotocol/subscriptionId") + + resource_events = sse_events(resource_io) + assert_equal 2, resource_events.size + assert_equal "notifications/resources/updated", resource_events[1]["method"] + assert_equal "file:///subscribed.txt", resource_events[1].dig("params", "uri") + assert_equal "listen-2", resource_events[1].dig("params", "_meta", "io.modelcontextprotocol/subscriptionId") + ensure + transport.close + end + + test "an unknown event kind published on the subscription bus is ignored" do + bus = SubscriptionBus.new + server = Server.new(name: "listen_test", capabilities: { tools: { listChanged: true } }) + transport = StreamableHTTPTransport.new(server, subscription_bus: bus) + + io = open_listen_stream(id: "listen-1", notifications: { toolsListChanged: true }, transport: transport) + + # A newer publisher sharing the bus may emit event kinds this worker does not know. + bus.publish(:unrecognized_event) + bus.publish(Subscriptions::ToolsListChanged.new) + + events = sse_events(io) + assert_equal 2, events.size + assert_equal "notifications/tools/list_changed", events[1]["method"] + ensure + transport.close + end + + test "a change published in one worker reaches listen streams another worker holds" do + bus = SubscriptionBus.new + notifying_server = Server.new(name: "worker_a", capabilities: { tools: { listChanged: true } }) + notifying_transport = StreamableHTTPTransport.new(notifying_server, subscription_bus: bus) + listening_server = Server.new(name: "worker_b", capabilities: { tools: { listChanged: true } }) + listening_transport = StreamableHTTPTransport.new(listening_server, subscription_bus: bus) + + io = open_listen_stream(id: "listen-1", notifications: { toolsListChanged: true }, transport: listening_transport) + notifying_server.notify_tools_list_changed + + events = sse_events(io) + assert_equal 2, events.size + assert_equal "notifications/tools/list_changed", events[1]["method"] + assert_equal "listen-1", events[1].dig("params", "_meta", "io.modelcontextprotocol/subscriptionId") + ensure + notifying_transport.close + listening_transport.close + end + + test "transport close unregisters its subscription bus listener" do + bus = UnsubscribeTrackingBus.new + transport = StreamableHTTPTransport.new(Server.new(name: "listen_test"), subscription_bus: bus) + + transport.close + + assert bus.unsubscribed + end + + test "a raising bus unsubscribe is reported and does not stop the graceful teardown" do + server = Server.new(name: "listen_test", capabilities: { tools: { listChanged: true } }) + transport = StreamableHTTPTransport.new(server, subscription_bus: RaisingUnsubscribeBus.new) + io = open_listen_stream(id: "listen-1", notifications: { toolsListChanged: true }, transport: transport) + + reported = [] + original_reporter = MCP.configuration.exception_reporter + MCP.configuration.exception_reporter = ->(error, context) { reported << [error, context] } + + begin + transport.close + ensure + MCP.configuration.exception_reporter = original_reporter + end + + assert_equal ["unsubscribe boom"], reported.map { |error, _context| error.message } + assert_equal "complete", sse_events(io).last.dig("result", "resultType") + end + + test "a raising bus publish is reported and does not stop the local delivery" do + # The change senders rescue on their own, so what a raising custom bus used to cost was the delivery after the publish: + # the legacy GET streams and modern sinks of this worker never heard of the change. + server = Server.new(name: "listen_test", capabilities: { tools: { listChanged: true } }) + transport = StreamableHTTPTransport.new(server, subscription_bus: RaisingPublishBus.new) + io = StringIO.new + open_sse_session(transport, io: io) + + reported = [] + original_reporter = MCP.configuration.exception_reporter + MCP.configuration.exception_reporter = ->(error, context) { reported << [error, context] } + + begin + server.notify_tools_list_changed + ensure + MCP.configuration.exception_reporter = original_reporter + end + + assert_equal [["publish boom", { error: "Subscription bus publish failed" }]], reported.map { |error, context| [error.message, context] } + methods = io.string.lines.grep(/\Adata: /).map { |line| JSON.parse(line.sub("data: ", ""))["method"] } + assert_includes methods, "notifications/tools/list_changed" + ensure + transport.close + end + + # A bus that hands the transport's listener to the test, like the reader thread of a broker that rescues nothing. + class ListenerCapturingBus + attr_reader :listener, :unsubscribed + + def publish(_event); end + + def subscribe(&listener) + @listener = listener + proc { @unsubscribed = true } + end + end + + test "a delivery that raises is reported instead of raised into the subscription bus" do + bus = ListenerCapturingBus.new + server = Server.new(name: "listen_test", capabilities: { tools: { listChanged: true } }) + transport = StreamableHTTPTransport.new(server, subscription_bus: bus) + transport.stubs(:deliver_to_listen_subscriptions).raises(Errno::ETIMEDOUT) + + reported = [] + original_reporter = MCP.configuration.exception_reporter + MCP.configuration.exception_reporter = ->(error, context) { reported << [error.class, context] } + + begin + bus.listener.call(Subscriptions::ToolsListChanged.new) + ensure + MCP.configuration.exception_reporter = original_reporter + end + + assert_equal [[Errno::ETIMEDOUT, { error: "Subscription bus delivery failed" }]], reported + ensure + transport.close + end + + test "a transport that cannot be built leaves no listener on the subscription bus" do + bus = ListenerCapturingBus.new + StreamableHTTPTransport.any_instance.stubs(:start_reaper_thread).raises(ThreadError, "can't create Thread") + + assert_raises(ThreadError) do + StreamableHTTPTransport.new(Server.new(name: "listen_test"), subscription_bus: bus, session_idle_timeout: 60) + end + + assert bus.unsubscribed + end + + # A bus that keeps the transport's listener whatever happens: its unsubscribe callable raises, + # and with `fail_subscribe` its `subscribe` raises after registering. + class ListenerKeepingBus + attr_reader :listener + + def initialize(fail_subscribe: false) + @fail_subscribe = fail_subscribe + end + + def publish(_event); end + + def subscribe(&listener) + @listener = listener + raise "subscribe boom" if @fail_subscribe + + proc { raise "unsubscribe boom" } + end + end + + def with_exception_reporter(reporter) + original_reporter = MCP.configuration.exception_reporter + MCP.configuration.exception_reporter = reporter + yield + ensure + MCP.configuration.exception_reporter = original_reporter + end + + test "a listener the bus kept after close delivers nothing to the closed transport" do + bus = ListenerKeepingBus.new + server = Server.new(name: "listen_test", capabilities: { tools: { listChanged: true } }) + transport = StreamableHTTPTransport.new(server, subscription_bus: bus) + + with_exception_reporter(->(_error, _context) {}) { transport.close } + + io = open_listen_stream(id: "listen-1", notifications: { toolsListChanged: true }, transport: transport) + bus.listener.call(Subscriptions::ToolsListChanged.new) + + assert_equal 1, sse_events(io).size + ensure + with_exception_reporter(->(_error, _context) {}) { transport.close } + end + + test "a listener registered by a subscribe that then raised delivers nothing" do + bus = ListenerKeepingBus.new(fail_subscribe: true) + StreamableHTTPTransport.any_instance.expects(:deliver_event_to_listen_subscriptions).never + + error = assert_raises(RuntimeError) do + StreamableHTTPTransport.new(Server.new(name: "listen_test"), subscription_bus: bus) + end + assert_equal "subscribe boom", error.message + + bus.listener.call(Subscriptions::ToolsListChanged.new) + end + + test "a transport that cannot be built raises the cause when the bus unsubscribe raises as well" do + bus = ListenerKeepingBus.new + StreamableHTTPTransport.any_instance.stubs(:start_reaper_thread).raises(ThreadError, "can't create Thread") + StreamableHTTPTransport.any_instance.expects(:deliver_event_to_listen_subscriptions).never + + reported = [] + with_exception_reporter(->(error, context) { reported << [error.message, context] }) do + assert_raises(ThreadError) do + StreamableHTTPTransport.new(Server.new(name: "listen_test"), subscription_bus: bus, session_idle_timeout: 60) + end + end + + assert_equal [["unsubscribe boom", { error: "Subscription bus unsubscribe failed" }]], reported + bus.listener.call(Subscriptions::ToolsListChanged.new) + end + + test "an exception reporter that raises is not raised into the subscription bus" do + bus = ListenerCapturingBus.new + server = Server.new(name: "listen_test", capabilities: { tools: { listChanged: true } }) + transport = StreamableHTTPTransport.new(server, subscription_bus: bus) + transport.stubs(:deliver_to_listen_subscriptions).raises(Errno::ETIMEDOUT) + + with_exception_reporter(->(_error, _context) { raise "reporter boom" }) do + assert_nothing_raised { bus.listener.call(Subscriptions::ToolsListChanged.new) } + end + ensure + transport.close + end + + test "an exception reporter that raises on a bus unsubscribe failure does not stop the graceful teardown" do + server = Server.new(name: "listen_test", capabilities: { tools: { listChanged: true } }) + transport = StreamableHTTPTransport.new(server, subscription_bus: RaisingUnsubscribeBus.new) + io = open_listen_stream(id: "listen-1", notifications: { toolsListChanged: true }, transport: transport) + + with_exception_reporter(->(_error, _context) { raise "reporter boom" }) { transport.close } + + assert_equal "complete", sse_events(io).last.dig("result", "resultType") + end + + test "an exception reporter that raises on a bus publish failure does not stop the local delivery" do + server = Server.new(name: "listen_test", capabilities: { tools: { listChanged: true } }) + transport = StreamableHTTPTransport.new(server, subscription_bus: RaisingPublishBus.new) + io = StringIO.new + open_sse_session(transport, io: io) + + with_exception_reporter(->(_error, _context) { raise "reporter boom" }) do + transport.send_notification("notifications/tools/list_changed") + end + + methods = io.string.lines.grep(/\Adata: /).map { |line| JSON.parse(line.sub("data: ", ""))["method"] } + assert_includes methods, "notifications/tools/list_changed" + ensure + transport.close + end + + test "subscription_bus must respond to publish and subscribe" do + error = assert_raises(ArgumentError) do + StreamableHTTPTransport.new(Server.new(name: "listen_test"), subscription_bus: Object.new) + end + assert_equal "subscription_bus must respond to publish and subscribe", error.message + end + test "subscriptions/listen streams for different subscriptions receive their own subscriptionId" do first = open_listen_stream(id: "listen-1", notifications: { toolsListChanged: true }) second = open_listen_stream(id: "listen-2", notifications: { toolsListChanged: true }) diff --git a/test/mcp/subscriptions_test.rb b/test/mcp/subscriptions_test.rb new file mode 100644 index 00000000..e62cd42b --- /dev/null +++ b/test/mcp/subscriptions_test.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +require "test_helper" +require "open3" +require "rbconfig" + +module MCP + class SubscriptionsTest < ActiveSupport::TestCase + test "the module resolves right after require mcp, before any server file is loaded" do + # A custom bus restores events from its broker, typically at boot before the transport exists, + # so the constant must autoload on its own rather than as a side effect of loading the bus. + lib = File.expand_path("../../lib", __dir__) + script = 'require "mcp"; MCP::Subscriptions::ResourceUpdated.new(uri: "file:///a.txt"); puts "resolved"' + + output, status = Open3.capture2e(RbConfig.ruby, "-I", lib, "-e", script) + + assert_predicate status, :success?, output + assert_includes output, "resolved" + end + + test "list-changed events compare by class" do + assert_equal Subscriptions::ToolsListChanged.new, Subscriptions::ToolsListChanged.new + refute_equal Subscriptions::ToolsListChanged.new, Subscriptions::PromptsListChanged.new + assert_equal Subscriptions::ToolsListChanged.new.hash, Subscriptions::ToolsListChanged.new.hash + assert_predicate Subscriptions::ToolsListChanged.new, :frozen? + end + + test "resource-updated events compare by URI and validate it" do + updated = Subscriptions::ResourceUpdated.new(uri: "file:///a.txt") + + assert_equal "file:///a.txt", updated.uri + assert_predicate updated, :frozen? + assert_equal Subscriptions::ResourceUpdated.new(uri: "file:///a.txt"), updated + refute_equal Subscriptions::ResourceUpdated.new(uri: "file:///b.txt"), updated + assert_raises(ArgumentError) { Subscriptions::ResourceUpdated.new(uri: nil) } + end + + test "event_from_wire decodes the four change notifications" do + assert_equal Subscriptions::ToolsListChanged.new, Subscriptions.event_from_wire("notifications/tools/list_changed", nil) + assert_equal Subscriptions::PromptsListChanged.new, Subscriptions.event_from_wire("notifications/prompts/list_changed", nil) + assert_equal Subscriptions::ResourcesListChanged.new, Subscriptions.event_from_wire("notifications/resources/list_changed", nil) + assert_equal( + Subscriptions::ResourceUpdated.new(uri: "file:///a.txt"), Subscriptions.event_from_wire("notifications/resources/updated", { uri: "file:///a.txt" }) + ) + end + + test "event_from_wire accepts string params keys" do + assert_equal( + Subscriptions::ResourceUpdated.new(uri: "file:///a.txt"), Subscriptions.event_from_wire("notifications/resources/updated", { "uri" => "file:///a.txt" }) + ) + end + + test "event_from_wire returns nil for other methods and malformed params" do + assert_nil Subscriptions.event_from_wire("notifications/progress", { progress: 1 }) + assert_nil Subscriptions.event_from_wire("notifications/resources/updated", nil) + assert_nil Subscriptions.event_from_wire("notifications/resources/updated", { uri: 42 }) + end + end +end