NEW Browse AI tools across categories — updated daily. See what's new →

Ast Grep

Guide for writing ast-grep rules to perform structural code search and analysis. Use when users need to search codebases using Abstract Syntax Tree (AST) patterns, find specific code structures, or...

Authorast-grep
Version1.0.0
LicenseMIT
Token count~2,825
UpdatedJun 5, 2026

Guide for writing ast-grep rules to perform structural code search and analysis. Use when users need to search codebases using Abstract Syntax Tree (AST) patterns, find specific code structures, or perform complex code queries that go beyond simple text search.

Install

Quick install

via npx skills · works with 57+ agents
npx skills add https://github.com/ast-grep/agent-skill/tree/main/ast-grep/skills/ast-grep
Or pick agent:
npx skills add ast-grep/agent-skill --skill ast-grep --agent claude-code
npx skills add ast-grep/agent-skill --skill ast-grep --agent cursor
npx skills add ast-grep/agent-skill --skill ast-grep --agent codex
npx skills add ast-grep/agent-skill --skill ast-grep --agent opencode
npx skills add ast-grep/agent-skill --skill ast-grep --agent github-copilot
npx skills add ast-grep/agent-skill --skill ast-grep --agent windsurf
More install options

Shorthand — useful for multi-skill repos:

npx skills add ast-grep/agent-skill --skill ast-grep

Manual — clone the repo and drop the folder into your agent's skills directory:

git clone https://github.com/ast-grep/agent-skill.git
cp -r agent-skill/ast-grep/skills/ast-grep ~/.claude/skills/
How to use: Once installed, ask your agent to "use the ast-grep skill" or describe what you want (e.g. "Guide for writing ast-grep rules to perform structural code search and analysis"). Requires Node.js 18+.

ast-grep

Guide for writing ast-grep rules to perform structural code search and analysis. Use when users need to search codebases using Abstract Syntax Tree (AST) patterns, find specific code structures, or perform complex code queries that go beyond simple text search.

ast-grepby ast-grep

Guide for writing ast-grep rules to perform structural code search and analysis. Use when users need to search codebases using Abstract Syntax Tree (AST) patterns, find specific code structures, or perform complex code queries that go beyond simple text search.

npx skills add https://github.com/ast-grep/agent-skill --skill ast-grepDownload ZIPGitHub

ast-grep Code Search

Overview

This skill helps translate natural language queries into ast-grep rules for structural code search. ast-grep uses Abstract Syntax Tree (AST) patterns to match code based on its structure rather than just text, enabling powerful and precise code search across large codebases.

When to Use This Skill

Use this skill when users:

  • Need to search for code patterns using structural matching (e.g., "find all async functions that don't have error handling")
  • Want to locate specific language constructs (e.g., "find all function calls with specific parameters")
  • Request searches that require understanding code structure rather than just text
  • Ask to search for code with particular AST characteristics
  • Need to perform complex code queries that traditional text search cannot handle

General Workflow

Follow this process to help users write effective ast-grep rules:

Step 1: Understand the Query

Clearly understand what the user wants to find. Ask clarifying questions if needed:

  • What specific code pattern or structure are they looking for?
  • Which programming language?
  • Are there specific edge cases or variations to consider?
  • What should be included or excluded from matches?

Step 2: Create Example Code

Write a simple code snippet that represents what the user wants to match. Save this to a temporary file for testing.

Example:
If searching for "async functions that use await", create a test file:

`// test_example.js
async function example() {
const result = await fetchData();
return result;
}
`

Step 3: Write the ast-grep Rule

Translate the pattern into an ast-grep rule. Start simple and add complexity as needed.

Key principles:

  • Always use stopBy: end for relational rules (inside, has) to ensure search goes to the end of the direction
  • Use pattern for simple structures
  • Use kind with has/inside for complex structures
  • Break complex queries into smaller sub-rules using all, any, or not

Example rule file (test_rule.yml):

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

See references/rule_reference.md for comprehensive rule documentation.

Step 4: Test the Rule

