|
1 | 1 | import anyio |
2 | 2 | import pytest |
| 3 | +from pydantic import AnyUrl |
3 | 4 |
|
4 | 5 | from mcp.server.fastmcp import FastMCP |
5 | 6 | from mcp.shared.memory import create_connected_server_and_client_session as create_session |
6 | 7 |
|
| 8 | +_resource_name = "slow://slow_resource" |
| 9 | + |
7 | 10 |
|
8 | 11 | @pytest.mark.anyio |
9 | | -async def test_messages_are_executed_concurrently(): |
| 12 | +async def test_messages_are_executed_concurrently_tools(): |
10 | 13 | server = FastMCP("test") |
11 | 14 | event = anyio.Event() |
12 | 15 | tool_started = anyio.Event() |
@@ -44,3 +47,42 @@ async def trigger(): |
44 | 47 | "trigger_end", |
45 | 48 | "tool_end", |
46 | 49 | ], f"Expected concurrent execution, but got: {call_order}" |
| 50 | + |
| 51 | + |
| 52 | +@pytest.mark.anyio |
| 53 | +async def test_messages_are_executed_concurrently_tools_and_resources(): |
| 54 | + server = FastMCP("test") |
| 55 | + event = anyio.Event() |
| 56 | + tool_started = anyio.Event() |
| 57 | + call_order = [] |
| 58 | + |
| 59 | + @server.tool("sleep") |
| 60 | + async def sleep_tool(): |
| 61 | + call_order.append("waiting_for_event") |
| 62 | + tool_started.set() |
| 63 | + await event.wait() |
| 64 | + call_order.append("tool_end") |
| 65 | + return "done" |
| 66 | + |
| 67 | + @server.resource(_resource_name) |
| 68 | + async def slow_resource(): |
| 69 | + # Wait for tool to start before setting the event |
| 70 | + await tool_started.wait() |
| 71 | + event.set() |
| 72 | + call_order.append("resource_end") |
| 73 | + return "slow" |
| 74 | + |
| 75 | + async with create_session(server._mcp_server) as client_session: |
| 76 | + # First tool will wait on event, second will set it |
| 77 | + async with anyio.create_task_group() as tg: |
| 78 | + # Start the tool first (it will wait on event) |
| 79 | + tg.start_soon(client_session.call_tool, "sleep") |
| 80 | + # Then the resource (it will set the event) |
| 81 | + tg.start_soon(client_session.read_resource, AnyUrl(_resource_name)) |
| 82 | + |
| 83 | + # Verify that both ran concurrently |
| 84 | + assert call_order == [ |
| 85 | + "waiting_for_event", |
| 86 | + "resource_end", |
| 87 | + "tool_end", |
| 88 | + ], f"Expected concurrent execution, but got: {call_order}" |
0 commit comments