|
| 1 | +"""Tests for `ServerSession`. |
| 2 | +
|
| 3 | +`ServerSession` is a thin proxy over a dispatcher and a `Connection`. Tested |
| 4 | +with a stub dispatcher so we can assert what reaches the wire (method, params, |
| 5 | +`CallOptions`, related-request-id) without standing up a full transport. |
| 6 | +""" |
| 7 | + |
| 8 | +from collections.abc import Mapping |
| 9 | +from typing import Any, cast |
| 10 | + |
| 11 | +import pytest |
| 12 | + |
| 13 | +from mcp import types |
| 14 | +from mcp.server.connection import Connection |
| 15 | +from mcp.server.session import ServerSession |
| 16 | +from mcp.shared.dispatcher import CallOptions |
| 17 | +from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher |
| 18 | +from mcp.shared.message import ServerMessageMetadata |
| 19 | +from mcp.types import ( |
| 20 | + LATEST_PROTOCOL_VERSION, |
| 21 | + ClientCapabilities, |
| 22 | + Implementation, |
| 23 | + InitializeRequestParams, |
| 24 | + SamplingCapability, |
| 25 | + SamplingToolsCapability, |
| 26 | +) |
| 27 | + |
| 28 | + |
| 29 | +class StubDispatcher: |
| 30 | + """Records `send_raw_request` / `notify` calls and returns a canned result.""" |
| 31 | + |
| 32 | + def __init__(self, result: dict[str, Any] | None = None) -> None: |
| 33 | + self.requests: list[tuple[str, Mapping[str, Any] | None, CallOptions | None, Any]] = [] |
| 34 | + self.result = result if result is not None else {} |
| 35 | + |
| 36 | + async def send_raw_request( |
| 37 | + self, |
| 38 | + method: str, |
| 39 | + params: Mapping[str, Any] | None, |
| 40 | + opts: CallOptions | None = None, |
| 41 | + *, |
| 42 | + _related_request_id: Any = None, |
| 43 | + ) -> dict[str, Any]: |
| 44 | + self.requests.append((method, params, opts, _related_request_id)) |
| 45 | + return self.result |
| 46 | + |
| 47 | + async def notify(self, method: str, params: Mapping[str, Any] | None) -> None: |
| 48 | + raise NotImplementedError |
| 49 | + |
| 50 | + |
| 51 | +def _make_session(dispatcher: StubDispatcher, *, capabilities: ClientCapabilities | None = None) -> ServerSession: |
| 52 | + conn = Connection(dispatcher, has_standalone_channel=True) |
| 53 | + if capabilities is not None: |
| 54 | + conn.client_params = InitializeRequestParams( |
| 55 | + protocol_version=LATEST_PROTOCOL_VERSION, |
| 56 | + capabilities=capabilities, |
| 57 | + client_info=Implementation(name="c", version="0"), |
| 58 | + ) |
| 59 | + # cast: `ServerSession` is typed to take `JSONRPCDispatcher` but only ever |
| 60 | + # calls `send_raw_request` / `notify`, so the stub is structurally sufficient. |
| 61 | + return ServerSession(cast("JSONRPCDispatcher[Any]", dispatcher), conn) |
| 62 | + |
| 63 | + |
| 64 | +@pytest.mark.anyio |
| 65 | +async def test_send_request_forwards_timeout_and_progress_callback_as_call_options(): |
| 66 | + dispatcher = StubDispatcher(result={"roots": []}) |
| 67 | + session = _make_session(dispatcher) |
| 68 | + |
| 69 | + async def on_progress(progress: float, total: float | None, message: str | None) -> None: |
| 70 | + raise NotImplementedError |
| 71 | + |
| 72 | + result = await session.send_request( |
| 73 | + types.ListRootsRequest(), |
| 74 | + types.ListRootsResult, |
| 75 | + request_read_timeout_seconds=2.5, |
| 76 | + metadata=ServerMessageMetadata(related_request_id=7), |
| 77 | + progress_callback=on_progress, |
| 78 | + ) |
| 79 | + assert isinstance(result, types.ListRootsResult) |
| 80 | + method, _params, opts, related = dispatcher.requests[0] |
| 81 | + assert method == "roots/list" |
| 82 | + assert opts == {"timeout": 2.5, "on_progress": on_progress} |
| 83 | + assert related == 7 |
| 84 | + |
| 85 | + |
| 86 | +@pytest.mark.anyio |
| 87 | +async def test_send_request_omits_call_options_when_none_given(): |
| 88 | + dispatcher = StubDispatcher(result={"roots": []}) |
| 89 | + session = _make_session(dispatcher) |
| 90 | + await session.send_request(types.ListRootsRequest(), types.ListRootsResult) |
| 91 | + _method, _params, opts, related = dispatcher.requests[0] |
| 92 | + assert opts is None |
| 93 | + assert related is None |
| 94 | + |
| 95 | + |
| 96 | +@pytest.mark.anyio |
| 97 | +async def test_create_message_with_tools_returns_with_tools_result(): |
| 98 | + dispatcher = StubDispatcher(result={"role": "assistant", "content": [{"type": "text", "text": "ok"}], "model": "m"}) |
| 99 | + session = _make_session( |
| 100 | + dispatcher, capabilities=ClientCapabilities(sampling=SamplingCapability(tools=SamplingToolsCapability())) |
| 101 | + ) |
| 102 | + result = await session.create_message( |
| 103 | + messages=[types.SamplingMessage(role="user", content=types.TextContent(type="text", text="hi"))], |
| 104 | + max_tokens=10, |
| 105 | + tools=[types.Tool(name="t", input_schema={"type": "object"})], |
| 106 | + ) |
| 107 | + assert isinstance(result, types.CreateMessageResultWithTools) |
| 108 | + method, params, _opts, _related = dispatcher.requests[0] |
| 109 | + assert method == "sampling/createMessage" |
| 110 | + assert params is not None and params["tools"][0]["name"] == "t" |
| 111 | + |
| 112 | + |
| 113 | +def test_check_client_capability_delegates_to_connection(): |
| 114 | + dispatcher = StubDispatcher() |
| 115 | + session = _make_session(dispatcher, capabilities=ClientCapabilities(sampling=SamplingCapability())) |
| 116 | + assert session.check_client_capability(ClientCapabilities(sampling=SamplingCapability())) is True |
| 117 | + assert session.check_client_capability(ClientCapabilities(experimental={"x": {}})) is False |
0 commit comments