search_files
Search for files by name pattern within a specified directory and its subdirectories, respecting exclusions and .gitignore rules. Returns matching absolute file paths or an error message.
Instructions
Search for files by name pattern in a directory recursively.
Args: dir (str): Directory to search in (absolute or relative to allowed directories) pattern (str): Glob-style pattern to match file names (e.g., '.py', 'test_') exclude (str, optional): Glob-style pattern to exclude file names
Returns: List[str] | str: List of matching absolute file paths, or error message if failed
Note: - Directory must be within allowed directory roots - Searches recursively through subdirectories - Respects .gitignore files, and ignores hidden files and folders - Returns list for successful searches, string for errors
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| dir | Yes | ||
| exclude | No | ||
| pattern | Yes |
Implementation Reference
- main.py:461-498 (handler)The main handler function for the MCP tool 'search_files'. It performs a recursive glob search in the specified directory, skipping directories, excluded patterns, ignored files per .gitignore, and returns matching file paths or an error string.@mcp.tool def search_files(dir: str, pattern: str, exclude: str | None = None) -> List[str] | str: """Search for files by name pattern in a directory recursively. Args: dir (str): Directory to search in (absolute or relative to allowed directories) pattern (str): Glob-style pattern to match file names (e.g., '*.py', 'test_*') exclude (str, optional): Glob-style pattern to exclude file names Returns: List[str] | str: List of matching absolute file paths, or error message if failed Note: - Directory must be within allowed directory roots - Searches recursively through subdirectories - Respects .gitignore files, and ignores hidden files and folders - Returns list for successful searches, string for errors """ try: root = _resolve(dir) if not root.is_dir(): return f"Error searching files: '{root}' is not a directory" spec_cache: Dict[Path, Optional[pathspec.PathSpec]] = {} matches: List[str] = [] for file in root.rglob("*"): if file.is_dir(): continue if exclude and fnmatch.fnmatch(file.name, exclude): continue if not fnmatch.fnmatch(file.name, pattern): continue if _skip_ignored(file, root, spec_cache): continue matches.append(str(file)) return matches except Exception as e: return _human_error(e, "searching files")
- main.py:461-461 (registration)The @mcp.tool decorator registers the search_files function as an MCP tool.@mcp.tool