moai-tool-ast-grep
БесплатноБез исполняемых скриптовНе проверенAST-based structural code search, security scanning, and refactoring using ast-grep (sg CLI) with pattern matching and code transformation across 40+…
Об этом скилле
AST-Grep Integration
Structural code search, lint, and transformation tool using Abstract Syntax Tree analysis.
Quick Reference
What is AST-Grep
AST-Grep (sg) is a fast, polyglot tool for structural code search and transformation. Unlike regex-based search, it understands code syntax and matches patterns based on AST structure.
When to Use
- Searching for code patterns that regex cannot capture such as nested function calls
- Refactoring code across multiple files with semantic awareness
- Security scanning for vulnerability patterns including SQL injection and XSS
- API migration and deprecation handling
- Enforcing code style rules at the syntax level
Core Commands
Pattern search: Execute sg run with pattern option specifying the code pattern to find, lang option for the programming language, and the source directory path.
Security scan with rules: Execute sg scan with config option pointing to your sgconfig.yml file.
Code transformation: Execute sg run with pattern option for the code to find, rewrite option for the replacement, lang option for the language, and source directory path.
Test rules: Execute sg test to validate your rule definitions.
Pattern Syntax Basics
The dollar sign followed by a variable name such as VAR matches any single AST node and acts as a meta-variable for capturing.
The dollar sign followed by three dollar signs and a variable name such as ARGS matches zero or more nodes using variadic capture.
The double dollar sign followed by underscore matches any single node as an anonymous capture when the value is not needed.
Supported Languages
Python, JavaScript, TypeScript, Go, Rust, Java, Kotlin, C, C++, Ruby, Swift, C#, PHP, Scala, Elixir, Lua, HTML, Vue, Svelte, and 30+ more.
Implementation Guide
Installation
For macOS, use brew install ast-grep.
For cross-platform via npm, use npm install -g @ast-grep/cli.
For Rust via Cargo, use cargo install ast-grep.
Basic Pattern Matching
Simple Pattern Search
To find all console.log calls, run sg with pattern console.log($MSG) and lang javascript.
To find all Python function definitions, run sg with pattern def $FUNC($$$ARGS): $$$BODY and lang python.
To find React useState hooks, run sg with pattern useState($INIT) and lang tsx.
Explore/Search Performance Optimization
AST-Grep provides significant performance benefits for codebase exploration compared to text-based search:
Why AST-Grep is Faster for Exploration
- Structural understanding eliminates false positives (50-80% reduction in irrelevant results)
- Syntax-aware matching reduces full file scans
- Single pass through AST vs multiple regex passes
Common Exploration Patterns
Find all function calls matching a pattern:
sg -p 'authenticate($$$)' --lang python -r src/
Find all classes inheriting from a base class:
sg -p 'class $A extends BaseService' --lang python -r src/
Find specific import patterns:
sg -p 'import fastapi' --lang python -r src/
Find React hooks usage:
sg -p 'useState($$)' --lang tsx -r src/
Find async function declarations:
sg -p 'async def $NAME($$$ARGS):' --lang python -r src/
Performance Comparison
grep -r "class.*Service" src/- scans all files textually (~10s for large codebase)sg -p 'class $X extends Service' --lang python -r src/- structural match (~2s)
Integration with Explore Agent When using the Explore agent, AST-Grep is automatically prioritized for:
- Class hierarchy analysis
- Function signature matching
- Import dependency mapping
- API usage pattern detection
Meta-variables
Meta-variables capture matching AST nodes in patterns.
Single node capture uses $NAME syntax. For example, pattern const $NAME = require($PATH) captures the variable name and path.
Variadic capture uses $$$ARGS syntax. For example, pattern function $NAME($$$ARGS) captures function name and all arguments.
Anonymous single capture uses $$_ syntax when you need to match but not reference the value.
Code Transformation
Simple Rewrite
To rename a function, run sg with pattern oldFunc($ARGS), rewrite newFunc($ARGS), and lang python.
To update an API call, run sg with pattern axios.get($URL), rewrite fetch($URL), and lang typescript.
Complex Transformation with YAML Rules
Create a YAML rule file with the following structure. Set the id field to a unique rule identifier such as convert-var-to-const. Set language to the target language such as javascript. Under the rule section, specify the pattern to match such as var $NAME = $VALUE. Set the fix field to the replacement pattern such as const $NAME = $VALUE. Add a message describing the issue and set severity to warning or error.
Run sg scan with the rule option pointing to your rule file and the source directory.
Rule-Based Scanning
Configuration File
Create an sgconfig.yml file with the following sections. The ruleDirs section li
Установить moai-tool-ast-grep в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobBash(sg:*)Bash(ast-grep:*)mcp__context7__resolve-library-idmcp__context7__get-library-docsВложенные файлы
FAQ
Что делает скилл moai-tool-ast-grep?
AST-based structural code search, security scanning, and refactoring using ast-grep (sg CLI) with pattern matching and code transformation across 40+ languages. Use when performing structural code search, AST-based refactoring, codemod operations, security pattern scanning, or syntax-aware code transformations across files. Do NOT use for simple text search (use Grep tool instead) or full codebase exploration (use Explore agent instead).
Как установить скилл moai-tool-ast-grep?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл moai-tool-ast-grep запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic