|
| 1 | +"""Server-side `subscriptions/listen` support (2026-07-28, SEP-2575). |
| 2 | +
|
| 3 | +On the 2026-07-28 wire there is no standing GET stream: a client opts in to |
| 4 | +server events by sending a `subscriptions/listen` request whose response IS |
| 5 | +the stream. This module provides the two pieces a server needs: |
| 6 | +
|
| 7 | +- `EventBus`: the pluggable fan-out seam. The bus carries typed `ServerEvent` |
| 8 | + values, not wire notifications - the listen handler owns subscription-id |
| 9 | + stamping and per-stream filtering, so a custom bus (e.g. backed by Redis |
| 10 | + pub/sub for multi-replica deployments) never sees JSON-RPC. The in-process |
| 11 | + default is `InMemoryEventBus`. |
| 12 | +- `ListenHandler`: the request handler that serves `subscriptions/listen`. |
| 13 | + `MCPServer` registers one automatically; lowlevel `Server` users pass an |
| 14 | + instance as `on_subscriptions_listen=`. |
| 15 | +
|
| 16 | +Per the spec, the handler acknowledges first (the ack is the first frame on |
| 17 | +the stream), tags every frame with the listen request's JSON-RPC id under |
| 18 | +`_meta["io.modelcontextprotocol/subscriptionId"]`, and never delivers an |
| 19 | +event kind the client did not request. Delivery is fire-and-forget with no |
| 20 | +replay: a dropped stream is not resumable - clients re-listen and refetch. |
| 21 | +""" |
| 22 | + |
| 23 | +from __future__ import annotations |
| 24 | + |
| 25 | +import math |
| 26 | +from collections.abc import Callable |
| 27 | +from dataclasses import dataclass |
| 28 | +from typing import Any, Protocol |
| 29 | + |
| 30 | +import anyio |
| 31 | +import anyio.streams.memory |
| 32 | +from mcp_types import ( |
| 33 | + INVALID_REQUEST, |
| 34 | + NotificationParams, |
| 35 | + PromptListChangedNotification, |
| 36 | + ResourceListChangedNotification, |
| 37 | + ResourceUpdatedNotification, |
| 38 | + ResourceUpdatedNotificationParams, |
| 39 | + ServerNotification, |
| 40 | + SubscriptionFilter, |
| 41 | + SubscriptionsAcknowledgedNotification, |
| 42 | + SubscriptionsAcknowledgedNotificationParams, |
| 43 | + SubscriptionsListenRequestParams, |
| 44 | + SubscriptionsListenResult, |
| 45 | + ToolListChangedNotification, |
| 46 | +) |
| 47 | + |
| 48 | +from mcp.server.context import ServerRequestContext |
| 49 | +from mcp.shared.exceptions import MCPError |
| 50 | + |
| 51 | +SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId" |
| 52 | +"""The `_meta` key carrying the subscription id on every listen-stream frame. |
| 53 | +
|
| 54 | +The value is the `subscriptions/listen` request's JSON-RPC id, verbatim. |
| 55 | +""" |
| 56 | + |
| 57 | + |
| 58 | +@dataclass(frozen=True) |
| 59 | +class ToolsListChanged: |
| 60 | + """The server's tool list changed.""" |
| 61 | + |
| 62 | + |
| 63 | +@dataclass(frozen=True) |
| 64 | +class PromptsListChanged: |
| 65 | + """The server's prompt list changed.""" |
| 66 | + |
| 67 | + |
| 68 | +@dataclass(frozen=True) |
| 69 | +class ResourcesListChanged: |
| 70 | + """The server's resource list changed.""" |
| 71 | + |
| 72 | + |
| 73 | +@dataclass(frozen=True) |
| 74 | +class ResourceUpdated: |
| 75 | + """The resource at `uri` changed and may need to be read again.""" |
| 76 | + |
| 77 | + uri: str |
| 78 | + |
| 79 | + |
| 80 | +ServerEvent = ToolsListChanged | PromptsListChanged | ResourcesListChanged | ResourceUpdated |
| 81 | +"""An event a server publishes for delivery to listen subscribers.""" |
| 82 | + |
| 83 | + |
| 84 | +class EventBus(Protocol): |
| 85 | + """Fan-out seam between event publishers and open listen streams. |
| 86 | +
|
| 87 | + Implement this over an external pub/sub backend (Redis, NATS, ...) to fan |
| 88 | + events out across replicas: `publish` forwards the event to the backend, |
| 89 | + and each replica's bus invokes its local listeners for events arriving |
| 90 | + from the backend. The same instance can be shared across servers. |
| 91 | +
|
| 92 | + Both methods are synchronous and must be called from the server's event |
| 93 | + loop thread. Listeners must not raise. |
| 94 | + """ |
| 95 | + |
| 96 | + def publish(self, event: ServerEvent) -> None: |
| 97 | + """Deliver `event` to every subscribed listener.""" |
| 98 | + ... |
| 99 | + |
| 100 | + def subscribe(self, listener: Callable[[ServerEvent], None]) -> Callable[[], None]: |
| 101 | + """Register `listener` and return an idempotent unsubscribe callable.""" |
| 102 | + ... |
| 103 | + |
| 104 | + |
| 105 | +class InMemoryEventBus: |
| 106 | + """In-process `EventBus`: synchronous fan-out to a set of listeners.""" |
| 107 | + |
| 108 | + def __init__(self) -> None: |
| 109 | + self._listeners: set[Callable[[ServerEvent], None]] = set() |
| 110 | + |
| 111 | + def publish(self, event: ServerEvent) -> None: |
| 112 | + """Deliver `event` to every subscribed listener.""" |
| 113 | + for listener in list(self._listeners): |
| 114 | + listener(event) |
| 115 | + |
| 116 | + def subscribe(self, listener: Callable[[ServerEvent], None]) -> Callable[[], None]: |
| 117 | + """Register `listener` and return an idempotent unsubscribe callable.""" |
| 118 | + self._listeners.add(listener) |
| 119 | + |
| 120 | + def unsubscribe() -> None: |
| 121 | + self._listeners.discard(listener) |
| 122 | + |
| 123 | + return unsubscribe |
| 124 | + |
| 125 | + |
| 126 | +def _honored_subset(requested: SubscriptionFilter) -> SubscriptionFilter: |
| 127 | + """The subset of `requested` the server will deliver, for the ack. |
| 128 | +
|
| 129 | + Every requested kind is honored - whether an event kind ever fires |
| 130 | + depends on what the server publishes, exactly as a subscription to a |
| 131 | + nonexistent resource URI is honored and never fires. Non-true flags and |
| 132 | + an empty URI list are dropped rather than echoed as falsy values. |
| 133 | + """ |
| 134 | + return SubscriptionFilter( |
| 135 | + tools_list_changed=True if requested.tools_list_changed else None, |
| 136 | + prompts_list_changed=True if requested.prompts_list_changed else None, |
| 137 | + resources_list_changed=True if requested.resources_list_changed else None, |
| 138 | + resource_subscriptions=list(requested.resource_subscriptions) if requested.resource_subscriptions else None, |
| 139 | + ) |
| 140 | + |
| 141 | + |
| 142 | +def _event_matches(honored: SubscriptionFilter, event: ServerEvent) -> bool: |
| 143 | + """Whether `event` is within the stream's honored filter.""" |
| 144 | + if isinstance(event, ToolsListChanged): |
| 145 | + return honored.tools_list_changed is True |
| 146 | + if isinstance(event, PromptsListChanged): |
| 147 | + return honored.prompts_list_changed is True |
| 148 | + if isinstance(event, ResourcesListChanged): |
| 149 | + return honored.resources_list_changed is True |
| 150 | + return honored.resource_subscriptions is not None and event.uri in honored.resource_subscriptions |
| 151 | + |
| 152 | + |
| 153 | +def _event_to_notification(event: ServerEvent, meta: dict[str, Any]) -> ServerNotification: |
| 154 | + """Build the stamped wire notification for `event`.""" |
| 155 | + if isinstance(event, ToolsListChanged): |
| 156 | + return ToolListChangedNotification(params=NotificationParams(_meta=meta)) |
| 157 | + if isinstance(event, PromptsListChanged): |
| 158 | + return PromptListChangedNotification(params=NotificationParams(_meta=meta)) |
| 159 | + if isinstance(event, ResourcesListChanged): |
| 160 | + return ResourceListChangedNotification(params=NotificationParams(_meta=meta)) |
| 161 | + return ResourceUpdatedNotification(params=ResourceUpdatedNotificationParams(uri=event.uri, _meta=meta)) |
| 162 | + |
| 163 | + |
| 164 | +class ListenHandler: |
| 165 | + """Serves `subscriptions/listen`: one call is one subscription stream. |
| 166 | +
|
| 167 | + Register on a lowlevel `Server` via `on_subscriptions_listen=` (or |
| 168 | + `add_request_handler`); `MCPServer` does so automatically. Each call |
| 169 | + acknowledges the honored filter first, then forwards matching bus events |
| 170 | + onto the request's response stream until the client disconnects (which |
| 171 | + cancels the handler; the stream just ends, per the spec's abrupt-close |
| 172 | + contract) or `close` ends all streams gracefully. |
| 173 | +
|
| 174 | + Requires a transport that can stream a request's response (streamable |
| 175 | + HTTP's SSE mode, stdio). |
| 176 | + """ |
| 177 | + |
| 178 | + def __init__(self, bus: EventBus) -> None: |
| 179 | + self._bus = bus |
| 180 | + self._streams: set[anyio.streams.memory.MemoryObjectSendStream[ServerEvent]] = set() |
| 181 | + |
| 182 | + async def __call__( |
| 183 | + self, |
| 184 | + ctx: ServerRequestContext[Any, Any], |
| 185 | + params: SubscriptionsListenRequestParams, |
| 186 | + ) -> SubscriptionsListenResult: |
| 187 | + """Serve one listen stream.""" |
| 188 | + subscription_id = ctx.request_id |
| 189 | + if subscription_id is None: |
| 190 | + raise MCPError(INVALID_REQUEST, "subscriptions/listen requires a request id") |
| 191 | + honored = _honored_subset(params.notifications) |
| 192 | + meta: dict[str, Any] = {SUBSCRIPTION_ID_META_KEY: subscription_id} |
| 193 | + |
| 194 | + # Ack first, subscribe second: no event can precede the ack frame. |
| 195 | + await ctx.session.send_notification( |
| 196 | + SubscriptionsAcknowledgedNotification( |
| 197 | + params=SubscriptionsAcknowledgedNotificationParams(notifications=honored, _meta=meta) |
| 198 | + ), |
| 199 | + related_request_id=subscription_id, |
| 200 | + ) |
| 201 | + |
| 202 | + # Unbounded buffer so publishers never block on a slow consumer (the |
| 203 | + # transport write happens in this handler task, not the publisher's). |
| 204 | + send, recv = anyio.create_memory_object_stream[ServerEvent](math.inf) |
| 205 | + |
| 206 | + def deliver(event: ServerEvent) -> None: |
| 207 | + if _event_matches(honored, event): |
| 208 | + try: |
| 209 | + send.send_nowait(event) |
| 210 | + except anyio.ClosedResourceError: |
| 211 | + # `aclose` closed this stream; the loop below is unwinding. |
| 212 | + pass |
| 213 | + |
| 214 | + unsubscribe = self._bus.subscribe(deliver) |
| 215 | + self._streams.add(send) |
| 216 | + try: |
| 217 | + async for event in recv: |
| 218 | + await ctx.session.send_notification( |
| 219 | + _event_to_notification(event, meta), related_request_id=subscription_id |
| 220 | + ) |
| 221 | + finally: |
| 222 | + unsubscribe() |
| 223 | + self._streams.discard(send) |
| 224 | + send.close() |
| 225 | + recv.close() |
| 226 | + return SubscriptionsListenResult(_meta=meta) |
| 227 | + |
| 228 | + def close(self) -> None: |
| 229 | + """Gracefully end every open listen stream. |
| 230 | +
|
| 231 | + Each stream sends its `SubscriptionsListenResult` (stamped with the |
| 232 | + subscription id) as the final frame and closes - the spec's graceful |
| 233 | + closure flow, signalling clients not to re-listen. |
| 234 | + """ |
| 235 | + for stream in list(self._streams): |
| 236 | + stream.close() |
0 commit comments