Skip to content

Commit b07b2b3

Browse files
committed
Add a subscription narrowing hook and stop sending unrequested change notifications
Two server-side gaps on the 2026-07-28 subscriptions/listen path, closed together because either alone leaves the other's leak open. Nothing let a server decide per caller what a subscription may watch: any client could name any resource URI in its filter and the server honored it verbatim. ListenHandler now takes an optional `narrow` hook (`MCPServer(narrow_subscriptions=...)`) that runs once before the acknowledgment and returns the filter to grant, or raises MCPError to refuse the request. The grant is intersected with the request so a hook can narrow but never widen, and any other exception fails closed rather than granting. Separately, the modern-era standalone channel forwarded every notification, so `ctx.session.send_tool_list_changed()` on a 2026-07-28 stdio connection wrote a bare, unstamped list_changed frame that no subscription had requested. That channel now drops the four change-notification methods; they reach clients only through listen streams, which stamp and filter them.
1 parent 923341c commit b07b2b3

8 files changed

Lines changed: 311 additions & 35 deletions

File tree

docs/handlers/subscriptions.md

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,36 @@ Two things the stream is *not*:
4343
* **It is not a replay log.** A dropped stream is gone, and events published while nobody was connected are not queued. Clients re-listen and refetch.
4444
* **It is not the 2025 path.** Clients that called `resources/subscribe` are served by `ctx.session.send_resource_updated(uri)`. The `notify_*` methods reach `subscriptions/listen` streams only.
4545

46-
!!! warning
47-
Don't publish sensitive per-user URIs through `notify_resource_updated` on a multi-tenant
48-
server. Any client may name any URI in its filter, and `MCPServer` honors it. The exposure
49-
is narrow but real: a subscriber learns that a URI it can guess changed, and when. It never
50-
learns content, and it cannot probe what exists, because an unknown URI is honored too and
51-
simply never fires. To narrow the filter per client today, serve the method with your own
52-
handler on the low-level `Server` and acknowledge a smaller filter than the client asked
53-
for; the acknowledgment is how the client learns what it actually got.
46+
## Deciding what a caller may watch
47+
48+
By default every requested kind and URI is honored: any caller may watch any URI you publish. On a multi-tenant server, decide per caller with a narrowing hook. It runs once per `subscriptions/listen`, before the acknowledgment, with the request context and the filter the client asked for, and returns the filter to grant:
49+
50+
```python
51+
from mcp.server.auth.middleware.auth_context import get_access_token
52+
from mcp.server.context import ServerRequestContext
53+
from mcp.server.mcpserver import MCPServer
54+
from mcp_types import SubscriptionFilter
55+
56+
57+
async def owned_only(ctx: ServerRequestContext, requested: SubscriptionFilter) -> SubscriptionFilter:
58+
token = get_access_token()
59+
prefix = f"user://{token.subject}/" if token and token.subject else ""
60+
watchable = [uri for uri in requested.resource_subscriptions or [] if prefix and uri.startswith(prefix)]
61+
return requested.model_copy(update={"resource_subscriptions": watchable})
62+
63+
64+
mcp = MCPServer("Sprint Board", narrow_subscriptions=owned_only)
65+
```
66+
67+
* The grant is intersected with the request, so a hook can drop kinds and URIs but never add them.
68+
* The acknowledgment reports the grant; that is how the client learns it got less than it asked for.
69+
* Decide by pattern, not by lookup. `owned_only` prunes everything outside the caller's own prefix without checking whether a URI exists, so the acknowledgment reveals the shape of the policy and nothing about which URIs are real.
70+
* To refuse the whole subscription, raise `MCPError` from the hook: the client gets the error and no stream. Any other exception refuses too - a broken policy never grants.
71+
* The decision holds for the stream's lifetime. There is no per-event re-check, so if a caller's access can lapse mid-stream (an expiring token), end that caller's connection when it does. `ListenHandler.close()` is not the tool for that: it ends every open stream at once, which you want at shutdown, not for one caller.
72+
73+
On the low-level `Server` the same hook is `ListenHandler(bus, narrow=owned_only)`.
74+
75+
Without a hook the exposure is narrow but real, so weigh it before publishing per-user URIs from a multi-tenant server: a subscriber learns that a URI it can guess changed, and when. It never learns content, and it cannot probe what exists, because an unknown URI is honored too and simply never fires.
5476

5577
## The client end
5678

docs/migration.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -721,7 +721,7 @@ This parameter was redundant because the SSE transport already handles sub-path
721721

722722
### Transport-specific parameters moved from MCPServer constructor to run()/app methods
723723

