name: ast-grep-find description: 基于AST的代码搜索和重构 via ast-grep MCP allowed-tools: [Bash, Read]
AST-Grep 查找
理解语法的结构化代码搜索。查找模式如函数调用、导入、类定义 - 不仅仅是文本。
何时使用
- 查找代码模式(忽略字符串/注释)
- 搜索函数调用、类定义、导入
- 使用AST精度重构代码
- 在代码库中重命名变量/函数
使用方式
搜索模式
uv run python -m runtime.harness scripts/ast_grep_find.py \
--pattern "import asyncio" --language python
在特定目录搜索
uv run python -m runtime.harness scripts/ast_grep_find.py \
--pattern "async def \$FUNC(\$\$\$)" --language python --path "./src"
重构/替换模式
uv run python -m runtime.harness scripts/ast_grep_find.py \
--pattern "console.log(\$MSG)" --replace "logger.info(\$MSG)" \
--language javascript
干运行(预览更改)
uv run python -m runtime.harness scripts/ast_grep_find.py \
--pattern "print(\$X)" --replace "logger.info(\$X)" \
--language python --dry-run
参数
| 参数 | 描述 |
|---|---|
--pattern |
要搜索的AST模式(必需) |
--language |
语言:python、javascript、typescript、go等 |
--path |
搜索目录(默认:.) |
--glob |
文件glob模式(例如:**/*.py) |
--replace |
用于重构的替换模式 |
--dry-run |
预览更改而不应用 |
--context |
上下文行数(默认:2) |
模式语法
| 语法 | 含义 |
|---|---|
$NAME |
匹配单个节点(变量、表达式) |
$$$ |
匹配多个节点(参数、语句) |
$_ |
匹配任何单个节点(通配符) |
示例
# 查找所有函数定义
uv run python -m runtime.harness scripts/ast_grep_find.py \
--pattern "def \$FUNC(\$\$\$):" --language python
# 查找console.log调用
uv run python -m runtime.harness scripts/ast_grep_find.py \
--pattern "console.log(\$\$\$)" --language javascript
# 用logging替换print
uv run python -m runtime.harness scripts/ast_grep_find.py \
--pattern "print(\$X)" --replace "logging.info(\$X)" \
--language python --dry-run
与morph/warpgrep对比
| 工具 | 最佳用途 |
|---|---|
| ast-grep | 结构化模式(理解代码语法) |
| warpgrep | 快速文本/正则搜索(比grep快20倍) |
当需要语法感知匹配时使用ast-grep。当需要原始速度时使用warpgrep。
需要MCP服务器
需要在mcp_config.json中配置ast-grep服务器。