|
| 1 | +"""Wire-level invariants observed at the client's transport boundary. |
| 2 | +
|
| 3 | +These behaviours are invisible to API callers -- they are properties of the raw JSON-RPC frames. |
| 4 | +The tests wrap the in-memory transport in a RecordingTransport, which tees every message crossing |
| 5 | +the transport seam into a list without touching the session, so the assertions hold for whatever |
| 6 | +the session implementation sends rather than for what its API returns. |
| 7 | +""" |
| 8 | + |
| 9 | +import anyio |
| 10 | +import pytest |
| 11 | +from inline_snapshot import snapshot |
| 12 | + |
| 13 | +from mcp import types |
| 14 | +from mcp.client._memory import InMemoryTransport |
| 15 | +from mcp.client.client import Client |
| 16 | +from mcp.server import Server, ServerRequestContext |
| 17 | +from mcp.shared.message import SessionMessage |
| 18 | +from mcp.types import CallToolResult, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, TextContent |
| 19 | +from tests.interaction._helpers import RecordingTransport, _RecordingReadStream |
| 20 | +from tests.interaction._requirements import requirement |
| 21 | + |
| 22 | +pytestmark = pytest.mark.anyio |
| 23 | + |
| 24 | + |
| 25 | +def _echo_server() -> Server: |
| 26 | + """A server with one echo tool, used by every test in this module.""" |
| 27 | + |
| 28 | + async def list_tools( |
| 29 | + ctx: ServerRequestContext, params: types.PaginatedRequestParams | None |
| 30 | + ) -> types.ListToolsResult: |
| 31 | + return types.ListToolsResult(tools=[types.Tool(name="echo", input_schema={"type": "object"})]) |
| 32 | + |
| 33 | + async def call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> CallToolResult: |
| 34 | + assert params.name == "echo" |
| 35 | + return CallToolResult(content=[TextContent(text="ok")]) |
| 36 | + |
| 37 | + return Server("wire", on_list_tools=list_tools, on_call_tool=call_tool) |
| 38 | + |
| 39 | + |
| 40 | +@requirement("protocol:request-id:unique") |
| 41 | +async def test_request_ids_are_unique_and_never_null() -> None: |
| 42 | + """Every request the client sends carries a distinct, non-null id. |
| 43 | +
|
| 44 | + The id sequence is pinned: sequential integers from zero, in send order, including the |
| 45 | + schema-cache refresh the client performs after the first successful tool call. |
| 46 | + """ |
| 47 | + recording = RecordingTransport(InMemoryTransport(_echo_server())) |
| 48 | + |
| 49 | + async with Client(recording) as client: |
| 50 | + await client.list_tools() |
| 51 | + await client.call_tool("echo", {}) |
| 52 | + await client.call_tool("echo", {}) |
| 53 | + await client.send_ping() |
| 54 | + |
| 55 | + sent = [message.message for message in recording.sent] |
| 56 | + request_ids = [message.id for message in sent if isinstance(message, JSONRPCRequest)] |
| 57 | + assert all(request_id is not None for request_id in request_ids) |
| 58 | + assert len(request_ids) == len(set(request_ids)) |
| 59 | + # initialize, tools/list, tools/call, tools/call, ping -- the client does not issue a |
| 60 | + # schema-cache refresh here because the explicit tools/list already populated the cache. |
| 61 | + assert request_ids == snapshot([0, 1, 2, 3, 4]) |
| 62 | + |
| 63 | + |
| 64 | +@requirement("protocol:notifications:no-response") |
| 65 | +async def test_notifications_are_never_answered() -> None: |
| 66 | + """A notification produces no response: everything the server sends back answers a request. |
| 67 | +
|
| 68 | + The client sends two notifications (initialized and roots/list_changed) and several requests; |
| 69 | + the messages received from the server must be exactly one response per request, each carrying |
| 70 | + the id of the request it answers, and nothing else. |
| 71 | + """ |
| 72 | + recording = RecordingTransport(InMemoryTransport(_echo_server())) |
| 73 | + |
| 74 | + async with Client(recording) as client: |
| 75 | + await client.send_roots_list_changed() |
| 76 | + await client.send_ping() |
| 77 | + |
| 78 | + sent = [message.message for message in recording.sent] |
| 79 | + sent_request_ids = [message.id for message in sent if isinstance(message, JSONRPCRequest)] |
| 80 | + sent_notifications = [message for message in sent if isinstance(message, JSONRPCNotification)] |
| 81 | + received = [message.message for message in recording.received if isinstance(message, SessionMessage)] |
| 82 | + received_responses = [message for message in received if isinstance(message, JSONRPCResponse)] |
| 83 | + |
| 84 | + assert len(sent_notifications) == 2 # notifications/initialized and notifications/roots/list_changed |
| 85 | + assert len(received_responses) == len(received) # nothing the server sent was anything but a response |
| 86 | + assert [message.id for message in received_responses] == sent_request_ids |
| 87 | + |
| 88 | + |
| 89 | +async def test_recording_read_stream_ends_iteration_when_the_sender_closes() -> None: |
| 90 | + """The recording wrapper preserves the end-of-stream behaviour of the stream it wraps. |
| 91 | +
|
| 92 | + This exercises the helper itself rather than an interaction-model behaviour: a transport whose |
| 93 | + far end closes must end the client's receive loop cleanly, and the wrapper must not swallow or |
| 94 | + mistranslate that. |
| 95 | + """ |
| 96 | + send_stream, receive_stream = anyio.create_memory_object_stream[SessionMessage | Exception](1) |
| 97 | + log: list[SessionMessage | Exception] = [] |
| 98 | + async with send_stream, _RecordingReadStream(receive_stream, log) as wrapped: |
| 99 | + await send_stream.aclose() |
| 100 | + items = [item async for item in wrapped] |
| 101 | + assert items == [] |
| 102 | + assert log == [] |
| 103 | + |
| 104 | + |
| 105 | +@requirement("lifecycle:initialized-notification") |
| 106 | +async def test_exactly_one_initialized_notification_is_sent_after_the_handshake() -> None: |
| 107 | + """The client sends initialized exactly once, between the initialize response and its first request. |
| 108 | +
|
| 109 | + The full method sequence the client puts on the wire is pinned in send order. |
| 110 | + """ |
| 111 | + recording = RecordingTransport(InMemoryTransport(_echo_server())) |
| 112 | + |
| 113 | + async with Client(recording) as client: |
| 114 | + await client.list_tools() |
| 115 | + |
| 116 | + sent_methods = [ |
| 117 | + message.message.method |
| 118 | + for message in recording.sent |
| 119 | + if isinstance(message.message, JSONRPCRequest | JSONRPCNotification) |
| 120 | + ] |
| 121 | + assert sent_methods.count("notifications/initialized") == 1 |
| 122 | + assert sent_methods == snapshot(["initialize", "notifications/initialized", "tools/list"]) |
0 commit comments