724-
Transport-specific parameters have been moved off the `MCPServer` constructor and onto `run()`, `sse_app()`, and `streamable_http_app()`, so transport configuration is passed when starting or building the server. The rest of the constructor is unchanged: identity (`name`, `instructions`, `website_url`, `icons`, plus the newly added positional `title`, `description`, and `version` covered [above](#mcpserver-constructor-title-description-and-version-added-to-the-positional-parameters)), authentication (`auth`, `token_verifier`, `auth_server_provider`), `lifespan`, `dependencies`, `tools`, `debug`, `log_level`, and the `warn_on_duplicate_*` flags; the new keyword-only parameters (`resources`, `extensions`, `resource_security`, `request_state_security`, `cache_hints`, `subscriptions`) are additive.
724+
Transport-specific parameters have been moved off the `MCPServer` constructor and onto `run()`, `sse_app()`, and `streamable_http_app()`, so transport configuration is passed when starting or building the server. The rest of the constructor is unchanged: identity (`name`, `instructions`, `website_url`, `icons`, plus the newly added positional `title`, `description`, and `version` covered [above](#mcpserver-constructor-title-description-and-version-added-to-the-positional-parameters)), authentication (`auth`, `token_verifier`, `auth_server_provider`), `lifespan`, `dependencies`, `tools`, `debug`, `log_level`, and the `warn_on_duplicate_*` flags; the new keyword-only parameters (`resources`, `extensions`, `resource_security`, `request_state_security`, `cache_hints`, `subscriptions`, `narrow_subscriptions`) are additive.
725725

726726
**Parameters moved:**
727727

@@ -2819,6 +2819,12 @@ async def book_table(date: str, answer: Annotated[Confirmation, Resolve(ask_to_c
28192819

28202820
The client's same `elicitation_callback` answers both; the resolver lets the server *return* the question instead of pushing it.
28212821

2822+
### Change notifications travel only on `subscriptions/listen` streams
2823+
2824+
On a 2026-07-28 connection, `notifications/tools/list_changed`, `notifications/prompts/list_changed`, `notifications/resources/list_changed`, and `notifications/resources/updated` reach a client only through a `subscriptions/listen` stream it opened — the spec forbids sending a notification type a subscription did not request. The v1-style session helpers (`ctx.session.send_tool_list_changed()`, `send_prompt_list_changed()`, `send_resource_list_changed()`, `send_resource_updated(uri)`) push a bare copy onto the connection's standalone channel instead, so on such a connection they are dropped with a debug log: silently on streamable HTTP (there is no standalone channel), and on stdio, where earlier v2 releases wrote the bare notification to the shared pipe, it is now dropped too. On pre-2026 connections the helpers behave as in v1.
2825+
2826+
Migrate to publishing on the subscription bus, which stamps and filters per stream: `await ctx.notify_tools_changed()`, `notify_prompts_changed()`, `notify_resources_changed()`, and `notify_resource_updated(uri)` on `MCPServer`'s `Context`, or `await bus.publish(...)` on a low-level `Server`'s own `SubscriptionBus` — see [Subscriptions](handlers/subscriptions.md). A stream only ever receives the kinds and URIs the server acknowledged for it; to decide per caller what that is, pass a `narrow_subscriptions` hook (`MCPServer(narrow_subscriptions=...)`, or `ListenHandler(bus, narrow=...)` on the low-level `Server`), covered on the same page.
2827+
28222828
### Servers validate `Mcp-Param-*` headers against the request body ([SEP-2243](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2243))
28232829

28242830
On the 2026-07-28 Streamable HTTP path, a `tools/call` whose tool declares `x-mcp-header` annotations is validated before dispatch — each annotated argument and its mirroring `Mcp-Param-*` header must be present together and agree (after base64-sentinel decoding; integers compare numerically), or absent together. A violation is rejected with HTTP 400 and JSON-RPC error `-32020` (`HeaderMismatch`), as the spec requires. A client that sends an annotated argument *without* its header — for example one that never listed the tool — is therefore rejected instead of silently served; the spec's recovery is to re-list and retry. On the client side, `ClientSession.call_tool` emits these headers automatically for annotated arguments of any tool it has listed; list the tool first, and note that pre-2026 connections and non-HTTP transports never emit them.

docs/whats-new.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ That file is the pitch in one place: one server, one `Resolve`-backed tool, and
191191

192192
### Change notifications become one stream
193193

194-
At 2026-07-28 the standalone HTTP GET stream and `resources/subscribe` are replaced by `subscriptions/listen`: the client opens one long-lived stream and names the notification kinds it wants. `MCPServer` serves it out of the box; you publish with `await ctx.notify_resource_updated(uri)` (and `notify_tools_changed()`, and so on), and multi-replica deployments plug in a shared `SubscriptionBus`. On the client (since `2.0.0b2`), `async with client.listen(...)` opens the stream: the filter goes in as keyword arguments, typed change events come back, and `sub.honored` is the subset the server agreed to deliver.
194+
At 2026-07-28 the standalone HTTP GET stream and `resources/subscribe` are replaced by `subscriptions/listen`: the client opens one long-lived stream and names the notification kinds it wants. `MCPServer` serves it out of the box; you publish with `await ctx.notify_resource_updated(uri)` (and `notify_tools_changed()`, and so on), a `narrow_subscriptions` hook decides per caller what a stream may watch, and multi-replica deployments plug in a shared `SubscriptionBus`. On the client (since `2.0.0b2`), `async with client.listen(...)` opens the stream: the filter goes in as keyword arguments, typed change events come back, and `sub.honored` is the subset the server agreed to deliver.
195195

196196
**[Subscriptions](handlers/subscriptions.md)** covers publishing and serving, **[its Clients twin](client/subscriptions.md)** the watching end, and **[Deploy & scale](run/deploy.md)** the bus.
197197

src/mcp/server/connection.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,19 @@ async def notify(self, method: str, params: Mapping[str, Any] | None, opts: Call
116116

117117
_NO_CHANNEL = _NoChannelOutbound()
118118

119+
# On the 2026-07-28 era these are `subscriptions/listen` stream goods only: the
120+
# spec forbids sending a change notification a subscription did not request, and
121+
# listen streams deliver them (stamped and filtered) via the request-scoped
122+
# outbound, never this connection-scoped channel.
123+
_SUBSCRIPTION_STREAM_METHODS = frozenset(
124+
{
125+
"notifications/tools/list_changed",
126+
"notifications/prompts/list_changed",
127+
"notifications/resources/list_changed",
128+
"notifications/resources/updated",
129+
}
130+
)
131+
119132

120133
class NotifyOnlyOutbound(_NoChannelOutbound):
121134
"""Connection-scoped `Outbound` that forwards notifications and refuses requests.
@@ -124,12 +137,21 @@ class NotifyOnlyOutbound(_NoChannelOutbound):
124137
over duplex stream transports: the pipe is real, so server notifications
125138
ride it, but the modern protocol forbids server-initiated JSON-RPC
126139
requests, so `send_raw_request` (inherited) refuses by construction.
140+
141+
Change notifications (`notifications/*/list_changed`,
142+
`notifications/resources/updated`) are dropped with a debug log: at this
143+
era they reach a client only through a `subscriptions/listen` stream it
144+
opened, so a bare copy on the shared channel would be an unrequested
145+
notification. Publish them on the server's `SubscriptionBus` instead.
127146
"""
128147

129148
def __init__(self, outbound: Outbound) -> None:
130149
self._outbound = outbound
131150

132151
async def notify(self, method: str, params: Mapping[str, Any] | None, opts: CallOptions | None = None) -> None:
152+
if method in _SUBSCRIPTION_STREAM_METHODS:
153+
logger.debug("dropped %s: delivered via subscriptions/listen at this era", method)
154+
return
133155
await self._outbound.notify(method, params, opts)
134156

135157

src/mcp/server/mcpserver/server.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@
8888
from mcp.server.stdio import stdio_server
8989
from mcp.server.streamable_http import EventStore
9090
from mcp.server.streamable_http_manager import DEFAULT_MAX_REQUEST_BODY_SIZE, StreamableHTTPSessionManager
91-
from mcp.server.subscriptions import InMemorySubscriptionBus, ListenHandler, SubscriptionBus
91+
from mcp.server.subscriptions import InMemorySubscriptionBus, ListenHandler, NarrowSubscription, SubscriptionBus
9292
from mcp.server.transport_security import TransportSecuritySettings
9393
from mcp.shared.exceptions import MCPError
9494
from mcp.shared.uri_template import UriTemplate
@@ -172,6 +172,7 @@ def __init__(
172172
request_state_security: RequestStateSecurity | None = None,
173173
cache_hints: Mapping[CacheableMethod, CacheHint] | None = None,
174174
subscriptions: SubscriptionBus | None = None,
175+
narrow_subscriptions: NarrowSubscription | None = None,
175176
):
176177
self._resource_security = resource_security
177178
self.settings = Settings(
@@ -193,7 +194,9 @@ def __init__(
193194
self._prompt_manager = PromptManager(warn_on_duplicate_prompts=self.settings.warn_on_duplicate_prompts)
194195
# The subscriptions/listen fan-out seam (2026-07-28). The default bus is
195196
# in-process; pass an `SubscriptionBus` implementation over an external pub/sub
196-
# backend to fan events out across replicas.
197+
# backend to fan events out across replicas. `narrow_subscriptions` is the
198+
# per-request grant hook (see `NarrowSubscription`); without it every
199+
# requested kind and resource URI is honored.
197200
self._subscriptions: SubscriptionBus = subscriptions if subscriptions is not None else InMemorySubscriptionBus()
198201
self._lowlevel_server = Server(
199202
name=name or "mcp-server",
@@ -211,7 +214,7 @@ def __init__(
211214
on_list_resource_templates=self._handle_list_resource_templates,
212215
on_list_prompts=self._handle_list_prompts,
213216
on_get_prompt=self._handle_get_prompt,
214-
on_subscriptions_listen=ListenHandler(self._subscriptions),
217+
on_subscriptions_listen=ListenHandler(self._subscriptions, narrow=narrow_subscriptions),
215218
# TODO(Marcelo): It seems there's a type mismatch between the lifespan type from an MCPServer and Server.
216219
# We need to create a Lifespan type that is a generic on the server type, like Starlette does.
217220
lifespan=(lifespan_wrapper(self, self.settings.lifespan) if self.settings.lifespan else default_lifespan), # type: ignore

0 commit comments

Comments
 (0)