Skip to content

[P6] subscriptions/listen: notification streams at 2026-07-28 (SEP-2575) - #365

Merged
jeanmatthieu merged 4 commits into
rel/1.0.0from
conformance/p6-listen
Nov 25, 2026
Merged

jeanmatthieu merged 4 commits into
rel/1.0.0from
conformance/p6-listen

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P6 of P0–P35, merged into rel/1.0.0 in order (previous: P5 (#366) · next: P7 (#364))
Branch conformance/p6-listen
Base conformance/p5-headers (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits 11985e7 subscriptions/listen: notification streams at 2026-07-28 (SEP-2575)
800cf9d subscriptions/listen: review fixes
39edf03 subscriptions/listen: second-pass review fixes
2c0474e subscriptions/listen: third-pass review fixes
Size 15 files, +2049 / -33

Summary

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.

Motivation

  • SEP-2575 (2026-07-28): stateless connections have no GET stream and no resources/subscribe/resources/unsubscribe. Notifications that do not belong to a request are delivered on subscriptions/listen streams; the first message is notifications/subscriptions/acknowledged, and every message carries _meta["io.modelcontextprotocol/subscriptionId"].
  • At 2026-07-28 over HTTP, a request is cancelled by closing its response stream.
  • Conformance: the server-stateless listen 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).
  • The client matches the Go SDK, which opens list-change streams from the registered handlers.

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.
  • Internal 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)

  • The unused subscriptions map is replaced by a listeners registry.
  • Built-in subscriptions/listen handler serveListen:
    • computes the honored filter: list-change kinds only when the matching capability declares listChanged, resource URIs only when resources.subscribe is declared;
    • registers the listener before sending the acknowledgement, so no event is lost;
    • forwards events with subscriptionId = the request id, buffering at most 256 (newest kept);
    • returns SubscriptionsListen.Result with the subscriptionId when 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 when isInitialized (an initialize session exists).
  • closeSubscriptions() ends every stream with its result; stop() calls it. Internal openSubscriptionCount.
  • StatelessRequests.statelessOnlyMethods uses SubscriptionsListen.name.

Transports

  • StatelessHTTPServerTransport:
    • JSONRPCMessageFields.replacingSubscriptionID rewrites the internal request id (mcp-http-<uuid>) to the client's id in params._meta and result._meta of messages on that exchange.
    • When the SSE response stream terminates with .cancelled (client gone), abandon removes the exchange and injects notifications/cancelled for the internal id, which cancels the handler.
  • HTTPClientTransport: in-flight POSTs are tracked by JSON-RPC id; new cancelRequest(_:) 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.invalidRequest otherwise); returns after the acknowledgement, or fails if the request ends first. The acknowledgement handler is registered in connect. The wait uses an AsyncStream of outcomes, because a task group whose child awaits Task.value cannot be cancelled.
    • cancelRequest(_:reason:) on a stateless HTTP connection aborts the POST through HTTPClientTransport.cancelRequest(_:) and does not send notifications/cancelled.
  • 11985e7 (reworked in 11985e7, see Review fixes):
    • refreshListChangeSubscription() runs after connect and whenever a handler for ToolListChangedNotification, PromptListChangedNotification or ResourceListChangedNotification is registered. Filter = kinds with a registered handler and a declared listChanged.
    • The stream opens in the background. A generation counter discards stale openings; the previous stream is cancelled after its successor is acknowledged. A stream that ends is forgotten, and the next refresh reopens it (no automatic retry).
    • subscribeToResource(uri:) at 2026-07-28 opens one stream per URI, waits for the acknowledgement, is idempotent, and throws MCPError.invalidRequest when the server does not honor the URI. Handshake connections still send resources/subscribe.
    • New unsubscribeFromResource(uri:): closes the URI's stream, or sends resources/unsubscribe on handshake connections.
    • New subscribedResourceURIs.
    • disconnect() cancels every listen stream before closing the connection.

