Skip to main content
Glama
thrawn01

ast-grep MCP Server

by thrawn01

MCP ast-grep Server

A Model Context Protocol (MCP) server that provides ast-grep integration for Claude Code, enabling powerful structural code search and refactoring across 20+ programming languages.

Features

  • AST-aware pattern matching: Search and replace based on code structure, not just text

  • Multi-language support: JavaScript, TypeScript, Python, Rust, Go, Java, C/C++, and more

  • Safe refactoring: Dry-run mode by default for replacements

  • Flexible filtering: Support for file globs and language-specific parsing

  • Rich output: Contextual matches with diff previews for replacements

Related MCP server: XRAY MCP

Prerequisites

  1. Node.js (>= 18.0.0)

  2. ast-grep CLI: Install globally with npm install -g @ast-grep/cli

  3. Claude Code with MCP support

Installation

Install both prerequisites and configure Claude Code in one go:

# Install ast-grep CLI
npm install -g @ast-grep/cli

# Clone and build the MCP server
git clone <repository-url>
cd mcp-ast-grep
npm install
npm run build

# Add to Claude Code using the MCP CLI tool
claude mcp install ast-grep node ./dist/index.js

Manual Installation

Option 1: npm install (if published)

npm install -g mcp-ast-grep
claude mcp install ast-grep mcp-ast-grep

Option 2: Build from source

git clone <repository-url>
cd mcp-ast-grep
npm install
npm run build

Configuration

The easiest way to add this server to Claude Code is using the claude mcp CLI tool:

# Add the server (from built source)
claude mcp install ast-grep node /path/to/mcp-ast-grep/dist/index.js

# Or if installed globally
claude mcp install ast-grep mcp-ast-grep

# Verify installation
claude mcp list

# Remove if needed
claude mcp remove ast-grep

Manual Configuration

If you prefer manual configuration, add the server to your Claude Code MCP settings:

macOS

~/Library/Application Support/Claude/claude_desktop_config.json

Windows

%APPDATA%/Claude/claude_desktop_config.json

Linux

~/.config/claude/claude_desktop_config.json

Add this configuration:

{
  "mcpServers": {
    "ast-grep": {
      "command": "mcp-ast-grep",
      "args": []
    }
  }
}

Or if building from source:

{
  "mcpServers": {
    "ast-grep": {
      "command": "node",
      "args": ["/path/to/mcp-ast-grep/dist/index.js"]
    }
  }
}

Restart Claude Code after adding the configuration.

Usage

Once installed, Claude Code will have access to the ast_grep tool. Here are some examples:

// Find all console.log calls
ast_grep({
  pattern: "console.log($msg)"
})

Search with File Filtering

// Find console.log only in JavaScript files
ast_grep({
  pattern: "console.log($msg)",
  glob: "**/*.js",
  language: "javascript"
})

Replace with Preview (Safe)

// Preview replacing console.log with logger.info
ast_grep({
  pattern: "console.log($msg)",
  replacement: "logger.info($msg)",
  dry_run: true  // default
})

Apply Changes

// Actually apply the replacement
ast_grep({
  pattern: "console.log($msg)",
  replacement: "logger.info($msg)",
  dry_run: false
})

Complex Patterns

// Convert function declarations to arrow functions
ast_grep({
  pattern: "function $name($args) { $$$body }",
  replacement: "const $name = ($args) => { $$$body }",
  language: "javascript"
})

Count Matches

// Count occurrences
ast_grep({
  pattern: "console.log($msg)",
  mode: "count"
})

Parameters

Parameter

Type

Description

Required

pattern

string

AST pattern to search for

replacement

string

Replacement pattern (enables replace mode)

path

string

File or directory to search (default: cwd)

glob

string

