Skip to main content
Glama
ast-grep MCP Server

ast-grep MCP Server

by ast-grep

ast-grep MCP Server

An experimental Model Context Protocol (MCP) server that provides AI assistants with powerful structural code search capabilities using ast-grep.

Overview

This MCP server enables AI assistants (like Cursor, Claude Desktop, etc.) to search and analyze codebases using Abstract Syntax Tree (AST) pattern matching rather than simple text-based search. By leveraging ast-grep's structural search capabilities, AI can:

  • Find code patterns based on syntax structure, not just text matching

  • Search for specific programming constructs (functions, classes, imports, etc.)

  • Write and test complex search rules using YAML configuration

  • Debug and visualize AST structures for better pattern development

Related MCP server: Code Search MCP

Prerequisites

  1. Install ast-grep: Follow ast-grep installation guide

    # macOS
    brew install ast-grep
    nix-shell -p ast-grep
    cargo install ast-grep --locked
  2. Install uv: Python package manager

    curl -LsSf https://astral.sh/uv/install.sh | sh
  3. MCP-compatible client: Such as Cursor, Claude Desktop, or other MCP clients

Installation

  1. Clone this repository:

    git clone https://github.com/ast-grep/ast-grep-mcp.git
    cd ast-grep-mcp
  2. Install dependencies:

    uv sync
  3. Verify ast-grep installation:

    ast-grep --version

Running with uvx

You can run the server directly from GitHub using uvx:

uvx --from git+https://github.com/ast-grep/ast-grep-mcp ast-grep-server

This is useful for quickly trying out the server without cloning the repository.

Configuration

For Cursor

Add to your MCP settings (usually in .cursor-mcp/settings.json):

{
  "mcpServers": {
    "ast-grep": {
      "command": "uv",
      "args": ["--directory", "/absolute/path/to/ast-grep-mcp", "run", "main.py"],
      "env": {}
    }
  }
}

For Claude Desktop

Add to your Claude Desktop MCP configuration:

{
  "mcpServers": {
    "ast-grep": {
      "command": "uv",
      "args": ["--directory", "/absolute/path/to/ast-grep-mcp", "run", "main.py"],
      "env": {}
    }
  }
}

Custom ast-grep Configuration

The MCP server supports using a custom sgconfig.yaml file to configure ast-grep behavior. See the ast-grep configuration documentation for details on the config file format.

You can provide the config file in two ways (in order of precedence):

  1. Command-line argument: --config /path/to/sgconfig.yaml

  2. Environment variable: AST_GREP_CONFIG=/path/to/sgconfig.yaml

Custom ast-grep Command

If ast-grep is not in PATH, or must be launched through another command, set AST_GREP_PATH. The value can be an executable path or a command prefix:

{
  "mcpServers": {
    "ast-grep": {
      "command": "uv",
      "args": ["--directory", "/absolute/path/to/ast-grep-mcp", "run", "main.py"],
      "env": {
        "AST_GREP_PATH": "uv run ast-grep"
      }
    }
  }
}

Other examples:

  • AST_GREP_PATH="/custom/path/to/ast-grep"

  • AST_GREP_PATH="npx ast-grep"

  • AST_GREP_PATH='"/path containing spaces/ast-grep"'

If unset, the command defaults to ast-grep.

Usage

This repository includes comprehensive ast-grep rule documentation in ast-grep.mdc. The documentation covers all aspects of writing effective ast-grep rules, from simple patterns to complex multi-condition searches.

You can add it to your cursor rule or Claude.md, and attach it when you need AI agent to create ast-grep rule for you.

The prompt will ask LLM to use MCP to create, verify and improve the rule it creates.

Features

The server provides four main tools for code analysis:

๐Ÿ” dump_syntax_tree

Visualize the Abstract Syntax Tree structure of code snippets. Essential for understanding how to write effective search patterns.

Use cases:

  • Debug why a pattern isn't matching

  • Understand the AST structure of target code

  • Learn ast-grep pattern syntax

๐Ÿงช test_match_code_rule

Test ast-grep YAML rules against code snippets before applying them to larger codebases.

Use cases:

  • Validate rules work as expected

  • Iterate on rule development

  • Debug complex matching logic

๐ŸŽฏ find_code

Search codebases using simple ast-grep patterns for straightforward structural matches.

Parameters:

  • max_results: Limit number of complete matches returned (default: unlimited)

  • output_format: Choose between "text" (default, ~75% fewer tokens) or "json" (full metadata)

Text Output Format:

Found 2 matches:

path/to/file.py:10-15
def example_function():
    # function body
    return result

path/to/file.py:20-22
def another_function():
    pass

Use cases:

  • Find function calls with specific patterns

  • Locate variable declarations

  • Search for simple code constructs

๐Ÿš€ find_code_by_rule

Advanced codebase search using complex YAML rules that can express sophisticated matching criteria.

Parameters:

  • max_results: Limit number of complete matches returned (default: unlimited)

  • output_format: Choose between "text" (default, ~75% fewer tokens) or "json" (full metadata)

Use cases:

  • Find nested code structures

  • Search with relational constraints (inside, has, precedes, follows)

  • Complex multi-condition searches

Usage Examples

Use Query:

Find all console.log statements

AI will generate rules like:

id: find-console-logs
language: javascript
rule:
  pattern: console.log($$$)

Complex Rule Example

User Query:

Find async functions that use await

AI will generate rules like:

id: async-with-await
language: javascript
rule:
  all:
    - kind: function_declaration
    - has:
        pattern: async
    - has:
        pattern: await $EXPR
        stopBy: end

Supported Languages

ast-grep supports many programming languages including:

  • JavaScript/TypeScript

  • Python

  • Rust

  • Go

  • Java

  • C/C++

  • C#

  • And many more...

For a complete list of built-in supported languages, see the ast-grep language support documentation.

You can also add support for custom languages through the sgconfig.yaml configuration file. See the custom language guide for details.

Troubleshooting

Common Issues

  1. "Command not found" errors: Ensure ast-grep is installed and in your PATH

  2. No matches found: Try adding stopBy: end to relational rules

  3. Pattern not matching: Use dump_syntax_tree to understand the AST structure

  4. Permission errors: Ensure the server has read access to target directories

Contributing

This is an experimental project. Issues and pull requests are welcome!

  • ast-grep - The core structural search tool

  • Model Context Protocol - The protocol this server implements

  • MCP Python SDK - The Python MCP framework used

  • Codemod MCP - Gives AI assistants tools like tree-sitter AST and node types, ast-grep instructions (YAML and JS ast-grep), and Codemod CLI commands to easily build, publish, and run ast-grep based codemods.

Available Tools

4 tools
dump_syntax_treeA

Dump code's syntax structure or dump a query's pattern structure. This is useful to discover correct syntax kind and syntax tree structure. Call it when debugging a rule. The tool requires three arguments: code, language and format. The first two are self-explanatory. format is the output format of the syntax tree. use format=cst to inspect the code's concrete syntax tree structure, useful to debug target code. use format=pattern to inspect how ast-grep interprets a pattern, useful to debug pattern rule.

Internally calls: ast-grep run --pattern --lang --debug-query=

Inputs: code (required), language (required), format.

find_codeA

Find code in a project folder that matches the given ast-grep pattern. Pattern is good for simple and single-AST node result. For more complex usage, please use YAML by find_code_by_rule.

Internally calls: ast-grep run --pattern [--json] <project_folder>

Output formats:

  • text (default): Compact text format with file:line-range headers and complete match text Example: Found 2 matches:

    path/to/file.py:10-15 def example_function(): # function body return result

    path/to/file.py:20-22 def another_function(): pass

  • json: Full match objects with metadata including ranges, meta-variables, etc.

The max_results parameter limits the number of complete matches returned (not individual lines). When limited, the header shows "Found X matches (showing first Y of Z)".

Example usage: find_code(pattern="class $NAME", max_results=20) # Returns text format find_code(pattern="class $NAME", output_format="json") # Returns JSON with metadata

Inputs: project_folder (required), pattern (required), language, max_results, +1 more.

find_code_by_ruleA

Find code using ast-grep's YAML rule in a project folder. YAML rule is more powerful than simple pattern and can perform complex search like find AST inside/having another AST. It is a more advanced search tool than the simple find_code.

Tip: When using relational rules (inside/has), add stopBy: end to ensure complete traversal.

Internally calls: ast-grep scan --inline-rules [--json] <project_folder>

Output formats:

  • text (default): Compact text format with file:line-range headers and complete match text Example: Found 2 matches:

    src/models.py:45-52 class UserModel: def init(self): self.id = None self.name = None

    src/views.py:12 class SimpleView: pass

  • json: Full match objects with metadata including ranges, meta-variables, etc.

The max_results parameter limits the number of complete matches returned (not individual lines). When limited, the header shows "Found X matches (showing first Y of Z)".

Example usage: find_code_by_rule(yaml="id: x\nlanguage: python\nrule: {pattern: 'class $NAME'}", max_results=20) find_code_by_rule(yaml="...", output_format="json") # For full metadata

Inputs: project_folder (required), yaml (required), max_results, output_format.

test_match_code_ruleA

Test a code against an ast-grep YAML rule. This is useful to test a rule before using it in a project.

Internally calls: ast-grep scan --inline-rules --json --stdin

Inputs: code (required), yaml (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelogโ€ฆ

    TDQS

    A4.1/5.0

    Scored across 4 tools

    Disambiguation4/5

    The tools have mostly distinct purposes: dump_syntax_tree is for debugging syntax structures, find_code and find_code_by_rule are for searching code with different rule formats, and test_match_code_rule is for testing rules. However, find_code and find_code_by_rule could be confused as both search for code matches, though their descriptions clarify the pattern vs. YAML rule distinction.

    Naming Consistency5/5

    All tool names follow a consistent snake_case pattern with clear verb_noun structures: dump_syntax_tree, find_code, find_code_by_rule, and test_match_code_rule. This makes them predictable and easy to understand at a glance.

    Tool Count5/5

    With 4 tools, this server is well-scoped for ast-grep functionality. Each tool serves a specific role in code analysis and debugging, covering core operations without being overly sparse or bloated.

    Completeness4/5

    The toolset covers essential ast-grep operations: debugging syntax, searching with patterns and YAML rules, and testing rules. A minor gap is the lack of a tool for modifying or refactoring code based on matches, but the server's focus on analysis and testing is adequately covered.

    Maintenance

    ActivityMaintained
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      Enables AI assistants to understand and navigate codebases through structural analysis. Provides code mapping, symbol search, and impact analysis using ast-grep for accurate parsing of Python, JavaScript, TypeScript, and Go projects.
      4
      52
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables LLMs to perform high-performance code search and analysis across multiple languages using symbol indexing, regex text search, and structural AST pattern matching. It also provides tools for technology stack detection and dependency analysis with persistent caching for optimized performance.
      12
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Enables structural code search and refactoring across 20+ programming languages using ast-grep patterns, with safe dry-run mode and flexible filtering.
      1
      MIT