Fixtures

  • Sources/MCPConformance/Server/main.swift: tools test_trigger_tool_change and test_trigger_prompt_change append test_dynamic_tool / test_dynamic_prompt to the lists and send the list-changed notification. Dynamic entries go at the end so tools[0] is unchanged.
  • Sources/MCPConformance/Server/HTTPApp.swift: the request task is cancelled on channelInactive.

Baselines

  • conformance-baseline.2026-07-28.yml, conformance-baseline.yml regenerated.

Docs

  • README.md: "Notification Streams" section (server and client behavior, example) and unsubscribeFromResource in the resources example.

Review fixes

Server (Sources/MCP/Server/Server.swift, Sources/MCP/Base/Subscriptions.swift)

  • Open streams and URIs per stream were unbounded. New Configuration.maxSubscriptionStreams (1000; -32600 beyond it) and maxResourceSubscriptions (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.
  • Any caller could listen to any resource URI. New withSubscriptionAuthorizer(_:): runs with the requested filter and the caller's HandlerContext before 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. New notify(_:to:) delivers only to streams whose caller's HandlerContext the predicate accepts; on an initialize session it also sends on the connection.
  • Resource-updated matching was a linear scan of each stream's URIs; listeners now keep a URI set. 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-alive comment every keepAliveInterval (new init parameter, default 15 seconds, nil for none). A listen request whose Accept lacks text/event-stream was accepted and its notifications could not be delivered; it is now refused with 406.
  • HTTPClientTransport: listen POSTs timed out after the session's timeoutIntervalForRequest; they now have an idle timeout of one hour. On Linux the transport reads whole bodies, so a listen response never arrived; package streamsResponses records this.

Client (Sources/MCP/Client/Client.swift)

  • One background stream (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 throws MCPError.invalidRequest when 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. subscribedResourceURIs lists the subscribed URIs the open stream serves.
  • A failed replacement dropped the working stream. The previous stream now stays open until a successor is acknowledged, and stays open when the successor fails; notifications of a replaced stream are dropped until it ends.
  • A failed stream was not reopened. It is now reopened after 1 second, doubling up to 60 seconds; a stream the server ends with its result is reopened by the next change.
  • On Linux with HTTPClientTransport, listen(_:) and subscribeToResource(uri:) throw MCPError.internalError at 2026-07-28 and no background stream is opened, instead of hanging.
  • disconnect() fails pending subscribeToResource calls 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
    end
Loading
stateDiagram-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: disconnect
Loading

API changes

Added

Symbol Notes
SubscriptionFilter Hashable, Codable, Sendable
SubscriptionsListen Method; Parameters, Result
SubscriptionsAcknowledgedNotification Notification
Metadata.subscriptionID ID?, key io.modelcontextprotocol/subscriptionId
Server.closeSubscriptions() ends every listen stream with its result
Client.Subscription id, notifications, cancel(), finished()
Client.listen(_:) stateless connections only
Client.unsubscribeFromResource(uri:) listen stream or resources/unsubscribe
Client.subscribedResourceURIs Set<String>
HTTPClientTransport.cancelRequest(_:) aborts the POST for a request id
Server.Configuration.maxSubscriptionStreams, maxResourceSubscriptions 1000 and 256; new defaulted init parameters
Server.withSubscriptionAuthorizer(_:) narrows or refuses a listen filter with the caller's HandlerContext
Server.notify(_:to:) delivers only to streams of matching callers
StatelessHTTPServerTransport.keepAliveInterval Duration?; new init parameter, default 15 seconds

Changed

Symbol Change
Client.subscribeToResource(uri:) adds the URI to the background listen stream on stateless connections
Client.cancelRequest(_:reason:) on stateless HTTP connections aborts the POST instead of sending notifications/cancelled
Server.notify(_:) list-changed and resource-updated notifications also go to listen streams, and go on the connection only after initialize

Removed

None (the removed subscriptions map was private).

Behavior changes

  • Server registers a subscriptions/listen handler by default.
  • Server.notify(_:) for notifications/{tools,prompts,resources}/list_changed and notifications/resources/updated returns without sending on the connection when the server has no initialize session. A server that sent these before initialize no longer sends them.
  • Server.stop() closes open listen streams.
  • On stateless connections, registering a list-changed handler opens a background subscriptions/listen request; disconnect() closes it.
  • StatelessHTTPServerTransport cancels the handler of a request whose SSE response stream the client closed.
  • On stateless connections the client keeps one background listen stream for list changes and subscribed resources. A failed stream is reopened after 1 second, doubling up to 60 seconds; a replacement that fails leaves the previous stream open.
  • Client.subscribedResourceURIs lists only the URIs the open stream serves.
  • Server refuses listen streams beyond maxSubscriptionStreams (-32600) and filters with more than maxResourceSubscriptions URIs or a URI longer than 4096 bytes (-32602).
  • StatelessHTTPServerTransport sends : keep-alive comments on open SSE streams every 15 seconds by default, and refuses a listen request without text/event-stream in Accept with 406.
  • Listen POSTs from HTTPClientTransport have a one-hour idle timeout.
  • On Linux, Client.listen(_:) and subscribeToResource(uri:) throw at 2026-07-28 over HTTPClientTransport.

Conformance

Baseline entries (server / client), alpha.11:

Leg Before (P5) After (P6)
2025-11-25 0 / 0 0 / 0
2026-07-28 18 / 31 13 / 31
default 43 / 35 38 / 35
  • Cleared: the five server-stateless:sep-2575-* listen entries, in both the 2026-07-28 and default legs.
  • Tier score 2026-07-28: server 27/37 (only MRTR left), client 11/32.
  • 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; closeSubscriptions ends streams with the listen result; listen requires 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; subscribeToResource opens one stream per URI; subscribeToResource fails 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.
  • 661 tests after 11985e7, 665 after 11985e7.
  • Review fixes:
    • 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 without text/event-stream is 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.
  • 736 swift-testing tests pass at the branch tip, plus XCTest.

Review notes

  • The honored filter is gated on the declared listChanged / resources.subscribe. The Python SDK honors every requested kind; this SDK acknowledges only what it can deliver.
  • Under StatelessHTTPServerTransport, HandlerContext.id is the internal id; the transport restores the client's id in subscriptionId by rewriting _meta on the way out. The rewrite only touches messages whose bytes contain the internal id.
  • The listener buffer keeps the 256 newest events per stream. Events are "refetch" triggers, so dropping older duplicates is safe.
  • abandon is 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.cancelRequest sends notifications/cancelled on stateless non-HTTP transports; only HTTP has a stream to close.
  • The background stream is not reopened when the server ends it with its result; the next handler registration or resource subscription reopens it (Go behavior). Streams that fail are reopened with backoff.
  • Without withSubscriptionAuthorizer, any caller can listen to every list change and any resource URI, and notify(_:) reaches every caller's matching stream.
  • Changing the client's filter replaces the whole stream: one more listen POST per handler registration or subscription change.

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.

swift build
swift test
BIN=$(swift build --show-bin-path)
scripts/run-conformance.sh --spec-version 2026-07-28 --mode server --bin-path "$BIN"
scripts/run-conformance.sh --spec-version 2026-07-28 --mode client --bin-path "$BIN"
scripts/run-conformance.sh --spec-version 2025-11-25 --bin-path "$BIN"
scripts/run-conformance.sh --bin-path "$BIN"
scripts/run-conformance.sh --requirements 2026-07-28 --bin-path "$BIN"

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.

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.
canarik
canarik previously approved these changes Nov 25, 2026

@canarik canarik left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @jeanmatthieu

Base automatically changed from conformance/p5-headers to rel/1.0.0 November 25, 2026 12:36
@jeanmatthieu
jeanmatthieu dismissed canarik’s stale review November 25, 2026 12:36

The base branch was changed.

@jeanmatthieu
jeanmatthieu merged commit d400768 into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/p6-listen branch November 25, 2026 12:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants