Skip to main content
Glama
Preston-Harrison

Filesystem MCP Server

grep

Search for text patterns in files using regular expressions to locate specific content within directories and subdirectories.

Instructions

Search for text patterns inside files using regular expressions.

Args: dir (str): Directory to search in (absolute or relative to allowed directories) pattern (str): Regular expression pattern to search for in file contents exclude (str, optional): File pattern to exclude from search

Returns: str: Newline-separated matches in format 'path:lineNo: line', or error message if failed

Note: - Directory must be within allowed directory roots - Searches recursively through subdirectories - Only searches UTF-8 text files - Respects .gitignore files and skips common lock files - Each match shows file path, line number, and the matching line - Uses Python regular expression syntax

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dirYes
patternYes
excludeNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • main.py:500-564 (handler)
    The main handler function for the MCP 'grep' tool. It performs recursive regex-based text search in files under the specified directory, skipping ignored files and binaries, and formats output as 'path:lineNo:\tline'.
    @mcp.tool
    def grep(dir: str, pattern: str, exclude: str | None = None) -> str:
        """Search for text patterns inside files using regular expressions.
    
        Args:
            dir (str): Directory to search in (absolute or relative to allowed directories)
            pattern (str): Regular expression pattern to search for in file contents
            exclude (str, optional): File pattern to exclude from search
    
        Returns:
            str: Newline-separated matches in format 'path:lineNo:\tline', or error message if failed
    
        Note:
            - Directory must be within allowed directory roots
            - Searches recursively through subdirectories
            - Only searches UTF-8 text files
            - Respects .gitignore files and skips common lock files
            - Each match shows file path, line number, and the matching line
            - Uses Python regular expression syntax
        """
        try:
            exclude_spec = (
                pathspec.PathSpec(
                    (pathspec.patterns.gitwildmatch.GitWildMatchPattern(exclude),)
                )
                if exclude
                else None
            )
            root = _resolve(dir)
            if not root.is_dir():
                return f"Error grepping: '{root}' is not a directory"
            spec_cache: Dict[Path, Optional[pathspec.PathSpec]] = {}
            try:
                regex = re.compile(pattern)
            except re.error as e:
                return (
                    f"Error grepping: invalid regular expression pattern '{pattern}' - {e}"
                )
            hits: List[str] = []
            for file in root.rglob("*"):
                if file.is_dir():
                    continue
    
                grep_ignore_spec = pathspec.PathSpec.from_lines(
                    pathspec.patterns.gitwildmatch.GitWildMatchPattern, GREP_IGNORE_FILES
                )
                if grep_ignore_spec.match_file(file):
                    continue
                if exclude_spec and exclude_spec.match_file(file):
                    continue
                if _skip_ignored(file, root, spec_cache):
                    continue
                if not _is_text(file):
                    continue
                try:
                    for idx, line in enumerate(
                        file.read_text(encoding="utf-8", errors="ignore").splitlines(), 1
                    ):
                        if regex.search(line):
                            hits.append(f"{file}:{idx}:\t{line}")
                except Exception:
                    continue
            return "\n".join(hits)
        except Exception as e:
            return _human_error(e, "grepping")
  • Constant defining file patterns to ignore during 'grep' tool execution (e.g., lock files). Used within the grep handler to skip specific files.
    GREP_IGNORE_FILES = [
        "*.lock",
        "package-lock.json",
    ]
  • main.py:500-500 (registration)
    MCP decorator registering the 'grep' function as a tool (name derived from function name).
    @mcp.tool
Behavior5/5

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

With no annotations provided, the description carries full burden and excels. It discloses key behavioral traits: recursive searching, UTF-8 text-only limitation, respect for .gitignore, skipping lock files, output format details, Python regex syntax, and directory access restrictions. This goes well beyond basic functionality.

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

Conciseness5/5

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

The description is well-structured with clear sections (purpose, Args, Returns, Note) and front-loaded key information. Every sentence earns its place by providing essential details without redundancy. It's comprehensive yet efficiently organized.

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

Completeness5/5

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

Given the tool's complexity (regex search with constraints), no annotations, and 0% schema coverage, the description is remarkably complete. It covers purpose, parameters, output format, behavioral constraints, and technical details. The output schema exists, so return values are documented, making this fully adequate.

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

Parameters5/5

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

Schema description coverage is 0%, so the description must compensate fully. It does: it explains all 3 parameters (dir, pattern, exclude) with semantic meaning, including dir constraints ('within allowed directory roots'), pattern type ('regular expression'), and exclude purpose ('file pattern to exclude'). This adds substantial value beyond the bare schema.

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

Purpose5/5

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

The description clearly states the tool's purpose: 'Search for text patterns inside files using regular expressions.' This specifies the verb ('search'), resource ('text patterns inside files'), and method ('using regular expressions'), distinguishing it from sibling tools like 'search_files' (likely filename-based) and 'read_text_file' (file reading).

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

Usage Guidelines4/5

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

The description provides clear context for when to use this tool: for searching file contents with regex patterns. It implicitly distinguishes from 'search_files' (which likely searches filenames) and 'read_text_file' (which reads entire files), but doesn't explicitly name alternatives or state when not to use it.

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/Preston-Harrison/fs-mcp-py'

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