🚀 The fast, Pythonic way to build MCP servers and clients.
resources: accept non-exploded list query params as comma-joined values (#5218)
nate nowackc68bed0ab29b
diff --git a/fastmcp_slim/fastmcp/resources/template.py b/fastmcp_slim/fastmcp/resources/template.pyindex 21116a456..693c1094b 100644--- a/fastmcp_slim/fastmcp/resources/template.py+++ b/fastmcp_slim/fastmcp/resources/template.py@@ -5,15 +5,16 @@ from __future__ import annotationsimport functoolsimport inspectimport re-from collections.abc import Callable+from collections.abc import Callable, Collectionfrom types import UnionTypefrom typing import Annotated, Any, ClassVar, Union, get_args, get_origin-from urllib.parse import parse_qs, quote, unquote+from urllib.parse import parse_qs, quote, unquote, unquote_plusfrom mcp_types import Annotations, Iconfrom mcp_types import ResourceTemplate as SDKResourceTemplatefrom pydantic import (Field,+ PrivateAttr,field_validator,validate_call,)@@ -48,7 +49,7 @@ def extract_query_params(uri_template: str) -> set[str]:return set()-def _requires_exploded_query(annotation: Any) -> bool:+def _is_list_only(annotation: Any) -> bool:"""Whether an annotation accepts only lists, optionally wrapped or nullable."""if annotation is list:return True@@ -56,10 +57,10 @@ def _requires_exploded_query(annotation: Any) -> bool:if origin is list:return Trueif origin is Annotated:- return _requires_exploded_query(get_args(annotation)[0])+ return _is_list_only(get_args(annotation)[0])if origin in (Union, UnionType):members = [arg for arg in get_args(annotation) if arg is not type(None)]- return bool(members) and all(_requires_exploded_query(arg) for arg in members)+ return bool(members) and all(_is_list_only(arg) for arg in members)return False@@ -192,12 +193,18 @@ def build_regex(template: str) -> re.Pattern[str] | None:return None-def match_uri_template(uri: str, uri_template: str) -> dict[str, Any] | None:+def match_uri_template(+ uri: str, uri_template: str, *, list_params: Collection[str] = ()+) -> dict[str, Any] | None:"""Match URI against template and extract both path and query parameters.Supports RFC 6570 URI templates:- Path params: `{var}`, `{var*}`- - Query params: `{?var1,var2}`+ - Query params: `{?var1,var2}`, `{?list*}` (repeated keys)++ `list_params` names non-exploded query params that hold lists. Per RFC 6570+ section 3.2.8 their value is comma-joined, with literal commas separating+ items and `%2C` inside an item, so they are split before decoding."""# Split URI into path and query partsuri_path, _, query_string = uri.partition("?")@@ -220,6 +227,10 @@ def match_uri_template(uri: str, uri_template: str) -> dict[str, Any] | None:parsed_query = parse_qs(query_string, keep_blank_values=True)exploded = extract_exploded_query_params(uri_template)+ raw_query: dict[str, str] = {}+ for pair in query_string.split("&"):+ raw_name, _, raw_value = pair.partition("=")+ raw_query.setdefault(unquote_plus(raw_name), raw_value)for name in query_param_names:if name in parsed_query:@@ -227,13 +238,20 @@ def match_uri_template(uri: str, uri_template: str) -> dict[str, Any] | None:# Don't overwrite path params that were already extracted.key = name.replace("-", "_")if key not in params:- # An exploded `{?name*}` param keeps every repetition;+ # An exploded `{?name*}` param keeps every repetition, a+ # list `{?name}` param splits its first value on commas, and# a plain `{?name}` param is a scalar, so take the first.- params[key] = (- parsed_query[name]- if name in exploded- else parsed_query[name][0]- )+ if name in exploded:+ params[key] = parsed_query[name]+ elif name in list_params:+ raw = raw_query.get(name, "")+ params[key] = (+ [unquote_plus(item) for item in raw.split(",")]+ if raw+ else []+ )+ else:+ params[key] = parsed_query[name][0]return params@@ -295,6 +313,10 @@ def expand_uri_template(uri_template: str, params: dict[str, Any]) -> str:parts.extend(f"{quote(name, safe='')}={quote(str(v), safe='')}" for v in value)+ elif isinstance(value, (list, tuple)):+ if value:+ joined = ",".join(quote(str(v), safe="") for v in value)+ parts.append(f"{quote(name, safe='')}={joined}")else:parts.append(f"{quote(name, safe='')}={quote(str(value), safe='')}")if parts:@@ -306,11 +328,29 @@ def expand_uri_template(uri_template: str, params: dict[str, Any]) -> str:return result+def forward_uri(uri_template: str, params: dict[str, Any], uri: str) -> str:+ """Build the URI a forwarding layer (mount or proxy) sends to the server behind it.++ The path is expanded from `uri_template` with `params`, but the query string+ is carried over from the incoming `uri` byte for byte. Re-expanding it would+ decode and re-encode values, and the forwarding layer does not know which+ `{?name}` params hold comma-joined lists, so `?tags=a%2Cb,c` would arrive as+ one item instead of two.+ """+ path_template = re.sub(r"\{\?[^}]+\}", "", uri_template)+ forwarded = expand_uri_template(path_template, params)+ _, _, query = uri.partition("?")+ return f"{forwarded}?{query}" if query else forwarded++class ResourceTemplate(FastMCPComponent):"""A template for dynamically creating resources."""KEY_PREFIX: ClassVar[str] = "template"+ # Non-exploded `{?name}` query params whose function parameter is a list.+ _list_query_params: frozenset[str] = PrivateAttr(default_factory=frozenset)+uri_template: str = Field(description="URI template with parameters (e.g. weather://{city}/current)")@@ -397,7 +437,9 @@ class ResourceTemplate(FastMCPComponent):def matches(self, uri: str) -> dict[str, Any] | None:"""Check if URI matches template and extract parameters."""- return match_uri_template(uri, self.uri_template)+ return match_uri_template(+ uri, self.uri_template, list_params=self._list_query_params+ )async def read(self, arguments: dict[str, Any]) -> str | bytes | ResourceResult:"""Read the resource content."""@@ -649,6 +691,7 @@ class FunctionResourceTemplate(ResourceTemplate):# Validate RFC 6570 query parameters# Query params must be optional (have defaults)+ list_query_params: set[str] = set()if query_params:invalid_query_params = query_params - optional_paramsif invalid_query_params:@@ -656,9 +699,8 @@ class FunctionResourceTemplate(ResourceTemplate):f"Query parameters {invalid_query_params} must be optional function parameters with default values")- # A list-typed query parameter needs the RFC 6570 explode modifier;- # without it the parameter is a scalar and every value but the first- # is silently dropped, which then fails validation at read time.+ # A list-typed query parameter reads `{?tags*}` as repeated keys and+ # `{?tags}` as one comma-joined value (RFC 6570 section 3.2.8).## Resolve the hints rather than reading the raw signature: under# `from __future__ import annotations` every annotation is a string,@@ -694,12 +736,13 @@ class FunctionResourceTemplate(ResourceTemplate):annotation = hints.get(param_name, user_sig.parameters[param_name].annotation)- if _requires_exploded_query(annotation):- raise ValueError(- f"Query parameter '{param_name}' is a list type, so it "- f"must be declared with the RFC 6570 explode modifier: "- f"use '{{?{param_name}*}}' instead of '{{?{param_name}}}' "- f"so repeated values (?{param_name}=a&{param_name}=b) are collected."+ if _is_list_only(annotation):+ list_query_params.add(+ next(+ name+ for name in extract_query_params(uri_template)+ if name.replace("-", "_") == param_name+ ))# Check if required parameters are a subset of the path parameters@@ -741,7 +784,7 @@ class FunctionResourceTemplate(ResourceTemplate):# Apply ui:// MIME default, then fall back to text/plainresolved_mime = resolve_ui_mime_type(uri_template, mime_type)- return cls(+ template = cls(uri_template=uri_template,name=func_name,version=str(version) if version is not None else None,@@ -757,3 +800,5 @@ class FunctionResourceTemplate(ResourceTemplate):auth=auth,security=security,)+ template._list_query_params = frozenset(list_query_params)+ return templatediff --git a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.pyindex 7cb9d9213..709b8e029 100644--- a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py@@ -18,7 +18,7 @@ from pydantic import AnyUrlfrom fastmcp.prompts.base import Prompt, PromptResultfrom fastmcp.resources.base import Resource, ResourceResult-from fastmcp.resources.template import ResourceTemplate, expand_uri_template+from fastmcp.resources.template import ResourceTemplate, forward_urifrom fastmcp.server.providers.base import Providerfrom fastmcp.server.telemetry import delegate_spanfrom fastmcp.tools.base import Tool, ToolResult@@ -306,8 +306,8 @@ class FastMCPProviderResourceTemplate(ResourceTemplate):We use `_original_uri_template` with `params` to construct the internalURI that the nested server understands."""- # Expand the original template with params to get internal URI- original_uri = expand_uri_template(self._original_uri_template or "", params)+ # Expand the original template's path; forward the query as sent+ original_uri = forward_uri(self._original_uri_template or "", params, uri)return FastMCPProviderResource(server=self._server,original_uri=original_uri,@@ -327,8 +327,8 @@ class FastMCPProviderResourceTemplate(ResourceTemplate):fn_key is already set by the parent server before calling this method."""- # Expand the original template with params to get internal URI- original_uri = expand_uri_template(self._original_uri_template or "", params)+ # Expand the original template's path; forward the query as sent+ original_uri = forward_uri(self._original_uri_template or "", params, uri)# Pass exact version so child reads the correct versionversion = VersionSpec(eq=self.version) if self.version else Nonediff --git a/fastmcp_slim/fastmcp/server/providers/proxy.py b/fastmcp_slim/fastmcp/server/providers/proxy.pyindex ae2a3fa98..23f04a3f7 100644--- a/fastmcp_slim/fastmcp/server/providers/proxy.py+++ b/fastmcp_slim/fastmcp/server/providers/proxy.py@@ -53,7 +53,7 @@ from fastmcp.resources.base import (ResourceContent,ResourceResult,)-from fastmcp.resources.template import expand_uri_template+from fastmcp.resources.template import forward_urifrom fastmcp.server.context import Contextfrom fastmcp.server.dependencies import fastmcp_request_ctx, get_contextfrom fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext@@ -640,11 +640,10 @@ class ProxyTemplate(ResourceTemplate):context: Context | None = None,) -> ProxyResource:"""Create a resource from the template by calling the remote server."""- # don't use the provided uri, because it may not be the same as the- # uri_template on the remote server. expand_uri_template percent-encodes- # path and query values so the backend URI round-trips correctly.+ # The path comes from the backend's own template, because the local+ # uri_template may differ; the query is forwarded exactly as sent.backend_template = self._backend_uri_template or self.uri_template- parameterized_uri = expand_uri_template(backend_template, params)+ parameterized_uri = forward_uri(backend_template, params, uri)client = await self._get_client()ctx = context or get_context()async with client:diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.pyindex d3ff596ac..f32b181a9 100644--- a/tests/resources/test_resource_template.py+++ b/tests/resources/test_resource_template.py@@ -14,6 +14,7 @@ from fastmcp.resources.template import (expand_uri_template,match_uri_template,)+from fastmcp.server import create_proxyclass TestResourceTemplate:@@ -907,18 +908,22 @@ class TestMalformedURITemplates:"tags": ["a", "b"],}- def test_from_function_rejects_collection_query_param_without_explode(self):- """Regression for #4378: `{?tags}` on a list param silently dropped every- value but the first, then failed validation at read time. Reject it up- front and point at the explode form."""+ async def test_list_query_param_without_explode_is_comma_separated(self):+ """RFC 6570 3.2.8: `{?tags}` on a list is `?tags=a,b`, one comma-joined value.++ 4.0.5 registered this shape, so rejecting it breaks servers at startup.+ """def search(category: str, tags: list[str] | None = None) -> dict:return {"category": category, "tags": tags}- with pytest.raises(ValueError, match="explode modifier"):- ResourceTemplate.from_function(- fn=search, uri_template="items://{category}{?tags}"- )+ template = ResourceTemplate.from_function(+ fn=search, uri_template="items://{category}{?tags}"+ )++ params = template.matches("items://books?tags=a,b")+ assert params == {"category": "books", "tags": ["a", "b"]}+ assert await template.read(params) == {"category": "books", "tags": ["a", "b"]}@pytest.fixturedef postponed_search(self):@@ -936,17 +941,16 @@ class TestMalformedURITemplates:)return namespace["search"]- def test_postponed_annotations_still_require_explode(self, postponed_search):- """Regression: a string annotation must not slip past the explode check.-- Under `from __future__ import annotations` the raw signature gives the- string `"list[str] | None"`, so the check has to resolve hints or the- template registers and fails later at read time instead.- """- with pytest.raises(ValueError, match="explode modifier"):- ResourceTemplate.from_function(- fn=postponed_search, uri_template="items://{category}{?tags}"- )+ def test_postponed_annotations_still_split_commas(self, postponed_search):+ """Under `from __future__ import annotations` the raw signature gives the+ string `"list[str] | None"`, so hints must be resolved to see the list."""+ template = ResourceTemplate.from_function(+ fn=postponed_search, uri_template="items://{category}{?tags}"+ )+ assert template.matches("items://books?tags=a,b") == {+ "category": "books",+ "tags": ["a", "b"],+ }async def test_postponed_annotations_accept_explode(self, postponed_search):"""The explode form registers and collects one or many values."""@@ -966,8 +970,8 @@ class TestMalformedURITemplates:assert many == {"category": "books", "tags": ["a", "b"]}assert await template.read(many) == {"category": "books", "tags": ["a", "b"]}- def test_annotated_list_query_param_requires_explode(self):- """`Annotated[...]` must be unwrapped before the collection check."""+ def test_annotated_list_query_param_splits_commas(self):+ """`Annotated[...]` must be unwrapped before the list check."""def search(category: str,@@ -975,10 +979,13 @@ class TestMalformedURITemplates:) -> dict:return {"category": category, "tags": tags}- with pytest.raises(ValueError, match="explode modifier"):- ResourceTemplate.from_function(- fn=search, uri_template="items://{category}{?tags}"- )+ template = ResourceTemplate.from_function(+ fn=search, uri_template="items://{category}{?tags}"+ )+ assert template.matches("items://books?tags=a,b") == {+ "category": "books",+ "tags": ["a", "b"],+ }async def test_union_with_scalar_query_param_does_not_require_explode(self):"""A scalar union branch preserves the existing plain-query contract."""@@ -1183,10 +1190,10 @@ class TestMatchExpandRoundTrip:element, contradicting the scalar contract `{?tags}` documents."""uri = expand_uri_template("test://x{?tags}", {"tags": ["a", "b"]})- assert uri.count("tags=") == 1+ assert uri == "test://x?tags=a,b"- params = match_uri_template(uri, "test://x{?tags}")- assert params is not None+ params = match_uri_template(uri, "test://x{?tags}", list_params={"tags"})+ assert params == {"tags": ["a", "b"]}assert expand_uri_template("test://x{?tags}", params) == uridef test_query_values_encode_reserved_characters(self):@@ -1435,3 +1442,103 @@ class TestLiteralMatchingAcceptsRawAndEncodedForms:)def test_encoded_literal_matches_in_either_hex_case(self, uri: str):assert match_uri_template(uri, "data://docs/naïve/{a}") == {"a": "one"}+++class TestNonExplodedListQueryParams:+ """RFC 6570 3.2.8: a non-exploded `{?name}` list is one comma-joined value.++ Separating commas are literal; a comma inside an item arrives as `%2C`.+ """++ @pytest.mark.parametrize(+ "uri, expected",+ [+ ("items://books?tags=a,b", ["a", "b"]),+ ("items://books?tags=a", ["a"]),+ ("items://books?tags=a%2Cb,c", ["a,b", "c"]),+ ("items://books?tags=caf%C3%A9,x%20y", ["café", "x y"]),+ ("items://books?tags=", []),+ ],+ )+ def test_match_splits_on_literal_commas(self, uri: str, expected: list[str]):+ result = match_uri_template(+ uri, "items://{category}{?tags}", list_params={"tags"}+ )+ assert result == {"category": "books", "tags": expected}++ def test_match_without_list_params_keeps_scalar_values(self):+ """A plain `{?q}` string keeps its commas, as on 4.0.5."""+ assert match_uri_template("items://books?q=a,b", "items://{category}{?q}") == {+ "category": "books",+ "q": "a,b",+ }++ @pytest.mark.parametrize(+ "tags, expected",+ [+ (["a", "b"], "items://books?tags=a,b"),+ (["a,b", "c"], "items://books?tags=a%2Cb,c"),+ ([], "items://books"),+ ],+ )+ def test_expand_joins_list_with_literal_commas(self, tags, expected):+ template = "items://{category}{?tags}"+ uri = expand_uri_template(template, {"category": "books", "tags": tags})+ assert uri == expected+ if tags:+ assert match_uri_template(uri, template, list_params={"tags"}) == {+ "category": "books",+ "tags": tags,+ }++ async def test_read_through_client(self):+ mcp = FastMCP("test")++ @mcp.resource("items://{category}{?tags,ids}")+ def search(+ category: str,+ tags: list[str] = Field(default_factory=list),+ ids: list[int] | None = None,+ ) -> str:+ return f"{category} {tags} {ids}"++ async with Client(mcp) as client:+ reads = {+ "items://books": "books [] None",+ "items://books?tags=a,b": "books ['a', 'b'] None",+ "items://books?tags=a%2Cb&ids=1,2": "books ['a,b'] [1, 2]",+ }+ for uri, expected in reads.items():+ [contents] = await client.read_resource(uri)+ assert isinstance(contents, TextResourceContents)+ assert contents.text == expected++ @pytest.mark.parametrize("layer", ["mounted", "proxy"])+ @pytest.mark.parametrize(+ "query, expected",+ [+ ("?tags=a,b", "['a', 'b']"),+ ("?tags=a%2Cb,c", "['a,b', 'c']"),+ ("", "[]"),+ ],+ )+ async def test_list_survives_mounts_and_proxies(self, layer, query, expected):+ """Forwarding layers must pass the query through, not decode and re-encode it."""+ child = FastMCP("child")++ @child.resource("items://{category}{?tags}")+ def search(category: str, tags: list[str] = Field(default_factory=list)) -> str:+ return str(tags)++ if layer == "mounted":+ server = FastMCP("parent")+ server.mount(child, namespace="ns")+ uri = f"items://ns/books{query}"+ else:+ server = create_proxy(child)+ uri = f"items://books{query}"++ async with Client(server) as client:+ [contents] = await client.read_resource(uri)+ assert isinstance(contents, TextResourceContents)+ assert contents.text == expected