Spaces:
Sleeping
Sleeping
Merge pull request #153 from jlowin/openapi-mount
Browse filesEnsure objects are copied properly and test mounting fastapi
Files changed (10)
- src/fastmcp/prompts/prompt.py-8
- src/fastmcp/prompts/prompt_manager.py+3-1
- src/fastmcp/resources/resource.py+1-9
- src/fastmcp/resources/resource_manager.py+5-4
- src/fastmcp/resources/template.py-8
- src/fastmcp/tools/tool.py-8
- src/fastmcp/tools/tool_manager.py+4-1
- src/fastmcp/utilities/openapi.py-87
- tests/server/test_openapi.py+392-28
- uv.lock+2-2
7 unmodified lines891011121314148 unmodified lines1631641651661671681691701711721731741757 unmodified linesimport pydantic_corefrom mcp.types import EmbeddedResource, ImageContent, TextContentfrom pydantic import BaseModel, BeforeValidator, Field, TypeAdapter, validate_callfrom typing_extensions import Selffrom fastmcp.utilities.types import _convert_set_defaults148 unmodified linesexcept Exception as e:raise ValueError(f"Error rendering prompt {self.name}: {e}")def copy(self, updates: dict[str, Any] | None = None) -> Self:"""Copy the prompt with optional updates."""data = self.model_dump()if updates:data.update(updates)return type(self)(**data)def __eq__(self, other: object) -> bool:if not isinstance(other, Prompt):return False7 unmodified lines8910111213148 unmodified lines1621631641651661677 unmodified linesimport pydantic_corefrom mcp.types import EmbeddedResource, ImageContent, TextContentfrom pydantic import BaseModel, BeforeValidator, Field, TypeAdapter, validate_callfrom fastmcp.utilities.types import _convert_set_defaults148 unmodified linesexcept Exception as e:raise ValueError(f"Error rendering prompt {self.name}: {e}")def __eq__(self, other: object) -> bool:if not isinstance(other, Prompt):return False
1234578 unmodified lines84858687888990"""Prompt management functionality."""from collections.abc import Awaitable, Callablefrom typing import Any78 unmodified lines# Create prefixed nameprefixed_name = f"{prefix}{name}" if prefix else namenew_prompt = prompt.copy(updates=dict(name=prefixed_name))# Store the prompt with the prefixed nameself.add_prompt(new_prompt)12345678 unmodified lines8586878889909192"""Prompt management functionality."""import copyfrom collections.abc import Awaitable, Callablefrom typing import Any78 unmodified lines# Create prefixed nameprefixed_name = f"{prefix}{name}" if prefix else namenew_prompt = copy.copy(prompt)new_prompt.name = prefixed_name# Store the prompt with the prefixed nameself.add_prompt(new_prompt)
12345675 unmodified lines1314151617181934 unmodified lines54555657585960616263646566"""Base classes and interfaces for FastMCP resources."""import abcfrom typing import Annotated, Anyfrom pydantic import (AnyUrl,5 unmodified linesValidationInfo,field_validator,)from typing_extensions import Selffrom fastmcp.utilities.types import _convert_set_defaults34 unmodified lines"""Read the resource content."""passdef copy(self, updates: dict[str, Any] | None = None) -> Self:"""Copy the resource with optional updates."""data = self.model_dump()if updates:data.update(updates)return type(self)(**data)def __eq__(self, other: object) -> bool:if not isinstance(other, Resource):return False12345675 unmodified lines13141516171834 unmodified lines535455565758"""Base classes and interfaces for FastMCP resources."""import abcfrom typing import Annotatedfrom pydantic import (AnyUrl,5 unmodified linesValidationInfo,field_validator,)from fastmcp.utilities.types import _convert_set_defaults34 unmodified lines"""Read the resource content."""passdef __eq__(self, other: object) -> bool:if not isinstance(other, Resource):return False
12345232 unmodified lines23823924024124224324421 unmodified lines266267268269270271272273274"""Resource manager functionality."""import inspectimport refrom collections.abc import Callable232 unmodified lines# Create prefixed URI and copy the resource with the new URIprefixed_uri = f"{prefix}{uri}" if prefix else urinew_resource = resource.copy(updates=dict(uri=prefixed_uri))# Store directly in resources dictionaryself.add_resource(new_resource)21 unmodified linesf"{prefix}{uri_template}" if prefix else uri_template)new_template = template.copy(updates=dict(uri_template=prefixed_uri_template))# Store directly in templates dictionaryself.add_template(new_template)123456232 unmodified lines23924024124224324424524621 unmodified lines268269270271272273274275"""Resource manager functionality."""import copyimport inspectimport refrom collections.abc import Callable232 unmodified lines# Create prefixed URI and copy the resource with the new URIprefixed_uri = f"{prefix}{uri}" if prefix else urinew_resource = copy.copy(resource)new_resource.uri = AnyUrl(prefixed_uri)# Store directly in resources dictionaryself.add_resource(new_resource)21 unmodified linesf"{prefix}{uri_template}" if prefix else uri_template)new_template = copy.copy(template)new_template.uri_template = prefixed_uri_template# Store directly in templates dictionaryself.add_template(new_template)
7 unmodified lines89101112131477 unmodified lines92939495969798991001011021031047 unmodified linesfrom typing import Annotated, Anyfrom pydantic import BaseModel, BeforeValidator, Field, TypeAdapter, validate_callfrom typing_extensions import Selffrom fastmcp.resources.types import FunctionResource, Resourcefrom fastmcp.utilities.types import _convert_set_defaults77 unmodified linesexcept Exception as e:raise ValueError(f"Error creating resource from template: {e}")def copy(self, updates: dict[str, Any] | None = None) -> Self:"""Copy the resource template with optional updates."""data = self.model_dump()if updates:data.update(updates)return type(self)(**data)def __eq__(self, other: object) -> bool:if not isinstance(other, ResourceTemplate):return False7 unmodified lines891011121377 unmodified lines9192939495967 unmodified linesfrom typing import Annotated, Anyfrom pydantic import BaseModel, BeforeValidator, Field, TypeAdapter, validate_callfrom fastmcp.resources.types import FunctionResource, Resourcefrom fastmcp.utilities.types import _convert_set_defaults77 unmodified linesexcept Exception as e:raise ValueError(f"Error creating resource from template: {e}")def __eq__(self, other: object) -> bool:if not isinstance(other, ResourceTemplate):return False
4 unmodified lines56789101190 unmodified lines1021031041051061071081091101111121131144 unmodified linesfrom typing import TYPE_CHECKING, Annotated, Anyfrom pydantic import BaseModel, BeforeValidator, Fieldfrom typing_extensions import Selffrom fastmcp.exceptions import ToolErrorfrom fastmcp.utilities.func_metadata import FuncMetadata, func_metadata90 unmodified linesexcept Exception as e:raise ToolError(f"Error executing tool {self.name}: {e}") from edef copy(self, updates: dict[str, Any] | None = None) -> Self:"""Copy the tool with optional updates."""data = self.model_dump()if updates:data.update(updates)return type(self)(**data)def __eq__(self, other: object) -> bool:if not isinstance(other, Tool):return False4 unmodified lines567891090 unmodified lines1011021031041051064 unmodified linesfrom typing import TYPE_CHECKING, Annotated, Anyfrom pydantic import BaseModel, BeforeValidator, Fieldfrom fastmcp.exceptions import ToolErrorfrom fastmcp.utilities.func_metadata import FuncMetadata, func_metadata90 unmodified linesexcept Exception as e:raise ToolError(f"Error executing tool {self.name}: {e}") from edef __eq__(self, other: object) -> bool:if not isinstance(other, Tool):return False
1234584 unmodified lines90919293949596from __future__ import annotations as _annotationsfrom collections.abc import Callablefrom typing import TYPE_CHECKING, Any84 unmodified linesfor name, tool in tool_manager._tools.items():prefixed_name = f"{prefix}{name}" if prefix else namenew_tool = tool.copy(updates=dict(name=prefixed_name))# Store the copied toolself.add_tool(new_tool)logger.debug(f'Imported tool "{name}" as "{prefixed_name}"')12345684 unmodified lines919293949596979899from __future__ import annotations as _annotationsimport copyfrom collections.abc import Callablefrom typing import TYPE_CHECKING, Any84 unmodified linesfor name, tool in tool_manager._tools.items():prefixed_name = f"{prefix}{name}" if prefix else namenew_tool = copy.copy(tool)new_tool.name = prefixed_name# Store the copied toolself.add_tool(new_tool)logger.debug(f'Imported tool "{name}" as "{prefixed_name}"')
149 unmodified lines150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242149 unmodified linesreturn itemdef _extract_schema_as_dict(schema_obj: Schema | Reference, openapi: OpenAPI) -> JsonSchema:"""Resolves a schema/reference and returns it as a dictionary."""resolved_schema = _resolve_ref(schema_obj, openapi)if isinstance(resolved_schema, Schema):# Using exclude_none=True might be better than exclude_unset sometimesreturn resolved_schema.model_dump(mode="json", by_alias=True, exclude_none=True)elif isinstance(resolved_schema, dict):logger.warning("Resolved schema reference resulted in a dict, not a Schema model.")return resolved_schemaelse:ref_str = getattr(schema_obj, "ref", "unknown")logger.warning(f"Expected Schema after resolving ref '{ref_str}', got {type(resolved_schema)}. Returning empty dict.")return {}def _convert_to_parameter_location(param_in: str) -> ParameterLocation:"""Convert string parameter location to our ParameterLocation type."""if param_in == "path":return "path"elif param_in == "query":return "query"elif param_in == "header":return "header"elif param_in == "cookie":return "cookie"else:logger.warning(f"Unknown parameter location: {param_in}, defaulting to 'query'")return "query"def _extract_responses(operation_responses: dict[str, Response | Reference] | None,openapi: OpenAPI,) -> dict[str, ResponseInfo]:"""Extracts and resolves response information for an operation."""extracted_responses: dict[str, ResponseInfo] = {}if not operation_responses:return extracted_responsesfor status_code, resp_or_ref in operation_responses.items():try:response = cast(Response, _resolve_ref(resp_or_ref, openapi))if not isinstance(response, Response):ref_str = getattr(resp_or_ref, "ref", "unknown")logger.warning(f"Expected Response after resolving ref '{ref_str}' for status code {status_code}, got {type(response)}. Skipping.")continuecontent_schemas: dict[str, JsonSchema] = {}if response.content:for media_type_str, media_type_obj in response.content.items():if (isinstance(media_type_obj, MediaType)and media_type_obj.media_type_schema):try:schema_dict = _extract_schema_as_dict(media_type_obj.media_type_schema, openapi)content_schemas[media_type_str] = schema_dictexcept ValueError as schema_err:logger.error(f"Failed to extract schema for media type '{media_type_str}' in response {status_code}: {schema_err}")resp_info = ResponseInfo(description=response.description, content_schema=content_schemas)extracted_responses[str(status_code)] = resp_infoexcept (ValidationError, ValueError, AttributeError) as e:ref_name = getattr(resp_or_ref, "ref", "unknown")logger.error(f"Failed to extract response for status code {status_code} (ref: '{ref_name}'): {e}",exc_info=False,)return extracted_responses# --- Main Parsing Function ---# (No changes needed in the main loop logic, only in the helpers it calls)def parse_openapi_to_http_routes(openapi_dict: dict[str, Any]) -> list[HTTPRoute]:149 unmodified lines150151152153154155149 unmodified linesreturn item# --- Main Parsing Function ---# (No changes needed in the main loop logic, only in the helpers it calls)def parse_openapi_to_http_routes(openapi_dict: dict[str, Any]) -> list[HTTPRoute]:
72 unmodified lines7374757677787933 unmodified lines11311411511611711811912012112212324 unmodified lines1481491501511521531541551561571581594 unmodified lines1641651661671681691701711721731741751761771781791801811823 unmodified lines1861871881891901911921 unmodified line1941951961971981992002012022032042052062072082092101 unmodified line2122132142152162172183 unmodified lines2222232242252262272282292302312322 unmodified lines2352362372382392402412422432442452462474 unmodified lines25225325425525625725825926026126226326426526626726826927027127220 unmodified lines2932942952962972982993003013028 unmodified lines3113123133143153163173183193203218 unmodified lines33033133233333433533633733833934012 unmodified lines35335435572 unmodified lines@pytest.fixtureasync def fastmcp_server(fastapi_app: FastAPI, api_client: httpx.AsyncClient) -> FastMCPOpenAPI:openapi_spec = fastapi_app.openapi()33 unmodified linesclass TestTools:async def test_list_tools(self, fastmcp_server: FastMCPOpenAPI):"""By default, tools exclude GET methods"""tools = await fastmcp_server._mcp_list_tools()assert len(tools) == 2assert tools[0].model_dump() == dict(24 unmodified lines)async def test_call_create_user_tool(self, fastmcp_server: FastMCPOpenAPI, api_client):"""The tool created by the OpenAPI server should be the same as the original"""tool_response = await fastmcp_server.call_tool("create_user_users_post", {"name": "David", "active": False})assert tool_response == User(id=4, name="David", active=False)4 unmodified linesassert len(response.json()) == 4# Check that the user was created via MCPuser_response = await fastmcp_server._mcp_read_resource("resource://openapi/get_user_users__user_id__get/4")user = user_response[0].contentassert user == tool_response.model_dump()async def test_call_update_user_name_tool(self, fastmcp_server: FastMCPOpenAPI, api_client):"""The tool created by the OpenAPI server should be the same as the original"""tool_response = await fastmcp_server.call_tool("update_user_name_users__user_id__name_patch", {"user_id": 1, "name": "XYZ"})assert tool_response == dict(id=1, name="XYZ", active=True)3 unmodified linesassert dict(id=1, name="XYZ", active=True) in response.json()# Check that the user was updated via MCPuser_response = await fastmcp_server._mcp_read_resource("resource://openapi/get_user_users__user_id__get/1")user = user_response[0].content1 unmodified lineclass TestResources:async def test_list_resources(self, fastmcp_server: FastMCPOpenAPI):"""By default, resources exclude GET methods without parameters"""resources = await fastmcp_server._mcp_list_resources()assert len(resources) == 1assert resources[0].uri == AnyUrl("resource://openapi/get_users_users_get")assert resources[0].name == "get_users_users_get"async def test_get_resource(self, fastmcp_server: FastMCPOpenAPI, api_client, users_db: dict[int, User]):"""The resource created by the OpenAPI server should be the same as the original1 unmodified linejson_users = TypeAdapter(list[User]).dump_python(sorted(users_db.values(), key=lambda x: x.id))resource_response = await fastmcp_server._mcp_read_resource("resource://openapi/get_users_users_get")resource = resource_response[0].content3 unmodified linesclass TestResourceTemplates:async def test_list_resource_templates(self, fastmcp_server: FastMCPOpenAPI):"""By default, resource templates exclude GET methods without parameters"""resource_templates = await fastmcp_server._mcp_list_resource_templates()assert len(resource_templates) == 1assert resource_templates[0].name == "get_user_users__user_id__get"assert (2 unmodified lines)async def test_get_resource_template(self, fastmcp_server: FastMCPOpenAPI, api_client, users_db: dict[int, User]):"""The resource template created by the OpenAPI server should be the same as the original"""user_id = 2resource_response = await fastmcp_server._mcp_read_resource(f"resource://openapi/get_user_users__user_id__get/{user_id}")4 unmodified linesclass TestPrompts:async def test_list_prompts(self, fastmcp_server: FastMCPOpenAPI):"""By default, there are no prompts."""prompts = await fastmcp_server._mcp_list_prompts()assert len(prompts) == 0class TestTagTransfer:"""Tests for transferring tags from OpenAPI to MCP objects."""async def test_tags_transferred_to_tools(self, fastmcp_server: FastMCPOpenAPI):"""Test that tags from OpenAPI routes are correctly transferred to Tools."""# Get internal tools directly (not the public API which returns MCP.Content)tools = fastmcp_server._tool_manager.list_tools()# Find the create_user and update_user_name toolscreate_user_tool = next(20 unmodified linesassert "update" in update_user_tool.tagsassert len(update_user_tool.tags) == 2async def test_tags_transferred_to_resources(self, fastmcp_server: FastMCPOpenAPI):"""Test that tags from OpenAPI routes are correctly transferred to Resources."""# Get internal resources directlyresources = fastmcp_server._resource_manager.list_resources()# Find the get_users resourceget_users_resource = next(8 unmodified linesassert len(get_users_resource.tags) == 2async def test_tags_transferred_to_resource_templates(self, fastmcp_server: FastMCPOpenAPI):"""Test that tags from OpenAPI routes are correctly transferred to ResourceTemplates."""# Get internal resource templates directlytemplates = fastmcp_server._resource_manager.list_templates()# Find the get_user templateget_user_template = next(8 unmodified linesassert len(get_user_template.tags) == 2async def test_tags_preserved_in_resources_created_from_templates(self, fastmcp_server: FastMCPOpenAPI):"""Test that tags are preserved when creating resources from templates."""# Get internal resource templates directlytemplates = fastmcp_server._resource_manager.list_templates()# Find the get_user templateget_user_template = next(12 unmodified linesassert "users" in resource.tagsassert "detail" in resource.tagsassert len(resource.tags) == 272 unmodified lines7374757677787933 unmodified lines11311411511611711811912012112212324 unmodified lines1481491501511521531541551561571581594 unmodified lines1641651661671681691701711721731741751761771781791801811823 unmodified lines1861871881891901911921 unmodified line1941951961971981992002012022032042052062072082092102112122131 unmodified line2152162172182192202213 unmodified lines2252262272282292302312322332342352362372 unmodified lines2402412422432442452462472482492502512522532542554 unmodified lines26026126226326426526626726826927027127227327427527627727827928028128220 unmodified lines3033043053063073083093103113123133148 unmodified lines3233243253263273283293303313323338 unmodified lines34234334434534634734834935035135212 unmodified lines36536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972 unmodified lines@pytest.fixtureasync def fastmcp_openapi_server(fastapi_app: FastAPI, api_client: httpx.AsyncClient) -> FastMCPOpenAPI:openapi_spec = fastapi_app.openapi()33 unmodified linesclass TestTools:async def test_list_tools(self, fastmcp_openapi_server: FastMCPOpenAPI):"""By default, tools exclude GET methods"""tools = await fastmcp_openapi_server._mcp_list_tools()assert len(tools) == 2assert tools[0].model_dump() == dict(24 unmodified lines)async def test_call_create_user_tool(self, fastmcp_openapi_server: FastMCPOpenAPI, api_client):"""The tool created by the OpenAPI server should be the same as the original"""tool_response = await fastmcp_openapi_server.call_tool("create_user_users_post", {"name": "David", "active": False})assert tool_response == User(id=4, name="David", active=False)4 unmodified linesassert len(response.json()) == 4# Check that the user was created via MCPuser_response = await fastmcp_openapi_server._mcp_read_resource("resource://openapi/get_user_users__user_id__get/4")user = user_response[0].contentassert user == tool_response.model_dump()async def test_call_update_user_name_tool(self, fastmcp_openapi_server: FastMCPOpenAPI, api_client):"""The tool created by the OpenAPI server should be the same as the original"""tool_response = await fastmcp_openapi_server.call_tool("update_user_name_users__user_id__name_patch", {"user_id": 1, "name": "XYZ"})assert tool_response == dict(id=1, name="XYZ", active=True)3 unmodified linesassert dict(id=1, name="XYZ", active=True) in response.json()# Check that the user was updated via MCPuser_response = await fastmcp_openapi_server._mcp_read_resource("resource://openapi/get_user_users__user_id__get/1")user = user_response[0].content1 unmodified lineclass TestResources:async def test_list_resources(self, fastmcp_openapi_server: FastMCPOpenAPI):"""By default, resources exclude GET methods without parameters"""resources = await fastmcp_openapi_server._mcp_list_resources()assert len(resources) == 1assert resources[0].uri == AnyUrl("resource://openapi/get_users_users_get")assert resources[0].name == "get_users_users_get"async def test_get_resource(self,fastmcp_openapi_server: FastMCPOpenAPI,api_client,users_db: dict[int, User],):"""The resource created by the OpenAPI server should be the same as the original1 unmodified linejson_users = TypeAdapter(list[User]).dump_python(sorted(users_db.values(), key=lambda x: x.id))resource_response = await fastmcp_openapi_server._mcp_read_resource("resource://openapi/get_users_users_get")resource = resource_response[0].content3 unmodified linesclass TestResourceTemplates:async def test_list_resource_templates(self, fastmcp_openapi_server: FastMCPOpenAPI):"""By default, resource templates exclude GET methods without parameters"""resource_templates = await fastmcp_openapi_server._mcp_list_resource_templates()assert len(resource_templates) == 1assert resource_templates[0].name == "get_user_users__user_id__get"assert (2 unmodified lines)async def test_get_resource_template(self,fastmcp_openapi_server: FastMCPOpenAPI,api_client,users_db: dict[int, User],):"""The resource template created by the OpenAPI server should be the same as the original"""user_id = 2resource_response = await fastmcp_openapi_server._mcp_read_resource(f"resource://openapi/get_user_users__user_id__get/{user_id}")4 unmodified linesclass TestPrompts:async def test_list_prompts(self, fastmcp_openapi_server: FastMCPOpenAPI):"""By default, there are no prompts."""prompts = await fastmcp_openapi_server._mcp_list_prompts()assert len(prompts) == 0class TestTagTransfer:"""Tests for transferring tags from OpenAPI routes to MCP objects."""async def test_tags_transferred_to_tools(self, fastmcp_openapi_server: FastMCPOpenAPI):"""Test that tags from OpenAPI routes are correctly transferred to Tools."""# Get internal tools directly (not the public API which returns MCP.Content)tools = fastmcp_openapi_server._tool_manager.list_tools()# Find the create_user and update_user_name toolscreate_user_tool = next(20 unmodified linesassert "update" in update_user_tool.tagsassert len(update_user_tool.tags) == 2async def test_tags_transferred_to_resources(self, fastmcp_openapi_server: FastMCPOpenAPI):"""Test that tags from OpenAPI routes are correctly transferred to Resources."""# Get internal resources directlyresources = fastmcp_openapi_server._resource_manager.list_resources()# Find the get_users resourceget_users_resource = next(8 unmodified linesassert len(get_users_resource.tags) == 2async def test_tags_transferred_to_resource_templates(self, fastmcp_openapi_server: FastMCPOpenAPI):"""Test that tags from OpenAPI routes are correctly transferred to ResourceTemplates."""# Get internal resource templates directlytemplates = fastmcp_openapi_server._resource_manager.list_templates()# Find the get_user templateget_user_template = next(8 unmodified linesassert len(get_user_template.tags) == 2async def test_tags_preserved_in_resources_created_from_templates(self, fastmcp_openapi_server: FastMCPOpenAPI):"""Test that tags are preserved when creating resources from templates."""# Get internal resource templates directlytemplates = fastmcp_openapi_server._resource_manager.list_templates()# Find the get_user templateget_user_template = next(12 unmodified linesassert "users" in resource.tagsassert "detail" in resource.tagsassert len(resource.tags) == 2class TestOpenAPI30Compatibility:"""Tests for compatibility with OpenAPI 3.0 specifications."""@pytest.fixturedef openapi_30_spec(self) -> dict:"""Fixture that returns a simple OpenAPI 3.0 specification."""return {"openapi": "3.0.0","info": {"title": "Product API (3.0)", "version": "1.0.0"},"paths": {"/products": {"get": {"operationId": "listProducts","summary": "List all products","responses": {"200": {"description": "A list of products"}},},"post": {"operationId": "createProduct","summary": "Create a new product","requestBody": {"required": True,"content": {"application/json": {"schema": {"type": "object","properties": {"name": {"type": "string"},"price": {"type": "number"},},"required": ["name", "price"],}}},},"responses": {"201": {"description": "Product created"}},},},"/products/{product_id}": {"get": {"operationId": "getProduct","summary": "Get product by ID","parameters": [{"name": "product_id","in": "path","required": True,"schema": {"type": "string"},}],"responses": {"200": {"description": "A product"}},}},},}@pytest.fixtureasync def mock_30_client(self) -> httpx.AsyncClient:"""Mock client that returns predefined responses for the 3.0 API."""async def _responder(request):if request.url.path == "/products" and request.method == "GET":return httpx.Response(200,json=[{"id": "p1", "name": "Product 1", "price": 19.99},{"id": "p2", "name": "Product 2", "price": 29.99},],)elif request.url.path == "/products" and request.method == "POST":import jsondata = json.loads(request.content)return httpx.Response(201, json={"id": "p3", "name": data["name"], "price": data["price"]})elif request.url.path.startswith("/products/") and request.method == "GET":product_id = request.url.path.split("/")[-1]products = {"p1": {"id": "p1", "name": "Product 1", "price": 19.99},"p2": {"id": "p2", "name": "Product 2", "price": 29.99},}if product_id in products:return httpx.Response(200, json=products[product_id])return httpx.Response(404, json={"error": "Product not found"})return httpx.Response(404)transport = httpx.MockTransport(_responder)return httpx.AsyncClient(transport=transport, base_url="http://test")@pytest.fixtureasync def openapi_30_server(self, openapi_30_spec, mock_30_client) -> FastMCPOpenAPI:"""Create a FastMCPOpenAPI server from the OpenAPI 3.0 spec."""return FastMCPOpenAPI(openapi_spec=openapi_30_spec, client=mock_30_client, name="Product API 3.0")async def test_server_creation(self, openapi_30_server):"""Test that a server can be created from an OpenAPI 3.0 spec."""assert isinstance(openapi_30_server, FastMCP)assert openapi_30_server.name == "Product API 3.0"async def test_resource_discovery(self, openapi_30_server):"""Test that resources are correctly discovered from an OpenAPI 3.0 spec."""resources = await openapi_30_server._mcp_list_resources()assert len(resources) == 1assert resources[0].uri == AnyUrl("resource://openapi/listProducts")async def test_resource_template_discovery(self, openapi_30_server):"""Test that resource templates are correctly discovered from an OpenAPI 3.0 spec."""templates = await openapi_30_server._mcp_list_resource_templates()assert len(templates) == 1assert templates[0].name == "getProduct"assert templates[0].uriTemplate == r"resource://openapi/getProduct/{product_id}"async def test_tool_discovery(self, openapi_30_server):"""Test that tools are correctly discovered from an OpenAPI 3.0 spec."""tools = await openapi_30_server._mcp_list_tools()assert len(tools) == 1assert tools[0].name == "createProduct"assert "name" in tools[0].inputSchema["properties"]assert "price" in tools[0].inputSchema["properties"]async def test_resource_access(self, openapi_30_server):"""Test reading a resource from an OpenAPI 3.0 server."""resource_response = await openapi_30_server._mcp_read_resource("resource://openapi/listProducts")content = resource_response[0].contentassert len(content) == 2assert content[0]["name"] == "Product 1"assert content[1]["name"] == "Product 2"async def test_resource_template_access(self, openapi_30_server):"""Test reading a resource from template from an OpenAPI 3.0 server."""resource_response = await openapi_30_server._mcp_read_resource("resource://openapi/getProduct/p1")content = resource_response[0].contentassert content["id"] == "p1"assert content["name"] == "Product 1"assert content["price"] == 19.99async def test_tool_execution(self, openapi_30_server):"""Test executing a tool from an OpenAPI 3.0 server."""tool_response = await openapi_30_server.call_tool("createProduct", {"name": "New Product", "price": 39.99})assert tool_response["id"] == "p3"assert tool_response["name"] == "New Product"assert tool_response["price"] == 39.99class TestOpenAPI31Compatibility:"""Tests for compatibility with OpenAPI 3.1 specifications."""@pytest.fixturedef openapi_31_spec(self) -> dict:"""Fixture that returns a simple OpenAPI 3.1 specification."""return {"openapi": "3.1.0","info": {"title": "Order API (3.1)", "version": "1.0.0"},"paths": {"/orders": {"get": {"operationId": "listOrders","summary": "List all orders","responses": {"200": {"description": "A list of orders"}},},"post": {"operationId": "createOrder","summary": "Place a new order","requestBody": {"required": True,"content": {"application/json": {"schema": {"type": "object","properties": {"customer": {"type": "string"},"items": {"type": "array","items": {"type": "string"},},},"required": ["customer", "items"],}}},},"responses": {"201": {"description": "Order created"}},},},"/orders/{order_id}": {"get": {"operationId": "getOrder","summary": "Get order by ID","parameters": [{"name": "order_id","in": "path","required": True,"schema": {"type": "string"},}],"responses": {"200": {"description": "An order"}},}},},}@pytest.fixtureasync def mock_31_client(self) -> httpx.AsyncClient:"""Mock client that returns predefined responses for the 3.1 API."""async def _responder(request):if request.url.path == "/orders" and request.method == "GET":return httpx.Response(200,json=[{"id": "o1", "customer": "Alice", "items": ["item1", "item2"]},{"id": "o2", "customer": "Bob", "items": ["item3"]},],)elif request.url.path == "/orders" and request.method == "POST":import jsondata = json.loads(request.content)return httpx.Response(201,json={"id": "o3","customer": data["customer"],"items": data["items"],},)elif request.url.path.startswith("/orders/") and request.method == "GET":order_id = request.url.path.split("/")[-1]orders = {"o1": {"id": "o1","customer": "Alice","items": ["item1", "item2"],},"o2": {"id": "o2", "customer": "Bob", "items": ["item3"]},}if order_id in orders:return httpx.Response(200, json=orders[order_id])return httpx.Response(404, json={"error": "Order not found"})return httpx.Response(404)transport = httpx.MockTransport(_responder)return httpx.AsyncClient(transport=transport, base_url="http://test")@pytest.fixtureasync def openapi_31_server(self, openapi_31_spec, mock_31_client) -> FastMCPOpenAPI:"""Create a FastMCPOpenAPI server from the OpenAPI 3.1 spec."""return FastMCPOpenAPI(openapi_spec=openapi_31_spec, client=mock_31_client, name="Order API 3.1")async def test_server_creation(self, openapi_31_server):"""Test that a server can be created from an OpenAPI 3.1 spec."""assert isinstance(openapi_31_server, FastMCP)assert openapi_31_server.name == "Order API 3.1"async def test_resource_discovery(self, openapi_31_server):"""Test that resources are correctly discovered from an OpenAPI 3.1 spec."""resources = await openapi_31_server._mcp_list_resources()assert len(resources) == 1assert resources[0].uri == AnyUrl("resource://openapi/listOrders")async def test_resource_template_discovery(self, openapi_31_server):"""Test that resource templates are correctly discovered from an OpenAPI 3.1 spec."""templates = await openapi_31_server._mcp_list_resource_templates()assert len(templates) == 1assert templates[0].name == "getOrder"assert templates[0].uriTemplate == r"resource://openapi/getOrder/{order_id}"async def test_tool_discovery(self, openapi_31_server):"""Test that tools are correctly discovered from an OpenAPI 3.1 spec."""tools = await openapi_31_server._mcp_list_tools()assert len(tools) == 1assert tools[0].name == "createOrder"assert "customer" in tools[0].inputSchema["properties"]assert "items" in tools[0].inputSchema["properties"]async def test_resource_access(self, openapi_31_server):"""Test reading a resource from an OpenAPI 3.1 server."""resource_response = await openapi_31_server._mcp_read_resource("resource://openapi/listOrders")content = resource_response[0].contentassert len(content) == 2assert content[0]["customer"] == "Alice"assert content[1]["customer"] == "Bob"async def test_resource_template_access(self, openapi_31_server):"""Test reading a resource from template from an OpenAPI 3.1 server."""resource_response = await openapi_31_server._mcp_read_resource("resource://openapi/getOrder/o1")content = resource_response[0].contentassert content["id"] == "o1"assert content["customer"] == "Alice"assert content["items"] == ["item1", "item2"]async def test_tool_execution(self, openapi_31_server):"""Test executing a tool from an OpenAPI 3.1 server."""tool_response = await openapi_31_server.call_tool("createOrder", {"customer": "Charlie", "items": ["item4", "item5"]})assert tool_response["id"] == "o3"assert tool_response["customer"] == "Charlie"assert tool_response["items"] == ["item4", "item5"]class TestMountFastMCP:"""Tests for mounting FastMCP servers."""async def test_mount_fastmcp(self, fastmcp_openapi_server: FastMCPOpenAPI):"""Test mounting an OpenAPI server."""mcp = FastMCP("MainApp")mcp.mount("fastapi", fastmcp_openapi_server)resources = await mcp._mcp_list_resources()assert len(resources) == 1assert resources[0].uri == AnyUrl("fastapi+resource://openapi/get_users_users_get")templates = await mcp._mcp_list_resource_templates()assert len(templates) == 1assert templates[0].name == "get_user_users__user_id__get"assert (templates[0].uriTemplate== r"fastapi+resource://openapi/get_user_users__user_id__get/{user_id}")tools = await mcp._mcp_list_tools()assert len(tools) == 2assert tools[0].name == "fastapi_create_user_users_post"assert tools[1].name == "fastapi_update_user_name_users__user_id__name_patch"prompts = await mcp._mcp_list_prompts()assert len(prompts) == 0
253 unmodified lines2542552562572582592601062 unmodified lines1323132413251326253 unmodified lines[[package]]name = "fastmcp"version = "2.1.1.dev3+4f58d82"source = { editable = "." }dependencies = [{ name = "dotenv" },1062 unmodified linessdist = { url = "https://files.pythonhosted.org/packages/60/d9/6625ead93412c5ce86db1f8b4f2a70b8043e0a7c1d30099ba3c6a81641ff/wmctrl-0.5.tar.gz", hash = "sha256:7839a36b6fe9e2d6fd22304e5dc372dbced2116ba41283ea938b2da57f53e962", size = 5202 }wheels = [{ url = "https://files.pythonhosted.org/packages/13/ca/723e3f8185738d7947f14ee7dc663b59415c6dee43bd71575f8c7f5cd6be/wmctrl-0.5-py2.py3-none-any.whl", hash = "sha256:ae695c1863a314c899e7cf113f07c0da02a394b968c4772e1936219d9234ddd7", size = 4268 },]253 unmodified lines2542552562572582592601062 unmodified lines1323132413251326253 unmodified lines[[package]]name = "fastmcp"version = "2.1.2.dev2+c0de75e"source = { editable = "." }dependencies = [{ name = "dotenv" },1062 unmodified linessdist = { url = "https://files.pythonhosted.org/packages/60/d9/6625ead93412c5ce86db1f8b4f2a70b8043e0a7c1d30099ba3c6a81641ff/wmctrl-0.5.tar.gz", hash = "sha256:7839a36b6fe9e2d6fd22304e5dc372dbced2116ba41283ea938b2da57f53e962", size = 5202 }wheels = [{ url = "https://files.pythonhosted.org/packages/13/ca/723e3f8185738d7947f14ee7dc663b59415c6dee43bd71575f8c7f5cd6be/wmctrl-0.5-py2.py3-none-any.whl", hash = "sha256:ae695c1863a314c899e7cf113f07c0da02a394b968c4772e1936219d9234ddd7", size = 4268 },]
src/fastmcp/prompts/prompt.py-8
src/fastmcp/prompts/prompt_manager.py+3-1
src/fastmcp/resources/resource.py+1-9
src/fastmcp/resources/resource_manager.py+5-4
src/fastmcp/resources/template.py-8
src/fastmcp/tools/tool.py-8
src/fastmcp/tools/tool_manager.py+4-1
src/fastmcp/utilities/openapi.py-87
tests/server/test_openapi.py+392-28
uv.lock+2-2