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
6 changes: 4 additions & 2 deletions src/mcp/server/mcpserver/resources/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,11 @@

Extracted parameters are URL-decoded to handle percent-encoded characters.
"""
# Convert template to regex pattern
pattern = self.uri_template.replace("{", "(?P<").replace("}", ">[^/]+)")
# Escape the template so literal text matches literally, then turn {param}
# placeholders into capture groups. re.escape may backslash the braces, so
# the placeholder pattern tolerates an optional backslash on each side.
pattern = re.sub(r"\\?\{(\w+)\\?\}", r"(?P<\1>[^/]+)", re.escape(self.uri_template))
match = re.match(f"^{pattern}$", uri)

Check notice on line 100 in src/mcp/server/mcpserver/resources/templates.py

View check run for this annotation

Claude / Claude Code Review

matches() raises re.error for templates with duplicated parameter names

Pre-existing issue (not introduced by this PR): a URI template that repeats a parameter name (e.g. `test://{id}/{id}`) produces a regex with two `(?P<id>...)` groups, so `re.match` raises `re.error: redefinition of group name` instead of `matches()` returning `None` — and since registration only validates the *set* of placeholders, the error surfaces unhandled at `read_resource` time. Since this PR rewrites this exact line, it may be worth either rejecting duplicate placeholders at registration
Comment on lines +99 to 100

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 Pre-existing issue (not introduced by this PR): a URI template that repeats a parameter name (e.g. test://{id}/{id}) produces a regex with two (?P<id>...) groups, so re.match raises re.error: redefinition of group name instead of matches() returning None — and since registration only validates the set of placeholders, the error surfaces unhandled at read_resource time. Since this PR rewrites this exact line, it may be worth either rejecting duplicate placeholders at registration or guarding the re.match call here.

Extended reasoning...

What the bug is. ResourceTemplate.matches converts the URI template into a regex by turning every {param} placeholder into a named capture group (?P<param>[^/]+). Python's re module forbids two groups with the same name in one pattern, so any template that repeats a parameter name — e.g. test://{id}/{id} — produces an invalid pattern, and re.match at templates.py:100 raises re.error('redefinition of group name id ...') instead of matches() returning None.

Why registration doesn't catch it. The @mcp.resource decorator (server.py:686) validates templates by comparing set(re.findall(r"{(\w+)}", uri)) against the function's parameter names. Because the comparison is over sets, a duplicated placeholder collapses to a single entry and passes validation as long as the function has a matching parameter. So @mcp.resource("test://{id}/{id}") over def fn(id: str) registers cleanly.

Where it blows up. ResourceManager.get_resource (resource_manager.py:97-99) iterates all registered templates and calls matches() on each one for every read_resource request. There is no try/except around that call, so a single template with a duplicated placeholder makes read_resource fail with an unhandled re.error — including for URIs that target other, perfectly valid templates — rather than producing a clean "unknown resource" or validation error.

Step-by-step proof.

  1. Register @mcp.resource("test://{id}/{id}") with def fn(id: str) -> str. Registration passes: set(re.findall(...)) == {"id"} == {"id"}.
  2. A client calls read_resource("anything://else") (or any URI). ResourceManager.get_resource loops over templates and calls template.matches(uri) on the broken one.
  3. re.escape("test://{id}/{id}")re.sub(...) yields test://(?P<id>[^/]+)/(?P<id>[^/]+).
  4. re.match(f"^{pattern}$", uri) raises re.error: redefinition of group name 'id' as group 2; was group 1.
  5. The exception propagates out of get_resource and the read_resource request fails with an internal error.

Why this is pre-existing. The previous implementation, self.uri_template.replace("{", "(?P<").replace("}", ">[^/]+)"), generated the exact same duplicate-group pattern, so the behavior is identical before and after this PR. The PR merely rewrites the line where the pattern is built; it neither introduces nor worsens the problem. It also requires a developer to author a template that repeats a parameter name, which is an unusual mistake that fails loudly on first use — so this should not block the PR.

How to fix. Either (a) reject duplicate placeholders at registration time — e.g. in the @resource decorator and ResourceTemplate.from_function, check re.findall(r"{(\w+)}", uri_template) for duplicates and raise a ValueError with a clear message — or (b) defensively wrap the re.match/pattern construction in matches() so an invalid template returns None (or logs and skips) instead of taking down unrelated read_resource calls. Option (a) is preferable since it surfaces the authoring mistake immediately.

if match:
# URL-decode all extracted parameter values
return {key: unquote(value) for key, value in match.groupdict().items()}
Expand Down
20 changes: 20 additions & 0 deletions tests/server/mcpserver/resources/test_resource_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,3 +331,23 @@ def blocking_fn(name: str) -> str:
assert isinstance(resource, FunctionResource)
assert await resource.read() == "hello world"
assert fn_thread[0] != main_thread


def test_matches_treats_template_specials_literally():
def fn(id: str) -> str: # pragma: no cover
return id

template = ResourceTemplate.from_function(fn=fn, uri_template="resource://a.b+c/{id}", name="t")

assert template.matches("resource://a.b+c/42") == {"id": "42"}
assert template.matches("resource://aXbYc/42") is None


def test_matches_does_not_interpret_template_as_regex():
def fn(id: str) -> str: # pragma: no cover
return id

template = ResourceTemplate.from_function(fn=fn, uri_template="resource://(.*)/{id}", name="t")

assert template.matches("resource://(.*)/7") == {"id": "7"}
assert template.matches("resource://anything/7") is None
Loading