Skip to content
Open
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
16 changes: 13 additions & 3 deletions src/mcp/server/fastmcp/resources/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,8 @@ def from_function(

def matches(self, uri: str) -> dict[str, Any] | None:
"""Check if URI matches template and extract parameters."""
# Convert template to regex pattern
pattern = self.uri_template.replace("{", "(?P<").replace("}", ">[^/]+)")
match = re.match(f"^{pattern}$", uri)
# Use precompiled regex pattern for much faster matching.
match = self._compiled_uri_re.match(uri)
if match:
return match.groupdict()
return None
Expand All @@ -83,3 +82,14 @@ async def create_resource(self, uri: str, params: dict[str, Any]) -> Resource:
)
except Exception as e:
raise ValueError(f"Error creating resource from template: {e}")

def __init__(self, **data: Any):
super().__init__(**data)
# Precompile the regex pattern only once per instance.
self._compiled_uri_re = self._build_uri_regex(self.uri_template)

@staticmethod
def _build_uri_regex(uri_template: str) -> re.Pattern:
# Replace {param} with named groups in regex.
pattern = re.sub(r"\{(\w+)\}", r"(?P<\1>[^/]+)", uri_template)
return re.compile(f"^{pattern}$")