Skip to main content
Glama
safurrier

MCP Filesystem Server

search_files

Find files and directories matching patterns with recursive search, content matching, and exclusion options to locate specific items in filesystems.

Instructions

Recursively search for files and directories matching a pattern.

Args:
    path: Starting directory
    pattern: Glob pattern to match against filenames
    recursive: Whether to search subdirectories
    exclude_patterns: Optional patterns to exclude
    content_match: Optional text to search within files
    max_results: Maximum number of results to return
    format: Output format ('text' or 'json')
    ctx: MCP context

Returns:
    Search results

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
patternYes
recursiveNo
exclude_patternsNo
content_matchNo
max_resultsNo
formatNotext

Implementation Reference

  • Registration of the 'search_files' MCP tool via @mcp.tool() decorator, including the wrapper handler function that formats results and delegates core logic to operations.search_files
    @mcp.tool()
    async def search_files(
        path: str,
        pattern: str,
        ctx: Context,
        recursive: bool = True,
        exclude_patterns: Optional[List[str]] = None,
        content_match: Optional[str] = None,
        max_results: int = 100,
        format: str = "text",
    ) -> str:
        """Recursively search for files and directories matching a pattern.
    
        Args:
            path: Starting directory
            pattern: Glob pattern to match against filenames
            recursive: Whether to search subdirectories
            exclude_patterns: Optional patterns to exclude
            content_match: Optional text to search within files
            max_results: Maximum number of results to return
            format: Output format ('text' or 'json')
            ctx: MCP context
    
        Returns:
            Search results
        """
        try:
            components = get_components()
            results = await components["operations"].search_files(
                path, pattern, recursive, exclude_patterns, content_match, max_results
            )
    
            if format.lower() == "json":
                return json.dumps(results, indent=2)
    
            # Format as text
            if not results:
                return "No matching files found"
    
            lines = []
            for item in results:
                is_dir = item.get("is_directory", False)
                type_label = "[DIR]" if is_dir else "[FILE]"
                size = f" ({item['size']:,} bytes)" if not is_dir else ""
                lines.append(f"{type_label} {item['path']}{size}")
    
            return f"Found {len(results)} matching files:\n\n" + "\n".join(lines)
        except Exception as e:
            return f"Error searching files: {str(e)}"
  • Core implementation of search_files logic in FileOperations class, handling file pattern matching, content search, and result formatting.
    async def search_files(
        self,
        root_path: Union[str, Path],
        pattern: str,
        recursive: bool = True,
        exclude_patterns: Optional[List[str]] = None,
        content_match: Optional[str] = None,
        max_results: int = 1000,
        encoding: str = "utf-8",
    ) -> List[Dict]:
        """Search for files matching pattern and/or containing text.
    
        Args:
            root_path: Starting directory for search
            pattern: Glob pattern to match against filenames
            recursive: Whether to search subdirectories
            exclude_patterns: Optional patterns to exclude
            content_match: Optional text to search within files
            max_results: Maximum number of results to return
            encoding: Text encoding for content matching
    
        Returns:
            List of matching file information
    
        Raises:
            ValueError: If root_path is outside allowed directories
        """
        # Find files matching the pattern
        matching_files = await self.validator.find_matching_files(
            root_path, pattern, recursive, exclude_patterns
        )
    
        results = []
    
        # If we don't need to match content, just return file info
        if content_match is None:
            for file_path in matching_files[:max_results]:
                try:
                    # Skip directories if pattern matched them
                    if file_path.is_dir():
                        continue
    
                    info = FileInfo(file_path)
                    results.append(info.to_dict())
                except (PermissionError, FileNotFoundError):
                    # Skip files we can't access
                    pass
    
            return results
    
        # If we need to match content, check each file
        for file_path in matching_files:
            if len(results) >= max_results:
                break
    
            try:
                # Skip directories
                if file_path.is_dir():
                    continue
    
                # Skip very large files for content matching (>10MB)
                if file_path.stat().st_size > 10_000_000:
                    continue
    
                # Check if file contains the search text
                try:
                    content = await anyio.to_thread.run_sync(
                        file_path.read_text, encoding
                    )
                    if content_match in content:
                        info = FileInfo(file_path)
                        results.append(info.to_dict())
                except UnicodeDecodeError:
                    # Skip binary files
                    pass
    
            except (PermissionError, FileNotFoundError):
                # Skip files we can't access
                pass
    
        return results
  • Helper function in PathValidator that finds files matching glob patterns within allowed directories, used by search_files.
    async def find_matching_files(
        self,
        root_path: Union[str, Path],
        pattern: str,
        recursive: bool = True,
        exclude_patterns: Optional[List[str]] = None,
    ) -> List[Path]:
        """Find files matching a pattern within allowed directories.
    
        Args:
            root_path: Starting directory for search
            pattern: Glob pattern to match against filenames
            recursive: Whether to search subdirectories
            exclude_patterns: Optional patterns to exclude
    
        Returns:
            List of matching file paths
    
        Raises:
            ValueError: If root_path is outside allowed directories
        """
        abs_path, allowed = await self.validate_path(root_path)
        if not allowed:
            raise ValueError(f"Search path outside allowed directories: {root_path}")
    
        if not abs_path.is_dir():
            raise ValueError(f"Search path is not a directory: {abs_path}")
    
        results = []
        exclude_regexes = []
    
        # Compile exclude patterns if provided
        if exclude_patterns:
            for exclude in exclude_patterns:
                try:
                    exclude_regexes.append(re.compile(exclude))
                except re.error:
                    logger.warning(f"Invalid exclude pattern: {exclude}")
    
        # Use glob for pattern matching
        glob_pattern = "**/" + pattern if recursive else pattern
        for matched_path in abs_path.glob(glob_pattern):
            # Skip if matched by exclude pattern
            path_str = str(matched_path)
            excluded = False
            for exclude_re in exclude_regexes:
                if exclude_re.search(path_str):
                    excluded = True
                    break
    
            if not excluded:
                # Verify path is still allowed (e.g., in case of symlinks)
                if self.is_path_allowed(matched_path):
                    results.append(matched_path)
    
        return results
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While it mentions the recursive nature and parameter purposes, it doesn't disclose important behavioral traits like whether this is a read-only operation, what permissions are required, how errors are handled, whether it follows symlinks, or what happens when max_results is exceeded. The description provides basic operational context but misses critical behavioral details.

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

