import pytest import asyncio import sys from unittest.mock import AsyncMock, MagicMock, patch from pydantic import AnyUrl import mcp.types as types from mcp_server_hello_world.server import HelloWorldServer, create_server class TestHandlers: """Test the MCP server handlers.""" @pytest.mark.asyncio async def test_resource_handler(self): """Test the resource handler.""" # Create a server mcp = create_server() # Get the resource URI uri = "hello://welcome" # Call the resource handler result = await mcp.read_resource(uri) # Verify the result assert len(result) == 1 assert result[0].content == "Welcome to the Hello World MCP Server! This is a simple static resource." @pytest.mark.asyncio async def test_tool_handler(self): """Test the tool handler.""" # Create a server mcp = create_server() # Call the tool handler result = await mcp.call_tool("hello", {"name": "Test User"}) # Verify the result assert len(result) == 1 assert result[0].text == "Hello, Test User! Welcome to the Hello World MCP Server." # Test with missing name argument with pytest.raises(Exception) as excinfo: await mcp.call_tool("hello", {}) assert "Error executing tool hello" in str(excinfo.value) assert "Field required" in str(excinfo.value) # Test with unknown tool with pytest.raises(Exception) as excinfo: await mcp.call_tool("unknown", {}) assert "Unknown tool: unknown" in str(excinfo.value) @pytest.mark.asyncio async def test_prompt_handler(self): """Test the prompt handler.""" # Create a server mcp = create_server() # Call the prompt handler result = await mcp.get_prompt("greeting", {"name": "Test User"}) # Verify the result assert len(result.messages) > 0 assert result.messages[0].role == "user" assert result.messages[0].content.type == "text" assert "Hello there! You've chosen to use the greeting prompt with the name: Test User." in result.messages[0].content.text