ast-grep MCP Server
ThinkDonk/ast-grep-mcp
Busca e refatore código via padrões AST, não regex
Ver no GitHubServidor MCP que integra ast-grep para buscas e substituições de código baseadas em AST (Abstract Syntax Tree) em 26 linguagens. Otimizado para IA com proteção contra path traversal, sandboxing de workspace e modo dry-run seguro para refatorações.
Instalação
npx convez-ai ThinkDonk/ast-grep-mcp1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
Casos de uso
- Refatoração de código em larga escala mantendo semântica
- Busca de padrões de código específicos em múltiplos arquivos
- Migração de APIs ou mudanças de nomenclatura estruturais
Veredito

Ferramenta de nível production para automação de refatoração. Excelente integração com Claude via MCP, segurança robusta (sandboxing, dry-run), mas requer compreensão de padrões AST. Ideal para equipes que trabalham com grandes codebases.
README
A tradução para o português deste README ainda está na fila.
ast-grep-mcp
Standalone MCP server wrapping ast-grep for AI-optimized AST code search and replace across 26 languages.
Extracted from oh-my-opencode.
Features
- AI-optimized tool descriptions: Explicitly warns LLMs that ast-grep is NOT regex
- Pattern hints on empty results: Detects regex misuse and language-specific mistakes (Python, JS/TS/TSX, Go, Rust, C#)
- Workspace sandboxing: Prevents path traversal, argument injection, and null byte injection
- Output truncation: 500 match / 1 MB / 5 min caps with JSON repair on truncated output
- Safe replace: Dry-run by default, two-pass write (search preview then --update-all)
- Bun/Node compatibility: Spawn shim handles both runtimes
Installation
npm install
npm run build
Usage
As MCP Server (stdio)
node dist/cli.js
Configure in OpenCode
Add to your opencode.json:
{
"mcp": {
"ast-grep": {
"type": "local",
"command": ["node", "path/to/ast-grep-mcp/dist/cli.js"],
"enabled": true
}
}
}
No AST_GREP_WORKSPACE needed — it defaults to the current working directory (i.e., whichever project you open in OpenCode).
Environment Variables
| Variable | Default | Description |
|---|---|---|
AST_GREP_WORKSPACE | process.cwd() | Override workspace directory for all path operations |
AST_GREP_DISABLED_TOOLS | (none) | Comma-separated list of tools to disable (e.g. search or replace) |
Tools
search
Search code by AST structure. Parameters:
pattern(required): AST pattern using$VARand$$$wildcardslang(required): Target languagepaths(optional): Paths to searchglobs(optional): Include/exclude globscontext(optional): Context lines around matches
Empty results automatically trigger pattern-hint diagnostics (regex misuse / language-specific mistakes).
replace
Rewrite code by AST pattern. Dry-run by default. Parameters:
pattern(required): AST pattern to matchrewrite(required): Replacement patternlang(required): Target languagepaths(optional): Paths to searchglobs(optional): Include/exclude globsdryRun(optional): Preview without applying (default: true)
Supported Languages
bash, c, cpp, csharp, css, elixir, go, haskell, hcl, html, java, javascript, json, kotlin, lua, nix, php, python, ruby, rust, scala, solidity, swift, typescript, tsx, yaml
Architecture
- MCP protocol: From-scratch JSON-RPC 2.0 implementation (no SDK dependency). Handles initialize, tools/list, tools/call, ping.
- Two-pass replace: First pass runs search+preview, second pass runs
--update-allfor actual file writes. - Workspace sandbox: All paths resolved via realpath, must stay inside workspace. Three-layer protection: path traversal (
../), argument injection (leading-), null byte injection (\0). - Output truncation: Matches capped at 500, output at 1 MB, timeout at 5 min. Truncated JSON gets repaired by finding last valid
},boundary. - sg binary detection: Three-level probe:
@ast-grep/clinpm package → platform-specific package → Homebrew. - Bun/Node compat:
bun-spawn-shim.tsdetects runtime and provides unified ReadableStream interface.
Known Issues
- No integration tests: Unit tests cover MCP handler and pattern hints, but no end-to-end test with actual
sgbinary execution. - process-output-timeout.ts uses Response API: Requires Node 18+. Node 16 is EOL and not supported.
- .gitignore pattern overlap:
*.d.tsand*.js.mapexclusions apply globally includingsrc/, but this is intentional — onlydist/should contain emitted files.
Development
npm install
npm run typecheck # tsc --noEmit
npm run build # esbuild bundle to dist/cli.js
npm test # vitest run
npm run start # node dist/cli.js
License
MIT