|
| 1 | +from typing import AsyncGenerator |
| 2 | + |
| 3 | +import pytest |
| 4 | + |
| 5 | +from mcp import StdioServerParameters, ClientSession, stdio_client |
| 6 | +from mcp.server import FastMCP |
| 7 | + |
| 8 | +params = StdioServerParameters(command="uv", args=["run", __file__]) |
| 9 | + |
| 10 | + |
| 11 | +def server() -> FastMCP: |
| 12 | + mcp = FastMCP("Echo") |
| 13 | + |
| 14 | + @mcp.resource("echo://{message}") |
| 15 | + def echo_resource(message: str) -> str: |
| 16 | + """Echo a message as a resource""" |
| 17 | + return f"Resource echo: {message}" |
| 18 | + |
| 19 | + @mcp.tool() |
| 20 | + def echo_tool(message: str) -> str: |
| 21 | + """Echo a message as a tool""" |
| 22 | + return f"Tool echo: {message}" |
| 23 | + |
| 24 | + @mcp.prompt() |
| 25 | + def echo_prompt(message: str) -> str: |
| 26 | + """Create an echo prompt""" |
| 27 | + return f"Please process this message: {message}" |
| 28 | + |
| 29 | + return mcp |
| 30 | + |
| 31 | + |
| 32 | +@pytest.fixture |
| 33 | +async def mcp_client_session() -> AsyncGenerator[ClientSession, None]: |
| 34 | + async with stdio_client(params) as streams: |
| 35 | + async with ClientSession(streams[0], streams[1]) as session: |
| 36 | + await session.initialize() |
| 37 | + yield session |
| 38 | + |
| 39 | + |
| 40 | +@pytest.mark.anyio |
| 41 | +async def test_list_resource_templates(mcp_client_session: ClientSession) -> None: |
| 42 | + res = await mcp_client_session.list_resource_templates() |
| 43 | + templates = set(template.name for template in res.resourceTemplates) |
| 44 | + |
| 45 | + assert "echo_resource" in templates |
| 46 | + |
| 47 | + |
| 48 | +@pytest.mark.anyio |
| 49 | +async def test_list_tools(mcp_client_session: ClientSession) -> None: |
| 50 | + res = await mcp_client_session.list_tools() |
| 51 | + tools = set(tool.name for tool in res.tools) |
| 52 | + |
| 53 | + assert "echo_tool" in tools |
| 54 | + |
| 55 | + |
| 56 | +@pytest.mark.anyio |
| 57 | +async def test_list_prompts(mcp_client_session: ClientSession) -> None: |
| 58 | + res = await mcp_client_session.list_prompts() |
| 59 | + prompts = set(prompt.name for prompt in res.prompts) |
| 60 | + |
| 61 | + assert "echo_prompt" in prompts |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + server().run() |
0 commit comments