Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

resources: keep each template's compiled pattern on the template (#5253)

nate nowack80bc24ed3383
diff --git a/fastmcp_slim/fastmcp/resources/template.py b/fastmcp_slim/fastmcp/resources/template.py
index 82da65b0b..c76dd7ed8 100644
--- a/fastmcp_slim/fastmcp/resources/template.py
+++ b/fastmcp_slim/fastmcp/resources/template.py
@@ -156,9 +156,7 @@ def _literal_pattern(text: str) -> str:
return "".join(pattern)
-# Unbounded: keys are server-defined templates, and a read walks every template,
-# so a capped cache would evict on every read once a server outgrew it.
[email protected]_cache(maxsize=4096)
def build_regex(template: str) -> re.Pattern[str] | None:
"""Build regex pattern for URI template, handling RFC 6570 syntax.
@@ -197,7 +195,11 @@ def build_regex(template: str) -> re.Pattern[str] | None:
def match_uri_template(
- uri: str, uri_template: str, *, list_params: Collection[str] = ()
+ uri: str,
+ uri_template: str,
+ *,
+ list_params: Collection[str] = (),
+ regex: re.Pattern[str] | None = None,
) -> dict[str, Any] | None:
"""Match URI against template and extract both path and query parameters.
@@ -208,12 +210,16 @@ def match_uri_template(
`list_params` names non-exploded query params that hold lists. Per RFC 6570
section 3.2.8 their value is comma-joined, with literal commas separating
items and `%2C` inside an item, so they are split before decoding.
+
+ `regex` is the template's compiled path pattern when the caller already
+ holds it; otherwise it is built from `uri_template` through a bounded cache.
"""
# Split URI into path and query parts
uri_path, _, query_string = uri.partition("?")
# Match path parameters
- regex = build_regex(uri_template)
+ if regex is None:
+ regex = build_regex(uri_template)
if regex is None:
return None
match = regex.match(uri_path)
@@ -353,6 +359,7 @@ class ResourceTemplate(FastMCPComponent):
# Non-exploded `{?name}` query params whose function parameter is a list.
_list_query_params: frozenset[str] = PrivateAttr(default_factory=frozenset)
+ _pattern: tuple[str, re.Pattern[str] | None] | None = PrivateAttr(default=None)
uri_template: str = Field(
description="URI template with parameters (e.g. weather://{city}/current)"
@@ -440,10 +447,30 @@ class ResourceTemplate(FastMCPComponent):
def matches(self, uri: str) -> dict[str, Any] | None:
"""Check if URI matches template and extract parameters."""
+ regex = self._compiled_pattern()
+ if regex is None:
+ return None
return match_uri_template(
- uri, self.uri_template, list_params=self._list_query_params
+ uri,
+ self.uri_template,
+ list_params=self._list_query_params if "?" in uri else (),
+ regex=regex,
)
+ def _compiled_pattern(self) -> re.Pattern[str] | None:
+ """This template's path pattern, built once per `uri_template`.
+
+ Reads match every template in turn, and pydantic's private-attribute
+ access costs ~0.3us, so the pattern lives in the private dict directly.
+ """
+ private = self.__pydantic_private__
+ assert private is not None
+ cached = private.get("_pattern")
+ if cached is None or cached[0] != self.uri_template:
+ cached = (self.uri_template, build_regex(self.uri_template))
+ private["_pattern"] = cached
+ return cached[1]
+
async def read(self, arguments: dict[str, Any]) -> str | bytes | ResourceResult:
"""Read the resource content."""
raise NotImplementedError(
diff --git a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py
index 709b8e029..9d0b0a92d 100644
--- a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py
+++ b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py
@@ -281,7 +281,7 @@ class FastMCPProviderResourceTemplate(ResourceTemplate):
cls, server: Any, template: ResourceTemplate
) -> FastMCPProviderResourceTemplate:
"""Wrap a ResourceTemplate to create FastMCPProviderResources."""
- return cls(
+ wrapped = cls(
server=server,
original_uri_template=template.uri_template,
uri_template=template.uri_template,
@@ -298,6 +298,11 @@ class FastMCPProviderResourceTemplate(ResourceTemplate):
icons=template.icons,
security=template.security,
)
+ # Mounts wrap every template on every list, so share the source's
+ # compiled pattern instead of rebuilding it per wrapper.
+ template._compiled_pattern()
+ wrapped._pattern = template._pattern
+ return wrapped
async def create_resource(self, uri: str, params: dict[str, Any]) -> Resource:
"""Create a FastMCPProviderResource for the given URI.
diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.py
index d8b423501..cdc8c0081 100644
--- a/tests/resources/test_resource_template.py
+++ b/tests/resources/test_resource_template.py
@@ -781,14 +781,18 @@ class TestMalformedURITemplates:
assert match is not None
assert match.group("user_id") == "alice"
- def test_pattern_cache_holds_more_templates_than_4096(self, monkeypatch):
- """A read walks every template, so a pattern must still be cached after a
- server with thousands of templates has matched against all of them."""
+ def test_template_keeps_its_own_pattern(self, monkeypatch):
+ """Reads walk every template, so each keeps its compiled pattern for as
+ long as it lives, independent of any shared cache."""
from fastmcp.resources import template as template_module
- templates = [f"many-templates://{i}/{{x}}" for i in range(5000)]
- for uri_template in templates:
- match_uri_template("many-templates://none", uri_template)
+ def weather(city: str) -> str:
+ return city
+
+ template = ResourceTemplate.from_function(
+ weather, uri_template="own-pattern://forecast/{city}"
+ )
+ assert template.matches("own-pattern://forecast/oslo") == {"city": "oslo"}
builds = 0
literal_pattern = template_module._literal_pattern
@@ -799,9 +803,76 @@ class TestMalformedURITemplates:
return literal_pattern(text)
monkeypatch.setattr(template_module, "_literal_pattern", counting)
- assert match_uri_template("many-templates://0/a", templates[0]) == {"x": "a"}
+ template_module.build_regex.cache_clear()
+ for _ in range(10):
+ assert template.matches("own-pattern://forecast/bergen") == {
+ "city": "bergen"
+ }
assert builds == 0
+ def test_template_pattern_follows_a_changed_uri_template(self):
+ def weather(city: str) -> str:
+ return city
+
+ template = ResourceTemplate.from_function(
+ weather, uri_template="before://{city}"
+ )
+ assert template.matches("before://oslo") == {"city": "oslo"}
+ renamed = template.model_copy(update={"uri_template": "after://{city}"})
+ assert renamed.matches("before://oslo") is None
+ assert renamed.matches("after://oslo") == {"city": "oslo"}
+
+ def test_mounted_template_wrapper_shares_the_source_pattern(self, monkeypatch):
+ """A mount wraps every template on every list, so a wrapper must not
+ compile the pattern again."""
+ from fastmcp.resources import template as template_module
+ from fastmcp.server.providers.fastmcp_provider import (
+ FastMCPProviderResourceTemplate,
+ )
+
+ def weather(city: str) -> str:
+ return city
+
+ source = ResourceTemplate.from_function(
+ weather, uri_template="mounted://forecast/{city}"
+ )
+ source.matches("mounted://forecast/oslo")
+
+ builds = 0
+ literal_pattern = template_module._literal_pattern
+
+ def counting(text: str) -> str:
+ nonlocal builds
+ builds += 1
+ return literal_pattern(text)
+
+ monkeypatch.setattr(template_module, "_literal_pattern", counting)
+ template_module.build_regex.cache_clear()
+ for _ in range(3):
+ wrapped = FastMCPProviderResourceTemplate.wrap(None, source)
+ assert wrapped.matches("mounted://forecast/bergen") == {"city": "bergen"}
+ assert builds == 0
+
+ def test_copy_can_override_list_query_params(self):
+ def search(tags: list[str] | None = None) -> str:
+ return ",".join(tags or [])
+
+ template = ResourceTemplate.from_function(
+ search, uri_template="items://all{?tags}"
+ )
+ assert template.matches("items://all?tags=a,b") == {"tags": ["a", "b"]}
+ scalar = template.model_copy(update={"_list_query_params": frozenset()})
+ assert scalar.matches("items://all?tags=a,b") == {"tags": "a,b"}
+
+ def test_shared_pattern_cache_is_bounded(self):
+ """Template strings can come from a proxied server, so the shared cache
+ must not grow with every template a remote ever sends."""
+ from fastmcp.resources import template as template_module
+
+ for i in range(5000):
+ match_uri_template("remote://none", f"remote-{i}://{{x}}")
+ assert template_module.build_regex.cache_info().currsize <= 4096
+
def test_matching_reuses_the_compiled_template_pattern(self, monkeypatch):
"""Reads try every template in turn, so a template's pattern is built
once, not on every match attempt."""