Serve subscriptions/listen with a pluggable event bus (SEP-2575) (#3035)

This commit is contained in:
Max 2026-06-30 23:01:04 +01:00 • committed by GitHub
commit ca10dade2c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 1722 additions and 66 deletions

View file

@ -121,11 +121,12 @@ async def test_read_resource_fills_in_a_template() -> None:
assert contents.text == "3 books filed under poetry."
async def test_mcpserver_does_not_implement_resource_subscriptions() -> None:
"""The Resources section: MCPServer advertises subscribe=False and rejects subscribe_resource with -32601."""
async def test_resource_subscriptions_are_listen_based_on_the_modern_wire() -> None:
"""The Resources section: at 2026-07-28 `resources.subscribe` is True (served via
subscriptions/listen) while the legacy subscribe_resource verb answers -32601."""
async with Client(tutorial004.mcp) as client:
assert client.server_capabilities.resources is not None
assert client.server_capabilities.resources.subscribe is False
assert client.server_capabilities.resources.subscribe is True
with pytest.raises(MCPError) as exc_info:
await client.subscribe_resource("catalog://genres")
assert exc_info.value.error.code == -32601

View file

@ -89,9 +89,9 @@ async def test_the_three_primitive_capabilities_are_always_declared() -> None:
# The exact dictionary the page prints from `model_dump(exclude_none=True)`.
assert declared.model_dump(exclude_none=True) == snapshot(
{
"prompts": {"list_changed": False},
"resources": {"subscribe": False, "list_changed": False},
"tools": {"list_changed": False},
"prompts": {"list_changed": True},
"resources": {"subscribe": True, "list_changed": True},
"tools": {"list_changed": True},
}
)
async with Client(MCPServer("Empty")) as client:

View file

@ -0,0 +1,138 @@
"""`docs/advanced/subscriptions.md`: every claim the page makes, proved against the real SDK."""
from typing import Any
import anyio
import mcp_types as types
import pytest
from docs_src.subscriptions import tutorial001, tutorial002
from mcp import Client
from mcp.server.subscriptions import SUBSCRIPTION_ID_META_KEY, ToolsListChanged
# See test_index.py for why this is a per-module mark and not a conftest hook.
pytestmark = [pytest.mark.anyio, pytest.mark.filterwarnings("error::mcp.MCPDeprecationWarning")]
class _Stream:
"""Collects listen-stream notifications and lets tests await arrival counts."""
def __init__(self) -> None:
self.received: list[types.ServerNotification] = []
self._arrival = anyio.Event()
async def handler(
self,
message: object,
) -> None:
# The only messages these connections produce are the stream's frames.
assert isinstance(
message,
types.SubscriptionsAcknowledgedNotification
| types.ResourceUpdatedNotification
| types.ToolListChangedNotification,
), message
self.received.append(message)
self._arrival.set()
self._arrival = anyio.Event()
async def wait_for(self, count: int) -> None:
with anyio.fail_after(5):
while len(self.received) < count:
await self._arrival.wait()
def _listen_request(**fields: Any) -> types.SubscriptionsListenRequest:
return types.SubscriptionsListenRequest(
params=types.SubscriptionsListenRequestParams(notifications=types.SubscriptionFilter(**fields))
)
async def test_publishes_reach_the_stream_filtered_and_tagged() -> None:
"""tutorial001: the full arc - ack first, exact-URI filtering, list_changed
leading to a refreshed tool list, and client-side close."""
stream = _Stream()
async with Client(tutorial001.mcp, mode="2026-07-28", message_handler=stream.handler) as client:
async with anyio.create_task_group() as tg:
async def listen() -> None:
await client.session.send_request(
_listen_request(tools_list_changed=True, resource_subscriptions=["note://todo"]),
types.SubscriptionsListenResult,
)
tg.start_soon(listen)
await stream.wait_for(1)
ack = stream.received[0]
assert isinstance(ack, types.SubscriptionsAcknowledgedNotification)
assert ack.params.notifications == types.SubscriptionFilter(
tools_list_changed=True, resource_subscriptions=["note://todo"]
)
assert ack.params.meta is not None and SUBSCRIPTION_ID_META_KEY in ack.params.meta
# An edit to a URI the stream did not subscribe to stays silent...
await client.call_tool("edit_note", {"name": "journal", "text": "day two"})
# ...and the subscribed URI delivers, tagged with the same subscription id.
await client.call_tool("edit_note", {"name": "todo", "text": "water plants"})
await stream.wait_for(2)
updated = stream.received[1]
assert isinstance(updated, types.ResourceUpdatedNotification)
assert updated.params.uri == "note://todo"
assert updated.params.meta == ack.params.meta
await client.call_tool("enable_search", {})
await stream.wait_for(3)
assert isinstance(stream.received[2], types.ToolListChangedNotification)
# The client ends the stream by closing it - cancel the parked request.
tg.cancel_scope.cancel()
# The list_changed told us to re-fetch: the new tool is there, and the
# session outlives the closed stream.
tools = await client.list_tools()
assert "search" in {tool.name for tool in tools.tools}
contents = (await client.read_resource("note://todo")).contents[0]
assert isinstance(contents, types.TextResourceContents)
assert contents.text == "water plants"
async def test_publish_with_no_subscribers_is_a_no_op() -> None:
"""tutorial001: publishing to an idle server does nothing and breaks nothing."""
async with Client(tutorial001.mcp, mode="2026-07-28") as client:
result = await client.call_tool("edit_note", {"name": "todo", "text": "buy milk"})
assert result.is_error is not True
async def test_lowlevel_composition_serves_the_same_stream() -> None:
"""tutorial002: bus + ListenHandler on the lowlevel Server is the same machinery."""
stream = _Stream()
async with Client(tutorial002.server, mode="2026-07-28", message_handler=stream.handler) as client:
tools = await client.list_tools()
assert [tool.name for tool in tools.tools] == ["edit_note"]
async with anyio.create_task_group() as tg:
async def listen() -> None:
await client.session.send_request(
_listen_request(resource_subscriptions=["note://todo"]),
types.SubscriptionsListenResult,
)
tg.start_soon(listen)
await stream.wait_for(1)
await client.call_tool("edit_note", {"name": "todo", "text": "water plants"})
await stream.wait_for(2)
updated = stream.received[1]
assert isinstance(updated, types.ResourceUpdatedNotification)
assert updated.params.uri == "note://todo"
# The bus you constructed is also the publish surface outside a
# request; an unrequested kind never reaches this stream.
await tutorial002.bus.publish(ToolsListChanged())
await client.call_tool("edit_note", {"name": "todo", "text": "done"})
await stream.wait_for(3)
assert isinstance(stream.received[2], types.ResourceUpdatedNotification)
tg.cancel_scope.cancel()