Use ast-grep CLI to verify the rule matches the example code. There are two main approaches:

Option A: Test with inline rules (for quick iterations)

`echo "async function test() { await fetch(); }" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
kind: function_declaration
has:
pattern: await \$EXPR
stopBy: end" --stdin
`

Option B: Test with rule files (recommended for complex rules)

`ast-grep scan --rule test_rule.yml test_example.js
`

Debugging if no matches:

  • Simplify the rule (remove sub-rules)
  • Add stopBy: end to relational rules if not present
  • Use --debug-query to understand the AST structure (see below)
  • Check if kind values are correct for the language

Step 5: Search the Codebase

Once the rule matches the example code correctly, search the actual codebase:

For simple pattern searches:

`ast-grep run --pattern 'console.log($ARG)' --lang javascript /path/to/project
`

For complex rule-based searches:

`ast-grep scan --rule my_rule.yml /path/to/project
`

For inline rules (without creating files):

`ast-grep scan --inline-rules "id: my-rule
language: javascript
rule:
pattern: \$PATTERN" /path/to/project
`

ast-grep CLI Commands

Inspect Code Structure (--debug-query)

Dump the AST structure to understand how code is parsed:

`ast-grep run --pattern 'async function example() { await fetch(); }' \
--lang javascript \
--debug-query=cst
`

Available formats:

  • cst: Concrete Syntax Tree (shows all nodes including punctuation)
  • ast: Abstract Syntax Tree (shows only named nodes)
  • pattern: Shows how ast-grep interprets your pattern

Use this to:

  • Find the correct kind values for nodes
  • Understand the structure of code you want to match
  • Debug why patterns aren't matching

Example:

`# See the structure of your target code
ast-grep run --pattern 'class User { constructor() {} }' \
--lang javascript \
--debug-query=cst

# See how ast-grep interprets your pattern
ast-grep run --pattern 'class $NAME { $$$BODY }' \
--lang javascript \
--debug-query=pattern
`

Test Rules (scan with --stdin)

Test a rule against code snippet without creating files:

`echo "const x = await fetch();" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
pattern: await \$EXPR" --stdin
`

Add --json for structured output:

`echo "const x = await fetch();" | ast-grep scan --inline-rules "..." --stdin --json
`

Search with Patterns (run)

Simple pattern-based search for single AST node matches:

`# Basic pattern search
ast-grep run --pattern 'console.log($ARG)' --lang javascript .

# Search specific files
ast-grep run --pattern 'class $NAME' --lang python /path/to/project

# JSON output for programmatic use
ast-grep run --pattern 'function $NAME($$$)' --lang javascript --json .
`

When to use:

  • Simple, single-node matches
  • Quick searches without complex logic
  • When you don't need relational rules (inside/has)

Search with Rules (scan)

YAML rule-based search for complex structural queries:

`# With rule file
ast-grep scan --rule my_rule.yml /path/to/project

# With inline rules
ast-grep scan --inline-rules "id: find-async
language: javascript
rule:
kind: function_declaration
has:
pattern: await \$EXPR
stopBy: end" /path/to/project

# JSON output
ast-grep scan --rule my_rule.yml --json /path/to/project
`

When to use:

  • Complex structural searches
  • Relational rules (inside, has, precedes, follows)
  • Composite logic (all, any, not)
  • When you need the power of full YAML rules

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

Tips for Writing Effective Rules

Always Use stopBy: end

For relational rules, always use stopBy: end unless there's a specific reason not to:

`has:
pattern: await $EXPR
stopBy: end
`

This ensures the search traverses the entire subtree rather than stopping at the first non-matching node.

Start Simple, Then Add Complexity

Begin with the simplest rule that could work:

  • Try a pattern first
  • If that doesn't work, try kind to match the node type
  • Add relational rules (has, inside) as needed
  • Combine with composite rules (all, any, not) for complex logic

Use the Right Rule Type

  • Pattern: For simple, direct code matching (e.g., console.log($ARG))
  • Kind + Relational: For complex structures (e.g., "function containing await")
  • Composite: For logical combinations (e.g., "function with await but not in try-catch")

