Skip to content

Commit 99623be

Browse files
committed
fix: enhance URI matching to support query parameters
1 parent e9bb9c3 commit 99623be

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

mcp-core/src/main/java/io/modelcontextprotocol/util/DefaultMcpUriTemplateManager.java

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,14 +141,34 @@ public boolean matches(String uri) {
141141
return uri.equals(this.uriTemplate);
142142
}
143143

144-
// Convert the pattern to a regex
145-
String regex = this.uriTemplate.replaceAll("\\{[^/]+?\\}", "([^/]+?)");
146-
regex = regex.replace("/", "\\/");
144+
// Convert the URI template into a robust regex pattern that escapes special
145+
// characters like '?'.
146+
StringBuilder patternBuilder = new StringBuilder("^");
147+
Matcher variableMatcher = URI_VARIABLE_PATTERN.matcher(this.uriTemplate);
148+
int lastEnd = 0;
149+
150+
while (variableMatcher.find()) {
151+
// Append the literal part of the template, safely quoted
152+
String textBefore = this.uriTemplate.substring(lastEnd, variableMatcher.start());
153+
patternBuilder.append(Pattern.quote(textBefore));
154+
// Append a capturing group for the variable itself
155+
patternBuilder.append("([^/]+?)");
156+
lastEnd = variableMatcher.end();
157+
}
158+
159+
// Append any remaining literal text after the last variable
160+
if (lastEnd < this.uriTemplate.length()) {
161+
patternBuilder.append(Pattern.quote(this.uriTemplate.substring(lastEnd)));
162+
}
163+
164+
patternBuilder.append("$");
147165

148166
// Check if the URI matches the regex
149-
return Pattern.compile(regex).matcher(uri).matches();
167+
return Pattern.compile(patternBuilder.toString()).matcher(uri).matches();
150168
}
151169

170+
171+
152172
@Override
153173
public boolean isUriTemplate(String uri) {
154174
return URI_VARIABLE_PATTERN.matcher(uri).find();

mcp-core/src/test/java/io/modelcontextprotocol/McpUriTemplateManagerTests.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,12 @@ void shouldMatchUriAgainstTemplatePattern() {
9494
assertFalse(uriTemplateManager.matches("/api/users/123/comments/456"));
9595
}
9696

97+
@Test
98+
void shouldMatchUriWithQueryParameters() {
99+
String templateWithQuery = "file://name/search?={search}";
100+
var uriTemplateManager = this.uriTemplateFactory.create(templateWithQuery);
101+
102+
assertTrue(uriTemplateManager.matches("file://name/search?=abcd"),
103+
"Should correctly match a URI containing query parameters.");
104+
}
97105
}

0 commit comments

Comments
 (0)