-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Match URI template literals literally in ResourceTemplate.matches
#2991
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+24
−2
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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, sore.matchraisesre.error: redefinition of group nameinstead ofmatches()returningNone— and since registration only validates the set of placeholders, the error surfaces unhandled atread_resourcetime. Since this PR rewrites this exact line, it may be worth either rejecting duplicate placeholders at registration or guarding there.matchcall here.Extended reasoning...
What the bug is.
ResourceTemplate.matchesconverts the URI template into a regex by turning every{param}placeholder into a named capture group(?P<param>[^/]+). Python'sremodule 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, andre.matchattemplates.py:100raisesre.error('redefinition of group name id ...')instead ofmatches()returningNone.Why registration doesn't catch it. The
@mcp.resourcedecorator (server.py:686) validates templates by comparingset(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}")overdef fn(id: str)registers cleanly.Where it blows up.
ResourceManager.get_resource(resource_manager.py:97-99) iterates all registered templates and callsmatches()on each one for everyread_resourcerequest. There is notry/exceptaround that call, so a single template with a duplicated placeholder makesread_resourcefail with an unhandledre.error— including for URIs that target other, perfectly valid templates — rather than producing a clean "unknown resource" or validation error.Step-by-step proof.
@mcp.resource("test://{id}/{id}")withdef fn(id: str) -> str. Registration passes:set(re.findall(...)) == {"id"} == {"id"}.read_resource("anything://else")(or any URI).ResourceManager.get_resourceloops over templates and callstemplate.matches(uri)on the broken one.re.escape("test://{id}/{id}")→re.sub(...)yieldstest://(?P<id>[^/]+)/(?P<id>[^/]+).re.match(f"^{pattern}$", uri)raisesre.error: redefinition of group name 'id' as group 2; was group 1.get_resourceand theread_resourcerequest 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
@resourcedecorator andResourceTemplate.from_function, checkre.findall(r"{(\w+)}", uri_template)for duplicates and raise aValueErrorwith a clear message — or (b) defensively wrap there.match/pattern construction inmatches()so an invalid template returnsNone(or logs and skips) instead of taking down unrelatedread_resourcecalls. Option (a) is preferable since it surfaces the authoring mistake immediately.