Skip to content

🚀 The fast, Pythonic way to build MCP servers and clients.

fix(resources): percent-encode URI template literals (RFC 6570 §3.1) (#5167)

Leogrox83e4bd3365a0
diff --git a/fastmcp_slim/fastmcp/resources/template.py b/fastmcp_slim/fastmcp/resources/template.py
index 866eb940a..ea08bc9e2 100644
--- a/fastmcp_slim/fastmcp/resources/template.py
+++ b/fastmcp_slim/fastmcp/resources/template.py
@@ -43,6 +43,34 @@ def extract_query_params(uri_template: str) -> set[str]:
return set()
+# RFC 3986 reserved characters, which stay as written in a template literal.
+_RESERVED = ":/?#[]@!$&'()*+,;="
+_PCT_TRIPLET = re.compile(r"%[0-9A-Fa-f]{2}")
+
+
+def encode_literal(text: str) -> str:
+ """Percent-encode literal template text per RFC 6570 section 3.1.
+
+ A template may be written with characters the URI grammar does not allow —
+ a non-ASCII `ucschar` (`file:///docs/café/`) or a space — and section 3.1
+ requires those to be UTF-8 percent-encoded in the expanded URI. Reserved
+ and unreserved characters are structural and stay as written, and existing
+ `%XX` triplets pass through so an already-encoded literal is not encoded
+ twice.
+
+ A resource URI reaches the server as an `AnyUrl`, which percent-encodes it,
+ so the encoded form is what matching has to line up with.
+ """
+ out: list[str] = []
+ last = 0
+ for match in _PCT_TRIPLET.finditer(text):
+ out.append(quote(text[last : match.start()], safe=_RESERVED))
+ out.append(match.group())
+ last = match.end()
+ out.append(quote(text[last:], safe=_RESERVED))
+ return "".join(out)
+
+
def build_regex(template: str) -> re.Pattern[str] | None:
"""Build regex pattern for URI template, handling RFC 6570 syntax.
@@ -73,7 +101,9 @@ def build_regex(template: str) -> re.Pattern[str] | None:
group = name.replace("-", "_")
pattern += f"(?P<{group}>[^/]+)"
else:
- pattern += re.escape(part)
+ # Encoded so the pattern lines up with the URI that actually
+ # arrives, and with what expand_uri_template emits (RFC 6570 3.1).
+ pattern += re.escape(encode_literal(part))
try:
return re.compile(f"^{pattern}$")
except re.error:
@@ -126,7 +156,12 @@ def expand_uri_template(uri_template: str, params: dict[str, Any]) -> str:
- Path params: `{var}`, `{var*}`
- Query params: `{?var1,var2}`
"""
- result = uri_template
+ # Literal runs carry their own encoding (RFC 6570 3.1); placeholders are
+ # left alone here and encoded with their substituted values below.
+ result = "".join(
+ part if part.startswith("{") and part.endswith("}") else encode_literal(part)
+ for part in re.split(r"(\{[^}]+\})", uri_template)
+ )
# Replace {name} and {name*} path placeholders, percent-encoding the
# substituted values so the result round-trips through match_uri_template
diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.py
index 58960c4b7..0a44f2071 100644
--- a/tests/resources/test_resource_template.py
+++ b/tests/resources/test_resource_template.py
@@ -1140,3 +1140,54 @@ class TestInternalMetaNotLeaked:
result = await client.read_resource("data://tagged/1")
assert result[0].meta == {"team": "infra"}
+
+
+class TestLiteralEncoding:
+ """RFC 6570 section 3.1: literal template text is percent-encoded."""
+
+ @pytest.mark.parametrize(
+ "uri_template, expected",
+ [
+ # A literal the URI grammar does not allow is UTF-8 percent-encoded.
+ ("file:///docs/café/{name}", "file:///docs/caf%C3%A9/a.txt"),
+ ("file:///my docs/{name}", "file:///my%20docs/a.txt"),
+ # Reserved and unreserved characters are structural, so they stay.
+ ("file:///a-b_c~d.e/{name}", "file:///a-b_c~d.e/a.txt"),
+ # An already-encoded literal is not encoded twice.
+ ("file:///docs/caf%C3%A9/{name}", "file:///docs/caf%C3%A9/a.txt"),
+ ],
+ )
+ def test_expand_encodes_literals(self, uri_template: str, expected: str):
+ assert expand_uri_template(uri_template, {"name": "a.txt"}) == expected
+
+ @pytest.mark.parametrize(
+ "uri_template, uri",
+ [
+ ("file:///docs/café/{name}", "file:///docs/caf%C3%A9/a.txt"),
+ ("file:///my docs/{name}", "file:///my%20docs/a.txt"),
+ ],
+ )
+ def test_match_accepts_the_encoded_form(self, uri_template: str, uri: str):
+ """An AnyUrl percent-encodes the URI, so that is the form matching sees."""
+ assert match_uri_template(uri, uri_template) == {"name": "a.txt"}
+
+ def test_expand_match_roundtrip(self):
+ uri_template = "file:///docs/café/{name}"
+ expanded = expand_uri_template(uri_template, {"name": "a.txt"})
+ assert match_uri_template(expanded, uri_template) == {"name": "a.txt"}
+
+ async def test_template_with_non_ascii_literal_is_readable(self):
+ """Regression: the template was listed but every read returned Not Found."""
+ mcp = FastMCP("test")
+
+ @mcp.resource("file:///docs/café/{name}")
+ def doc(name: str) -> str:
+ return f"contents of {name}"
+
+ async with Client(mcp) as client:
+ templates = await client.list_resource_templates()
+ assert templates[0].uri_template == "file:///docs/café/{name}"
+
+ result = await client.read_resource("file:///docs/caf%C3%A9/a.txt")
+
+ assert result[0].text == "contents of a.txt" # type: ignore[union-attr]