|
| 1 | +"""Composed multi-feature flows against the low-level Server, driven through the public Client API. |
| 2 | +
|
| 3 | +Each test reads as the scenario it proves: the steps run top to bottom in the order a real client |
| 4 | +would perform them, composing two or more feature areas (a tool call followed by a resource read; |
| 5 | +a chain of elicitations inside one tool call; the full URL-elicitation-required retry loop). The |
| 6 | +individual features are pinned by their own tests; these prove they compose. |
| 7 | +""" |
| 8 | + |
| 9 | +from collections.abc import Awaitable, Callable |
| 10 | + |
| 11 | +import anyio |
| 12 | +import pytest |
| 13 | +from inline_snapshot import snapshot |
| 14 | + |
| 15 | +from mcp import MCPError, UrlElicitationRequiredError, types |
| 16 | +from mcp.client import ClientRequestContext |
| 17 | +from mcp.server import Server, ServerRequestContext |
| 18 | +from mcp.server.session import ServerSession |
| 19 | +from mcp.types import ( |
| 20 | + URL_ELICITATION_REQUIRED, |
| 21 | + CallToolResult, |
| 22 | + ElicitCompleteNotification, |
| 23 | + ElicitRequestFormParams, |
| 24 | + ElicitRequestURLParams, |
| 25 | + ElicitResult, |
| 26 | + ListToolsResult, |
| 27 | + ReadResourceResult, |
| 28 | + ResourceLink, |
| 29 | + TextContent, |
| 30 | + TextResourceContents, |
| 31 | + Tool, |
| 32 | +) |
| 33 | +from tests.interaction._connect import Connect |
| 34 | +from tests.interaction._helpers import IncomingMessage |
| 35 | +from tests.interaction._requirements import requirement |
| 36 | + |
| 37 | +pytestmark = pytest.mark.anyio |
| 38 | + |
| 39 | +ListToolsHandler = Callable[ |
| 40 | + [ServerRequestContext, types.PaginatedRequestParams | None], Awaitable[types.ListToolsResult] |
| 41 | +] |
| 42 | + |
| 43 | + |
| 44 | +def _list_tools(*names: str) -> ListToolsHandler: |
| 45 | + """A list_tools handler advertising the named tools, so call_tool's implicit list succeeds.""" |
| 46 | + |
| 47 | + async def list_tools(ctx: ServerRequestContext, params: types.PaginatedRequestParams | None) -> ListToolsResult: |
| 48 | + return ListToolsResult(tools=[Tool(name=name, input_schema={"type": "object"}) for name in names]) |
| 49 | + |
| 50 | + return list_tools |
| 51 | + |
| 52 | + |
| 53 | +@requirement("flow:tool-result:resource-link-follow") |
| 54 | +async def test_a_resource_link_returned_by_a_tool_can_be_followed_with_read(connect: Connect) -> None: |
| 55 | + """A tool returns a resource_link; reading that link's URI returns the referenced contents. |
| 56 | +
|
| 57 | + Steps: (1) call the tool, (2) extract the link from its content, (3) read_resource on the |
| 58 | + link's URI, (4) the read result carries the linked contents. |
| 59 | + """ |
| 60 | + |
| 61 | + async def call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> CallToolResult: |
| 62 | + assert params.name == "generate" |
| 63 | + return CallToolResult(content=[ResourceLink(uri="file:///report.txt", name="report")]) |
| 64 | + |
| 65 | + async def read_resource(ctx: ServerRequestContext, params: types.ReadResourceRequestParams) -> ReadResourceResult: |
| 66 | + assert str(params.uri) == "file:///report.txt" |
| 67 | + return ReadResourceResult(contents=[TextResourceContents(uri="file:///report.txt", text="generated")]) |
| 68 | + |
| 69 | + server = Server( |
| 70 | + "linker", on_list_tools=_list_tools("generate"), on_call_tool=call_tool, on_read_resource=read_resource |
| 71 | + ) |
| 72 | + |
| 73 | + async with connect(server) as client: |
| 74 | + called = await client.call_tool("generate", {}) |
| 75 | + link = called.content[0] |
| 76 | + assert isinstance(link, ResourceLink) |
| 77 | + read = await client.read_resource(link.uri) |
| 78 | + |
| 79 | + assert called == snapshot(CallToolResult(content=[ResourceLink(name="report", uri="file:///report.txt")])) |
| 80 | + assert read == snapshot( |
| 81 | + ReadResourceResult(contents=[TextResourceContents(uri="file:///report.txt", text="generated")]) |
| 82 | + ) |
| 83 | + |
| 84 | + |
| 85 | +@requirement("flow:elicitation:multi-step-form") |
| 86 | +async def test_a_tool_handler_chains_form_elicitations_feeding_each_answer_forward(connect: Connect) -> None: |
| 87 | + """Sequential form elicitations inside one tool call: each accepted answer feeds the next step. |
| 88 | +
|
| 89 | + Steps: (1) call the tool, (2) the handler issues a step-one form elicitation that the client |
| 90 | + accepts with content, (3) the handler issues a step-two elicitation whose message references |
| 91 | + the step-one answer, (4) the client accepts step two, (5) the tool result summarises both |
| 92 | + answers. The callback is invoked exactly twice with the expected messages and schemas. The |
| 93 | + short-circuit on decline is the application's choice (proven separately by the per-action |
| 94 | + elicitation tests); what this flow pins is that the chain itself works end to end. |
| 95 | + """ |
| 96 | + received: list[ElicitRequestFormParams] = [] |
| 97 | + answers: list[dict[str, str | int | float | bool | list[str] | None]] = [{"name": "ada"}, {"age": 37}] |
| 98 | + |
| 99 | + async def call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> CallToolResult: |
| 100 | + assert params.name == "onboard" |
| 101 | + first = await ctx.session.elicit_form( |
| 102 | + "Step 1: choose a username.", {"type": "object", "properties": {"name": {"type": "string"}}} |
| 103 | + ) |
| 104 | + assert first.action == "accept" and first.content is not None |
| 105 | + second = await ctx.session.elicit_form( |
| 106 | + f"Step 2: confirm age for {first.content['name']}.", |
| 107 | + {"type": "object", "properties": {"age": {"type": "integer"}}}, |
| 108 | + ) |
| 109 | + assert second.action == "accept" and second.content is not None |
| 110 | + return CallToolResult(content=[TextContent(text=f"{first.content['name']} is {second.content['age']}")]) |
| 111 | + |
| 112 | + server = Server("onboarder", on_list_tools=_list_tools("onboard"), on_call_tool=call_tool) |
| 113 | + |
| 114 | + async def answer(context: ClientRequestContext, params: types.ElicitRequestParams) -> ElicitResult: |
| 115 | + assert isinstance(params, ElicitRequestFormParams) |
| 116 | + received.append(params) |
| 117 | + return ElicitResult(action="accept", content=answers[len(received) - 1]) |
| 118 | + |
| 119 | + async with connect(server, elicitation_callback=answer) as client: |
| 120 | + result = await client.call_tool("onboard", {}) |
| 121 | + |
| 122 | + assert result == snapshot(CallToolResult(content=[TextContent(text="ada is 37")])) |
| 123 | + assert [(p.message, p.requested_schema) for p in received] == snapshot( |
| 124 | + [ |
| 125 | + ("Step 1: choose a username.", {"type": "object", "properties": {"name": {"type": "string"}}}), |
| 126 | + ("Step 2: confirm age for ada.", {"type": "object", "properties": {"age": {"type": "integer"}}}), |
| 127 | + ] |
| 128 | + ) |
| 129 | + |
| 130 | + |
| 131 | +@requirement("flow:elicitation:url-required-then-retry") |
| 132 | +async def test_a_tool_rejected_with_url_elicitation_required_succeeds_on_retry_after_completion( |
| 133 | + connect: Connect, |
| 134 | +) -> None: |
| 135 | + """The full URL-elicitation-required retry loop: -32042, completion announced, retry succeeds. |
| 136 | +
|
| 137 | + Steps: (1) the first call is rejected with -32042 carrying the required URL elicitation in |
| 138 | + its error data, (2) the client extracts the elicitation id from the error, (3) the server |
| 139 | + announces completion via the elicitation/complete notification (driven via the captured |
| 140 | + session, the same way a real out-of-band callback would reach a held session reference), |
| 141 | + (4) the client observes the matching completion notification and retries, (5) the retry |
| 142 | + succeeds. The handler distinguishes the two calls by a closure flag the test flips between |
| 143 | + them; the test waits on the completion notification with an event so the retry only happens |
| 144 | + after the announcement has arrived. |
| 145 | + """ |
| 146 | + elicitation_id = "auth-001" |
| 147 | + authorised: list[bool] = [False] |
| 148 | + captured: list[ServerSession] = [] |
| 149 | + completed = anyio.Event() |
| 150 | + notifications: list[ElicitCompleteNotification] = [] |
| 151 | + |
| 152 | + async def call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> CallToolResult: |
| 153 | + assert params.name == "read_files" |
| 154 | + captured.append(ctx.session) |
| 155 | + if not authorised[0]: |
| 156 | + # The log line gives the message handler a non-completion notification, so the test's |
| 157 | + # filtering branch is exercised in both directions and the wait remains specific. |
| 158 | + await ctx.session.send_log_message(level="warning", data="authorisation required", logger="gate") |
| 159 | + raise UrlElicitationRequiredError( |
| 160 | + [ |
| 161 | + ElicitRequestURLParams( |
| 162 | + message="Authorize file access.", |
| 163 | + url="https://example.com/oauth/authorize", |
| 164 | + elicitation_id=elicitation_id, |
| 165 | + ) |
| 166 | + ] |
| 167 | + ) |
| 168 | + return CallToolResult(content=[TextContent(text="contents")]) |
| 169 | + |
| 170 | + server = Server("gatekeeper", on_list_tools=_list_tools("read_files"), on_call_tool=call_tool) |
| 171 | + |
| 172 | + async def collect(message: IncomingMessage) -> None: |
| 173 | + if isinstance(message, ElicitCompleteNotification): |
| 174 | + notifications.append(message) |
| 175 | + completed.set() |
| 176 | + |
| 177 | + async with connect(server, message_handler=collect) as client: |
| 178 | + with pytest.raises(MCPError) as exc_info: |
| 179 | + await client.call_tool("read_files", {}) |
| 180 | + assert exc_info.value.error.code == URL_ELICITATION_REQUIRED |
| 181 | + required = UrlElicitationRequiredError.from_error(exc_info.value.error) |
| 182 | + assert [e.elicitation_id for e in required.elicitations] == [elicitation_id] |
| 183 | + |
| 184 | + # The out-of-band interaction completes; the server announces it on the same session. |
| 185 | + await captured[0].send_elicit_complete(elicitation_id) |
| 186 | + with anyio.fail_after(5): |
| 187 | + await completed.wait() |
| 188 | + assert notifications[0].params.elicitation_id == elicitation_id |
| 189 | + |
| 190 | + authorised[0] = True |
| 191 | + result = await client.call_tool("read_files", {}) |
| 192 | + |
| 193 | + assert result == snapshot(CallToolResult(content=[TextContent(text="contents")])) |
0 commit comments