Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions docs/_server/subscriptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
3 changes: 2 additions & 1 deletion docs/_server/transports.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
1 change: 1 addition & 0 deletions lib/mcp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
1 change: 1 addition & 0 deletions lib/mcp/server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
63 changes: 63 additions & 0 deletions lib/mcp/server/subscription_bus.rb
Original file line number Diff line number Diff line change
@@ -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
Loading