π The fast, Pythonic way to build MCP servers and clients.
Fix resource templates with multiple query expressions (#6061)
xiong-wei1d1849a301f02
diff --git a/fastmcp_slim/fastmcp/resources/template.py b/fastmcp_slim/fastmcp/resources/template.pyindex f836996b8..af1bbc631 100644--- a/fastmcp_slim/fastmcp/resources/template.py+++ b/fastmcp_slim/fastmcp/resources/template.py@@ -42,15 +42,17 @@ from fastmcp.utilities.types import get_cached_typeadapterdef extract_query_params(uri_template: str) -> set[str]:- """Extract query parameter names from RFC 6570 `{?param1,param2}` syntax.+ """Extract query parameter names from RFC 6570 query expressions.+ Both the `{?param1,param2}` form and the `{¶m}` continuation form+ contribute names, and a template may carry several query expressions.The explode modifier is stripped, so `{?tags*}` yields `{"tags"}`. Use`extract_exploded_query_params` to find which names carried it."""- match = re.search(r"\{\?([^}]+)\}", uri_template)- if match:- return {p.strip().removesuffix("*") for p in match.group(1).split(",")}- return set()+ names: set[str] = set()+ for match in re.finditer(r"\{[?&]([^}]+)\}", uri_template):+ names.update(p.strip().removesuffix("*") for p in match.group(1).split(","))+ return namesdef _is_list_only(annotation: Any) -> bool:@@ -95,11 +97,11 @@ def extract_exploded_query_params(uri_template: str) -> set[str]:`{?tags*}` marks `tags` as repeatable β `?tags=a&tags=b` collects into alist rather than collapsing to the first value."""- match = re.search(r"\{\?([^}]+)\}", uri_template)- if match:+ exploded: set[str] = set()+ for match in re.finditer(r"\{[?&]([^}]+)\}", uri_template):names = [p.strip() for p in match.group(1).split(",")]- return {n.removesuffix("*") for n in names if n.endswith("*")}- return set()+ exploded.update(n.removesuffix("*") for n in names if n.endswith("*"))+ return explodeddef _has_literal_query(uri_template: str) -> bool:@@ -191,7 +193,7 @@ def build_regex(template: str) -> re.Pattern[str] | None:Supports:- `{var}` - simple path parameter- `{var*}` - wildcard path parameter (captures multiple segments)- - `{?var1,var2}` - query parameters (ignored in path matching)+ - `{?var1,var2}` / `{&var}` - query parameters (ignored in path matching)- `?key={var}` - a query written out literally; `{var}` is that key's valueParameter names are normalized to valid Python identifiers through@@ -202,7 +204,7 @@ def build_regex(template: str) -> re.Pattern[str] | None:parameter names that normalize to the same group)."""# Remove query parameter syntax for path matching- template_without_query = re.sub(r"\{\?[^}]+\}", "", template)+ template_without_query = re.sub(r"\{[?&][^}]+\}", "", template)parts = re.split(r"(\{[^}]+\})", template_without_query)pattern = ""@@ -240,7 +242,8 @@ def match_uri_template(Supports RFC 6570 URI templates:- Path params: `{var}`, `{var*}`- - Query params: `{?var1,var2}`, `{?list*}` (repeated keys)+ - Query params: `{?var1,var2}`, `{&var}`, `{?list*}` (repeated keys);+ several query expressions in one template are all read`list_params` names non-exploded query params that hold lists. Per RFC 6570section 3.2.8 their value is comma-joined, with literal commas separating@@ -314,7 +317,7 @@ def expand_uri_template(uri_template: str, params: dict[str, Any]) -> str:Supports the same RFC 6570 subset:- Path params: `{var}`, `{var*}`- - Query params: `{?var1,var2}`+ - Query params: `{?var1,var2}`, `{&var}` (multiple blocks allowed)"""# Literal runs carry their own encoding (RFC 6570 3.1); placeholders are# left alone here and encoded with their substituted values below.@@ -347,8 +350,16 @@ def expand_uri_template(uri_template: str, params: dict[str, Any]) -> str:result = re.sub(r"\{([^?}][^}]*)\}", substitute, result)- # Expand {?param1,param2,...} query parameter blocks+ # Expand {?param1,param2,...} and {¶m,...} query blocks. The first+ # block that emits parameters opens the query string with "?", and later+ # blocks continue it with "&": emitting "?" for every block would bury+ # the later parameters inside the first parameter's value.+ first_block = re.search(r"\{[?&]", result)+ prefix = result[: first_block.start()] if first_block else result+ query_started = "?" in prefix+def _expand_query_block(match: re.Match[str]) -> str:+ nonlocal query_startednames = [n.strip() for n in match.group(1).split(",")]parts = []for name in names:@@ -380,10 +391,12 @@ def expand_uri_template(uri_template: str, params: dict[str, Any]) -> str:else:parts.append(f"{quote(name, safe='')}={quote(str(value), safe='')}")if parts:- return "?" + "&".join(parts)+ separator = "&" if query_started else "?"+ query_started = True+ return separator + "&".join(parts)return ""- result = re.sub(r"\{\?([^}]+)\}", _expand_query_block, result)+ result = re.sub(r"\{[?&]([^}]+)\}", _expand_query_block, result)return result@@ -397,7 +410,7 @@ def forward_uri(uri_template: str, params: dict[str, Any], uri: str) -> str:`{?name}` params hold comma-joined lists, so `?tags=a%2Cb,c` would arrive asone item instead of two."""- path_template = re.sub(r"\{\?[^}]+\}", "", uri_template)+ path_template = re.sub(r"\{[?&][^}]+\}", "", uri_template)forwarded = expand_uri_template(path_template, params)if _has_literal_query(uri_template):# The query is literal template text, so the expansion already has it.diff --git a/tests/resources/test_resource_template_query_params.py b/tests/resources/test_resource_template_query_params.pyindex 9d7f86b57..198b7511c 100644--- a/tests/resources/test_resource_template_query_params.py+++ b/tests/resources/test_resource_template_query_params.py@@ -408,3 +408,81 @@ class TestResourceTemplateFieldDefaults:assert result2["limit"] == 50 # overriddenassert result2["offset"] == 0 # defaultassert result2["format"] == "xml" # overridden+++class TestMultipleQueryExpressions:+ """Templates with more than one query expression (`{?a}{?b}`, `{?a}{&b}`).++ RFC 6570 allows several query expressions in one template. Every block's+ parameters must be extracted on a match, and expansion must join the+ blocks into a single query string.+ """++ async def test_second_query_block_params_are_matched(self):+ def get_data(id: str, x: str = "dx", y: str = "dy") -> str:+ return f"{id}/{x}/{y}"++ template = ResourceTemplate.from_function(+ fn=get_data,+ uri_template="data://{id}{?x}{?y}",+ name="test",+ )++ params = template.matches("data://7?x=1&y=2")+ assert params == {"id": "7", "x": "1", "y": "2"}++ async def test_query_continuation_block_matches(self):+ def get_data(id: str, x: str = "dx", y: str = "dy") -> str:+ return f"{id}/{x}/{y}"++ template = ResourceTemplate.from_function(+ fn=get_data,+ uri_template="data://{id}{?x}{&y}",+ name="test",+ )++ params = template.matches("data://7?x=1&y=2")+ assert params == {"id": "7", "x": "1", "y": "2"}++ resource = await template.create_resource("data://7?x=1&y=2", params)+ assert await resource.read() == "7/1/2"++ async def test_exploded_param_in_second_block(self):+ def get_data(id: str, x: str = "dx", tags: list[str] | None = None) -> str:+ return ",".join(tags or [])++ template = ResourceTemplate.from_function(+ fn=get_data,+ uri_template="data://{id}{?x}{&tags*}",+ name="test",+ )++ params = template.matches("data://7?x=1&tags=a&tags=b")+ assert params == {"id": "7", "x": "1", "tags": ["a", "b"]}++ def test_expand_joins_blocks_into_one_query_string(self):+ from fastmcp.resources.template import expand_uri_template++ assert (+ expand_uri_template("data://{id}{?x}{?y}", {"id": 1, "x": "1", "y": "2"})+ == "data://1?x=1&y=2"+ )+ assert (+ expand_uri_template("data://{id}{?x}{&y}", {"id": 1, "x": "1", "y": "2"})+ == "data://1?x=1&y=2"+ )++ def test_expand_match_round_trip_across_blocks(self):+ from fastmcp.resources.template import (+ expand_uri_template,+ match_uri_template,+ )++ uri = expand_uri_template(+ "data://{id}{?x}{?y}", {"id": 1, "x": "a b", "y": "2"}+ )+ assert match_uri_template(uri, "data://{id}{?x}{?y}") == {+ "id": "1",+ "x": "a b",+ "y": "2",+ }