Skip to content
Development
Skill

/ast-grep

Searches and rewrites code by AST shape across 25 languages. Use when the target is a syntax pattern (every call/class/import shaped like X, a codemod, a YAML rule) rather than literal text; for plain strings, comments, or filenames, use rg.

From plugin
lazycodex
3.9k28 skills5 MCP

Claude Code

$ npx -y skills add code-yeongyu/lazycodex --skill ast-grep --agent claude-code

SKILL.md

ast-grep.SKILL.md
name: ast-grep
description: "Searches and rewrites code by AST shape across 25 languages. Use when the target is a syntax pattern (every call/class/import shaped like X, a codemod, a YAML rule) rather than literal text; for plain strings, comments, or filenames, use rg."

ast-grep

`sg` (also installed as `ast-grep`) is an **AST-aware search and rewrite tool** across 25 languages. It treats your pattern as code, parses it the same way it parses your project, and matches structurally. It is the right tool whenever your question depends on **code shape** rather than text bytes.

This skill ships a Python wrapper at `scripts/ast_grep_helper.py` and platform install scripts at `install.sh` (POSIX) and `install.ps1` (Windows). The helper adds offline pattern validation, the two-pass write trick, and binary auto-resolution. Use it as your default entry point.

---

OmO native: the ast-grep MCP tools (fastest path, no CLI needed)

OmO native also registers a bundled ast-grep MCP server. Its three tools are **deferred**: they are absent from the resident tool list and activate automatically the first time you call them by name — no `tool_search` round trip needed.

  • `mcp__ast_grep_search({ pattern, language, paths })` — AST-shape search, the MCP equivalent of `sg run -p`. Prefer this over shelling out to `sg` for one-off lookups: no install, no PATH issues.
  • `mcp__ast_grep_rewrite({ pattern, rewrite, language, paths, apply })` — preview matches (`apply: false`, the default) or apply the rewrite (`apply: true`). Same two-pass discipline as `sg run -r`: preview first, then apply.
  • `mcp__ast_grep_scan({ ruleFile | inlineRules, paths, apply })` — run exactly one explicit YAML rule source (a rule file or inline rules), the MCP equivalent of `sg scan --rule` / `--inline-rules`. It never discovers `sgconfig.yml`; to run a project's whole rule set, use `sg scan` (or the helper's `scan`) from the shell.

Same pattern language as the CLI: `$VAR` matches one AST node, `$$$VAR` matches zero or more, and the pattern is code, not regex. `paths` accepts a file or directory list; `language` is always required by `mcp__ast_grep_search` and `mcp__ast_grep_rewrite`.

---

When to use this skill

Use it whenever the user's question is about **code structure**, not bytes:

  • "Find every function that takes a `Request` parameter."
  • "Rewrite every `console.log(x)` to `logger.info(x)`."
  • "Strip every `as any` cast."
  • "Replace `require(...)` with `import` across the repo."
  • "Find empty catch blocks."
  • "Migrate `Optional[X]` to `X | None`."
  • "Apply this codemod across these 200 files."
  • "Run our YAML lint rules and surface violations."

Switch to plain `grep` / `rg` when the question is text-shaped (string literal contents, comments, license headers, file names, cross-language regex). When in doubt, ask: "does the answer depend on the language's syntax tree, or just on the file's bytes?" If the former, ast-grep. If the latter, grep.

---

Three things the agent must internalize

1. ast-grep is NOT regex

The wildcards are `$VAR` (one AST node) and `$$$` (zero or more nodes). Regex syntax fails silently:

| You wrote | What ast-grep saw | What you wanted | |---|---|---| | `foo\|bar` | bitwise-or of `foo` and `bar` | run two separate searches | | `.*foo` | not parseable | `$$$ foo` (if `$$$` is a list of nodes) or use `rg` | | `\w+` | not parseable | `$VAR` to capture any identifier | | `[a-z]` | character class, not parseable | switch to `rg` |

The full anti-pattern table is in `references/pitfalls.md` §1. The helper's `validate` subcommand catches these mechanically — call it before debugging "no matches" by hand.

2. Patterns must be valid code

