Mmcp.market

ast-grep skill

by code-yeongyu·code-yeongyu/oh-my-openagent·70k stars

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.

A90/100content scan

Is the ast-grep skill safe?

Clean: nothing in its files matched our rules. We read 17 files in the folder on 2026-09-28.

  • mediumreferences/cli.md:196

    Edits shell startup files, cron or launch agents, so something runs again after the skill is done.

    sg completions bash >> ~/.bashrc

Install the ast-grep skill

A skill is a folder. Copy it into your agent's skills folder and the agent loads it when the task matches its description.

git clone --depth 1 https://github.com/code-yeongyu/oh-my-openagent.git /tmp/oh-my-openagent
mkdir -p ~/.claude/skills
cp -r /tmp/oh-my-openagent/packages/shared-skills/skills/ast-grep ~/.claude/skills/ast-grep
available in every project

In the Claude apps, zip the folder and upload it from the Skills settings. The folder on GitHub

The instructions your agent would load

SKILL.md as published, without the frontmatter. Read it on GitHub

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/astgrephelper.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.

  • mcpastgrep_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.
  • mcpastgrep_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.
  • mcpastgrep_scan({ paths }) — run project YAML rules (sgconfig.yml, rules/), the MCP equivalent of sg scan.

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 required for patterns that are ambiguous across languages.

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:

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/astgrephelper.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)' --lang ts src/

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)' --lang ts src/

# Actually apply
python3 scripts/ast_grep_helper.py replace 'console.log($MSG)' 'logger.info($MSG)' --lang ts src/ --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/

# Apply auto-fixes
python3 scripts/ast_grep_helper.py scan -U src/

# CI-friendly GitHub annotations
python3 scripts/ast_grep_helper.py scan --report-style short src/

validate — offline pattern check (no sg call)

Useful for CI lints, pre-commit hooks, and quick sanity checks:

python3 scripts/ast_grep_helper.py validate '\w+' --lang ts
# → exit 2: regex \w not supported. Use $VAR for identifiers.

python3 scripts/ast_grep_helper.py validate 'console.log($MSG)' --lang ts
# → exit 0: pattern looks plausible for ast-grep.

langs / doctor / install

python3 scripts/ast_grep_helper.py langs       # list 25 supported languages and aliases
python3 scripts/ast_grep_helper.py doctor      # check ast-grep binary availability
python3 scripts/ast_grep_helper.py install     # delegate to install.sh / install.ps1

new and test subcommands proxy directly to sg new and sg test.