Debug with AST Inspection

When rules don't match:

  • Use --debug-query=cst to see the actual AST structure
  • Check if metavariables are being detected correctly
  • Verify the node kind matches what you expect
  • Ensure relational rules are searching in the right direction

Escaping in Inline Rules

When using --inline-rules, escape metavariables in shell commands:

  • Use \$VAR instead of $VAR (shell interprets $ as variable)
  • Or use single quotes: '$VAR' works in most shells

Example:

`# Correct: escaped $
ast-grep scan --inline-rules "rule: {pattern: 'console.log(\$ARG)'}" .

# Or use single quotes
ast-grep scan --inline-rules 'rule: {pattern: "console.log($ARG)"}' .
`

Common Use Cases

Find Functions with Specific Content

Find async functions that use await:

`ast-grep scan --inline-rules "id: async-await
language: javascript
rule:
all:
- kind: function_declaration
- has:
pattern: await \$EXPR
stopBy: end" /path/to/project
`

Find Code Inside Specific Contexts

Find console.log inside class methods:

`ast-grep scan --inline-rules "id: console-in-class
language: javascript
rule:
pattern: console.log(\$\$\$)
inside:
kind: method_definition
stopBy: end" /path/to/project
`

Find Code Missing Expected Patterns

Find async functions without try-catch:

`ast-grep scan --inline-rules "id: async-no-trycatch
language: javascript
rule:
all:
- kind: function_declaration
- has:
pattern: await \$EXPR
stopBy: end
- not:
has:
pattern: try { \$\$\$ } catch (\$E) { \$\$\$ }
stopBy: end" /path/to/project
`

Resources

references/

Contains detailed documentation for ast-grep rule syntax:

  • rule_reference.md: Comprehensive ast-grep rule documentation covering atomic rules, relational rules, composite rules, and metavariables

Load these references when detailed rule syntax information is needed.

Related Skills

azure-kustoby microsoftQuery and analyze data in Azure Data Explorer (Kusto/ADX) using KQL for log analytics, telemetry, and time series analysis. WHEN: KQL queries, Kusto database…aspireifyby microsoftOne-time skill for completing Aspire initialization in an existing app after aspire init has dropped the skeleton AppHost. Use this skill when an…sandbox-bridgeby cloudflareUse when you need to exercise a real, running Sandbox deployment via HTTP — for example to validate SDK changes against a live container, reproduce a…breakdown-epic-archby githubArchitectural planning prompt for translating product requirements into modular, scalable technical specifications. Generates comprehensive Epic Architecture Specifications in Markdown, including system diagrams, feature lists, and technology stack recommendations Enforces domain-driven design patterns with Docker containerization, TypeScript/Next.js, Turborepo monorepos, tRPC APIs, and Stack Auth authentication Produces Mermaid diagrams spanning user, application, service, data, and...write-api-referenceby vercelProduce an API reference page that documents a single API surface (function, component, file convention, directive, or config option). The page should be concise, scannable, and example-driven.recipe-watch-drive-changesby GoogleSubscribe to change notifications on a Google Drive file or folder.winapp-signingby microsoftCreate and manage code signing certificates for Windows apps and MSIX packages. Use when generating a certificate, signing a Windows app or installer, or…nekiby planetscaleOverview and information about Neki, the sharded Postgres product by PlanetScale. Load when working with Neki-related tasks and the need to scale or shard…

---

Source: https://github.com/ast-grep/agent-skill/tree/main/ast-grep/skills/ast-grep
Author: ast-grep
Discovered via: mcpservers.org

SKILL.md source

---
name: ast-grep
description: Guide for writing ast-grep rules to perform structural code search and analysis. Use when users need to search codebases using Abstract Syntax Tree (AST) patterns, find specific code structures, or...
---

# ast-grep

Guide for writing ast-grep rules to perform structural code search and analysis. Use when users need to search codebases using Abstract Syntax Tree (AST) patterns, find specific code structures, or perform complex code queries that go beyond simple text search.

