Skip to main content
Glama

search_code_advanced

Search for code patterns in projects using optimized command-line tools with pagination, regex, fuzzy matching, and file filtering capabilities.

Instructions

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.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
patternYes
case_sensitiveNo
context_linesNo
file_patternNo
fuzzyNo
regexNo
start_indexNo
max_resultsNo

Implementation Reference

  • The MCP tool handler and registration for 'search_code_advanced'. Decorated with @mcp.tool(), includes input schema via parameters and comprehensive docstring describing args and returns. Delegates execution to SearchService.search_code.
    @mcp.tool()
    @handle_mcp_tool_errors(return_type='dict')
    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 logic of the search functionality in SearchService.search_code method. Handles 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
  • The @mcp.tool() decorator registers the search_code_advanced tool with the MCP server.
    @mcp.tool()

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