Skip to main content
Glama
SDGLBL
by SDGLBL

grep_ast

Search source code with AST context to understand how matches fit within functions, classes, and code structures.

Instructions

Search through source code files and see matching lines with useful AST (Abstract Syntax Tree) context. This tool helps you understand code structure by showing how matched lines fit into functions, classes, and other code blocks.

Unlike traditional search tools like search_content that only show matching lines, grep_ast leverages the AST to reveal the structural context around matches, making it easier to understand the code organization.

When to use this tool:

  1. When you need to understand where a pattern appears within larger code structures

  2. When searching for function or class definitions that match a pattern

  3. When you want to see not just the matching line but its surrounding context in the code

  4. When exploring unfamiliar codebases and need structural context

  5. When examining how a specific pattern is used across different parts of the codebase

This tool is superior to regular grep/search_content when you need to understand code structure, not just find text matches.

Example usage:

grep_ast(pattern="function_name", path="/path/to/file.py", ignore_case=False, line_number=True)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
patternYesThe regex pattern to search for in source code files
pathYesThe path to search in (file or directory)
ignore_caseNoWhether to ignore case when matching
line_numberNoWhether to display line numbers

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Core handler logic for executing grep_ast tool: validates path, processes files/directories, uses TreeContext.grep() to find AST matches with context, formats and returns results.
    async def call(
        self,
        ctx: MCPContext,
        **params: Unpack[GrepAstToolParams],
    ) -> str:
        """Execute the tool with the given parameters.
    
        Args:
            ctx: MCP context
            **params: Tool parameters
    
        Returns:
            Tool result
        """
        tool_ctx = self.create_tool_context(ctx)
        self.set_tool_context_info(tool_ctx)
    
        # Extract parameters
        pattern: Pattern = params["pattern"]
        path: SearchPath = params["path"]
        ignore_case = params.get("ignore_case", False)
        line_number = params.get("line_number", False)
    
        # Validate the path
        path_validation = self.validate_path(path)
        if not path_validation.is_valid:
            await tool_ctx.error(f"Invalid path: {path_validation.error_message}")
            return f"Error: Invalid path: {path_validation.error_message}"
    
        # Check if path is allowed
        is_allowed, error_message = await self.check_path_allowed(path, tool_ctx)
        if not is_allowed:
            return error_message
    
        # Check if path exists
        is_exists, error_message = await self.check_path_exists(path, tool_ctx)
        if not is_exists:
            return error_message
    
        await tool_ctx.info(f"Searching for '{pattern}' in {path}")
    
        # Get the files to process
        path_obj = Path(path)
        files_to_process = []
    
        if path_obj.is_file():
            files_to_process.append(str(path_obj))
        elif path_obj.is_dir():
            for root, _, files in os.walk(path_obj):
                for file in files:
                    file_path = Path(root) / file
                    if self.is_path_allowed(str(file_path)):
                        files_to_process.append(str(file_path))
    
        if not files_to_process:
            await tool_ctx.warning(f"No source code files found in {path}")
            return f"No source code files found in {path}"
    
        # Process each file
        results = []
        processed_count = 0
    
        await tool_ctx.info(f"Found {len(files_to_process)} file(s) to process")
    
        for file_path in files_to_process:
            await tool_ctx.report_progress(processed_count, len(files_to_process))
    
            try:
                # Read the file
                with open(file_path, "r", encoding="utf-8") as f:
                    code = f.read()
    
                # Process the file with grep-ast
                try:
                    tc = TreeContext(
                        file_path,
                        code,
                        color=False,
                        verbose=False,
                        line_number=line_number,
                    )
    
                    # Find matches
                    loi = tc.grep(pattern, ignore_case)
    
                    if loi:
                        tc.add_lines_of_interest(loi)
                        tc.add_context()
                        output = tc.format()
    
                        # Add the result to our list
                        results.append(f"\n{file_path}:\n{output}\n")
                except Exception as e:
                    # Skip files that can't be parsed by tree-sitter
                    await tool_ctx.warning(f"Could not parse {file_path}: {str(e)}")
            except UnicodeDecodeError:
                await tool_ctx.warning(f"Could not read {file_path} as text")
            except Exception as e:
                await tool_ctx.error(f"Error processing {file_path}: {str(e)}")
    
            processed_count += 1
    
        # Final progress report
        await tool_ctx.report_progress(len(files_to_process), len(files_to_process))
    
        if not results:
            await tool_ctx.warning(f"No matches found for '{pattern}' in {path}")
            return f"No matches found for '{pattern}' in {path}"
    
        await tool_ctx.info(f"Found matches in {len(results)} file(s)")
    
        # Join the results
        return "\n".join(results)
  • Registers the grep_ast tool with the MCP server using @mcp_server.tool decorator, defining input schema via Annotated types and delegating to self.call().
    @mcp_server.tool(name=self.name, description=self.description)
    async def grep_ast(
        ctx: MCPContext,
        pattern: Pattern,
        path: SearchPath,
        ignore_case: IgnoreCase,
        line_number: LineNumber,
    ) -> str:
        ctx = get_context()
        return await tool_self.call(
            ctx,
            pattern=pattern,
            path=path,
            ignore_case=ignore_case,
            line_number=line_number,
        )
  • TypedDict defining the input parameters for the GrepAstTool.call() method, using pre-defined Annotated types.
    class GrepAstToolParams(TypedDict):
        """Parameters for the GrepAstTool.
    
        Attributes:
            pattern: The regex pattern to search for in source code files
            path: The path to search in (file or directory)
            ignore_case: Whether to ignore case when matching
            line_number: Whether to display line numbers
        """
    
        pattern: Pattern
        path: SearchPath
        ignore_case: IgnoreCase
        line_number: LineNumber
  • Pydantic Annotated types defining input schema with descriptions, defaults, and constraints for tool parameters.
    Pattern = Annotated[
        str,
        Field(
            description="The regex pattern to search for in source code files",
            min_length=1,
        ),
    ]
    
    SearchPath = Annotated[
        str,
        Field(
            description="The path to search in (file or directory)",
            min_length=1,
        ),
    ]
    
    IgnoreCase = Annotated[
        bool,
        Field(
            description="Whether to ignore case when matching",
            default=False,
        ),
    ]
    
    LineNumber = Annotated[
        bool,
        Field(
            description="Whether to display line numbers",
            default=False,
        ),
    ]
  • Registers all filesystem tools including GrepAstTool by calling ToolRegistry.register_tools, which invokes each tool's register method.
    def register_filesystem_tools(
        mcp_server: FastMCP,
        permission_manager: PermissionManager,
    ) -> list[BaseTool]:
        """Register all filesystem tools with the MCP server.
    
        Args:
            mcp_server: The FastMCP server instance
            permission_manager: Permission manager for access control
    
        Returns:
            List of registered tools
        """
        tools = get_filesystem_tools(permission_manager)
        ToolRegistry.register_tools(mcp_server, tools)
        return tools