# ast-grepby ast-grep
Guide for writing ast-grep rules to perform structural code search and analysis. Use when users need to search codebases using Abstract Syntax Tree (AST) patterns, find specific code structures, or perform complex code queries that go beyond simple text search.

`npx skills add https://github.com/ast-grep/agent-skill --skill ast-grep`Download ZIPGitHub

## ast-grep Code Search

## Overview

This skill helps translate natural language queries into ast-grep rules for structural code search. ast-grep uses Abstract Syntax Tree (AST) patterns to match code based on its structure rather than just text, enabling powerful and precise code search across large codebases.

## When to Use This Skill

Use this skill when users:

* Need to search for code patterns using structural matching (e.g., "find all async functions that don't have error handling")

* Want to locate specific language constructs (e.g., "find all function calls with specific parameters")

* Request searches that require understanding code structure rather than just text

* Ask to search for code with particular AST characteristics

* Need to perform complex code queries that traditional text search cannot handle

## General Workflow

Follow this process to help users write effective ast-grep rules:

### Step 1: Understand the Query

Clearly understand what the user wants to find. Ask clarifying questions if needed:

* What specific code pattern or structure are they looking for?

* Which programming language?

* Are there specific edge cases or variations to consider?

* What should be included or excluded from matches?

### Step 2: Create Example Code

Write a simple code snippet that represents what the user wants to match. Save this to a temporary file for testing.

Example:
If searching for "async functions that use await", create a test file:

```
`// test_example.js
async function example() {
const result = await fetchData();
return result;
}
`
```

### Step 3: Write the ast-grep Rule

Translate the pattern into an ast-grep rule. Start simple and add complexity as needed.

Key principles:

* Always use `stopBy: end` for relational rules (`inside`, `has`) to ensure search goes to the end of the direction

* Use `pattern` for simple structures

* Use `kind` with `has`/`inside` for complex structures

* Break complex queries into smaller sub-rules using `all`, `any`, or `not`

Example rule file (test_rule.yml):

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

See `references/rule_reference.md` for comprehensive rule documentation.

### Step 4: Test the Rule

Use ast-grep CLI to verify the rule matches the example code. There are two main approaches:

Option A: Test with inline rules (for quick iterations)

```
`echo "async function test() { await fetch(); }" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
kind: function_declaration
has:
pattern: await \$EXPR
stopBy: end" --stdin
`
```

Option B: Test with rule files (recommended for complex rules)

```
`ast-grep scan --rule test_rule.yml test_example.js
`
```

Debugging if no matches:

* Simplify the rule (remove sub-rules)

* Add `stopBy: end` to relational rules if not present

* Use `--debug-query` to understand the AST structure (see below)

* Check if `kind` values are correct for the language

### Step 5: Search the Codebase

Once the rule matches the example code correctly, search the actual codebase:

For simple pattern searches:

```
`ast-grep run --pattern 'console.log($ARG)' --lang javascript /path/to/project
`
```

For complex rule-based searches:

```
`ast-grep scan --rule my_rule.yml /path/to/project
`
```

For inline rules (without creating files):

```
`ast-grep scan --inline-rules "id: my-rule
language: javascript
rule:
pattern: \$PATTERN" /path/to/project
`
```

## ast-grep CLI Commands

### Inspect Code Structure (--debug-query)

Dump the AST structure to understand how code is parsed:

```
`ast-grep run --pattern 'async function example() { await fetch(); }' \
--lang javascript \
--debug-query=cst
`
```

Available formats:

* `cst`: Concrete Syntax Tree (shows all nodes including punctuation)

* `ast`: Abstract Syntax Tree (shows only named nodes)

* `pattern`: Shows how ast-grep interprets your pattern

Use this to:

* Find the correct `kind` values for nodes

* Understand the structure of code you want to match

* Debug why patterns aren't matching

Example:

```
`# See the structure of your target code
ast-grep run --pattern 'class User { constructor() {} }' \
--lang javascript \
--debug-query=cst