File glob pattern (e.g., **/*.js)

language

string

Target language for parsing

mode

"search" | "replace" | "count"

Operation mode

context

number

Lines of context around matches (0-20)

dry_run

boolean

Preview mode (default: true for replacements)

head_limit

number

Limit results to first N matches (1-1000)

Supported Languages

JavaScript, TypeScript, Python, Rust, Go, Java, C, C++, C#, HTML, CSS, JSON, YAML, Bash, Lua, PHP, Ruby, Swift, Kotlin, Dart, Scala

Pattern Syntax

ast-grep uses powerful pattern matching syntax:

  • $VAR - matches any single AST node

  • $$$VAR - matches multiple AST nodes (like function body)

  • console.log($msg) - matches console.log with any argument

  • function $name($args) { $$$body } - matches any function declaration

For more details, see the ast-grep documentation.

Error Handling

The server provides helpful error messages for common issues:

  • ast-grep not found: Install with npm install -g @ast-grep/cli

  • Invalid pattern: Check ast-grep pattern syntax

  • File not found: Verify the path parameter

  • Language not supported: Use one of the supported languages listed above

Development

# Install dependencies
npm install

# Run in development mode
npm run dev

# Build for production
npm run build

# Start production server
npm start

Troubleshooting

Tool not appearing in Claude Code

  1. Verify installation: claude mcp list (should show "ast-grep")

  2. Check that ast-grep CLI is installed: ast-grep --version

  3. Restart Claude Code after configuration changes

  4. If using manual config, verify the JSON syntax is correct

  5. Check Claude Code logs for MCP connection errors

Using the claude mcp CLI

# List all installed MCP servers
claude mcp list

# Check if ast-grep is installed
claude mcp status ast-grep

# Reinstall if there are issues
claude mcp remove ast-grep
claude mcp install ast-grep node /path/to/mcp-ast-grep/dist/index.js

# View Claude Code MCP configuration
claude mcp config

Permission errors

Make sure the server has read/write access to the target files and directories.

Pattern not matching

License

MIT

Contributing

Contributions welcome! Please open issues for bugs or feature requests.

Available Tools

1 tool
ast_grepB

A powerful AST-based code search and refactoring tool that understands code structure across 20+ programming languages. Performs syntax-aware pattern matching and transformations.

ParametersJSON Schema
NameRequiredDescriptionDefault
globNoGlob pattern to filter files (e.g. '*.js', '**/*.{ts,tsx}')
modeNoOperation modesearch
pathNoFile or directory to search in. Defaults to current working directory.
contextNoNumber of lines to show around matches (like grep -C)
dry_runNoPreview changes without modifying files (default: true for replace mode)
patternYesAST pattern to search for using ast-grep syntax (e.g., 'console.log($MSG)', 'function $NAME($ARGS) { $$$BODY }')
languageNoTarget language for parsing. Auto-detected if not specified.
head_limitNoLimit output to first N matches
replacementNoReplacement pattern (optional). If provided, performs replacement instead of search. Uses same variable syntax as pattern.

TDQS

B3.3/5.0
Behavior3/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It explains the core behavior (syntax-aware, cross-language), but fails to mention important traits: whether it modifies files outside dry_run, error handling when pattern doesn't match anything, or performance implications on large codebases. It does highlight AST-based operation and 20+ language support, which adds some valuable behavioral context beyond the schema.

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 two dense sentences (44 words) with no fluff. Every phrase adds value: 'AST-based,' '20+ programming languages,' 'syntax-aware,' 'pattern matching and transformations.' It's front-loaded with the most critical differentiator ('AST-based'). Minor deduction for not including a brief usage scenario or caveat, but overall very concise.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given 9 parameters, 3 operation modes (mode enum), and no output schema, the description is moderately complete. It covers the what and general how (AST pattern matching, cross-language) but misses when-not-to-use, output format expectations (e.g., returns matches with line numbers?), and side effects like file modification in replace mode. For a complex code transformation tool, an agent would benefit from knowing that ast-grep uses Tree-sitter grammars for parsing, which is not mentioned.

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

Parameters4/5

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

Schema description coverage is 100% (all 9 parameters have descriptions), but the tool description adds contextual meaning beyond those individual definitions. It explains the overarching purpose (AST-based, structural matching) which helps an agent understand that parameters like 'pattern' use ast-grep's special syntax (e.g., '$MSG', '$$$BODY') – a concept not fully explained in the pattern parameter's own description. This cross-parameter justification earns a high score.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it's an 'AST-based code search and refactoring tool' that 'understands code structure across 20+ programming languages' and performs 'syntax-aware pattern matching and transformations.' This is specific, uses a verb+resource structure, and distinguishes it from simple grep-like tools. However, it doesn't differentiate it from sibling tools because none are listed.

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

Usage Guidelines2/5

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

The description provides no guidance on when or when not to use this tool, nor does it mention any alternatives. It gives a general functional overview but lacks explicit context signals like prerequisites (e.g., project root setup) or situations where regex might be preferred over AST matching. Some usage context is implied through the parameter enum 'mode' (search/replace/count), but the description itself says nothing about usage boundaries.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

TDQS

A3.5/5.0
Disambiguation5/5

With only one tool, there is no risk of confusion or overlapping purposes. The tool's description is clear and distinct by default.

Naming Consistency5/5

A single tool name provides no opportunity for inconsistency. The naming is trivially consistent.

Tool Count3/5

One tool is borderline for a server that claims to handle both search and refactoring across many languages. While the tool may be comprehensive, a single tool feels thin compared to typical servers with 3-15 tools.

Completeness3/5

The tool covers search and transformations, which are the core operations. However, there may be missing capabilities like pattern management or language-specific configurations, leading to notable gaps.

Maintenance

ActivityInactive
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    B
    quality
    D
    maintenance
    Advanced code search and transformation MCP server for AI assistants. Combines ugrep's speed with intelligent replace capabilities, dry-run previews, and language-aware refactoring across 11 tools.
    1
    10
    MIT
  • A
    license
    A
    quality
    D
    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
    A
    quality
    C
    maintenance
    Enables AI assistants to search and analyze codebases using Abstract Syntax Tree (AST) pattern matching with ast-grep. Supports structural code search, pattern testing, and AST visualization across multiple programming languages.
    4
    454
    MIT

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/thrawn01/mcp-ast-grep'

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