Repository navigation
[P6] subscriptions/listen: notification streams at 2026-07-28 (SEP-2575) - #365
Merged
Merged
Conversation
Adds `subscriptions/listen`, the 2026-07-28 replacement for the standalone GET stream and `resources/subscribe`. `Server` serves listen streams itself: it acknowledges with the honored filter, forwards matching list-changed and resource-updated notifications tagged with the subscription id, and ends streams on cancellation, `closeSubscriptions()` or `stop()`. `Client` gains `listen(_:)` and opens list-change and resource streams automatically, so existing handler-based code works on stateless connections without changes. The client also keeps one background stream for list changes and resources, reopens it with backoff when it fails, and keeps the working stream when a replacement fails. The server caps streams and URIs, can narrow or refuse filters through an authorizer, can target notifications at some callers, and keeps idle SSE streams alive.
- A replaced background listen stream delivers the notifications the client still wants (a list change it has a handler for, an update for a subscribed URI) until it ends. An event the server published before it registered the successor exists only on the replaced stream, so dropping all of them lost events; one sent during the overlap may now arrive twice. - A failed opening of the background stream fails and unsubscribes only the URIs whose subscribeToResource call is still waiting. Before, a failed reopen after the stream dropped unsubscribed every resource and no further reopen was scheduled. - subscribeToResource throws when the client is disconnected instead of waiting forever, and disconnect() also fails a call made while it was closing the stream. - The reopen backoff is reset when a stream ends normally or after it stayed open for the longest delay, not when a stream is acknowledged, so a server that acknowledges and then drops each stream sees growing delays. - HTTPClientTransport.cancelRequest remembers, up to 64, ids whose POST has not started; send then throws CancellationError instead of posting a request the client already cancelled.
- A background listen stream the server ends with its result is now reopened after the backoff delay, like one that failed. A server ends streams this way on stop() and closeSubscriptions(), as for a restart, and the client otherwise stopped receiving list-changed and resource-updated notifications until the next handler registration or subscribe. A stream that ends within 60 seconds of opening counts toward the backoff, so a server that closes every stream at once is asked at most once a minute. The 2026-07-28 subscriptions page lets the client reconnect; it does not tie that to an abrupt drop only. - subscribeToResource now ends when its task is cancelled: it throws CancellationError, and drops the URI again when this call added it, the stream does not serve it yet, and no other call waits for it. Before, a server that never acknowledged the stream kept the call and the subscription pending after the caller gave up.
- Server.stop() now waits for the listen streams it ends to send their result before it closes the transport. closeSubscriptions() only finishes the event streams; the handlers resume once stop() suspends, which was in connection.disconnect(), so the results went to a closed transport and Subscription.finished() never returned. A listen stream that finishes authorization while the server stops, or after it stopped, is refused instead of opening on a closed connection. - Cancelling subscribeToResource drops the URI when the last call waiting for it leaves and no stream has served it yet. Ownership was decided per call: of two concurrent calls for one URI only the first could drop it, so cancelling the first and then the second left the URI subscribed and still requested on the stream. A URI a stream has served stays when a later call for it is cancelled. - subscribeToResource from an already-cancelled task throws before it touches the subscription, instead of opening a stream for the URI that its cancellation then replaced. - A replacement stream acknowledged after its predecessor ended keeps its filter and cancels the reopen that the end scheduled. The end cleared the filter, so the next refresh, a handler registration or the retry, opened the same stream again. - README: until a replaced stream ends, its notifications the client still wants are delivered; a stream that ends, with an error or with its result, is reopened with the backoff; stop() waits for the listen results.
This was referenced Nov 25, 2026
canarik
approved these changes
Nov 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
rel/1.0.0in order (previous: P5 (#366) · next: P7 (#364))conformance/p6-listenconformance/p5-headers(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)11985e7subscriptions/listen: notification streams at 2026-07-28 (SEP-2575)800cf9dsubscriptions/listen: review fixes39edf03subscriptions/listen: second-pass review fixes2c0474esubscriptions/listen: third-pass review fixesSummary
Adds
subscriptions/listen, the 2026-07-28 replacement for the standalone GET stream andresources/subscribe.Serverserves listen streams itself: it acknowledges with the honored filter, forwards matching list-changed and resource-updated notifications tagged with the subscription id, and ends streams on cancellation,closeSubscriptions()orstop().Clientgainslisten(_:)and opens list-change and resource streams automatically, so existing handler-based code works on stateless connections without changes.The client also keeps one background stream for list changes and resources, reopens it with backoff when it fails, and keeps the working stream when a replacement fails. The server caps streams and URIs, can narrow or refuse filters through an authorizer, can target notifications at some callers, and keeps idle SSE streams alive.
Motivation
resources/subscribe/resources/unsubscribe. Notifications that do not belong to a request are delivered onsubscriptions/listenstreams; the first message isnotifications/subscriptions/acknowledged, and every message carries_meta["io.modelcontextprotocol/subscriptionId"].server-statelesslisten checks (sep-2575-server-sends-subscription-ack,-honors-notification-filter,-tags-subscription-id,-sends-tools-list-changed-on-subscription,-sends-prompts-list-changed-on-subscription).Changes
Base types (
Sources/MCP/Base/Subscriptions.swift, new)SubscriptionFilter:toolsListChanged,promptsListChanged,resourcesListChanged,resourceSubscriptions.SubscriptionsListen(subscriptions/listen):Parameters(notifications:),Result(_meta:).SubscriptionsAcknowledgedNotification(notifications/subscriptions/acknowledged).Metadata.subscriptionID.SubscriptionEvent: maps the four notification methods to events, matches filters, builds the tagged message.Server (
Sources/MCP/Server/Server.swift,Sources/MCP/Server/StatelessRequests.swift)subscriptionsmap is replaced by alistenersregistry.subscriptions/listenhandlerserveListen:listChanged, resource URIs only whenresources.subscribeis declared;subscriptionId= the request id, buffering at most 256 (newest kept);SubscriptionsListen.Resultwith thesubscriptionIdwhen the stream is closed by the server; throws on cancellation.notify(_:)publishes list-changed and resource-updated notifications to matching listeners, and sends them on the connection only whenisInitialized(aninitializesession exists).closeSubscriptions()ends every stream with its result;stop()calls it. InternalopenSubscriptionCount.StatelessRequests.statelessOnlyMethodsusesSubscriptionsListen.name.Transports
StatelessHTTPServerTransport:JSONRPCMessageFields.replacingSubscriptionIDrewrites the internal request id (mcp-http-<uuid>) to the client's id inparams._metaandresult._metaof messages on that exchange..cancelled(client gone),abandonremoves the exchange and injectsnotifications/cancelledfor the internal id, which cancels the handler.HTTPClientTransport: in-flight POSTs are tracked by JSON-RPC id; newcancelRequest(_:)aborts the POST, closing its response stream. Cancelling the caller's task also cancels the POST.Client (
Sources/MCP/Client/Client.swift)11985e7:Client.Subscription(id,notifications,cancel(),finished()).listen(_:): stateless only (MCPError.invalidRequestotherwise); returns after the acknowledgement, or fails if the request ends first. The acknowledgement handler is registered inconnect. The wait uses anAsyncStreamof outcomes, because a task group whose child awaitsTask.valuecannot be cancelled.cancelRequest(_:reason:)on a stateless HTTP connection aborts the POST throughHTTPClientTransport.cancelRequest(_:)and does not sendnotifications/cancelled.11985e7(reworked in11985e7, see Review fixes):refreshListChangeSubscription()runs afterconnectand whenever a handler forToolListChangedNotification,PromptListChangedNotificationorResourceListChangedNotificationis registered. Filter = kinds with a registered handler and a declaredlistChanged.subscribeToResource(uri:)at 2026-07-28 opens one stream per URI, waits for the acknowledgement, is idempotent, and throwsMCPError.invalidRequestwhen the server does not honor the URI. Handshake connections still sendresources/subscribe.unsubscribeFromResource(uri:): closes the URI's stream, or sendsresources/unsubscribeon handshake connections.subscribedResourceURIs.disconnect()cancels every listen stream before closing the connection.Fixtures
Sources/MCPConformance/Server/main.swift: toolstest_trigger_tool_changeandtest_trigger_prompt_changeappendtest_dynamic_tool/test_dynamic_promptto the lists and send the list-changed notification. Dynamic entries go at the end sotools[0]is unchanged.Sources/MCPConformance/Server/HTTPApp.swift: the request task is cancelled onchannelInactive.Baselines
conformance-baseline.2026-07-28.yml,conformance-baseline.ymlregenerated.Docs
README.md: "Notification Streams" section (server and client behavior, example) andunsubscribeFromResourcein the resources example.Review fixes
Server (
Sources/MCP/Server/Server.swift,Sources/MCP/Base/Subscriptions.swift)Configuration.maxSubscriptionStreams(1000; -32600 beyond it) andmaxResourceSubscriptions(256; -32602 beyond it); a URI longer than 4096 bytes is refused with -32602; duplicate URIs are dropped. Both keys decode with their defaults when absent.withSubscriptionAuthorizer(_:): runs with the requested filter and the caller'sHandlerContextbefore the acknowledgement, returns the filter to serve or throws to refuse. Its result is checked against the same limits.notify(_:)reached every caller's matching stream. Newnotify(_:to:)delivers only to streams whose caller'sHandlerContextthe predicate accepts; on aninitializesession it also sends on the connection.SubscriptionEvent(_:)reads the typed notification instead of re-encoding its parameters.Transports
StatelessHTTPServerTransport: idle listen streams were closed by client or proxy timeouts. Open SSE streams now carry a: keep-alivecomment everykeepAliveInterval(new init parameter, default 15 seconds,nilfor none). A listen request whoseAcceptlackstext/event-streamwas accepted and its notifications could not be delivered; it is now refused with 406.HTTPClientTransport: listen POSTs timed out after the session'stimeoutIntervalForRequest; they now have an idle timeout of one hour. On Linux the transport reads whole bodies, so a listen response never arrived; packagestreamsResponsesrecords this.Client (
Sources/MCP/Client/Client.swift)notificationStream) now carries the wanted list changes and every subscribed resource, instead of one stream per URI plus one for list changes.subscribeToResource(uri:)adds the URI and returns once a stream that names it is acknowledged; it throwsMCPError.invalidRequestwhen the server does not serve the URI, or the error that kept the stream from opening.unsubscribeFromResource(uri:)replaces the stream with one without the URI.subscribedResourceURIslists the subscribed URIs the open stream serves.HTTPClientTransport,listen(_:)andsubscribeToResource(uri:)throwMCPError.internalErrorat 2026-07-28 and no background stream is opened, instead of hanging.disconnect()fails pendingsubscribeToResourcecalls and cancels a pending reopen.Docs
README.md: one client stream, reopen backoff, limits, authorizer,notify(_:to:), keep-alive, the 406, the Linux limitation.Diagram
sequenceDiagram participant C as Client participant T as StatelessHTTPServerTransport participant S as Server C->>T: POST subscriptions/listen, id 7 T->>S: request with internal id S->>S: register listener with honored filter S->>T: notifications/subscriptions/acknowledged T-->>C: SSE ack, subscriptionId 7 Note over S: server.notify(ToolListChangedNotification) S->>T: tools/list_changed, subscriptionId internal T-->>C: SSE tools/list_changed, subscriptionId 7 alt client cancels C->>T: close POST stream T->>S: notifications/cancelled for internal id S->>S: handler cancelled, listener removed else server closes Note over S: closeSubscriptions() or stop() S->>T: listen result T-->>C: SSE result, subscriptionId 7 endstateDiagram-v2 [*] --> None None --> Opening: handler registered or resource subscribed Opening --> Open: acknowledged, current generation Opening --> Retrying: listen failed, previous stream kept Retrying --> Opening: backoff, 1 s doubling to 60 s Opening --> Opening: wanted filter changed, new generation Open --> Opening: wanted filter changed, open until successor acknowledged Open --> Retrying: stream failed Open --> None: server ends stream with its result Open --> None: disconnectAPI changes
Added
SubscriptionFilterHashable,Codable,SendableSubscriptionsListenMethod;Parameters,ResultSubscriptionsAcknowledgedNotificationNotificationMetadata.subscriptionIDID?, keyio.modelcontextprotocol/subscriptionIdServer.closeSubscriptions()Client.Subscriptionid,notifications,cancel(),finished()Client.listen(_:)Client.unsubscribeFromResource(uri:)resources/unsubscribeClient.subscribedResourceURIsSet<String>HTTPClientTransport.cancelRequest(_:)Server.Configuration.maxSubscriptionStreams,maxResourceSubscriptionsinitparametersServer.withSubscriptionAuthorizer(_:)HandlerContextServer.notify(_:to:)StatelessHTTPServerTransport.keepAliveIntervalDuration?; newinitparameter, default 15 secondsChanged
Client.subscribeToResource(uri:)Client.cancelRequest(_:reason:)notifications/cancelledServer.notify(_:)initializeRemoved
None (the removed
subscriptionsmap was private).Behavior changes
Serverregisters asubscriptions/listenhandler by default.Server.notify(_:)fornotifications/{tools,prompts,resources}/list_changedandnotifications/resources/updatedreturns without sending on the connection when the server has noinitializesession. A server that sent these beforeinitializeno longer sends them.Server.stop()closes open listen streams.subscriptions/listenrequest;disconnect()closes it.StatelessHTTPServerTransportcancels the handler of a request whose SSE response stream the client closed.Client.subscribedResourceURIslists only the URIs the open stream serves.Serverrefuses listen streams beyondmaxSubscriptionStreams(-32600) and filters with more thanmaxResourceSubscriptionsURIs or a URI longer than 4096 bytes (-32602).StatelessHTTPServerTransportsends: keep-alivecomments on open SSE streams every 15 seconds by default, and refuses a listen request withouttext/event-streaminAcceptwith 406.HTTPClientTransporthave a one-hour idle timeout.Client.listen(_:)andsubscribeToResource(uri:)throw at 2026-07-28 overHTTPClientTransport.Conformance
Baseline entries (server / client), alpha.11:
server-stateless:sep-2575-*listen entries, in both the 2026-07-28 and default legs.11985e7,11985e7: all conformance legs pass unchanged.Tests
Tests/MCPTests/SubscriptionTests.swift(new, "Subscription Tests"):11985e7: acknowledgement with the supported subset; notifications reach the requesting streams tagged with the stream id; cancelling a subscription ends the server's stream;closeSubscriptionsends streams with the listen result;listenrequires a stateless connection; list changes go on the connection only to handshake sessions; filter and acknowledgement encode with spec member names.11985e7: list-change handlers open a background stream; no stream when the server does not declare list changes;subscribeToResourceopens one stream per URI;subscribeToResourcefails when the server does not send resource updates.Tests/MCPTests/StatelessServerTests.swift("Stateless HTTP Tests"): listen streams carry the client's id and end when the client goes away.11985e7, 665 after11985e7.Tests/MCPTests/SubscriptionTests.swift: resource subscriptions share one background stream (replaces the one-stream-per-URI test); a replacement that fails to open leaves the working stream open; the reopen delay doubles from one second up to a minute; a failed background stream is reopened; the server caps streams and URIs and removes duplicates; the authorizer narrows the filter with the caller's context;notify(_:to:)reaches only matching callers.Tests/MCPTests/StatelessServerTests.swift: listen withouttext/event-streamis refused with 406; open SSE streams carry keep-alive comments.Tests/MCPTests/HTTPClientReliabilityTests.swift, new suite "HTTP client listen requests": a listen POST has the long idle timeout, other POSTs keep the default.Review notes
listChanged/resources.subscribe. The Python SDK honors every requested kind; this SDK acknowledges only what it can deliver.StatelessHTTPServerTransport,HandlerContext.idis the internal id; the transport restores the client's id insubscriptionIdby rewriting_metaon the way out. The rewrite only touches messages whose bytes contain the internal id.abandonis wired only to the SSE path. A pending JSON (non-SSE) reply is not cancelled when the client disconnects; found during the P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362) doc review (issue 7) and fixed in P11 ([P11] fix: request lifecycle, server replies, OAuth hardening #360) (conformance/p11-fixes).Client.cancelRequestsendsnotifications/cancelledon stateless non-HTTP transports; only HTTP has a stream to close.withSubscriptionAuthorizer, any caller can listen to every list change and any resource URI, andnotify(_:)reaches every caller's matching stream.Verification
Every branch of the stack builds and passes
swift test; all conformance legs pass at their baselines. On this branch, 736 swift-testing tests plus XCTest, all passed.AI usage disclosure: the changes, the tests, the commit messages and this description were written with Claude Opus 5.5 and reviewed by the authors.