π The fast, Pythonic way to build MCP servers and clients.
Add tests
Jeremiah Lowinb924dd54d436
diff --git a/tests/server/openapi/test_openapi.py b/tests/server/openapi/test_openapi.pyindex 6eed469b5..f07f6c87c 100644--- a/tests/server/openapi/test_openapi.py+++ b/tests/server/openapi/test_openapi.py@@ -2114,3 +2114,287 @@ class TestRouteMapTags:"getMetrics",}assert tool_names == expected_tools+++class TestMCPNames:+ """Tests for the mcp_names dictionary functionality."""++ @pytest.fixture+ def mcp_names_openapi_spec(self) -> dict:+ """OpenAPI spec with various operationIds for testing naming strategies."""+ return {+ "openapi": "3.1.0",+ "info": {"title": "MCP Names Test API", "version": "1.0.0"},+ "paths": {+ "/users": {+ "get": {+ "operationId": "list_users__with_pagination",+ "summary": "Get All Users",+ "responses": {"200": {"description": "Success"}},+ },+ "post": {+ "operationId": "create_user_admin__special_permissions",+ "summary": "Create New User",+ "requestBody": {+ "required": True,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {"name": {"type": "string"}},+ "required": ["name"],+ }+ }+ },+ },+ "responses": {"201": {"description": "Created"}},+ },+ },+ "/users/{id}": {+ "get": {+ "operationId": "get_user_by_id__admin_only",+ "summary": "Fetch Single User Profile",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "required": True,+ "schema": {"type": "integer"},+ }+ ],+ "responses": {"200": {"description": "Success"}},+ }+ },+ "/very-long-endpoint-name": {+ "get": {+ "operationId": "this_is_a_very_long_operation_id_that_exceeds_fifty_six_characters_and_should_be_truncated",+ "summary": "This Is A Very Long Summary That Should Also Be Truncated When Used As Name",+ "responses": {"200": {"description": "Success"}},+ }+ },+ "/special": {+ "get": {+ "operationId": "special-chars@and#spaces in$operation%id",+ "summary": "Special Chars & Spaces In Summary!",+ "responses": {"200": {"description": "Success"}},+ }+ },+ },+ }++ @pytest.fixture+ async def mock_client(self) -> httpx.AsyncClient:+ """Mock client for testing."""++ async def _responder(request):+ return httpx.Response(200, json={"status": "ok"})++ transport = httpx.MockTransport(_responder)+ return httpx.AsyncClient(transport=transport, base_url="http://test")++ async def test_mcp_names_custom_mapping(self, mcp_names_openapi_spec, mock_client):+ """Test that mcp_names dictionary provides custom names for components."""+ mcp_names = {+ "list_users__with_pagination": "user_list",+ "create_user_admin__special_permissions": "admin_create_user",+ "get_user_by_id__admin_only": "user_detail",+ }++ server = FastMCPOpenAPI(+ openapi_spec=mcp_names_openapi_spec,+ client=mock_client,+ mcp_names=mcp_names,+ )++ # Check tools use custom names+ tools = server._tool_manager.list_tools()+ tool_names = {tool.name for tool in tools}+ assert "admin_create_user" in tool_names++ # Check resource templates use custom names+ templates = list(server._resource_manager.get_templates().values())+ template_names = {template.name for template in templates}+ assert "user_detail" in template_names++ # Check resources use custom names+ resources = list(server._resource_manager.get_resources().values())+ resource_names = {resource.name for resource in resources}+ assert "user_list" in resource_names++ async def test_mcp_names_fallback_to_operation_id_short(+ self, mcp_names_openapi_spec, mock_client+ ):+ """Test fallback to operationId up to double underscore when not in mcp_names."""+ # Only provide mapping for one operationId+ mcp_names = {+ "list_users__with_pagination": "custom_user_list",+ }++ server = FastMCPOpenAPI(+ openapi_spec=mcp_names_openapi_spec,+ client=mock_client,+ mcp_names=mcp_names,+ )++ tools = server._tool_manager.list_tools()+ tool_names = {tool.name for tool in tools}++ templates = list(server._resource_manager.get_templates().values())+ template_names = {template.name for template in templates}++ resources = list(server._resource_manager.get_resources().values())+ resource_names = {resource.name for resource in resources}++ # Custom mapped name should be used+ assert "custom_user_list" in resource_names++ # Unmapped operationIds should use short version (up to __)+ assert "create_user_admin" in tool_names+ assert "get_user_by_id" in template_names++ async def test_names_are_slugified(self, mcp_names_openapi_spec, mock_client):+ """Test that names are properly slugified (spaces, special chars removed)."""+ server = FastMCPOpenAPI(+ openapi_spec=mcp_names_openapi_spec,+ client=mock_client,+ )++ resources = list(server._resource_manager.get_resources().values())+ resource_names = {+ resource.name for resource in resources if resource.name is not None+ }++ # Special chars and spaces should be slugified+ slugified_name = next(+ (name for name in resource_names if "special" in name), None+ )+ assert slugified_name is not None+ # Should not contain special characters or spaces+ assert "@" not in slugified_name+ assert "#" not in slugified_name+ assert "$" not in slugified_name+ assert "%" not in slugified_name+ assert " " not in slugified_name++ async def test_names_are_truncated_to_56_chars(+ self, mcp_names_openapi_spec, mock_client+ ):+ """Test that names are truncated to 56 characters maximum."""+ server = FastMCPOpenAPI(+ openapi_spec=mcp_names_openapi_spec,+ client=mock_client,+ )++ # Check all component types+ all_names = []++ tools = server._tool_manager.list_tools()+ all_names.extend(tool.name for tool in tools)++ resources = list(server._resource_manager.get_resources().values())+ all_names.extend(resource.name for resource in resources)++ templates = list(server._resource_manager.get_templates().values())+ all_names.extend(template.name for template in templates)++ # All names should be 56 characters or less+ for name in all_names:+ assert len(name) <= 56, (+ f"Name '{name}' exceeds 56 characters (length: {len(name)})"+ )++ # Verify that the long operationId was actually truncated+ long_name = next((name for name in all_names if len(name) > 50), None)+ assert long_name is not None, "Expected to find a truncated name for testing"++ async def test_mcp_names_with_from_openapi_classmethod(+ self, mcp_names_openapi_spec, mock_client+ ):+ """Test mcp_names works with FastMCP.from_openapi() classmethod."""+ mcp_names = {+ "list_users__with_pagination": "openapi_user_list",+ }++ server = FastMCP.from_openapi(+ openapi_spec=mcp_names_openapi_spec,+ client=mock_client,+ mcp_names=mcp_names,+ )++ resources = list(server._resource_manager.get_resources().values())+ resource_names = {resource.name for resource in resources}+ assert "openapi_user_list" in resource_names++ async def test_mcp_names_with_from_fastapi_classmethod(self):+ """Test mcp_names works with FastMCP.from_fastapi() classmethod."""+ from fastapi import FastAPI+ from pydantic import BaseModel++ app = FastAPI(title="FastAPI MCP Names Test")++ class User(BaseModel):+ name: str++ @app.get("/users", operation_id="list_users__with_filters")+ async def get_users() -> list[User]:+ return [User(name="test")]++ @app.post("/users", operation_id="create_user__admin_required")+ async def create_user(user: User) -> User:+ return user++ mcp_names = {+ "list_users__with_filters": "fastapi_user_list",+ "create_user__admin_required": "fastapi_create_user",+ }++ server = FastMCP.from_fastapi(+ app=app,+ mcp_names=mcp_names,+ )++ tools = server._tool_manager.list_tools()+ tool_names = {tool.name for tool in tools}++ resources = list(server._resource_manager.get_resources().values())+ resource_names = {resource.name for resource in resources}++ assert "fastapi_create_user" in tool_names+ assert "fastapi_user_list" in resource_names++ async def test_mcp_names_custom_names_are_also_truncated(+ self, mcp_names_openapi_spec, mock_client+ ):+ """Test that custom names in mcp_names are also truncated to 56 characters."""+ # Provide a custom name that's longer than 56 characters+ very_long_custom_name = "this_is_a_very_long_custom_name_that_exceeds_fifty_six_characters_and_should_be_truncated"++ mcp_names = {+ "list_users__with_pagination": very_long_custom_name,+ }++ server = FastMCPOpenAPI(+ openapi_spec=mcp_names_openapi_spec,+ client=mock_client,+ mcp_names=mcp_names,+ )++ resources = list(server._resource_manager.get_resources().values())+ resource_names = {+ resource.name for resource in resources if resource.name is not None+ }++ # Find the resource that should have the custom name+ truncated_name = next(+ (+ name+ for name in resource_names+ if "this_is_a_very_long_custom_name" in name+ ),+ None,+ )+ assert truncated_name is not None+ assert len(truncated_name) <= 56+ assert (+ len(truncated_name) == 56+ ) # Should be exactly 56 since original was longer