Skip to main content
Glama

search

Recursively search for a text pattern in files within a specified directory. Define the pattern and path to locate matching files.

Instructions

Recursively search for pattern in files under path.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
patternYes
pathNo.
max_resultsNo

Implementation Reference

  • The main handler for the 'search' tool. Uses os.walk to recursively search files under a sandboxed path for lines containing the given pattern, up to max_results.
    @tool
    def search(self, pattern: str, path: str = ".", max_results: int = 100) -> list[dict]:
        """Recursively search for `pattern` in files under `path`."""
        if not pattern:
            raise ValueError("pattern must be non-empty")
        root = self._safe_join(path)
        if not root.exists():
            raise FileNotFoundError(f"no such path: {path}")
        if not root.is_dir():
            raise NotADirectoryError(f"not a directory: {path}")
    
        results: list[dict] = []
        for dirpath, _dirs, files in os.walk(root):
            for fname in files:
                fpath = Path(dirpath) / fname
                try:
                    with fpath.open("r", encoding="utf-8", errors="ignore") as f:
                        for lineno, line in enumerate(f, start=1):
                            if pattern in line:
                                results.append({
                                    "file": str(fpath.relative_to(self.root)),
                                    "line": lineno,
                                    "text": line.rstrip("\n"),
                                })
                                if len(results) >= max_results:
                                    return results
                except (OSError, UnicodeDecodeError):
                    continue
        return results
  • The function signature defines the input schema: pattern (str, required), path (str, default '.'), max_results (int, default 100). Return type list[dict].
    def search(self, pattern: str, path: str = ".", max_results: int = 100) -> list[dict]:
        """Recursively search for `pattern` in files under `path`."""
        if not pattern:
            raise ValueError("pattern must be non-empty")
        root = self._safe_join(path)
        if not root.exists():
            raise FileNotFoundError(f"no such path: {path}")
        if not root.is_dir():
            raise NotADirectoryError(f"not a directory: {path}")
    
        results: list[dict] = []
        for dirpath, _dirs, files in os.walk(root):
            for fname in files:
                fpath = Path(dirpath) / fname
                try:
                    with fpath.open("r", encoding="utf-8", errors="ignore") as f:
                        for lineno, line in enumerate(f, start=1):
                            if pattern in line:
                                results.append({
                                    "file": str(fpath.relative_to(self.root)),
                                    "line": lineno,
                                    "text": line.rstrip("\n"),
                                })
                                if len(results) >= max_results:
                                    return results
                except (OSError, UnicodeDecodeError):
                    continue
        return results
  • The @tool decorator (from mcpforge.decorator) marks this method as an MCP tool, which is then collected by the @serve decorator on the class.
    @tool
    def search(self, pattern: str, path: str = ".", max_results: int = 100) -> list[dict]:
        """Recursively search for `pattern` in files under `path`."""
  • The @serve decorator registers the FilesystemTools class as an MCP server, which collects all @tool-decorated methods (including 'search') during class creation.
    @serve(
        name="filesystem",
        version="0.1.0",
        description="Sandboxed filesystem read/list/search tools",
    )
  • Helper used by search() to safely resolve paths within the sandbox root, preventing path traversal attacks.
    def _safe_join(self, path: str) -> Path:
        """Resolve `path` under self.root and verify it stays inside."""
        candidate = (self.root / path).resolve()
        try:
            candidate.relative_to(self.root)
        except ValueError:
            raise ValueError(
                f"path escapes sandbox root: {path!r} resolves outside {self.root}"
            )
        return candidate
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Without annotations, the description must disclose behavior fully. It mentions recursion but omits critical details: pattern syntax (regex/glob?), case sensitivity, file inclusion criteria, effect of max_results, and whether any side effects occur. This is insufficient for an agent to predict tool behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness3/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single sentence, making it concise, but it omits necessary details, so it is under-specified rather than efficiently compact. It could be longer to include essential context without becoming wordy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 3 parameters, no output schema, and no annotations, the description must explain return values, error handling, and behavior under limits. It does not, leaving major gaps for an agent using this tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description should compensate. It mentions pattern and path but does not define pattern semantics or default behavior for path. max_results is not explained at all. The description adds minimal value beyond parameter names.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool recursively searches for a pattern in files under a path. It uses a specific verb ('search') and resource ('files'), and differentiates from sibling tools like list_dir and read_file, which serve different purposes.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool versus alternatives or when not to use it. The description lacks context about prerequisites, such as file types or permissions, and does not mention any alternative search methods.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/vigilancetrent/mcpforge'

If you have feedback or need assistance with the MCP directory API, please join our Discord server