重要前提
安装AI Skills的关键前提是:必须科学上网,且开启TUN模式,这一点至关重要,直接决定安装能否顺利完成,在此郑重提醒三遍:科学上网,科学上网,科学上网。查看完整安装教程 →
moai-tool-ast-grep by modu-ai/moai-adk
npx skills add https://github.com/modu-ai/moai-adk --skill moai-tool-ast-grep基于抽象语法树分析的结构化代码搜索、检查与转换工具。
AST-Grep (sg) 是一款快速、多语言的工具,用于结构化代码搜索和转换。与基于正则表达式的搜索不同,它能理解代码语法并根据 AST 结构匹配模式。
模式搜索:执行 sg run,使用 pattern 选项指定要查找的代码模式,lang 选项指定编程语言,以及源代码目录路径。
使用规则进行安全扫描:执行 sg scan,使用 config 选项指向您的 sgconfig.yml 文件。
代码转换:执行 sg run,使用 选项指定要查找的代码, 选项指定替换内容, 选项指定语言,以及源代码目录路径。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
patternrewritelang测试规则:执行 sg test 以验证您的规则定义。
美元符号后跟变量名(例如 $VAR)匹配任意单个 AST 节点,并作为捕获的元变量。
美元符号后跟三个美元符号和变量名(例如 $$$ARGS)使用可变参数捕获匹配零个或多个节点。
双美元符号后跟下划线($$_)匹配任意单个节点作为匿名捕获,当不需要该值时使用。
Python, JavaScript, TypeScript, Go, Rust, Java, Kotlin, C, C++, Ruby, Swift, C#, PHP, Scala, Elixir, Lua, HTML, Vue, Svelte 以及 30 多种其他语言。
对于 macOS,使用 brew install ast-grep。
对于通过 npm 跨平台安装,使用 npm install -g @ast-grep/cli。
对于通过 Cargo 安装 Rust 版本,使用 cargo install ast-grep。
要查找所有 console.log 调用,运行 sg,使用 pattern console.log($MSG) 和 lang javascript。
要查找所有 Python 函数定义,运行 sg,使用 pattern def $FUNC($$$ARGS): $$$BODY 和 lang python。
要查找 React useState 钩子,运行 sg,使用 pattern useState($INIT) 和 lang tsx。
与基于文本的搜索相比,AST-Grep 为代码库探索提供了显著的性能优势:
为何 AST-Grep 在探索中更快
常见的探索模式
查找匹配模式的所有函数调用:
sg -p 'authenticate($$$)' --lang python -r src/
查找继承自基类的所有类:
sg -p 'class $A extends BaseService' --lang python -r src/
查找特定的导入模式:
sg -p 'import fastapi' --lang python -r src/
查找 React 钩子使用情况:
sg -p 'useState($$)' --lang tsx -r src/
查找异步函数声明:
sg -p 'async def $NAME($$$ARGS):' --lang python -r src/
性能对比
grep -r "class.*Service" src/ - 以文本方式扫描所有文件(大型代码库约需 10 秒)sg -p 'class $X extends Service' --lang python -r src/ - 结构化匹配(约需 2 秒)与探索代理集成 当使用探索代理时,AST-Grep 会自动优先用于:
元变量在模式中捕获匹配的 AST 节点。
单节点捕获使用 $NAME 语法。例如,模式 const $NAME = require($PATH) 捕获变量名和路径。
可变参数捕获使用 $$$ARGS 语法。例如,模式 function $NAME($$$ARGS) 捕获函数名和所有参数。
匿名单节点捕获使用 $$_ 语法,当您需要匹配但不引用该值时使用。
要重命名函数,运行 sg,使用 pattern oldFunc($ARGS)、rewrite newFunc($ARGS) 和 lang python。
要更新 API 调用,运行 sg,使用 pattern axios.get($URL)、rewrite fetch($URL) 和 lang typescript。
创建一个具有以下结构的 YAML 规则文件。将 id 字段设置为唯一的规则标识符,例如 convert-var-to-const。将 language 设置为目标语言,例如 javascript。在 rule 部分下,指定要匹配的模式,例如 var $NAME = $VALUE。将 fix 字段设置为替换模式,例如 const $NAME = $VALUE。添加一条描述问题的消息,并将 severity 设置为 warning 或 error。
运行 sg scan,使用 rule 选项指向您的规则文件和源代码目录。
创建一个 sgconfig.yml 文件,包含以下部分。ruleDirs 部分列出了包含规则文件的目录,例如 ./rules/security 和 ./rules/quality。testConfigs 部分指定测试文件模式。languageGlobs 部分将语言映射到文件模式,例如将 python 映射到 .py 文件,typescript 映射到 .ts 和 .tsx 文件,javascript 映射到 .js 和 .jsx 文件。
创建一个用于 SQL 注入检测的安全规则文件。将 id 设置为 sql-injection-risk。将 language 设置为 python,severity 设置为 error。编写一条描述漏洞的消息。在 rule 部分下,使用 any 操作符来匹配多个模式,包括使用百分号格式化的 cursor.execute、使用 format 方法的 cursor.execute 以及使用 f-string 插值的 cursor.execute。将 fix 设置为显示参数化查询的替代方案。
创建一个规则,仅在函数声明内部搜索 console.log 调用。将模式设置为 console.log($$$ARGS),并添加一个带有模式 function $NAME($$$PARAMS) 的 inside 约束。
创建一个规则来查找没有 await 的异步函数。将模式设置为 async function $NAME($$$PARAMS),并添加一个包含带有模式 await $EXPR 的 has 规则的 not 约束。添加一条消息,指示异步函数缺少 await。
创建一个规则来检测缺失的错误处理。将模式设置为匹配错误赋值 $ERR := $CALL,并添加一个带有 follows 规则的 not 约束,该规则检查 if $ERR != nil 错误处理块。
使用 all 操作符创建组合多个条件的复杂规则。例如,将模式 useState($INIT) 与针对函数组件的 inside 约束以及针对 useEffect 调用的 not precedes 约束结合起来。
有关全面的文档,包括复杂的多文件转换、自定义语言配置、CI/CD 集成模式和性能优化技巧,请参阅以下模块文件。
模式语法参考可在 modules/pattern-syntax.md 中找到。
安全扫描规则模板记录在 modules/security-rules.md 中。
常见的重构模式涵盖在 modules/refactoring-patterns.md 中。
特定于语言的模式在 modules/language-specific.md 中有详细说明。
要获取最新的 AST-Grep 文档,请遵循以下两步流程。
步骤 1:使用 mcp__context7__resolve-library-id,查询 ast-grep 以解析库标识符。
步骤 2:使用 mcp__context7__get-library-docs 和解析出的库 ID 来获取当前文档。
AST-Grep 通过以下方式集成到 MoAI-ADK 中:在 internal/hook/registry.go 中作为 AST_ANALYZER 类型注册到工具注册表,用于在 Write/Edit 操作后自动进行安全扫描的 PostToolUse 钩子,以及自动允许 Bash(sg:_) 和 Bash(ast-grep:_) 的权限。
要使用 MoAI-ADK 规则进行扫描,执行 sg scan,使用 config 指向 .claude/skills/moai-tool-ast-grep/rules/sgconfig.yml。
要扫描特定目录,执行 sg scan,使用 config sgconfig.yml 和 src/ 目录。
对于适合 CI/CD 的 JSON 输出,执行 sg scan,使用 config 和 json 标志,并重定向到 results.json。
如需更多信息,请查阅 AST-Grep 官方文档 ast-grep.github.io、AST-Grep GitHub 仓库 github.com/ast-grep/ast-grep、模式演练场 ast-grep.github.io/playground.html 以及规则配置参考 ast-grep.github.io/reference/yaml.html。
每周安装次数
57
仓库
GitHub 星标数
888
首次出现
2026年1月22日
安全审计
安装于
codex47
opencode47
gemini-cli45
claude-code45
cursor43
antigravity42
Structural code search, lint, and transformation tool using Abstract Syntax Tree analysis.
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.
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.
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.
Python, JavaScript, TypeScript, Go, Rust, Java, Kotlin, C, C++, Ruby, Swift, C#, PHP, Scala, Elixir, Lua, HTML, Vue, Svelte, and 30+ more.
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.
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.
AST-Grep provides significant performance benefits for codebase exploration compared to text-based search:
Why AST-Grep is Faster for Exploration
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:
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.
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.
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.
Create an sgconfig.yml file with the following sections. The ruleDirs section lists directories containing rule files such as ./rules/security and ./rules/quality. The testConfigs section specifies test file patterns. The languageGlobs section maps languages to file patterns, mapping python to .py files, typescript to .ts and .tsx files, and javascript to .js and .jsx files.
Create a security rule file for SQL injection detection. Set the id to sql-injection-risk. Set language to python and severity to error. Write a descriptive message about the vulnerability. Under the rule section, use the any operator to match multiple patterns including cursor.execute with percent formatting, cursor.execute with format method, and cursor.execute with f-string interpolation. Set the fix to show the parameterized query alternative.
Create a rule that searches for console.log calls only inside function declarations. Set the pattern to console.log($$$ARGS) and add an inside constraint with pattern function $NAME($$$PARAMS).
Create a rule to find async functions without await. Set the pattern to async function $NAME($$$PARAMS) with a not constraint containing a has rule with pattern await $EXPR. Add message indicating async function without await.
Create a rule to detect missing error handling. Set the pattern to match error assignment $ERR := $CALL and add a not constraint with follows rule checking for if $ERR != nil error handling block.
Create complex rules using the all operator to combine multiple conditions. For example, combine pattern useState($INIT) with inside constraint for function component and not precedes constraint for useEffect call.
For comprehensive documentation including complex multi-file transformations, custom language configuration, CI/CD integration patterns, and performance optimization tips, see the following module files.
Pattern syntax reference is available in modules/pattern-syntax.md.
Security scanning rule templates are documented in modules/security-rules.md.
Common refactoring patterns are covered in modules/refactoring-patterns.md.
Language-specific patterns are detailed in modules/language-specific.md.
For latest AST-Grep documentation, follow this two-step process.
Step 1: Use mcp__context7__resolve-library-id with query ast-grep to resolve the library identifier.
Step 2: Use mcp__context7__get-library-docs with the resolved library ID to fetch current documentation.
AST-Grep is integrated into MoAI-ADK through the Tool Registry as AST_ANALYZER type in internal/hook/registry.go, PostToolUse Hook for automatic security scanning after Write/Edit operations, and Permissions with Bash(sg:) and Bash(ast-grep:) auto-allowed.
To scan with MoAI-ADK rules, execute sg scan with config pointing to .claude/skills/moai-tool-ast-grep/rules/sgconfig.yml.
To scan a specific directory, execute sg scan with config sgconfig.yml and the src/ directory.
For JSON output suitable for CI/CD, execute sg scan with config and json flag, redirecting to results.json.
For additional information, consult the AST-Grep Official Documentation at ast-grep.github.io, the AST-Grep GitHub Repository at github.com/ast-grep/ast-grep, the Pattern Playground at ast-grep.github.io/playground.html, and the Rule Configuration Reference at ast-grep.github.io/reference/yaml.html.
Weekly Installs
57
Repository
GitHub Stars
888
First Seen
Jan 22, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykWarn
Installed on
codex47
opencode47
gemini-cli45
claude-code45
cursor43
antigravity42
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
123,700 周安装
Eve 部署与调试指南:快速诊断应用问题,掌握基础设施变更与流水线部署
221 周安装
Elastic APM 服务健康评估指南:使用 Observability APIs 与 ES|QL 监控 SLO、延迟、错误率
240 周安装
AWS DynamoDB 单表设计指南:NoSQL 数据库建模与 TypeScript/Python SDK 实战
225 周安装
Auth0 Express 集成指南:为 Express.js 应用快速添加身份验证
220 周安装
OAuth 2.0与OpenID Connect完整实现指南:JWT令牌、安全会话与最佳实践
218 周安装
WordPress WooCommerce开发工作流:AI集成、支付配置与商店优化
57 周安装