Conciseness4/5

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

The description is well-structured with a clear purpose statement followed by organized parameter explanations. Every sentence earns its place, though the 'Returns: Search results' line is somewhat redundant given the tool name and could be more specific. The formatting with clear sections (Args, Returns) enhances readability without unnecessary verbosity.

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

Completeness3/5

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

Given the tool's moderate complexity (7 parameters, file system operations) and complete lack of annotations and output schema, the description provides adequate but incomplete coverage. It explains parameters well but misses behavioral context about permissions, error handling, and result formatting details. For a search tool with no structured safety or output information, the description should do more to compensate.

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?

With 0% schema description coverage, the description fully compensates by providing clear semantic explanations for all 7 parameters. Each parameter gets a concise explanation that adds meaning beyond the bare schema: 'path: Starting directory', 'pattern: Glob pattern to match against filenames', 'recursive: Whether to search subdirectories', etc. The description transforms the parameter list from just names to meaningful usage guidance.

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 with specific verbs ('recursively search for files and directories') and resources ('matching a pattern'), distinguishing it from siblings like list_directory (simple listing), grep_files (content-only search), or find_large_files (size-based filtering). The description explicitly mentions both file and directory search capabilities.

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

Usage Guidelines3/5

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

The description implies usage context through the mention of 'recursively search' and parameter explanations, but doesn't explicitly state when to use this tool versus alternatives like grep_files (for content-only searches) or list_directory (for simple directory listing without pattern matching). No explicit when-not-to-use guidance or sibling tool comparisons are provided.

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/safurrier/mcp-filesystem'

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