Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Match resource templates that spell out a literal query (#6248)

nate nowacka5634e3b6b66
diff --git a/docs/servers/resources.mdx b/docs/servers/resources.mdx
index 06e046dce..a03b137ec 100644
--- a/docs/servers/resources.mdx
+++ b/docs/servers/resources.mdx
@@ -702,6 +702,23 @@ A single value still arrives as a one-element list, so the parameter's type is s
A URI fragment (`#section`) is not part of the resource identity. FastMCP drops it before matching, so `data://42?format=json#top` yields `id="42"` and `format="json"`. A template that contains a literal `#` is matched against the full URI, fragment included.
+**Required query parameters:**
+
+A `{?param}` block is always optional. When a resource cannot be read without a query value, write the query into the template as literal text and put a regular placeholder where the value goes. The placeholder then behaves like a path parameter: it maps to a required function parameter, and a URI without that key does not match the template.
+
+```python
+from fastmcp import FastMCP
+
+mcp = FastMCP(name="SearchServer")
+
[email protected]("search://items?q={q}")
+def search_items(q: str) -> str:
+ """Search items by a required query."""
+ return f"Results for {q}"
+```
+
+Reading `search://items?q=shoes` calls `search_items("shoes")`. The value runs up to the next `&` and may be empty or contain `/`, so `search://items?q=` passes an empty string. An `&` that belongs to the value must be percent-encoded. Only the keys written in the template are accepted: `search://items?q=shoes&page=2` does not match, so add `&page={page}` to the template when the resource needs a second key. Keys must appear in the order the template writes them. A literal query cannot be combined with a `{?param}` block in the same template.
+
**Query parameters vs. hidden defaults:**
Query parameters expose optional configuration to clients. To hide optional parameters from clients entirely (always use defaults), simply omit them from the URI template:
diff --git a/fastmcp_slim/fastmcp/resources/template.py b/fastmcp_slim/fastmcp/resources/template.py
index 1c8baf467..1b7dfa9c7 100644
--- a/fastmcp_slim/fastmcp/resources/template.py
+++ b/fastmcp_slim/fastmcp/resources/template.py
@@ -102,6 +102,11 @@ def extract_exploded_query_params(uri_template: str) -> set[str]:
return set()
+def _has_literal_query(uri_template: str) -> bool:
+ """Whether the template writes `?` as literal text, outside a `{?...}` block."""
+ return uri_template.count("?") > uri_template.count("{?")
+
+
# RFC 3986 reserved characters, which stay as written in a template literal.
_RESERVED = ":/?#[]@!$&'()*+,;="
_PCT_TRIPLET = re.compile(r"%[0-9A-Fa-f]{2}")
@@ -168,6 +173,7 @@ def build_regex(template: str) -> re.Pattern[str] | None:
- `{var}` - simple path parameter
- `{var*}` - wildcard path parameter (captures multiple segments)
- `{?var1,var2}` - query parameters (ignored in path matching)
+ - `?key={var}` - a query written out literally; `{var}` is that key's value
Hyphens in parameter names are normalized to underscores in regex group
names so that matched groups are valid Python identifiers.
@@ -180,10 +186,16 @@ def build_regex(template: str) -> re.Pattern[str] | None:
parts = re.split(r"(\{[^}]+\})", template_without_query)
pattern = ""
+ # Past a literal `?` a placeholder is a query value: it may be empty, may
+ # hold `/`, and ends at the next `&`.
+ in_query = False
for part in parts:
if part.startswith("{") and part.endswith("}"):
name = part[1:-1]
- if name.endswith("*"):
+ if in_query:
+ group = name.removesuffix("*").replace("-", "_")
+ pattern += f"(?P<{group}>[^&]*)"
+ elif name.endswith("*"):
name = name[:-1]
group = name.replace("-", "_")
pattern += f"(?P<{group}>.+)"
@@ -192,6 +204,7 @@ def build_regex(template: str) -> re.Pattern[str] | None:
pattern += f"(?P<{group}>[^/]+)"
else:
pattern += _literal_pattern(part)
+ in_query = in_query or "?" in part
try:
return re.compile(f"^{pattern}$")
except re.error:
@@ -223,7 +236,12 @@ def match_uri_template(
# matched against the full URI.
if "#" not in uri_template:
uri = uri.partition("#")[0]
- uri_path, _, query_string = uri.partition("?")
+ # Likewise a template that spells out a literal `?` (`search://items?q={q}`)
+ # carries its query in the path pattern, so there is nothing to split off.
+ if _has_literal_query(uri_template):
+ uri_path, query_string = uri, ""
+ else:
+ uri_path, _, query_string = uri.partition("?")
# Match path parameters
if regex is None:
@@ -356,6 +374,9 @@ def forward_uri(uri_template: str, params: dict[str, Any], uri: str) -> str:
"""
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.
+ return forwarded
_, _, query = uri.partition("?")
return f"{forwarded}?{query}" if query else forwarded
diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.py
index 5a2c8c6f2..9cb3bd4ef 100644
--- a/tests/resources/test_resource_template.py
+++ b/tests/resources/test_resource_template.py
@@ -1101,6 +1101,53 @@ class TestMalformedURITemplates:
)
assert result == {"id": "a#b"}
+ def test_literal_query_in_template_still_matches(self):
+ result = match_uri_template(
+ "search://items?q=abc",
+ "search://items?q={q}",
+ )
+ assert result == {"q": "abc"}
+
+ def test_literal_query_in_template_rejects_other_query(self):
+ result = match_uri_template(
+ "search://items?page=abc",
+ "search://items?q={q}",
+ )
+ assert result is None
+
+ def test_literal_query_in_template_round_trips_reserved_value(self):
+ template = "search://items?q={q}"
+ uri = expand_uri_template(template, {"q": "a b&c=d/e"})
+ assert match_uri_template(uri, template) == {"q": "a b&c=d/e"}
+
+ def test_literal_query_in_template_round_trips_empty_value(self):
+ template = "search://items?q={q}"
+ uri = expand_uri_template(template, {"q": ""})
+ assert uri == "search://items?q="
+ assert match_uri_template(uri, template) == {"q": ""}
+
+ def test_literal_query_in_template_rejects_extra_key(self):
+ """A raw `&` starts another key, so it never ends up inside the value."""
+ result = match_uri_template(
+ "search://items?q=abc&page=2",
+ "search://items?q={q}",
+ )
+ assert result is None
+
+ def test_literal_query_in_template_with_two_keys(self):
+ result = match_uri_template(
+ "search://items?q=a/b&page=2",
+ "search://items?q={q}&page={page}",
+ )
+ assert result == {"q": "a/b", "page": "2"}
+
+ def test_literal_query_in_template_wildcard_stops_at_ampersand(self):
+ result = match_uri_template(
+ "search://items?q=abc&page=2",
+ "search://items?q={q*}",
+ )
+ assert result is None
+
def test_query_param_with_blank_and_present_values(self):
"""Mix of blank and non-blank query values are both surfaced."""
result = match_uri_template(
@@ -1801,6 +1848,35 @@ class TestNonExplodedListQueryParams:
assert contents.text == expected
+class TestLiteralQueryInTemplate:
+ """A template may spell its query out literally: `search://items?q={q}`."""
+
+ @pytest.mark.parametrize("via", ["direct", "mount", "proxy"])
+ async def test_template_with_literal_query_is_readable(self, via: str):
+ child = FastMCP("child")
+
+ @child.resource("search://items?q={q}")
+ def search(q: str) -> str:
+ return f"q={q}"
+
+ uri = "search://items?q=abc"
+ if via == "direct":
+ server = child
+ elif via == "mount":
+ server = FastMCP("parent")
+ server.mount(child, namespace="ns")
+ uri = "search://ns/items?q=abc"
+ else:
+ server = create_proxy(child)
+
+ async with Client(server) as client:
+ [template] = await client.list_resource_templates()
+ assert template.uri_template == uri.replace("abc", "{q}")
+ [contents] = await client.read_resource(uri)
+ assert isinstance(contents, TextResourceContents)
+ assert contents.text == "q=abc"
+
+
class TestTemplateComponentMetaPropagation:
"""A template's component meta must reach list[ResourceContent] reads."""