# See how ast-grep interprets your pattern
ast-grep run --pattern 'class $NAME { $$$BODY }' \
--lang javascript \
--debug-query=pattern
`
```

### Test Rules (scan with --stdin)

Test a rule against code snippet without creating files:

```
`echo "const x = await fetch();" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
pattern: await \$EXPR" --stdin
`
```

Add --json for structured output:

```
`echo "const x = await fetch();" | ast-grep scan --inline-rules "..." --stdin --json
`
```

### Search with Patterns (run)

Simple pattern-based search for single AST node matches:

```
`# Basic pattern search
ast-grep run --pattern 'console.log($ARG)' --lang javascript .

# Search specific files
ast-grep run --pattern 'class $NAME' --lang python /path/to/project

# JSON output for programmatic use
ast-grep run --pattern 'function $NAME($$$)' --lang javascript --json .
`
```

When to use:

* Simple, single-node matches

* Quick searches without complex logic

* When you don't need relational rules (inside/has)

### Search with Rules (scan)

YAML rule-based search for complex structural queries:

```
`# With rule file
ast-grep scan --rule my_rule.yml /path/to/project

# With inline rules
ast-grep scan --inline-rules "id: find-async
language: javascript
rule:
kind: function_declaration
has:
pattern: await \$EXPR
stopBy: end" /path/to/project

# JSON output
ast-grep scan --rule my_rule.yml --json /path/to/project
`
```

When to use:

* Complex structural searches

* Relational rules (inside, has, precedes, follows)

* Composite logic (all, any, not)

* When you need the power of full YAML rules

Tip: For relational rules (inside/has), always add `stopBy: end` to ensure complete traversal.

## Tips for Writing Effective Rules

### Always Use stopBy: end

For relational rules, always use `stopBy: end` unless there's a specific reason not to:

```
`has:
pattern: await $EXPR
stopBy: end
`
```

This ensures the search traverses the entire subtree rather than stopping at the first non-matching node.

### Start Simple, Then Add Complexity

Begin with the simplest rule that could work:

* Try a `pattern` first

* If that doesn't work, try `kind` to match the node type

* Add relational rules (`has`, `inside`) as needed

* Combine with composite rules (`all`, `any`, `not`) for complex logic

### Use the Right Rule Type

* Pattern: For simple, direct code matching (e.g., `console.log($ARG)`)

* Kind + Relational: For complex structures (e.g., "function containing await")

* Composite: For logical combinations (e.g., "function with await but not in try-catch")

### Debug with AST Inspection

When rules don't match:

* Use `--debug-query=cst` to see the actual AST structure

* Check if metavariables are being detected correctly

* Verify the node `kind` matches what you expect

* Ensure relational rules are searching in the right direction

### Escaping in Inline Rules

When using `--inline-rules`, escape metavariables in shell commands:

* Use `\$VAR` instead of `$VAR` (shell interprets `$` as variable)

* Or use single quotes: `'$VAR'` works in most shells

Example:

```
`# Correct: escaped $
ast-grep scan --inline-rules "rule: {pattern: 'console.log(\$ARG)'}" .

# Or use single quotes
ast-grep scan --inline-rules 'rule: {pattern: "console.log($ARG)"}' .
`
```

## Common Use Cases

### Find Functions with Specific Content

Find async functions that use await:

```
`ast-grep scan --inline-rules "id: async-await
language: javascript
rule:
all:
- kind: function_declaration
- has:
pattern: await \$EXPR
stopBy: end" /path/to/project
`
```

### Find Code Inside Specific Contexts

Find console.log inside class methods:

```
`ast-grep scan --inline-rules "id: console-in-class
language: javascript
rule:
pattern: console.log(\$\$\$)
inside:
kind: method_definition
stopBy: end" /path/to/project
`
```

### Find Code Missing Expected Patterns

Find async functions without try-catch:

```
`ast-grep scan --inline-rules "id: async-no-trycatch
language: javascript
rule:
all:
- kind: function_declaration
- has:
pattern: await \$EXPR
stopBy: end
- not:
has:
pattern: try { \$\$\$ } catch (\$E) { \$\$\$ }
stopBy: end" /path/to/project
`
```