Direct sg use (when the helper isn't enough)

The helper is opinionated. For full control, drop to sg. The skill ships a CLI cheat sheet in references/cli.md. The minimal idioms:

# Search
sg run -p 'console.log($MSG)' --lang ts src/

# Search with JSON for scripting
sg run -p 'console.log($MSG)' --lang ts --json=compact src/ | jq '.[] | .file'

# Rewrite, dry-run
sg run -p 'console.log($MSG)' -r 'logger.info($MSG)' --lang ts --json=compact src/

# Rewrite, apply
sg run -p 'console.log($MSG)' -r 'logger.info($MSG)' --lang ts --update-all src/

# Pattern from stdin (great for ad-hoc experiments)
echo 'console.log("hi")' | sg run -p 'console.log($MSG)' --lang js --stdin

# Debug a pattern that returns 0 matches
sg run -p '<your pattern>' --lang <lang> --debug-query=ast --stdin <<< '<sample-code>'

# Run YAML rules
sg scan src/

# Inline YAML rule (one-off)
sg scan --inline-rules '
id: no-todo
language: TypeScript
severity: warning
rule: { pattern: TODO }' src/

When using sg directly in a shell, always single-quote patterns so $VAR is not expanded by the shell.

Decision tree — what to use, when

USER asks for "find/rewrite/codemod"
│
├─ structural pattern (function shape, call, class, import, control flow)
│  └→ ast-grep (this skill)
│
├─ text pattern (regex, alternation, character classes, file names)
│  └→ rg / grep
│
├─ semantic question (what variable does this refer to? does this throw?)
│  └→ LSP tools, TypeScript compiler, Pyright, Semgrep with type inference
│
└─ multiple repos / federated search
   └→ a search engine + then ast-grep / rg / LSP per-repo

If the user says "find all" or "every", default to ast-grep when the target is shaped (function, class, call, import, statement). Default to rg when the target is text (string content, comment, license header, file name, identifier substring).

Always run dry-run first when rewriting

A bad pattern silently rewrites the wrong thing. The helper's replace defaults to dry-run for this reason. The flow is:

  1. Search to confirm matches: helper search '' --lang X .
  2. Dry-run rewrite: helper replace '' '' --lang X . (no --apply)
  3. Inspect the dry-run summary: number of matches, files affected, the per-location preview.
  4. If wrong: refine pattern, go back to step 1.
  5. If right: helper replace '' '' --lang X . --apply.

Never apply a rewrite that you have not first dry-run.

When sg returns 0 matches but you know the code is there

In priority order:

  1. Run helper validate '' --lang — catches regex misuse, missing function bodies, Python trailing colons.
  2. Check --lang — sg infers from extension; if you pass a .tsx file with --lang ts (not tsx), JSX won't parse.
  3. Inspect the parsed pattern: sg run -p '' --lang --debug-query=ast --stdin <<< ''. If it shows ERROR nodes, the pattern is malformed.
  4. Check the AST of the target file: sg run -p '$_' --lang --debug-query=cst path/to/file | head -40 — find the kind you're trying to match.
  5. Try the playground: — paste code + pattern, see what's happening.

Do not blindly retry with variations. Each failure has a reason; surface it.

When to use YAML rules vs inline -p patterns

Use inline -p when:

  • One-off ad-hoc query.
  • The pattern is simple (no constraints, no fix template).
  • You're exploring.

Use YAML rules (file under rules/, run via sg scan) when:

  • The pattern is reused (lint rule, codemod that runs in CI).
  • You need constraints, transform, complex inside/has, or composite logic.
  • You want auto-fix (fix: field).
  • You want to test the rule (snapshot tests via sg test).

More skills from code-yeongyu/oh-my-openagent

  • AbrowserDrives a real browser through the omowright library from the js eval kernel: sites the user is already signed into, forms and clicks, JS-rendered pages, screenshots, web QA, extension popups, a human handoff for login, CAPTCHA or OTP, and a browser you own for scraping, bot-scored targets, network capture and QA traces. Use for any interactive browser task; not for a plain search or an unblocked static fetch.
  • Acodex-qaQA the omo Codex Light edition (lazycodex / packages/omo-codex) itself, in strict isolation so ONLY our plugin is exercised, never the user's real ~/.codex. The first-party method drives the real `codex app-server` against an isolated CODEX_HOME plus a LOCAL mock model (no real API call), and proves a plugin hook fired by asserting hook/started + hook/completed notifications. Also: isolated install verification, per-component hook probes, a tmux TUI smoke, and runtime log observation (RUST_LOG / logs SQLite / /debug-config). Ships tested helper scripts each with a --self-test. Use whenever someone changes anything under packages/omo-codex or wants to QA, smoke-test, verify, or debug the Codex plugin, its hooks/components, the installer/config.toml, the app-server flow, or the Codex TUI. Triggers: codex qa, qa codex, codex-qa, test codex plugin, verify codex hook, codex app-server, lazycodex qa, isolated CODEX_HOME, prove codex hook fired, codex tui test.
  • Acoding-agent-sessionsFinds, reads, and reconstructs coding-agent sessions across Codex, Claude, OpenCode, OMO/Senpi, and other local agent logs. Use when asked to find or search past sessions, transcripts, or subagent runs, or to recover what an earlier session did.
  • Acomment-checkerUse when Codex needs to understand or respond to automatic comment-checker feedback emitted after an edit-like PostToolUse hook.
  • Adag-libraryStores a DAG definition once and re-runs it by name, instead of pasting the definition into every run. Use when the user wants to save a DAG, run a saved one, or schedule the same multi-agent graph repeatedly.
  • Ddata-scientistProcesses and analyzes data with resident-kernel engines (DuckDB, Polars) and one-shot tools. Use for CSV/parquet/JSON analysis, group-by/join/aggregation, time series, distributions, cleaning, or plotting a dataset.
  • AdebuggingRuns a hypothesis-driven debugging loop across any language or binary, escalating to orthogonal oracle angles and locking the fix with a failing test. Use for crashes, silent failures, hangs, wrong responses, memory leaks, async misbehavior, or reverse engineering.
  • Adev-browserBrowser automation with persistent page state. Use when users ask to navigate websites, fill forms, take screenshots, extract web data, test web apps, or automate browser workflows. Trigger phrases include "go to [url]", "click on", "fill out the form", "take a screenshot", "scrape", "automate", "test the website", "log into", or any browser interaction request.
  • CfrontendBuilds, styles, and polishes web UI and UX. Use for any frontend, page, component, styling, layout, animation, or visual-quality task, or when asked to make an interface look or feel a certain way.
  • AfrontendBuilds, styles, and polishes web UI and UX. Use for any frontend, page, component, styling, layout, animation, or visual-quality task, or when asked to make an interface look or feel a certain way.
  • Aget-unpublished-changesCompare HEAD with the latest published npm versions and list all unpublished changes by release layer. Triggers: unpublished changes, changelog, what changed, whats new.
  • Agit-masterHandles git work: atomic commits, rebase, squash, blame, bisect, reflog, and history questions. Use whenever a task needs a commit or a git-history investigation; skip for ordinary code edits.

All agent skills → · MCP servers