Skip to content

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

resources: match template literals whether they arrive raw or percent-encoded (#5216)

nate nowack49064826fa25
diff --git a/fastmcp_slim/fastmcp/resources/template.py b/fastmcp_slim/fastmcp/resources/template.py
index 7919128ac..21116a456 100644
--- a/fastmcp_slim/fastmcp/resources/template.py
+++ b/fastmcp_slim/fastmcp/resources/template.py
@@ -125,6 +125,36 @@ def encode_literal(text: str) -> str:
return "".join(out)
+def _literal_pattern(text: str) -> str:
+ """Regex for a literal run that matches it either as written or percent-encoded.
+
+ `AnyUrl` percent-encodes some characters that section 3.1 requires encoding
+ (non-ASCII, a space in a hierarchical path) but leaves others as written
+ (`|`, `^`, `\\`, a stray `%`, a space in an opaque path), and in-process
+ reads skip `AnyUrl` entirely. Each character that encoding would change
+ therefore matches in both forms, with the hex digits in either case.
+ """
+
+ def chars(run: str) -> str:
+ out = []
+ for ch in run:
+ encoded = quote(ch, safe=_RESERVED)
+ if encoded == ch:
+ out.append(re.escape(ch))
+ else:
+ out.append(f"(?:{re.escape(ch)}|(?i:{re.escape(encoded)}))")
+ return "".join(out)
+
+ pattern: list[str] = []
+ last = 0
+ for match in _PCT_TRIPLET.finditer(text):
+ pattern.append(chars(text[last : match.start()]))
+ pattern.append(f"(?i:{re.escape(match.group())})")
+ last = match.end()
+ pattern.append(chars(text[last:]))
+ return "".join(pattern)
+
+
def build_regex(template: str) -> re.Pattern[str] | None:
"""Build regex pattern for URI template, handling RFC 6570 syntax.
@@ -155,9 +185,7 @@ def build_regex(template: str) -> re.Pattern[str] | None:
group = name.replace("-", "_")
pattern += f"(?P<{group}>[^/]+)"
else:
- # 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))
+ pattern += _literal_pattern(part)
try:
return re.compile(f"^{pattern}$")
except re.error:
diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.py
index f14d761a9..d3ff596ac 100644
--- a/tests/resources/test_resource_template.py
+++ b/tests/resources/test_resource_template.py
@@ -3,6 +3,7 @@ from typing import Annotated
from urllib.parse import quote
import pytest
+from mcp.types import TextResourceContents
from pydantic import BaseModel, Field
from fastmcp import Client, Context, FastMCP
@@ -1395,3 +1396,42 @@ class TestLiteralEncoding:
result = await client.read_resource("file:///docs/caf%C3%A9/a.txt")
assert result[0].text == "contents of a.txt" # type: ignore[union-attr]
+
+
+class TestLiteralMatchingAcceptsRawAndEncodedForms:
+ """AnyUrl leaves some literal characters as written, and in-process reads skip it."""
+
+ @pytest.mark.parametrize(
+ "uri_template, uri",
+ [
+ ("data://pair/{a}|{b}", "data://pair/one|two"),
+ ("data://pct/100%/{a}", "data://pct/100%/one"),
+ ("data://caret/v^{a}", "data://caret/v^one"),
+ ("note:my notes/{a}", "note:my notes/one"),
+ ("data://docs/café/{a}", "data://docs/café/one"),
+ ],
+ )
+ async def test_read_through_client_and_in_process(
+ self, uri_template: str, uri: str
+ ):
+ mcp = FastMCP("test")
+
+ @mcp.resource(uri_template)
+ def read(a: str, b: str = "") -> str:
+ return f"{a}{b}"
+
+ async with Client(mcp) as client:
+ [contents] = await client.read_resource(uri)
+ assert isinstance(contents, TextResourceContents)
+ assert contents.text.startswith("one")
+
+ result = await mcp.read_resource(uri)
+ content = result.contents[0].content
+ assert isinstance(content, str) and content.startswith("one")
+
+ @pytest.mark.parametrize(
+ "uri",
+ ["data://docs/na%C3%AFve/one", "data://docs/na%c3%afve/one"],
+ )
+ def test_encoded_literal_matches_in_either_hex_case(self, uri: str):
+ assert match_uri_template(uri, "data://docs/naïve/{a}") == {"a": "one"}