π The fast, Pythonic way to build MCP servers and clients.
Update route map logic
Jeremiah Lowine6b1c6984c22
diff --git a/docs/patterns/openapi.mdx b/docs/patterns/openapi.mdxindex 0934cec8e..cab51a4aa 100644--- a/docs/patterns/openapi.mdx+++ b/docs/patterns/openapi.mdx@@ -64,37 +64,34 @@ DEFAULT_ROUTE_MAPPINGS = [RouteMap(methods=["GET"],pattern=r".*\{.*\}.*",- route_type=RouteType.RESOURCE_TEMPLATE,+ mcp_type=MCPType.RESOURCE_TEMPLATE,),# GET without path parameters -> ResourceRouteMap(methods=["GET"],pattern=r".*",- route_type=RouteType.RESOURCE,+ mcp_type=MCPType.RESOURCE,),# All other methods -> Tool- RouteMap(- methods="*",- pattern=r".*",- route_type=RouteType.TOOL,- ),+ ALL_TOOLS(),]```+### Custom Route MapsUsers can add custom route maps to override the default mapping behavior. User-supplied route maps are always applied first, before the default route maps.```python-from fastmcp.server.openapi import RouteMap, RouteType+from fastmcp.server.openapi import RouteMap, MCPType# Custom mapping rulescustom_maps = [# Force all analytics endpoints to be ToolsRouteMap(methods=["GET"],pattern=r"^/analytics/.*",- route_type=RouteType.TOOL)+ mcp_type=MCPType.TOOL)]# Apply custom mappings@@ -105,6 +102,9 @@ mcp = await FastMCP.from_openapi()```+<Info>+For backward compatibility, FastMCP still supports the `route_type` parameter and `RouteType` enum, but they are deprecated and will be removed in a future version. You will see deprecation warnings if you use them.+</Info>### All Routes as Tools@@ -127,13 +127,46 @@ mcp = FastMCP.from_openapi(openapi_spec=spec,client=api_client,route_maps=[- RouteMap(methods="*", pattern=r".*", route_type=RouteType.TOOL)+ RouteMap(methods="*", pattern=r".*", mcp_type=MCPType.TOOL)])```Note that `all_routes_as_tools` and `route_maps` cannot be used together - if you need more complex mapping rules, use `route_maps` instead.+### Excluding Routes++If you want to exclude certain routes from being converted to MCP components, you can map them to `MCPType.EXCLUDE`. This is useful for endpoints that should not be accessible to the agent.++```python+from fastmcp.server.openapi import RouteMap, MCPType++# Custom mapping rules to exclude specific routes+custom_maps = [+ # Exclude all admin endpoints+ RouteMap(+ methods="*",+ pattern=r"^/admin/.*",+ mcp_type=MCPType.EXCLUDE+ ),+ # Exclude analytics GET endpoints+ RouteMap(+ methods=["GET"],+ pattern=r"^/analytics/.*",+ mcp_type=MCPType.EXCLUDE+ )+]++# Apply custom mappings+mcp = FastMCP.from_openapi(+ openapi_spec=spec,+ client=api_client,+ route_maps=custom_maps+)+```++When a route is mapped to `MCPType.EXCLUDE`, FastMCP will log its presence but won't create any MCP component for it, effectively making it invisible to clients and agents using the MCP server.+## How It Works1. FastMCP parses your OpenAPI spec to extract routes and schemas@@ -261,3 +294,68 @@ if __name__ == "__main__":mcp.run()```+### Route Map Shortcuts++FastMCP provides several shortcut functions to create common route maps more easily:++```python+from fastmcp.server.openapi import (+ ALL_TOOLS,+ EXCLUDE_ALL,+ EXCLUDE_PATTERN,+ PATTERN_AS_TOOLS,+)++# Create an MCP server with custom route maps using shortcuts+mcp = FastMCP.from_openapi(+ openapi_spec=spec,+ client=api_client,+ route_maps=[+ # First exclude all admin endpoints+ EXCLUDE_PATTERN(r"^/admin/.*"),++ # Make all /api/v1 endpoints tools+ PATTERN_AS_TOOLS(r"^/api/v1/.*"),++ # Make all remaining routes tools+ ALL_TOOLS(),+ ]+)+```++Available shortcuts:++| Shortcut Function | Description |+|------------------|-------------|+| `ALL_TOOLS()` | Converts all matching routes to tools |+| `EXCLUDE_ALL()` | Excludes all matching routes from being converted to any component |+| `PATTERN_AS_TOOLS(pattern)` | Converts routes matching a specific pattern to tools |+| `EXCLUDE_PATTERN(pattern)` | Excludes routes matching a specific pattern |++These shortcuts are particularly useful for:++1. Converting all remaining unmatched routes to tools (use `ALL_TOOLS()`)+2. Excluding whole sections of your API (use `EXCLUDE_PATTERN("/path/.*")`)+3. Converting routes matching specific patterns to tools (use `PATTERN_AS_TOOLS("/path/.*")`)++The `all_routes_as_tools=True` parameter is equivalent to using just `[ALL_TOOLS()]` as your route maps.++<Tip>+You can use `EXCLUDE_ALL()` as the last entry in your custom route maps to completely ignore the default route maps. Since custom route maps are applied first and default maps are appended afterward, having `EXCLUDE_ALL()` at the end of your custom maps will match any routes that your earlier custom rules didn't match, preventing the default maps from having any effect.++```python+# Create server that only uses custom route maps, ignoring defaults+mcp = FastMCP.from_openapi(+ openapi_spec=spec,+ client=api_client,+ route_maps=[+ # Routes to keep as tools+ PATTERN_AS_TOOLS(r"^/api/v1/.*"),++ # Exclude everything else (ignores default route maps)+ EXCLUDE_ALL(),+ ]+)+```+</Tip>+diff --git a/src/fastmcp/server/openapi.py b/src/fastmcp/server/openapi.pyindex 687790653..ed3e21aa1 100644--- a/src/fastmcp/server/openapi.py+++ b/src/fastmcp/server/openapi.py@@ -5,8 +5,9 @@ from __future__ import annotationsimport enumimport jsonimport re+import warningsfrom collections.abc import Callable-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom re import Patternfrom typing import TYPE_CHECKING, Any, Literal@@ -33,46 +34,176 @@ logger = get_logger(__name__)HttpMethod = Literal["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]+class MCPType(enum.Enum):+ """Type of FastMCP component to create from a route.++ Enum values:+ TOOL: Convert the route to a callable Tool+ RESOURCE: Convert the route to a Resource (typically GET endpoints)+ RESOURCE_TEMPLATE: Convert the route to a ResourceTemplate (typically GET with path params)+ PROMPT: Convert the route to a Prompt (not yet implemented)+ EXCLUDE: Exclude the route from being converted to any MCP component+ IGNORE: Deprecated, use EXCLUDE instead+ """++ TOOL = "TOOL"+ RESOURCE = "RESOURCE"+ RESOURCE_TEMPLATE = "RESOURCE_TEMPLATE"+ PROMPT = "PROMPT"+ EXCLUDE = "EXCLUDE"+++# Keep RouteType as an alias to MCPType for backward compatibilityclass RouteType(enum.Enum):- """Type of FastMCP component to create from a route."""+ """+ Deprecated: Use MCPType instead.++ This enum is kept for backward compatibility and will be removed in a future version.+ """TOOL = "TOOL"RESOURCE = "RESOURCE"RESOURCE_TEMPLATE = "RESOURCE_TEMPLATE"PROMPT = "PROMPT"- IGNORE = "IGNORE"+ EXCLUDE = "EXCLUDE"+ IGNORE = "IGNORE" # Deprecated, use EXCLUDE instead++ def __new__(cls, value):+ # Deprecated in 2.4.1+ warnings.warn(+ "RouteType is deprecated and will be removed in a future version. "+ "Use MCPType instead.",+ DeprecationWarning,+ stacklevel=2,+ )++ # Add a specific warning for the deprecated IGNORE value+ if value == "IGNORE":+ warnings.warn(+ "RouteType.IGNORE is deprecated and will be removed in a future version. "+ "Use MCPType.EXCLUDE instead.",+ DeprecationWarning,+ stacklevel=2,+ )++ instance = object.__new__(cls)+ instance._value_ = value+ return instance@dataclassclass RouteMap:"""Mapping configuration for HTTP routes to FastMCP component types."""- methods: list[HttpMethod] | Literal["*"]- pattern: Pattern[str] | str- route_type: RouteType+ methods: list[HttpMethod] | Literal["*"] = field(default="*")+ pattern: Pattern[str] | str = field(default=r".*")+ mcp_type: MCPType | None = field(default=None)+ route_type: RouteType | MCPType | None = field(default=None)++ def __post_init__(self):+ """Validate and process the route map after initialization."""+ # Handle backward compatibility for route_type+ if self.mcp_type is None and self.route_type is not None:+ warnings.warn(+ "The 'route_type' parameter is deprecated and will be removed in a future version. "+ "Use 'mcp_type' instead with the appropriate MCPType value.",+ DeprecationWarning,+ stacklevel=2,+ )++ # Check for the deprecated IGNORE value+ if self.route_type == RouteType.IGNORE:+ warnings.warn(+ "RouteType.IGNORE is deprecated and will be removed in a future version. "+ "Use MCPType.EXCLUDE instead.",+ DeprecationWarning,+ stacklevel=2,+ )++ # Convert from RouteType to MCPType if needed+ if isinstance(self.route_type, RouteType):+ route_type_name = self.route_type.name+ if route_type_name == "IGNORE":+ route_type_name = "EXCLUDE"+ self.mcp_type = getattr(MCPType, route_type_name)+ else:+ self.mcp_type = self.route_type+ elif self.mcp_type is None:+ raise ValueError("`mcp_type` must be provided")++ # Set route_type to match mcp_type for backward compatibility+ if self.route_type is None:+ self.route_type = self.mcp_type+++# Common route map pattern functions+def EXCLUDE_ALL() -> RouteMap:+ """+ Create a RouteMap that excludes all routes that haven't been matched by earlier rules.++ This is useful as the last route map to exclude any routes that don't match specific patterns.++ Returns:+ RouteMap: A route map that excludes all routes+ """+ return RouteMap(methods="*", pattern=r".*", mcp_type=MCPType.EXCLUDE)+++def ALL_TOOLS() -> RouteMap:+ """+ Create a RouteMap that converts all routes to tools that haven't been matched by earlier rules.++ This is useful to replace the last item in the default route mappings to make all unmatched routes tools.++ Returns:+ RouteMap: A route map that converts all routes to tools+ """+ return RouteMap(methods="*", pattern=r".*", mcp_type=MCPType.TOOL)+++def PATTERN_AS_TOOLS(pattern: str) -> RouteMap:+ """+ Create a RouteMap that converts routes matching a specific pattern to tools.++ Args:+ pattern: Regex pattern to match routes++ Returns:+ RouteMap: A route map that converts routes matching the pattern to tools+ """+ return RouteMap(methods="*", pattern=pattern, mcp_type=MCPType.TOOL)+++def EXCLUDE_PATTERN(pattern: str) -> RouteMap:+ """+ Create a RouteMap that excludes routes matching a specific pattern.++ Args:+ pattern: Regex pattern to match routes to exclude++ Returns:+ RouteMap: A route map that excludes routes matching the pattern+ """+ return RouteMap(methods="*", pattern=pattern, mcp_type=MCPType.EXCLUDE)# Default route mappings as a list, where order determines priorityDEFAULT_ROUTE_MAPPINGS = [# GET requests with path parameters go to ResourceTemplateRouteMap(- methods=["GET"], pattern=r".*\{.*\}.*", route_type=RouteType.RESOURCE_TEMPLATE+ methods=["GET"], pattern=r".*\{.*\}.*", mcp_type=MCPType.RESOURCE_TEMPLATE),# GET requests without path parameters go to Resource- RouteMap(methods=["GET"], pattern=r".*", route_type=RouteType.RESOURCE),+ RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE),# All other HTTP methods go to Tool- RouteMap(- methods=["POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"],- pattern=r".*",- route_type=RouteType.TOOL,- ),+ ALL_TOOLS(),]def _determine_route_type(route: openapi.HTTPRoute,mappings: list[RouteMap],-) -> RouteType:+) -> MCPType:"""Determines the FastMCP component type based on the route and mappings.@@ -81,7 +212,7 @@ def _determine_route_type(mappings: List of RouteMap objects in priority orderReturns:- RouteType for this route+ MCPType for this route"""# Check mappings in priority order (first match wins)for route_map in mappings:@@ -94,13 +225,15 @@ def _determine_route_type(pattern_matches = re.search(route_map.pattern, route.path)if pattern_matches:+ # We know mcp_type is not None here due to post_init validation+ assert route_map.mcp_type is not Nonelogger.debug(- f"Route {route.method} {route.path} matched mapping to {route_map.route_type.name}"+ f"Route {route.method} {route.path} matched mapping to {route_map.mcp_type.name}")- return route_map.route_type+ return route_map.mcp_type# Default fallback- return RouteType.TOOL+ return MCPType.TOOL# Placeholder function to provide function metadata@@ -555,13 +688,13 @@ class FastMCPOpenAPI(FastMCP):RouteMap(methods=["GET", "POST", "PATCH"],pattern=r".*/users/.*",- route_type=RouteType.RESOURCE_TEMPLATE+ mcp_type=MCPType.RESOURCE_TEMPLATE),# Map all analytics endpoints to ToolRouteMap(methods=["GET"],pattern=r".*/analytics/.*",- route_type=RouteType.TOOL+ mcp_type=MCPType.TOOL),]@@ -615,19 +748,19 @@ class FastMCPOpenAPI(FastMCP):path_name = "_".join(p for p in path_parts if not p.startswith("{"))operation_id = f"{route.method.lower()}_{path_name}"- if route_type == RouteType.TOOL:+ if route_type == MCPType.TOOL:self._create_openapi_tool(route, operation_id)- elif route_type == RouteType.RESOURCE:+ elif route_type == MCPType.RESOURCE:self._create_openapi_resource(route, operation_id)- elif route_type == RouteType.RESOURCE_TEMPLATE:+ elif route_type == MCPType.RESOURCE_TEMPLATE:self._create_openapi_template(route, operation_id)- elif route_type == RouteType.PROMPT:+ elif route_type == MCPType.PROMPT:# Not implemented yetlogger.warning(f"PROMPT route type not implemented: {route.method} {route.path}")- elif route_type == RouteType.IGNORE:- logger.info(f"Ignoring route: {route.method} {route.path}")+ elif route_type == MCPType.EXCLUDE:+ logger.info(f"Excluding route: {route.method} {route.path}")logger.info(f"Created FastMCP OpenAPI server with {len(http_routes)} routes")diff --git a/tests/deprecated/test_route_type_ignore.py b/tests/deprecated/test_route_type_ignore.pynew file mode 100644index 000000000..1382d7137--- /dev/null+++ b/tests/deprecated/test_route_type_ignore.py@@ -0,0 +1,113 @@+"""Tests for the deprecated RouteType.IGNORE."""++import warnings++import httpx+import pytest++from fastmcp.server.openapi import (+ FastMCPOpenAPI,+ MCPType,+ RouteMap,+ RouteType,+)+++def test_route_type_ignore_deprecation_warning():+ """Test that using RouteType.IGNORE emits a deprecation warning."""+ # Let's manually capture the warnings++ # Record all warnings+ with warnings.catch_warnings(record=True) as recorded:+ # Make sure warnings are always triggered+ warnings.simplefilter("always")++ # Create a RouteMap with RouteType.IGNORE+ route_map = RouteMap(+ methods=["GET"], pattern=r"^/analytics$", route_type=RouteType.IGNORE+ )++ # Check for the expected warnings in the recorded warnings+ route_type_warning = False+ ignore_warning = False++ for w in recorded:+ if issubclass(w.category, DeprecationWarning):+ message = str(w.message)+ if "route_type' parameter is deprecated" in message:+ route_type_warning = True+ if "RouteType.IGNORE is deprecated" in message:+ ignore_warning = True++ # Make sure both warnings were triggered+ assert route_type_warning, "Missing 'route_type' deprecation warning"+ assert ignore_warning, "Missing 'RouteType.IGNORE' deprecation warning"++ # Verify that RouteType.IGNORE was converted to MCPType.EXCLUDE+ assert route_map.mcp_type == MCPType.EXCLUDE+++class TestRouteTypeIgnoreDeprecation:+ """Test class for the deprecated RouteType.IGNORE."""++ @pytest.fixture+ def basic_openapi_spec(self) -> dict:+ """Create a simple OpenAPI spec for testing."""+ return {+ "openapi": "3.0.0",+ "info": {"title": "Test API", "version": "1.0.0"},+ "paths": {+ "/items": {+ "get": {+ "operationId": "get_items",+ "summary": "Get all items",+ "responses": {"200": {"description": "Success"}},+ }+ },+ "/analytics": {+ "get": {+ "operationId": "get_analytics",+ "summary": "Get analytics data",+ "responses": {"200": {"description": "Success"}},+ }+ },+ },+ }++ @pytest.fixture+ async def mock_client(self) -> httpx.AsyncClient:+ """Create a mock client for testing."""++ async def _responder(request):+ return httpx.Response(200, json={"success": True})++ return httpx.AsyncClient(transport=httpx.MockTransport(_responder))++ async def test_route_type_ignore_conversion(self, basic_openapi_spec, mock_client):+ """Test that routes with RouteType.IGNORE are properly excluded."""+ # Capture the deprecation warning without checking the exact message+ with pytest.warns(DeprecationWarning):+ server = FastMCPOpenAPI(+ openapi_spec=basic_openapi_spec,+ client=mock_client,+ route_maps=[+ # Use the deprecated RouteType.IGNORE+ RouteMap(+ methods=["GET"],+ pattern=r"^/analytics$",+ route_type=RouteType.IGNORE,+ ),+ # Make everything else a resource+ RouteMap(+ methods=["GET"], pattern=r".*", route_type=RouteType.RESOURCE+ ),+ ],+ )++ # Check that the analytics route was excluded (converted from IGNORE to EXCLUDE)+ resources = await server.get_resources()+ resource_uris = [str(r.uri) for r in resources.values()]++ # Analytics should be excluded+ assert "resource://openapi/get_items" in resource_uris+ assert "resource://openapi/get_analytics" not in resource_urisdiff --git a/tests/server/test_openapi.py b/tests/server/test_openapi.pyindex 3149ac19c..f38ae4acc 100644--- a/tests/server/test_openapi.py+++ b/tests/server/test_openapi.py@@ -2152,3 +2152,71 @@ class TestAllRoutesAsTools:)],)+++class TestRouteTypeExclude:+ @pytest.fixture+ def basic_openapi_spec(self) -> dict:+ return {+ "openapi": "3.0.0",+ "info": {"title": "Test API", "version": "1.0.0"},+ "paths": {+ "/items": {+ "get": {+ "operationId": "get_items",+ "summary": "Get all items",+ "responses": {"200": {"description": "Success"}},+ }+ },+ "/users": {+ "get": {+ "operationId": "get_users",+ "summary": "Get all users",+ "responses": {"200": {"description": "Success"}},+ }+ },+ "/analytics": {+ "get": {+ "operationId": "get_analytics",+ "summary": "Get analytics data",+ "responses": {"200": {"description": "Success"}},+ }+ },+ },+ }++ @pytest.fixture+ async def mock_client(self) -> httpx.AsyncClient:+ async def _responder(request):+ return httpx.Response(200, json={"success": True})++ return httpx.AsyncClient(transport=httpx.MockTransport(_responder))++ async def test_exclude_routes(self, basic_openapi_spec, mock_client):+ # Create a server with custom mappings that exclude specific routes+ server = FastMCPOpenAPI(+ openapi_spec=basic_openapi_spec,+ client=mock_client,+ route_maps=[+ # Exclude analytics endpoints+ RouteMap(+ methods=["GET"],+ pattern=r"^/analytics$",+ route_type=RouteType.IGNORE,+ ),+ # Make everything else a resource+ RouteMap(methods=["GET"], pattern=r".*", route_type=RouteType.RESOURCE),+ ],+ )++ # Check that resources were created for non-excluded routes+ resources = await server.get_resources()+ resource_uris = [str(r.uri) for r in resources.values()]++ # The /analytics endpoint should be excluded+ assert "resource://openapi/get_items" in resource_uris+ assert "resource://openapi/get_users" in resource_uris+ assert "resource://openapi/get_analytics" not in resource_uris++ # Should only have 2 resources (analytics is excluded)+ assert len(resources) == 2diff --git a/tests/server/test_route_map_shortcuts.py b/tests/server/test_route_map_shortcuts.pynew file mode 100644index 000000000..a64be9910--- /dev/null+++ b/tests/server/test_route_map_shortcuts.py@@ -0,0 +1,207 @@+"""Tests for the route map shortcut functions."""++import httpx+import pytest++from fastmcp.server.openapi import (+ ALL_TOOLS,+ EXCLUDE_ALL,+ EXCLUDE_PATTERN,+ PATTERN_AS_TOOLS,+ FastMCPOpenAPI,+ MCPType,+ RouteMap,+ RouteType,+)+++class TestRouteMapShortcuts:+ """Tests for the route map shortcut functions."""++ def test_functions_return_correct_route_maps(self):+ """Test that each shortcut function returns a RouteMap with the expected properties."""+ # Test EXCLUDE_ALL+ exclude_all = EXCLUDE_ALL()+ assert isinstance(exclude_all, RouteMap)+ assert exclude_all.methods == "*"+ assert exclude_all.pattern == ".*"+ assert exclude_all.mcp_type == MCPType.EXCLUDE++ # Test ALL_TOOLS+ all_tools = ALL_TOOLS()+ assert isinstance(all_tools, RouteMap)+ assert all_tools.methods == "*"+ assert all_tools.pattern == ".*"+ assert all_tools.mcp_type == MCPType.TOOL++ # Test PATTERN_AS_TOOLS+ pattern = r"^/api/.*"+ pattern_as_tools = PATTERN_AS_TOOLS(pattern)+ assert isinstance(pattern_as_tools, RouteMap)+ assert pattern_as_tools.methods == "*"+ assert pattern_as_tools.pattern == pattern+ assert pattern_as_tools.mcp_type == MCPType.TOOL++ # Test EXCLUDE_PATTERN+ pattern = r"^/admin/.*"+ exclude_pattern = EXCLUDE_PATTERN(pattern)+ assert isinstance(exclude_pattern, RouteMap)+ assert exclude_pattern.methods == "*"+ assert exclude_pattern.pattern == pattern+ assert exclude_pattern.mcp_type == MCPType.EXCLUDE++ def test_backward_compatibility(self):+ """Test that backward compatibility with RouteType and route_type works."""+ # Test creating a RouteMap with route_type+ with pytest.warns(DeprecationWarning):+ route_map = RouteMap(+ methods=["GET"], pattern=r".*", route_type=RouteType.TOOL+ )+ assert route_map.mcp_type == MCPType.TOOL++ # Test accessing fields on RouteType directly+ # Note: importing RouteType already causes the deprecation warning,+ # so we don't need to check for it again here+ rt = RouteType.RESOURCE+ assert rt.value == "RESOURCE"+ assert rt.name == "RESOURCE"+++class TestRouteMapShortcutsIntegration:+ """Integration tests for the route map shortcut functions with FastMCPOpenAPI."""++ @pytest.fixture+ def basic_openapi_spec(self) -> dict:+ """Create a simple OpenAPI spec for testing."""+ return {+ "openapi": "3.0.0",+ "info": {"title": "Test API", "version": "1.0.0"},+ "paths": {+ "/items": {+ "get": {+ "operationId": "get_items",+ "summary": "Get all items",+ "responses": {"200": {"description": "Success"}},+ },+ "post": {+ "operationId": "create_item",+ "summary": "Create an item",+ "responses": {"201": {"description": "Created"}},+ },+ },+ "/users": {+ "get": {+ "operationId": "get_users",+ "summary": "Get all users",+ "responses": {"200": {"description": "Success"}},+ },+ },+ "/admin": {+ "get": {+ "operationId": "get_admin",+ "summary": "Admin endpoint",+ "responses": {"200": {"description": "Success"}},+ },+ },+ "/items/{item_id}": {+ "get": {+ "operationId": "get_item",+ "summary": "Get an item by ID",+ "parameters": [+ {+ "name": "item_id",+ "in": "path",+ "required": True,+ "schema": {"type": "string"},+ }+ ],+ "responses": {"200": {"description": "Success"}},+ },+ },+ },+ }++ @pytest.fixture+ async def mock_client(self) -> httpx.AsyncClient:+ """Create a mock client for testing."""++ async def _responder(request):+ return httpx.Response(200, json={"success": True})++ return httpx.AsyncClient(transport=httpx.MockTransport(_responder))++ async def test_all_tools(self, basic_openapi_spec, mock_client):+ """Test using ALL_TOOLS() to convert all routes to tools."""+ server = FastMCPOpenAPI(+ openapi_spec=basic_openapi_spec,+ client=mock_client,+ route_maps=[ALL_TOOLS()],+ )++ # Check that all routes are tools+ tools = await server.get_tools()+ resources = await server.get_resources()+ templates = await server.get_resource_templates()++ # All 5 routes should be tools+ assert len(tools) == 5+ assert len(resources) == 0+ assert len(templates) == 0++ # Check that all expected tools exist+ tool_names = [t.name for t in tools.values()]+ assert "get_items" in tool_names+ assert "create_item" in tool_names+ assert "get_users" in tool_names+ assert "get_admin" in tool_names+ assert "get_item" in tool_names++ async def test_exclude_pattern(self, basic_openapi_spec, mock_client):+ """Test using EXCLUDE_PATTERN() to exclude specific routes."""+ server = FastMCPOpenAPI(+ openapi_spec=basic_openapi_spec,+ client=mock_client,+ route_maps=[+ # Exclude admin endpoints+ EXCLUDE_PATTERN(r"^/admin"),+ # Make everything else a tool+ ALL_TOOLS(),+ ],+ )++ # Check that admin route is excluded+ tools = await server.get_tools()+ tool_names = [t.name for t in tools.values()]++ # All routes except admin should be tools+ assert "get_items" in tool_names+ assert "create_item" in tool_names+ assert "get_users" in tool_names+ assert "get_item" in tool_names+ assert "get_admin" not in tool_names # This should be excluded++ async def test_pattern_as_tools(self, basic_openapi_spec, mock_client):+ """Test using PATTERN_AS_TOOLS() to convert routes matching a pattern to tools."""+ server = FastMCPOpenAPI(+ openapi_spec=basic_openapi_spec,+ client=mock_client,+ route_maps=[+ # Make /items routes tools regardless of method+ PATTERN_AS_TOOLS(r"^/items"),+ # Make everything else a resource+ RouteMap(methods="*", pattern=r".*", mcp_type=MCPType.RESOURCE),+ ],+ )++ # Check that /items routes are tools+ tools = await server.get_tools()+ tool_names = [t.name for t in tools.values()]+ assert "get_items" in tool_names+ assert "create_item" in tool_names+ assert "get_item" in tool_names++ # Check that other routes are resources+ resources = await server.get_resources()+ resource_names = [r.name for r in resources.values()]+ assert "get_users" in resource_names+ assert "get_admin" in resource_names