Behavior4/5

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

No annotations are provided, so the description carries the full burden. It effectively discloses key behavioral traits: it's a search/read operation (implied by 'search through' and 'see matching lines'), provides AST-based structural context, and includes an example usage. However, it doesn't mention potential limitations like performance with large files, supported languages, or error handling, leaving some gaps.

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 clear sections: purpose, differentiation from siblings, usage guidelines, and an example. It's appropriately sized but could be slightly more concise by integrating the example more seamlessly. Most sentences earn their place, though the 'When to use' list is detailed yet necessary.

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 (AST-based search), no annotations, and the presence of an output schema (which handles return values), the description is complete enough. It covers purpose, usage guidelines, behavioral context, and includes an example, providing sufficient information for an agent to understand and invoke the tool effectively.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema already documents all four parameters thoroughly. The description adds minimal value beyond the schema, only mentioning parameters in the example usage without explaining their semantics further. This meets the baseline of 3 when schema coverage is high.

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 searches through source code files with AST context, specifying it shows matching lines within functions, classes, and code blocks. It explicitly distinguishes from sibling tools like `search_content` (implied by 'traditional search tools') and `grep` by emphasizing structural understanding over text matching.

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

Usage Guidelines5/5

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

The description includes a dedicated 'When to use this tool' section with five specific scenarios (e.g., understanding pattern context, finding definitions, exploring codebases). It explicitly contrasts with alternatives like `search_content` and regular grep, stating it's superior for structural context, providing clear guidance on when to use versus when not to.

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/SDGLBL/mcp-claude-code'

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