The pattern itself must parse. `def $FN($$$):` fails because the trailing `:` makes it incomplete; use `def $FN($$$)`. `function $NAME` without params/body fails; use `function $NAME($$$) { $$$ }`. Full table per language in `references/pitfalls.md` §2.

3. `--update-all` and `--json` are mutually exclusive (silently)

This is the single biggest gotcha when scripting. `sg run -p P -r R --json --update-all` returns the JSON but **does not mutate files**. To both preview AND apply, run **two passes**:

sg run -p P -r R --json=compact .   # pass 1: see what would change
sg run -p P -r R --update-all .     # pass 2: actually apply

The helper does this automatically when you call `replace --apply`. Read `references/pitfalls.md` §9.

---

The helper script — `scripts/ast_grep_helper.py`

A single-file Python 3 stdlib wrapper. Same on every OS. The agent's default entry point.

`search` — find all matches of a pattern

python3 scripts/ast_grep_helper.py search 'console.log($MSG)' src/ --lang ts

Validates the pattern offline first. If the pattern looks like regex (`\w`, `.*`, `|`, etc.) the helper exits with a hint and never calls `sg` — saves a round-trip. Pass `--force` to skip validation.

Flags:

  • `--lang ts` (or any of the 25 languages; aliases like `js`, `py`, `rs`, `kt` accepted)
  • `--globs '!**/*.test.ts'` (repeatable; prefix `!` to exclude)
  • `-C 3` (context lines)
  • `--json-out` (raw JSON instead of human format)

`replace` — rewrite by pattern, dry-run by default

# Dry-run preview (default — no files mutated)
python3 scripts/ast_grep_helper.py replace 'console.log($MSG)' 'logger.info($MSG)' src/ --lang ts

# Actually apply
python3 scripts/ast_grep_helper.py replace 'console.log($MSG)' 'logger.info($MSG)' src/ --lang ts --apply

The helper: 1. Validates both `pattern` and `rewrite` for hint-detectable mistakes. 2. Runs pass 1 with `--json=compact` to collect matches and show a preview. 3. If `--apply` is set, runs pass 2 with `--update-all` to mutate files.

`scan` — run YAML rules

# Discover sgconfig.yml from cwd and run all rules
python3 scripts/ast_grep_helper.py scan src/

# Run a single rule file
python3 scripts/ast_grep_helper.py scan -r rules/no-console.yml src/

# A
Read more
@code-yeongyu
Ships withlazycodex

The one and only agent harness for complex codebases. Project memory, planning, execution, and verified completion inside Codex.

3.9k28 skills5 MCP
Get the whole plugin

Stars on GitHub

Momentum

stars in total
3.9k
Star history of code-yeongyu/lazycodex on GitHub, a chart by star-history.com

Other skills on lazycodex.

comment-checker

comment-checker

Use when Codex needs to understand or respond to automatic comment-checker feedback emitted after an edit-like PostToolUse hook.

lcx-doctor

lcx-doctor

Diagnose LazyCodex and Codex CLI installation health against the latest sources. Use whenever the user asks for a doctor or…

lcx-report-bug

lcx-report-bug

Create a high-signal bug issue or PR in the repo that owns the defect. Use this whenever the user asks to report, file, open, or…

lsp

lsp

Use when Codex needs language-server diagnostics, definitions, references, symbols, or rename safety checks in the current…

rules

rules

Use when the user asks about Codex Rules behavior, injected project rules, supported rule file locations, matching, or…

More skills from other plugins.

brainstorming
Auto-invoked

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or…

@obra@obraInstall Skill
ask-matt

ask-matt

Ask which skill or flow fits your situation. A router over the skills in this repo.

skills13d309k
@mattpocock@mattpocockInstall Skill
accessibility
Auto-invoked

accessibility

Design, implement, and audit accessible UI to WCAG 2.2 Level AA across Web, iOS, and Android — semantic ARIA roles and labels,…

ecc2w293k
@affaan-m@affaan-mInstall Skill
compiler-commit

compiler-commit

Use when you want to verify compiler changes and commit with the correct convention. Runs tests, lint, and format, then commits…

react3d252k
@facebook@facebookInstall Skill

Questions about ast-grep.

Which coding agents can use ast-grep?
ast-grep installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.