## Resources

### references/

Contains detailed documentation for ast-grep rule syntax:

* `rule_reference.md`: Comprehensive ast-grep rule documentation covering atomic rules, relational rules, composite rules, and metavariables

Load these references when detailed rule syntax information is needed.

## Related Skills
azure-kustoby microsoftQuery and analyze data in Azure Data Explorer (Kusto/ADX) using KQL for log analytics, telemetry, and time series analysis. WHEN: KQL queries, Kusto database…aspireifyby microsoftOne-time skill for completing Aspire initialization in an existing app after `aspire init` has dropped the skeleton AppHost. Use this skill when an…sandbox-bridgeby cloudflareUse when you need to exercise a real, running Sandbox deployment via HTTP — for example to validate SDK changes against a live container, reproduce a…breakdown-epic-archby githubArchitectural planning prompt for translating product requirements into modular, scalable technical specifications. Generates comprehensive Epic Architecture Specifications in Markdown, including system diagrams, feature lists, and technology stack recommendations Enforces domain-driven design patterns with Docker containerization, TypeScript/Next.js, Turborepo monorepos, tRPC APIs, and Stack Auth authentication Produces Mermaid diagrams spanning user, application, service, data, and...write-api-referenceby vercelProduce an API reference page that documents a single API surface (function, component, file convention, directive, or config option). The page should be concise, scannable, and example-driven.recipe-watch-drive-changesby GoogleSubscribe to change notifications on a Google Drive file or folder.winapp-signingby microsoftCreate and manage code signing certificates for Windows apps and MSIX packages. Use when generating a certificate, signing a Windows app or installer, or…nekiby planetscaleOverview and information about Neki, the sharded Postgres product by PlanetScale. Load when working with Neki-related tasks and the need to scale or shard…

---

**Source**: https://github.com/ast-grep/agent-skill/tree/main/ast-grep/skills/ast-grep
**Author**: ast-grep
**Discovered via**: mcpservers.org

Related skills 6

caveman

★ Featured

Ultra-compressed communication mode. Cuts token usage ~75% by speaking like caveman while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra, wenyan-lite, wenyan-full, wenyan-ultra. Use when user says "caveman mode", "talk like caveman", "use caveman", "less tokens", "be brief", or invokes /caveman. Also auto-triggers when token efficiency is requested.

juliusbrussee 167k
Development

secure-linux-web-hosting

★ Featured

Use when setting up, hardening, or reviewing a cloud server for self-hosting, including DNS, SSH, firewalls, Nginx, static-site hosting, reverse-proxying an app, HTTPS with Let's Encrypt or ACME clients, safe HTTP-to-HTTPS redirects, or optional post-launch network tuning such as BBR.

xixu-me 155k
Development

readme-i18n

★ Featured

Use when the user wants to translate a repository README, make a repo multilingual, localize docs, add a language switcher, internationalize the README, or update localized README variants in a GitHub-style repository.

xixu-me 155k
Development

lark-shared

★ Featured

Use when first setting up lark-cli, running auth login, switching user/bot identity (--as), handling permission denied or scope errors, needing to update lark-cli, or seeing _notice in JSON output.

larksuite 155k
Development

improve-codebase-architecture

★ Featured

Find deepening opportunities in a codebase, informed by the domain language in CONTEXT.md and the decisions in docs/adr/. Use when the user wants to improve architecture, find refactoring opportunities, consolidate tightly-coupled modules, or make a codebase more testable and AI-navigable.

mattpocock 151k
Development

paper-context-resolver

★ Featured

Optional RigorPilot helper for README-first deep learning repo reproduction. Use only when the README and repository files leave a narrow reproduction-critical gap and the task is to resolve a specific paper detail such as dataset split, preprocessing, evaluation protocol, checkpoint mapping, or runtime assumption from primary paper sources while recording conflicts. Do not use for general paper summary, repo scanning, environment setup, command execution, title-only paper lookup, or replacin...

lllllllama 127k
Development