Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/mcp/shared/uri_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ def expand(self, variables: Mapping[str, str | Sequence[str]]) -> str:
out: list[str] = []
for part in self._parts:
if isinstance(part, str):
out.append(part)
out.append(_encode(part, allow_reserved=True))
else:
out.append(_expand_expression(part, variables))
return "".join(out)
Expand Down Expand Up @@ -892,6 +892,7 @@ def _flatten(parts: list[_Part]) -> list[_Atom]:
def push_lit(text: str) -> None:
if not text:
return
text = _encode(text, allow_reserved=True)
if atoms and isinstance(atoms[-1], _Lit):
atoms[-1] = _Lit(atoms[-1].text + text)
else:
Expand Down
10 changes: 10 additions & 0 deletions tests/shared/test_uri_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,11 @@ def test_expand_encodes_special_chars_in_simple():
assert t.expand({"v": "a&b=c"}) == "a%26b%3Dc"


def test_expand_encodes_non_ascii_literal():
t = UriTemplate.parse("file:///docs/café/{name}")
assert t.expand({"name": "a.txt"}) == "file:///docs/caf%C3%A9/a.txt"


def test_expand_preserves_special_chars_in_reserved():
t = UriTemplate.parse("{+v}")
assert t.expand({"v": "a&b=c"}) == "a&b=c"
Expand Down Expand Up @@ -764,6 +769,11 @@ def test_match_decodes_percent_encoding():
assert t.match("file://docs/hello%20world.txt") == {"name": "hello world.txt"}


def test_match_encodes_non_ascii_literal():
t = UriTemplate.parse("file:///docs/café/{name}")
assert t.match("file:///docs/caf%C3%A9/a.txt") == {"name": "a.txt"}


def test_match_escapes_template_literals():
# Regression: previous impl didn't escape . in literals, making it
# a regex wildcard. "fileXtxt" should NOT match "file.txt/{id}".
Expand Down
Loading