π The fast, Pythonic way to build MCP servers and clients.
Bound regex tool search by pattern length and time (#5771)
nate nowackfb52bd367954
diff --git a/docs/servers/transforms/tool-search.mdx b/docs/servers/transforms/tool-search.mdxindex 72a32b163..5a28fdc12 100644--- a/docs/servers/transforms/tool-search.mdx+++ b/docs/servers/transforms/tool-search.mdx@@ -66,7 +66,9 @@ result = await client.call_tool("search_tools", {"pattern": "send.*email|notify"# Returns: send_email```-Results are returned in catalog order. Patterns follow [Rust regex syntax](https://docs.rs/regex/latest/regex/#syntax), with support for groups, alternation, repetition, character classes, anchors, and inline flags. Lookahead, lookbehind, and backreferences are unsupported. Invalid or unsupported patterns return an empty list rather than raising an error.+Results are returned in catalog order. Patterns follow [Rust regex syntax](https://docs.rs/regex/latest/regex/#syntax), with support for groups, alternation, repetition, character classes, anchors, and inline flags. Lookahead, lookbehind, and backreferences are unsupported. Invalid or unsupported patterns, and patterns longer than 1,000 characters, return an empty list rather than raising an error.++A search stops after about a second and returns the matches it found up to that point, so a costly pattern can't hold the server. Ordinary patterns finish far sooner, even across catalogs with thousands of tools. When a search stops early, the server logs a warning.If you previously used Python-specific syntax, rewrite those patterns using the supported syntax. For example, use `send.*email` instead of `send(?=.*email)` and `\z` instead of `\Z` for the end-of-text anchor. Python's `(?a)` ASCII-mode flag is unsupported.diff --git a/fastmcp_slim/fastmcp/server/transforms/search/regex.py b/fastmcp_slim/fastmcp/server/transforms/search/regex.pyindex de82a5bda..2c25dcfc4 100644--- a/fastmcp_slim/fastmcp/server/transforms/search/regex.py+++ b/fastmcp_slim/fastmcp/server/transforms/search/regex.py@@ -1,5 +1,6 @@"""Regex-based search transform."""+import timefrom collections.abc import Sequencefrom typing import Annotated, Any@@ -11,6 +12,9 @@ from fastmcp.server.transforms.search.base import (_extract_searchable_text,)from fastmcp.tools.base import Tool+from fastmcp.utilities.logging import get_logger++logger = get_logger(__name__)class RegexSearchTransform(BaseSearchTransform):@@ -19,23 +23,29 @@ class RegexSearchTransform(BaseSearchTransform):Tools are matched against their name, description, and parameterinformation using Pydantic's Rust regex engine with case-insensitivematching. Lookarounds and backreferences are not supported.++ A search stops after about a second and returns the matches found so+ far, so a costly pattern cannot hold the worker for long."""+ _max_pattern_length = 1000+ _search_time_budget = 1.0+def _make_search_tool(self) -> Tool:transform = selfasync def search_tools(pattern: Annotated[str,- "Case-insensitive regex pattern for tool names, descriptions, and parameters; "- "lookarounds and backreferences are not supported",+ "Case-insensitive regex pattern for tool names, descriptions, and parameters, "+ "up to 1000 characters; lookarounds and backreferences are not supported",],ctx: Context = None, # type: ignore[assignment] # ty:ignore[invalid-parameter-default]) -> str | list[dict[str, Any]]:"""Search for tools matching a regex pattern.Returns matching tool definitions in the same format as list_tools.- Invalid or unsupported patterns return an empty list.+ Invalid, unsupported, or overlong patterns return an empty list."""hidden = await transform._get_visible_tools(ctx)results = await transform._search(hidden, pattern)@@ -44,6 +54,9 @@ class RegexSearchTransform(BaseSearchTransform):return Tool.from_function(fn=search_tools, name=self._search_tool_name)async def _search(self, tools: Sequence[Tool], query: str) -> Sequence[Tool]:+ if len(query) > self._max_pattern_length:+ return []+ deadline = time.monotonic() + self._search_time_budgettry:matcher = SchemaValidator(core_schema.str_schema(@@ -55,6 +68,13 @@ class RegexSearchTransform(BaseSearchTransform):matches: list[Tool] = []for tool in tools:+ if time.monotonic() > deadline:+ logger.warning(+ "Regex tool search exceeded %ss; returning %d partial matches",+ self._search_time_budget,+ len(matches),+ )+ breaktext = _extract_searchable_text(tool)try:matcher.validate_python(text)diff --git a/tests/server/transforms/test_search_regex.py b/tests/server/transforms/test_search_regex.pyindex bc8c7ff5b..31fb162b0 100644--- a/tests/server/transforms/test_search_regex.py+++ b/tests/server/transforms/test_search_regex.py@@ -79,3 +79,52 @@ def test_search_repeated_alternatives() -> None:timeout=8,)assert result.returncode == 0, result.stderr+++async def test_overlong_pattern_returns_no_results() -> None:+ server = FastMCP("search")++ @server.tool+ def send_email() -> str:+ """Send an email."""+ return "sent"++ server.add_transform(RegexSearchTransform())+ pattern = "send_email|" + "x" * 1000+ async with Client(server) as client:+ result = await client.call_tool("search_tools", {"pattern": pattern})++ assert result.structured_content == {"result": []}++[email protected]_heavy+def test_costly_pattern_stops_within_the_search_budget() -> None:+ # Counted repetition keeps the Rust engine linear but slow (about 0.2s per+ # kilobyte of tool text), so a large catalog must hit the time budget.+ code = textwrap.dedent(+ """+ import asyncio, time+ from fastmcp import Client, FastMCP+ from fastmcp.server.transforms.search import RegexSearchTransform++ async def main():+ server = FastMCP("search")+ for index in range(50):+ server.tool(lambda: "ok", name=f"tool_{index}", description="lorem " * 170)+ server.add_transform(RegexSearchTransform())+ async with Client(server) as client:+ started = time.monotonic()+ await client.call_tool("search_tools", {"pattern": "(?:[^z]?){9000}zzz"})+ assert time.monotonic() - started < 3++ asyncio.run(main())+ """+ )+ result = subprocess.run(+ [sys.executable, "-c", code],+ capture_output=True,+ text=True,+ timeout=12,+ )+ assert result.returncode == 0, result.stderr