π The fast, Pythonic way to build MCP servers and clients.
OpenAPI components send only declared arguments and keep configured headers (#5423)
Jeremiah Lowind691911998cd
diff --git a/docs/integrations/openapi.mdx b/docs/integrations/openapi.mdxindex 6bac8da16..7d5271b1b 100644--- a/docs/integrations/openapi.mdx+++ b/docs/integrations/openapi.mdx@@ -399,6 +399,10 @@ mcp = FastMCP.from_openapi(## Request Parameter Handling+Tool arguments map to the parameters and request body that the operation declares. FastMCP ignores any other arguments.++Headers you configure on the HTTP client are sent with each request, except `Host`, which FastMCP takes from the request URL. When the MCP server runs over HTTP, FastMCP also forwards headers from the incoming MCP request, except credential and connection headers such as `Authorization`, `Cookie`, and `Host`. Forwarded headers only fill in headers that the outgoing request does not already set. This applies to tools, resources, and resource templates.+FastMCP intelligently handles different types of parameters in OpenAPI requests:### Query Parametersdiff --git a/fastmcp_slim/fastmcp/server/providers/openapi/components.py b/fastmcp_slim/fastmcp/server/providers/openapi/components.pyindex a6b88538e..5f0771a37 100644--- a/fastmcp_slim/fastmcp/server/providers/openapi/components.py+++ b/fastmcp_slim/fastmcp/server/providers/openapi/components.py@@ -319,7 +319,9 @@ class OpenAPIResource(Resource):)mcp_headers = get_http_headers()if mcp_headers:- request.headers.update(mcp_headers)+ for key, value in mcp_headers.items():+ if key not in request.headers:+ request.headers[key] = valueresponse = await _send_request(self._client, request)_raise_for_status(response)diff --git a/fastmcp_slim/fastmcp/utilities/openapi/director.py b/fastmcp_slim/fastmcp/utilities/openapi/director.pyindex 6910ad624..8f6113da4 100644--- a/fastmcp_slim/fastmcp/utilities/openapi/director.py+++ b/fastmcp_slim/fastmcp/utilities/openapi/director.py@@ -12,6 +12,7 @@ from jsonschema_path import SchemaPathfrom fastmcp.utilities.logging import get_loggerfrom .models import HTTPRoute, ParameterInfo+from .schemas import _combine_schemas_and_map_paramslogger = get_logger(__name__)@@ -41,6 +42,35 @@ def _uses_default_multipart_encoding(encoding: dict[str, Any]) -> bool:)+def _prepare_parameter_map(+ route: HTTPRoute,+) -> tuple[HTTPRoute, dict[str, dict[str, str]]]:+ """Return the route's parameter map, building it if the route lacks one.++ Routes from the OpenAPI parser carry a precomputed map. Routes constructed+ directly may declare parameters or a request body without one; those get+ the map the parser would have built, computed on a copy so the caller's+ route is left unchanged. Those routes also accept `<name>__<location>`+ for each declared parameter, naming the parameter at that location. An+ empty map for a route with no parameters and no request body is already+ complete.+ """+ if route.parameter_map or not (route.parameters or route.request_body):+ return route, route.parameter_map++ request_body = (+ route.request_body.model_copy(deep=True) if route.request_body else None+ )+ prepared = route.model_copy(update={"request_body": request_body})+ _, parameter_map = _combine_schemas_and_map_params(prepared, convert_refs=False)+ for param in route.parameters:+ parameter_map.setdefault(+ f"{param.name}__{param.location}",+ {"location": param.location, "openapi_name": param.name},+ )+ return prepared, parameter_map++class RequestDirector:"""Builds httpx2.Request objects from HTTPRoute and arguments using openapi-core."""@@ -201,6 +231,10 @@ class RequestDirector:"""Maps flat arguments back to their OpenAPI locations using the parameter map.+ The parameter map is the only source of argument locations. Arguments+ that are not in the map are dropped, so a route that declares no+ parameters and no request body sends none.+Args:route: HTTPRoute with parameter_map containing location mappingsflat_args: Flat arguments from LLM call@@ -214,78 +248,36 @@ class RequestDirector:cookie_params = {}body_props = {}- # Use parameter map to route arguments to correct locations- if hasattr(route, "parameter_map") and route.parameter_map:- for arg_name, value in flat_args.items():- if value is None:- continue # Skip None values for optional parameters-- if arg_name not in route.parameter_map:- logger.warning(- f"Argument '{arg_name}' not found in parameter map for {route.operation_id}"- )- continue+ route, parameter_map = _prepare_parameter_map(route)- mapping = route.parameter_map[arg_name]- location = mapping["location"]- openapi_name = mapping["openapi_name"]-- if location == "path":- path_params[openapi_name] = value- elif location == "query":- query_params[openapi_name] = value- elif location == "header":- header_params[openapi_name] = value- elif location == "cookie":- cookie_params[openapi_name] = value- elif location == "body":- body_props[openapi_name] = value- else:- logger.warning(- f"Unknown parameter location '{location}' for {arg_name}"- )- else:- # Fallback: try to map arguments based on parameter definitions- logger.debug("No parameter map available, using fallback mapping")-- # Create a mapping from parameter names to their locations- param_locations = {}- for param in route.parameters:- param_locations[param.name] = param.location-- # Map arguments to locations- for arg_name, value in flat_args.items():- if value is None:- continue-- # Check if it's a suffixed parameter (e.g., id__path)- if "__" in arg_name:- base_name, location = arg_name.rsplit("__", 1)- if location in ["path", "query", "header", "cookie"]:- if location == "path":- path_params[base_name] = value- elif location == "query":- query_params[base_name] = value- elif location == "header":- header_params[base_name] = value- elif location == "cookie":- cookie_params[base_name] = value- continue+ for arg_name, value in flat_args.items():+ if value is None:+ continue # Skip None values for optional parameters- # Check if it's a known parameter- if arg_name in param_locations:- location = param_locations[arg_name]- if location == "path":- path_params[arg_name] = value- elif location == "query":- query_params[arg_name] = value- elif location == "header":- header_params[arg_name] = value- elif location == "cookie":- cookie_params[arg_name] = value- else:- # Assume it's a body property- body_props[arg_name] = value+ if arg_name not in parameter_map:+ logger.warning(+ f"Argument '{arg_name}' not found in parameter map for {route.operation_id}"+ )+ continue++ mapping = parameter_map[arg_name]+ location = mapping["location"]+ openapi_name = mapping["openapi_name"]++ if location == "path":+ path_params[openapi_name] = value+ elif location == "query":+ query_params[openapi_name] = value+ elif location == "header":+ header_params[openapi_name] = value+ elif location == "cookie":+ cookie_params[openapi_name] = value+ elif location == "body":+ body_props[openapi_name] = value+ else:+ logger.warning(+ f"Unknown parameter location '{location}' for {arg_name}"+ )# Handle body constructionbody = Nonediff --git a/tests/client/test_openapi.py b/tests/client/test_openapi.pyindex 236e6efb3..8aa40ceb2 100644--- a/tests/client/test_openapi.py+++ b/tests/client/test_openapi.py@@ -161,7 +161,7 @@ async def test_client_headers_shttp_tool(shttp_server: str):assert headers["x-test"] == "test-123"-async def test_client_overrides_server_headers(shttp_server: str):+async def test_server_headers_take_precedence_over_client_headers(shttp_server: str):async with Client(transport=StreamableHttpTransport(shttp_server, headers={"x-server-header": "test-client"}@@ -170,7 +170,7 @@ async def test_client_overrides_server_headers(shttp_server: str):result = await client.read_resource("resource://get_headers_headers_get")assert isinstance(result[0], TextResourceContents)headers = json.loads(result[0].text)- assert headers["x-server-header"] == "test-client"+ assert headers["x-server-header"] == "test-abc"async def test_client_with_excluded_header_is_ignored(sse_server: str):diff --git a/tests/server/providers/openapi/test_undeclared_arguments.py b/tests/server/providers/openapi/test_undeclared_arguments.pynew file mode 100644index 000000000..bf2946f83--- /dev/null+++ b/tests/server/providers/openapi/test_undeclared_arguments.py@@ -0,0 +1,337 @@+"""OpenAPI components ignore undeclared arguments and keep configured headers."""++import json+from typing import Any++import httpx2+import pytest+from jsonschema_path import SchemaPath++from fastmcp import Client, FastMCP+from fastmcp.client.transports import StreamableHttpTransport+from fastmcp.exceptions import ToolError+from fastmcp.server.providers.openapi.routing import MCPType, RouteMap+from fastmcp.utilities.openapi import director, parser+from fastmcp.utilities.openapi.director import RequestDirector+from fastmcp.utilities.openapi.models import (+ HTTPRoute,+ ParameterInfo,+ RequestBodyInfo,+)+from fastmcp.utilities.tests import run_server_async++BASE_URL = "https://api.example.com"+CONFIGURED_HEADERS = {+ "Authorization": "Bearer configured",+ "X-Api-Key": "configured-key",+ "X-Roles": "readonly",+}+CONFIGURED_COOKIES = {"session": "configured-session"}++UNDECLARED_ARGUMENTS = [+ pytest.param({"Authorization__header": "Bearer other"}, id="authorization-header"),+ pytest.param({"X-Roles__header": "admin"}, id="custom-header"),+ pytest.param({"Host__header": "other.invalid"}, id="host-header"),+ pytest.param({"session__cookie": "other-session"}, id="cookie"),+ pytest.param({"include_private__query": "true"}, id="query"),+ pytest.param({"extra": {"nested": "value"}}, id="body"),+ pytest.param({"X-Api-Key__header": "other-key"}, id="configured-api-key"),+ pytest.param({"note__header": "hello"}, id="note-header"),+ pytest.param({"theme__cookie": "dark"}, id="theme-cookie"),+ pytest.param({"extra__query": "true"}, id="extra-query"),+ pytest.param({"debug": True}, id="debug-body"),+]+++def _spec(path: str, method: str, operation: dict[str, Any]) -> dict[str, Any]:+ return {+ "openapi": "3.1.0",+ "info": {"title": "Test API", "version": "1.0"},+ "paths": {+ path: {+ method: {+ "operationId": "operation",+ "responses": {"200": {"description": "OK"}},+ **operation,+ }+ }+ },+ }+++def _upstream_client(requests: list[httpx2.Request]) -> httpx2.AsyncClient:+ def capture(request: httpx2.Request) -> httpx2.Response:+ requests.append(request)+ return httpx2.Response(200, json={"ok": True})++ return httpx2.AsyncClient(+ base_url=BASE_URL,+ headers=CONFIGURED_HEADERS,+ cookies=CONFIGURED_COOKIES,+ transport=httpx2.MockTransport(capture),+ )+++async def _call_tool(+ spec: dict[str, Any], arguments: dict[str, Any]+) -> list[httpx2.Request]:+ requests: list[httpx2.Request] = []+ async with _upstream_client(requests) as http_client:+ server = FastMCP.from_openapi(openapi_spec=spec, client=http_client)+ async with Client(server) as client:+ await client.call_tool("operation", arguments)+ return requests+++def _assert_sent_as_configured(request: httpx2.Request) -> None:+ assert request.headers["Authorization"] == "Bearer configured"+ assert request.headers["X-Api-Key"] == "configured-key"+ assert request.headers["X-Roles"] == "readonly"+ assert request.headers["Host"] == "api.example.com"+ assert request.headers["Cookie"] == "session=configured-session"+ assert "note" not in request.headers++[email protected]("method", ["get", "post"])[email protected]("arguments", UNDECLARED_ARGUMENTS)+async def test_undeclared_arguments_are_ignored(+ method: str, arguments: dict[str, Any]+) -> None:+ spec = _spec("/health", method, {})++ [request] = await _call_tool(spec, arguments)++ _assert_sent_as_configured(request)+ assert str(request.url) == f"{BASE_URL}/health"+ assert request.content == b""+++async def test_undeclared_arguments_are_ignored_after_schema_precalculation_fails(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail(*args: Any, **kwargs: Any) -> Any:+ raise ValueError("schema pre-calculation failed")++ monkeypatch.setattr(parser, "_combine_schemas_and_map_params", fail)+ limit = {"name": "limit", "in": "query", "schema": {"type": "integer"}}+ spec = _spec("/items", "get", {"parameters": [limit]})++ [request] = await _call_tool(+ spec,+ {+ "limit": 5,+ "Authorization__header": "Bearer other",+ "note__header": "hello",+ "debug": True,+ },+ )++ _assert_sent_as_configured(request)+ assert dict(request.url.params) == {"limit": "5"}+ assert request.content == b""+++async def test_tool_call_fails_when_parameter_map_cannot_be_built(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail(*args: Any, **kwargs: Any) -> Any:+ raise ValueError("schema pre-calculation failed")++ monkeypatch.setattr(parser, "_combine_schemas_and_map_params", fail)+ monkeypatch.setattr(director, "_combine_schemas_and_map_params", fail)+ limit = {"name": "limit", "in": "query", "schema": {"type": "integer"}}+ spec = _spec("/items", "get", {"parameters": [limit]})++ requests: list[httpx2.Request] = []+ async with _upstream_client(requests) as http_client:+ server = FastMCP.from_openapi(openapi_spec=spec, client=http_client)+ async with Client(server) as client:+ with pytest.raises(ToolError, match="schema pre-calculation failed"):+ await client.call_tool(+ "operation", {"limit": 5, "Authorization__header": "Bearer other"}+ )++ assert requests == []+++ "schema",+ [+ pytest.param({"type": "object"}, id="default-additional-properties"),+ pytest.param(+ {"type": "object", "additionalProperties": True},+ id="additional-properties",+ ),+ ],+)+async def test_whole_body_is_sent_unchanged(+ schema: dict[str, Any],+) -> None:+ body_schema = {"$ref": "#/components/schemas/Thing"}+ request_body = {+ "required": True,+ "content": {"application/json": {"schema": body_schema}},+ }+ spec = _spec("/things", "post", {"requestBody": request_body})+ spec["components"] = {"schemas": {"Thing": schema}}+ body = {+ "Authorization__header": "body data",+ "note__header": "body data",+ "debug": True,+ }++ [request] = await _call_tool(+ spec,+ {+ "body": body,+ "Authorization__header": "Bearer other",+ "note__header": "hello",+ },+ )++ _assert_sent_as_configured(request)+ assert json.loads(request.content) == body+++ "component",+ ["tool", "resource", "resource_template"],+)+async def test_configured_headers_keep_their_values(+ component: str,+) -> None:+ ok = {"200": {"description": "OK"}}+ item_id = {"name": "item_id", "in": "path", "required": True, "schema": {}}+ spec = {+ "openapi": "3.1.0",+ "info": {"title": "Test API", "version": "1.0"},+ "paths": {+ "/actions": {"post": {"operationId": "act", "responses": ok}},+ "/status": {"get": {"operationId": "status", "responses": ok}},+ "/items/{item_id}": {+ "get": {"operationId": "item", "parameters": [item_id], "responses": ok}+ },+ },+ }+ route_maps = [+ RouteMap(pattern=r"\{", mcp_type=MCPType.RESOURCE_TEMPLATE),+ RouteMap(methods=["GET"], mcp_type=MCPType.RESOURCE),+ ]+ requests: list[httpx2.Request] = []++ async with _upstream_client(requests) as http_client:+ server = FastMCP.from_openapi(+ openapi_spec=spec, client=http_client, route_maps=route_maps+ )+ async with run_server_async(server) as url:+ transport = StreamableHttpTransport(+ url, headers={"X-Api-Key": "client-key", "X-Client-Tag": "forwarded"}+ )+ async with Client(transport) as client:+ if component == "tool":+ await client.call_tool("act", {})+ elif component == "resource":+ await client.read_resource("resource://status")+ else:+ await client.read_resource("resource://item/7")++ [request] = requests+ _assert_sent_as_configured(request)+ assert request.headers["X-Client-Tag"] == "forwarded"+++def test_manual_route_uses_canonical_parameter_names() -> None:+ route = HTTPRoute(+ path="/things/{id}",+ method="GET",+ parameters=[+ ParameterInfo(+ name="id", location="path", required=True, schema={"type": "string"}+ ),+ ParameterInfo(name="id", location="query", schema={"type": "string"}),+ ParameterInfo(name="id", location="header", schema={"type": "string"}),+ ],+ )+ request_director = RequestDirector(SchemaPath.from_dict({}))++ request = request_director.build(+ route,+ {+ "id__path": "path-value",+ "id__query": "query-value",+ "id__header": "header-value",+ "Authorization__header": "Bearer other",+ "note__header": "hello",+ "debug": True,+ },+ BASE_URL,+ )++ assert request.url.path == "/things/path-value"+ assert dict(request.url.params) == {"id": "query-value"}+ assert request.headers["id"] == "header-value"+ assert "Authorization" not in request.headers+ assert "note" not in request.headers+ assert request.content == b""+++def test_manual_route_accepts_location_suffix_for_declared_parameter() -> None:+ route = HTTPRoute(+ path="/users/{id}",+ method="GET",+ parameters=[+ ParameterInfo(+ name="id", location="path", required=True, schema={"type": "integer"}+ )+ ],+ )+ request_director = RequestDirector(SchemaPath.from_dict({}))++ request = request_director.build(+ route,+ {+ "id__path": 123,+ "id__header": "header-value",+ "id__query": "query-value",+ "Authorization__header": "Bearer other",+ },+ BASE_URL,+ )++ assert str(request.url) == f"{BASE_URL}/users/123"+ assert "id" not in request.headers+ assert "Authorization" not in request.headers+ assert request.content == b""+++def test_manual_route_with_allof_body_sends_declared_properties() -> None:+ content_schema = {+ "application/json": {"allOf": [{"$ref": "#/components/schemas/Thing"}]}+ }+ route = HTTPRoute(+ path="/things",+ method="POST",+ request_body=RequestBodyInfo(content_schema=content_schema),+ request_schemas={+ "Thing": {"type": "object", "properties": {"name": {"type": "string"}}}+ },+ )+ request_director = RequestDirector(SchemaPath.from_dict({}))++ request = request_director.build(+ route,+ {+ "name": "thing",+ "Authorization__header": "Bearer other",+ "note__header": "hello",+ },+ BASE_URL,+ )++ assert json.loads(request.content) == {"name": "thing"}+ assert "Authorization" not in request.headers+ assert "note" not in request.headers+ assert route.request_body is not None+ assert route.request_body.content_schema == {+ "application/json": {"allOf": [{"$ref": "#/components/schemas/Thing"}]}+ }