Skip to main content
Glama

search_code_advanced

Search and analyze code patterns in projects using advanced CLI tools (e.g., ugrep, ripgrep). Supports regex, fuzzy matching, file filtering, and case-sensitive options for efficient code discovery.

Instructions

Search for a code pattern in the project using an advanced, fast tool. This tool automatically selects the best available command-line search tool (like ugrep, ripgrep, ag, or grep) for maximum performance. Args: pattern: The search pattern. Can be literal text or regex (see regex parameter). case_sensitive: Whether the search should be case-sensitive. context_lines: Number of lines to show before and after the match. file_pattern: A glob pattern to filter files to search in (e.g., "*.py", "*.js", "test_*.py"). All search tools now handle glob patterns consistently: - ugrep: Uses glob patterns (*.py, *.{js,ts}) - ripgrep: Uses glob patterns (*.py, *.{js,ts}) - ag (Silver Searcher): Automatically converts globs to regex patterns - grep: Basic glob pattern matching All common glob patterns like "*.py", "test_*.js", "src/*.ts" are supported. fuzzy: If True, enables fuzzy/partial matching behavior varies by search tool: - ugrep: Native fuzzy search with --fuzzy flag (true edit-distance fuzzy search) - ripgrep, ag, grep, basic: Word boundary pattern matching (not true fuzzy search) IMPORTANT: Only ugrep provides true fuzzy search. Other tools use word boundary matching which allows partial matches at word boundaries. For exact literal matches, set fuzzy=False (default and recommended). regex: Controls regex pattern matching behavior: - If True, enables regex pattern matching - If False, forces literal string search - If None (default), automatically detects regex patterns and enables regex for patterns like "ERROR|WARN" The pattern will always be validated for safety to prevent ReDoS attacks. Returns: A dictionary containing the search results or an error message.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
case_sensitiveNo
context_linesNo
file_patternNo
fuzzyNo
patternYes
regexNo

Implementation Reference

  • Registration of the search_code_advanced tool using @mcp.tool() decorator.
    @mcp.tool()
  • The handler function for the search_code_advanced tool, including schema via type hints and docstring, and logic delegating to SearchService.
    def search_code_advanced( pattern: str, ctx: Context, case_sensitive: bool = True, context_lines: int = 0, file_pattern: str = None, fuzzy: bool = False, regex: bool = None, start_index: int = 0, max_results: Optional[int] = 10 ) -> Dict[str, Any]: """ Search for a code pattern in the project using an advanced, fast tool with pagination support. This tool automatically selects the best available command-line search tool (like ugrep, ripgrep, ag, or grep) for maximum performance. Args: pattern: The search pattern. Can be literal text or regex (see regex parameter). case_sensitive: Whether the search should be case-sensitive. context_lines: Number of lines to show before and after the match. file_pattern: A glob pattern to filter files to search in (e.g., "*.py", "*.js", "test_*.py"). All search tools now handle glob patterns consistently: - ugrep: Uses glob patterns (*.py, *.{js,ts}) - ripgrep: Uses glob patterns (*.py, *.{js,ts}) - ag (Silver Searcher): Automatically converts globs to regex patterns - grep: Basic glob pattern matching All common glob patterns like "*.py", "test_*.js", "src/*.ts" are supported. fuzzy: If True, enables fuzzy/partial matching behavior varies by search tool: - ugrep: Native fuzzy search with --fuzzy flag (true edit-distance fuzzy search) - ripgrep, ag, grep, basic: Word boundary pattern matching (not true fuzzy search) IMPORTANT: Only ugrep provides true fuzzy search. Other tools use word boundary matching which allows partial matches at word boundaries. For exact literal matches, set fuzzy=False (default and recommended). regex: Controls regex pattern matching behavior: - If True, enables regex pattern matching - If False, forces literal string search - If None (default), automatically detects regex patterns and enables regex for patterns like "ERROR|WARN" The pattern will always be validated for safety to prevent ReDoS attacks. start_index: Zero-based offset into the flattened match list. Use to fetch subsequent pages. max_results: Maximum number of matches to return (default 10). Pass None to retrieve all matches. Returns: A dictionary containing: - results: List of matches with file, line, and text keys. - pagination: Metadata with total_matches, returned, start_index, end_index, has_more, and optionally max_results. If an error occurs, an error message is returned instead. """ return SearchService(ctx).search_code( pattern=pattern, case_sensitive=case_sensitive, context_lines=context_lines, file_pattern=file_pattern, fuzzy=fuzzy, regex=regex, start_index=start_index, max_results=max_results )
  • Core implementation of the search logic in SearchService.search_code, handling validation, strategy selection, execution via search strategy, result filtering, pagination, and response formatting.
    def search_code( # pylint: disable=too-many-arguments, too-many-locals self, pattern: str, case_sensitive: bool = True, context_lines: int = 0, file_pattern: Optional[str] = None, fuzzy: bool = False, regex: Optional[bool] = None, start_index: int = 0, max_results: Optional[int] = 10 ) -> Dict[str, Any]: """Search for code patterns in the project.""" self._require_project_setup() if regex is None: regex = is_safe_regex_pattern(pattern) error = ValidationHelper.validate_search_pattern(pattern, regex) if error: raise ValueError(error) if file_pattern: error = ValidationHelper.validate_glob_pattern(file_pattern) if error: raise ValueError(f"Invalid file pattern: {error}") pagination_error = ValidationHelper.validate_pagination(start_index, max_results) if pagination_error: raise ValueError(pagination_error) if not self.settings: raise ValueError("Settings not available") strategy = self.settings.get_preferred_search_tool() if not strategy: raise ValueError("No search strategies available") self._configure_strategy(strategy) try: results = strategy.search( pattern=pattern, base_path=self.base_path, case_sensitive=case_sensitive, context_lines=context_lines, file_pattern=file_pattern, fuzzy=fuzzy, regex=regex ) filtered = self._filter_results(results) formatted_results, pagination = self._paginate_results( filtered, start_index=start_index, max_results=max_results ) return ResponseFormatter.search_results_response( formatted_results, pagination ) except Exception as exc: raise ValueError(f"Search failed using '{strategy.name}': {exc}") from exc

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/johnhuang316/code-index-mcp'

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