|
1 | 1 | import json |
| 2 | +import math |
2 | 3 | import multiprocessing |
3 | 4 | import socket |
4 | 5 | import time |
5 | | -from collections.abc import AsyncGenerator, Generator |
| 6 | +from collections.abc import AsyncGenerator, Awaitable, Callable, Generator |
| 7 | +from datetime import timedelta |
6 | 8 | from typing import Any |
7 | 9 | from unittest.mock import Mock |
8 | 10 |
|
|
24 | 26 | from mcp.server import Server |
25 | 27 | from mcp.server.sse import SseServerTransport |
26 | 28 | from mcp.server.transport_security import TransportSecuritySettings |
| 29 | +from mcp.shared.context import RequestContext |
27 | 30 | from mcp.shared.exceptions import McpError |
28 | 31 | from mcp.shared.message import SessionMessage |
29 | 32 | from mcp.types import ( |
| 33 | + CallToolResult, |
30 | 34 | EmptyResult, |
31 | 35 | ErrorData, |
32 | 36 | Implementation, |
33 | 37 | InitializeResult, |
34 | 38 | JSONRPCResponse, |
| 39 | + ListRootsResult, |
| 40 | + ListToolsResult, |
35 | 41 | ReadResourceResult, |
36 | 42 | ServerCapabilities, |
37 | 43 | TextContent, |
38 | 44 | TextResourceContents, |
39 | 45 | Tool, |
| 46 | + ToolsCapability, |
40 | 47 | ) |
41 | 48 | from tests.test_helpers import wait_for_server |
42 | 49 |
|
@@ -640,3 +647,243 @@ def factory( |
640 | 647 |
|
641 | 648 | assert exc_info.group_contains(httpx.HTTPStatusError, match="307 Temporary Redirect") |
642 | 649 | assert received == ["http://test/sse"] |
| 650 | + |
| 651 | + |
| 652 | +class _RejectingSseServer: |
| 653 | + """An in-process SSE server that answers on its event stream and fails chosen message POSTs.""" |
| 654 | + |
| 655 | + def __init__(self, endpoint: str = "/messages/?session_id=abc123") -> None: |
| 656 | + self.endpoint = endpoint |
| 657 | + self.post_status: dict[str, int] = {} |
| 658 | + self.post_error: dict[str, Exception] = {} |
| 659 | + self.before_rejecting: Callable[[], Awaitable[None]] | None = None |
| 660 | + self._events, self._events_reader = anyio.create_memory_object_stream[str](math.inf) |
| 661 | + |
| 662 | + async def __aenter__(self) -> "_RejectingSseServer": |
| 663 | + return self |
| 664 | + |
| 665 | + async def __aexit__(self, *exc_info: object) -> None: |
| 666 | + self._events.close() |
| 667 | + self._events_reader.close() |
| 668 | + |
| 669 | + def client_factory( |
| 670 | + self, |
| 671 | + headers: dict[str, str] | None = None, |
| 672 | + timeout: httpx.Timeout | None = None, |
| 673 | + auth: httpx.Auth | None = None, |
| 674 | + ) -> httpx.AsyncClient: |
| 675 | + return httpx.AsyncClient(transport=httpx.MockTransport(self._handle)) |
| 676 | + |
| 677 | + def push(self, message: dict[str, Any]) -> None: |
| 678 | + self._events.send_nowait(f"event: message\ndata: {json.dumps(message)}\n\n") |
| 679 | + |
| 680 | + async def _event_stream(self) -> AsyncGenerator[bytes, None]: |
| 681 | + yield f"event: endpoint\ndata: {self.endpoint}\n\n".encode() |
| 682 | + async for event in self._events_reader: # pragma: no branch |
| 683 | + yield event.encode() |
| 684 | + |
| 685 | + async def _handle(self, request: httpx.Request) -> httpx.Response: |
| 686 | + if request.method == "GET": |
| 687 | + return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=self._event_stream()) |
| 688 | + message = json.loads(request.content) |
| 689 | + method = message.get("method") |
| 690 | + if method in self.post_error: |
| 691 | + raise self.post_error[method] |
| 692 | + if method in self.post_status: |
| 693 | + if self.before_rejecting is not None: |
| 694 | + await self.before_rejecting() |
| 695 | + return httpx.Response(self.post_status[method]) |
| 696 | + if method is not None and "id" in message: |
| 697 | + self.push( |
| 698 | + {"jsonrpc": "2.0", "id": message["id"], "result": self._result(method, message.get("params", {}))} |
| 699 | + ) |
| 700 | + return httpx.Response(202) |
| 701 | + |
| 702 | + @staticmethod |
| 703 | + def _result(method: str, params: dict[str, Any]) -> dict[str, Any]: |
| 704 | + if method == "initialize": |
| 705 | + result = InitializeResult( |
| 706 | + protocolVersion=params["protocolVersion"], |
| 707 | + capabilities=ServerCapabilities(tools=ToolsCapability()), |
| 708 | + serverInfo=Implementation(name=SERVER_NAME, version="1.0"), |
| 709 | + ) |
| 710 | + elif method == "tools/list": |
| 711 | + result = ListToolsResult(tools=[Tool(name="test_tool", inputSchema={"type": "object"})]) |
| 712 | + elif method == "tools/call": |
| 713 | + result = CallToolResult(content=[TextContent(type="text", text=f"Called {params['name']}")]) |
| 714 | + else: |
| 715 | + result = EmptyResult() |
| 716 | + return result.model_dump(by_alias=True, mode="json", exclude_none=True) |
| 717 | + |
| 718 | + |
| 719 | +@pytest.mark.anyio |
| 720 | +@pytest.mark.parametrize("status_code", [302, 401, 429, 500, 503]) |
| 721 | +async def test_sse_client_initialize_post_http_error_fails_initialize_promptly(status_code: int) -> None: |
| 722 | + """A non-2xx on the initialize POST fails initialize at once instead of after the session |
| 723 | + read timeout (#2110: the status error was only logged, so the caller waited out the timeout).""" |
| 724 | + server = _RejectingSseServer() |
| 725 | + server.post_status["initialize"] = status_code |
| 726 | + with anyio.fail_after(5): |
| 727 | + async with ( |
| 728 | + server, |
| 729 | + sse_client("http://test/sse", httpx_client_factory=server.client_factory) as streams, |
| 730 | + ClientSession(*streams, read_timeout_seconds=timedelta(seconds=20)) as session, |
| 731 | + ): |
| 732 | + with pytest.raises(McpError) as exc_info: |
| 733 | + await session.initialize() |
| 734 | + assert exc_info.value.error == snapshot(ErrorData(code=-32603, message="Server returned an error response")) |
| 735 | + |
| 736 | + |
| 737 | +@pytest.mark.anyio |
| 738 | +async def test_sse_client_request_post_http_error_fails_request_and_session_survives() -> None: |
| 739 | + """A non-2xx on a later request's POST fails that request at once, and the writer keeps |
| 740 | + sending: the next requests in the same session still reach the server (#2110).""" |
| 741 | + server = _RejectingSseServer() |
| 742 | + with anyio.fail_after(5): |
| 743 | + async with ( |
| 744 | + server, |
| 745 | + sse_client("http://test/sse", httpx_client_factory=server.client_factory) as streams, |
| 746 | + ClientSession(*streams, read_timeout_seconds=timedelta(seconds=20)) as session, |
| 747 | + ): |
| 748 | + await session.initialize() |
| 749 | + server.post_status["tools/call"] = 500 |
| 750 | + |
| 751 | + with pytest.raises(McpError) as exc_info: |
| 752 | + await session.call_tool("test_tool", {}) |
| 753 | + assert exc_info.value.error.code == types.INTERNAL_ERROR |
| 754 | + |
| 755 | + assert isinstance(await session.send_ping(), EmptyResult) |
| 756 | + server.post_status.clear() |
| 757 | + result = await session.call_tool("test_tool", {}) |
| 758 | + assert result.content == [TextContent(type="text", text="Called test_tool")] |
| 759 | + |
| 760 | + |
| 761 | +@pytest.mark.anyio |
| 762 | +async def test_sse_client_request_post_network_error_fails_request_and_session_survives() -> None: |
| 763 | + """A POST that raises before any response fails its request with CONNECTION_CLOSED, and the |
| 764 | + writer keeps sending (#2110).""" |
| 765 | + server = _RejectingSseServer() |
| 766 | + with anyio.fail_after(5): |
| 767 | + async with ( |
| 768 | + server, |
| 769 | + sse_client("http://test/sse", httpx_client_factory=server.client_factory) as streams, |
| 770 | + ClientSession(*streams, read_timeout_seconds=timedelta(seconds=20)) as session, |
| 771 | + ): |
| 772 | + await session.initialize() |
| 773 | + server.post_error["tools/call"] = httpx.ConnectError("connection refused") |
| 774 | + |
| 775 | + with pytest.raises(McpError) as exc_info: |
| 776 | + await session.call_tool("test_tool", {}) |
| 777 | + assert exc_info.value.error == snapshot( |
| 778 | + ErrorData(code=-32000, message="Failed to send message: connection refused") |
| 779 | + ) |
| 780 | + |
| 781 | + assert isinstance(await session.send_ping(), EmptyResult) |
| 782 | + |
| 783 | + |
| 784 | +@pytest.mark.anyio |
| 785 | +@pytest.mark.parametrize( |
| 786 | + ("endpoint", "expected"), |
| 787 | + [ |
| 788 | + ("/messages/?session_id=abc123", ErrorData(code=-32600, message="Session terminated")), |
| 789 | + ("/messages/", ErrorData(code=-32603, message="Server returned an error response")), |
| 790 | + ], |
| 791 | +) |
| 792 | +async def test_sse_client_request_post_404_reports_session_terminated_only_with_a_session( |
| 793 | + endpoint: str, expected: ErrorData |
| 794 | +) -> None: |
| 795 | + """A 404 on a POST to an endpoint that carries a session id means the session is gone, as in |
| 796 | + the streamable HTTP transport; without a session id it is a generic error.""" |
| 797 | + server = _RejectingSseServer(endpoint=endpoint) |
| 798 | + with anyio.fail_after(5): |
| 799 | + async with ( |
| 800 | + server, |
| 801 | + sse_client("http://test/sse", httpx_client_factory=server.client_factory) as streams, |
| 802 | + ClientSession(*streams) as session, |
| 803 | + ): |
| 804 | + await session.initialize() |
| 805 | + server.post_status["tools/call"] = 404 |
| 806 | + with pytest.raises(McpError) as exc_info: |
| 807 | + await session.call_tool("test_tool", {}) |
| 808 | + assert exc_info.value.error == expected |
| 809 | + |
| 810 | + |
| 811 | +@pytest.mark.anyio |
| 812 | +async def test_sse_client_notification_post_error_leaves_session_usable() -> None: |
| 813 | + """A failed notification POST has no waiting caller, so it is only logged and the session |
| 814 | + keeps working.""" |
| 815 | + server = _RejectingSseServer() |
| 816 | + server.post_status["notifications/initialized"] = 500 |
| 817 | + with anyio.fail_after(5): |
| 818 | + async with ( |
| 819 | + server, |
| 820 | + sse_client("http://test/sse", httpx_client_factory=server.client_factory) as streams, |
| 821 | + ClientSession(*streams) as session, |
| 822 | + ): |
| 823 | + await session.initialize() |
| 824 | + assert isinstance(await session.send_ping(), EmptyResult) |
| 825 | + |
| 826 | + |
| 827 | +@pytest.mark.anyio |
| 828 | +async def test_sse_client_failed_post_while_answering_a_server_request_does_not_deadlock() -> None: |
| 829 | + """The session answers server requests inside its receive loop, so its reply can be waiting on |
| 830 | + the writer while a POST fails. Both must still complete: the failed request gets its error and |
| 831 | + the reply reaches the server.""" |
| 832 | + server = _RejectingSseServer() |
| 833 | + roots_requested = anyio.Event() |
| 834 | + |
| 835 | + async def list_roots(context: RequestContext[ClientSession, Any]) -> ListRootsResult: |
| 836 | + roots_requested.set() |
| 837 | + return ListRootsResult(roots=[]) |
| 838 | + |
| 839 | + async def ask_for_roots_first() -> None: |
| 840 | + server.push({"jsonrpc": "2.0", "id": "srv-1", "method": "roots/list"}) |
| 841 | + await roots_requested.wait() |
| 842 | + |
| 843 | + server.before_rejecting = ask_for_roots_first |
| 844 | + with anyio.fail_after(5): |
| 845 | + async with ( |
| 846 | + server, |
| 847 | + sse_client("http://test/sse", httpx_client_factory=server.client_factory) as streams, |
| 848 | + ClientSession(*streams, list_roots_callback=list_roots) as session, |
| 849 | + ): |
| 850 | + await session.initialize() |
| 851 | + server.post_status["tools/call"] = 500 |
| 852 | + with pytest.raises(McpError): |
| 853 | + await session.call_tool("test_tool", {}) |
| 854 | + assert isinstance(await session.send_ping(), EmptyResult) |
| 855 | + |
| 856 | + |
| 857 | +@pytest.mark.anyio |
| 858 | +async def test_sse_client_post_error_after_reader_closed_is_contained() -> None: |
| 859 | + """A failed POST whose error can no longer be delivered, because the read stream already |
| 860 | + closed, is contained: the writer keeps sending.""" |
| 861 | + posted: list[str] = [] |
| 862 | + second_post = anyio.Event() |
| 863 | + |
| 864 | + async def serve(request: httpx.Request) -> httpx.Response: |
| 865 | + if request.method == "GET": |
| 866 | + return httpx.Response( |
| 867 | + 200, headers={"content-type": "text/event-stream"}, text="event: endpoint\ndata: /messages/\n\n" |
| 868 | + ) |
| 869 | + posted.append(json.loads(request.content)["method"]) |
| 870 | + if len(posted) == 2: |
| 871 | + second_post.set() |
| 872 | + return httpx.Response(500) |
| 873 | + |
| 874 | + def factory( |
| 875 | + headers: dict[str, str] | None = None, |
| 876 | + timeout: httpx.Timeout | None = None, |
| 877 | + auth: httpx.Auth | None = None, |
| 878 | + ) -> httpx.AsyncClient: |
| 879 | + return httpx.AsyncClient(transport=httpx.MockTransport(serve)) |
| 880 | + |
| 881 | + with anyio.fail_after(5): |
| 882 | + async with sse_client("http://test/sse", httpx_client_factory=factory) as (read_stream, write_stream): |
| 883 | + with pytest.raises(anyio.EndOfStream): |
| 884 | + await read_stream.receive() |
| 885 | + for request_id, method in [(1, "first/call"), (2, "second/call")]: |
| 886 | + request = types.JSONRPCRequest(jsonrpc="2.0", id=request_id, method=method, params={}) |
| 887 | + await write_stream.send(SessionMessage(types.JSONRPCMessage(request))) |
| 888 | + await second_post.wait() |
| 889 | + assert posted == ["first/call", "second/call"] |
0 commit comments