π The fast, Pythonic way to build MCP servers and clients.
Raise when a required OpenAPI path parameter is missing (#5614)
Asem ahmed5e36a960d162
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/director.py b/fastmcp_slim/fastmcp/utilities/openapi/director.pyindex cab9c71ba..0517119f7 100644--- a/fastmcp_slim/fastmcp/utilities/openapi/director.py+++ b/fastmcp_slim/fastmcp/utilities/openapi/director.py@@ -2,6 +2,7 @@import ioimport json as _json+import refrom email.message import Messagefrom typing import Any, ClassVarfrom urllib.parse import quote, unquote@@ -17,6 +18,7 @@ from .schemas import _combine_schemas_and_map_params, _ref_is_mergeable_objectlogger = get_logger(__name__)_MAX_PATH_DECODINGS = 32+_PATH_TEMPLATE_PARAM = re.compile(r"\{([^{}]+)\}")def _query_scalar_to_str(value: Any) -> str:@@ -406,7 +408,19 @@ class RequestDirector:Returns:Complete URL with path parameters substituted++ Raises:+ ValueError: If the template has a parameter with no value"""+ missing = [+ name+ for name in dict.fromkeys(_PATH_TEMPLATE_PARAM.findall(path_template))+ if name not in path_params+ ]+ if missing:+ names = ", ".join(repr(name) for name in missing)+ raise ValueError(f"Missing required path parameters: {{{names}}}")+# Substitute path parameters with URL-encoding to prevent# path traversal and SSRF via crafted parameter valuesurl_path = path_templatediff --git a/tests/utilities/openapi/test_path_values.py b/tests/utilities/openapi/test_path_values.pyindex 7b6dff1e8..3cdd9ae03 100644--- a/tests/utilities/openapi/test_path_values.py+++ b/tests/utilities/openapi/test_path_values.py@@ -161,3 +161,82 @@ async def test_colon_path_segment_reaches_http_endpoint():assert [str(request.url) for request in requests] == ["https://api.example.com/v1/abc123:cancel"]+++def test_path_template_requires_every_parameter_value():+ director = RequestDirector(SchemaPath.from_dict({}))+ with pytest.raises(+ ValueError, match=r"Missing required path parameters: \{'org', 'repo'\}"+ ):+ director._build_url("/orgs/{org}/repos/{repo}/{org}", {}, "https://x.test")+ with pytest.raises(+ ValueError, match=r"Missing required path parameters: \{'repo'\}"+ ):+ director._build_url(+ "/orgs/{org}/repos/{repo}", {"org": "acme"}, "https://x.test"+ )++[email protected]("value,segment", [("", ""), (0, "0")])+def test_path_template_accepts_falsy_values(value: str | int, segment: str):+ url = RequestDirector(SchemaPath.from_dict({}))._build_url(+ "/items/{id}", {"id": value}, "https://x.test"+ )+ assert url == f"https://x.test/items/{segment}"+++ "arguments",+ [{}, {"user_id": None}, {"user_id__path": None, "user_id__query": "x"}],+)+async def test_missing_path_parameter_is_not_sent_as_placeholder(+ arguments: dict[str, str | None],+):+ spec = {+ "openapi": "3.1.0",+ "info": {"title": "API", "version": "1"},+ "paths": {+ "/users/{user_id}": {+ "delete": {+ "operationId": "delete_user",+ "parameters": [+ {+ "name": "user_id",+ "in": "path",+ "required": True,+ "schema": {"type": "integer"},+ },+ *(+ [+ {+ "name": "user_id",+ "in": "query",+ "schema": {"type": "string"},+ }+ ]+ if "user_id__query" in arguments+ else []+ ),+ ],+ "responses": {"200": {"description": "OK"}},+ }+ }+ },+ }+ requests: list[httpx2.Request] = []++ def capture(request: httpx2.Request) -> httpx2.Response:+ requests.append(request)+ return httpx2.Response(200, json={"ok": True})++ async with httpx2.AsyncClient(+ base_url="https://api.example.com", transport=httpx2.MockTransport(capture)+ ) as http:+ server = FastMCP.from_openapi(openapi_spec=spec, client=http)+ async with Client(server) as client:+ with pytest.raises(+ ToolError, match=r"Missing required path parameters: \{'user_id'\}"+ ):+ await client.call_tool("delete_user", arguments)++ assert requests == []