ast-grep-edit-mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ All notable changes to `ast-grep-edit-mcp`. Format based on
4
+ [Keep a Changelog](https://keepachangelog.com/); versioning follows [SemVer](https://semver.org/).
5
+
6
+ ## [Unreleased]
7
+
8
+ ## [0.1.0] — 2026-12-05
9
+
10
+ First version: `ast_grep_search` and `ast_grep_edit` (ported from opencode-ast-grep by Don Bowman) as MCP
11
+ tools over stdio, both protocol eras, server instructions and the `ast-grep` skill.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Antonio Orizondo Leyva
4
+ Copyright (c) 2026 Don Bowman (opencode-ast-grep, from which the tools are ported)
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,87 @@
1
- # Temporary Holding Version
1
+ # ast-grep-edit-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An [MCP](https://modelcontextprotocol.io) server that gives an AI agent [ast-grep](https://ast-grep.github.io/)
4
+ **structural search** and **multi-file rewrite** as first-class tools, so it reaches for syntax-aware tooling when
5
+ a task is about the *shape* of code instead of plain text.
6
+
7
+ | Tool | What it does |
8
+ | ---------------- | ------------------------------------------------------------------------------------------------ |
9
+ | `ast_grep_search` | Finds code by AST pattern: calls with arguments, JSX, declarations, nesting, missing guards. Returns compact `file:line:column` matches. |
10
+ | `ast_grep_edit` | Multi-file structural rewrite that keeps the surrounding formatting. Returns a diff by default; `apply: true` writes. |
11
+
12
+ The server also tells the agent when to use each tool (MCP instructions) and ships a skill, `ast-grep`, with
13
+ pattern examples. It works over stdio with any MCP client (OpenCode, Claude Code, VS Code…) in both protocol
14
+ eras (2026-07-28 and 2025).
15
+
16
+ The tools are ported from [opencode-ast-grep](https://github.com/donbowman/opencode-ast-grep) by Don Bowman,
17
+ an OpenCode plugin; this package makes them available to every MCP client.
18
+
19
+ ## Requirements
20
+
21
+ - Node 22 or later.
22
+ - `ast-grep` 0.40+ on `PATH` (`pip install ast-grep-cli`, `npm i -g @ast-grep/cli`,
23
+ `cargo install ast-grep --locked`, or `brew install ast-grep`).
24
+
25
+ ## Install
26
+
27
+ ```jsonc
28
+ // OpenCode (opencode.json)
29
+ {
30
+ "mcp": {
31
+ "servers": {
32
+ "ast-grep": { "type": "local", "command": ["npx", "-y", "ast-grep-edit-mcp"] }
33
+ }
34
+ }
35
+ }
36
+ ```
37
+
38
+ ```sh
39
+ # Claude Code
40
+ claude mcp add ast-grep -- npx -y ast-grep-edit-mcp
41
+ ```
42
+
43
+ Then ask for something structural: *"find every `console.log` call with its arguments"* or
44
+ *"rename all `oldApi(...)` calls to `newApi(...)` under `src`"*.
45
+
46
+ ## Usage
47
+
48
+ ```jsonc
49
+ // ast_grep_search — pattern is code with metavariables: $A one node, $$$ many, $_ no capture
50
+ { "pattern": "console.log($$$ARGS)", "lang": "ts", "paths": ["src"] }
51
+ { "pattern": "$A && $A()", "globs": ["!**/node_modules/**"], "limit": 50 }
52
+
53
+ // ast_grep_edit — 1) preview: returns a diff, writes nothing
54
+ { "pattern": "console.log($$$ARGS)", "rewrite": "logger.info($$$ARGS)", "lang": "ts" }
55
+ // 2) apply
56
+ { "pattern": "console.log($$$ARGS)", "rewrite": "logger.info($$$ARGS)", "lang": "ts", "apply": true }
57
+ ```
58
+
59
+ Both tools accept `lang`, `paths`, `globs` and `strictness` (`cst` | `smart` | `ast` | `relaxed` | `signature` |
60
+ `template`). Search also accepts `context` (lines around each match) and `limit`; edit also accepts `apply`.
61
+
62
+ - Patterns are code, not regex. A pattern matches a whole node: `std::env::var($X)` does not match a bare
63
+ `env::var($X)`; try both forms.
64
+ - `$$$` absorbs any number of nodes: argument lists, bodies.
65
+ - Zero matches is a normal result, not an error.
66
+
67
+ ## Configuration
68
+
69
+ | Variable | Default | Meaning |
70
+ | --------------- | ---------------------------------------- | ----------------------------------------------- |
71
+ | `AST_GREP_BIN` | `ast-grep`, then `sg` if it is ast-grep | Path to the ast-grep binary |
72
+ | `AST_GREP_ROOT` | the directory the client starts it in | Project directory that paths are relative to |
73
+
74
+ Timeouts are fixed (20 s search, 30 s edit) and output is cut at about 50,000 characters so a huge match set
75
+ cannot flood the context. The binary runs directly, never through a shell.
76
+
77
+ ## Development
78
+
79
+ ```sh
80
+ npm install
81
+ npm test # build + smoke test over stdio (needs ast-grep)
82
+ npm run typecheck
83
+ ```
84
+
85
+ ## License
86
+
87
+ MIT — see [LICENSE](LICENSE). Tools ported from opencode-ast-grep © Don Bowman (MIT).
@@ -0,0 +1,210 @@
1
+ /**
2
+ * ast-grep runner: structural search and multi-file rewrite through the local `ast-grep` binary,
3
+ * run directly (no shell), asking for compact JSON, with timeouts and truncated output. Ported
4
+ * from opencode-ast-grep by Don Bowman (MIT): https://github.com/donbowman/opencode-ast-grep
5
+ */
6
+ import { execFileSync, spawn } from "node:child_process";
7
+ export const MAX_OUTPUT_CHARS = 50_000;
8
+ export const DEFAULT_SEARCH_LIMIT = 80;
9
+ export const SEARCH_TIMEOUT_MS = 20_000;
10
+ export const EDIT_TIMEOUT_MS = 30_000;
11
+ export const STRICTNESS_VALUES = ["cst", "smart", "ast", "relaxed", "signature", "template"];
12
+ // ---------------------------------------------------------------------------
13
+ // Binary discovery: AST_GREP_BIN, else `ast-grep`, else `sg` (only if it really is ast-grep:
14
+ // Linux also ships `sg` as setgroups(1)).
15
+ // ---------------------------------------------------------------------------
16
+ let binCache;
17
+ export function findBinary(env = process.env) {
18
+ if (binCache !== undefined)
19
+ return binCache;
20
+ const explicit = (env.AST_GREP_BIN ?? "").trim();
21
+ const candidates = explicit ? [{ command: explicit, verify: false }] : [{ command: "ast-grep", verify: true }, { command: "sg", verify: true }];
22
+ for (const candidate of candidates) {
23
+ try {
24
+ const out = execFileSync(candidate.command, ["--version"], { encoding: "utf8", timeout: 5_000, windowsHide: true });
25
+ if (!candidate.verify || /^ast-grep\s/i.test(String(out).trim()))
26
+ return (binCache = candidate.command);
27
+ }
28
+ catch {
29
+ // next candidate
30
+ }
31
+ }
32
+ return (binCache = null);
33
+ }
34
+ export function binaryMissingMessage() {
35
+ return ("ast-grep was not found on PATH. Install it (`pip install ast-grep-cli`, `npm i -g @ast-grep/cli`, " +
36
+ "`cargo install ast-grep --locked`, or `brew install ast-grep`) or point AST_GREP_BIN at the binary.");
37
+ }
38
+ // ---------------------------------------------------------------------------
39
+ // Search
40
+ // ---------------------------------------------------------------------------
41
+ export async function search(input, cwd, signal) {
42
+ const pattern = input.pattern.trim();
43
+ if (!pattern)
44
+ return "ast_grep_search: `pattern` is required, e.g. `console.log($$$ARGS)` or `$A && $A()`.";
45
+ const bin = findBinary();
46
+ if (!bin)
47
+ return binaryMissingMessage();
48
+ const contextLines = clamp(input.context, 0, 10, 0);
49
+ const args = ["run", "-p", pattern, ...optionArgs(input)];
50
+ if (contextLines > 0)
51
+ args.push("--context", String(contextLines));
52
+ args.push("--json=compact", ...targetArgs(input));
53
+ const result = await run(bin, args, cwd, SEARCH_TIMEOUT_MS, signal);
54
+ if (result.spawnError)
55
+ return `ast-grep failed to start: ${result.spawnError}`;
56
+ if (result.timedOut)
57
+ return `ast-grep search timed out after ${SEARCH_TIMEOUT_MS / 1000}s; narrow the paths or pattern.`;
58
+ if (result.code > 1)
59
+ return `ast-grep exited with code ${result.code}.\n${truncate(result.stderr.trim() || result.stdout.trim(), 2_000)}`;
60
+ let matches = [];
61
+ try {
62
+ const parsed = JSON.parse(result.stdout.trim() || "[]");
63
+ if (Array.isArray(parsed))
64
+ matches = parsed;
65
+ }
66
+ catch {
67
+ return clampOutput(result.stdout.trim() || "ast-grep returned no parseable output.");
68
+ }
69
+ const warnings = result.stderr.trim();
70
+ const scope = input.lang ? ` (lang: ${input.lang})` : "";
71
+ if (matches.length === 0)
72
+ return (`No matches for \`${pattern}\`${scope}.\n` +
73
+ "ast-grep matches whole syntax nodes: try the bare and qualified forms, add `$$$` to absorb nodes, " +
74
+ "or set `lang`." +
75
+ (warnings ? `\nWarning: ${truncate(warnings, 500)}` : ""));
76
+ const limit = clamp(input.limit, 1, 500, DEFAULT_SEARCH_LIMIT);
77
+ const lines = matches.slice(0, limit).map(formatMatch);
78
+ const more = matches.length > limit ? `\n… ${matches.length - limit} more match(es); narrow with paths/globs or raise limit.` : "";
79
+ return clampOutput(`Found ${matches.length} match${matches.length === 1 ? "" : "es"} for \`${pattern}\`${scope}:\n${lines.join("\n")}${more}` +
80
+ (warnings ? `\nWarning: ${truncate(warnings, 500)}` : ""));
81
+ }
82
+ // ---------------------------------------------------------------------------
83
+ // Edit: dry run by default, apply=true writes
84
+ // ---------------------------------------------------------------------------
85
+ export async function edit(input, cwd, signal) {
86
+ const pattern = input.pattern.trim();
87
+ const rewrite = input.rewrite.trim();
88
+ if (!pattern || !rewrite)
89
+ return "ast_grep_edit: both `pattern` and `rewrite` are required, e.g. pattern `console.log($$$ARGS)` with rewrite `logger.info($$$ARGS)`.";
90
+ const bin = findBinary();
91
+ if (!bin)
92
+ return binaryMissingMessage();
93
+ const options = optionArgs(input);
94
+ const targets = targetArgs(input);
95
+ const preview = await run(bin, ["run", "-p", pattern, "-r", rewrite, ...options, ...targets], cwd, EDIT_TIMEOUT_MS, signal);
96
+ if (preview.spawnError)
97
+ return `ast-grep failed to start: ${preview.spawnError}`;
98
+ if (preview.timedOut)
99
+ return `ast-grep edit preview timed out after ${EDIT_TIMEOUT_MS / 1000}s; narrow the paths or pattern.`;
100
+ if (preview.code > 1)
101
+ return `ast-grep exited with code ${preview.code}.\n${truncate(preview.stderr.trim() || preview.stdout.trim(), 2_000)}`;
102
+ const diff = preview.stdout.trim();
103
+ if (!diff)
104
+ return `No matches for \`${pattern}\`; nothing to rewrite.${preview.stderr.trim() ? `\nWarning: ${truncate(preview.stderr.trim(), 500)}` : ""}`;
105
+ const files = countDiffFiles(preview.stdout);
106
+ const summary = `${files} file${files === 1 ? "" : "s"} would change`;
107
+ if (input.apply !== true)
108
+ return clampOutput(`${diff}\n\nDry run: ${summary}. Pass apply=true to write the changes.`);
109
+ const applied = await run(bin, ["run", "-p", pattern, "-r", rewrite, ...options, "-U", ...targets], cwd, EDIT_TIMEOUT_MS, signal);
110
+ if (applied.spawnError)
111
+ return `ast-grep failed to start: ${applied.spawnError}`;
112
+ if (applied.timedOut)
113
+ return `ast-grep edit timed out after ${EDIT_TIMEOUT_MS / 1000}s; some changes may or may not have been written.`;
114
+ if (applied.code > 1)
115
+ return `ast-grep exited with code ${applied.code} while applying.\n${truncate(applied.stderr.trim(), 2_000)}`;
116
+ // ast-grep writes "Applied N changes" to stderr; stdout stays empty.
117
+ const appliedLine = applied.stdout.match(/^Applied .*$/m)?.[0] ?? applied.stderr.match(/^Applied .*$/m)?.[0] ?? `Applied changes (${summary}).`;
118
+ return clampOutput(`${diff}\n\n${appliedLine}`);
119
+ }
120
+ // ---------------------------------------------------------------------------
121
+ // Helpers
122
+ // ---------------------------------------------------------------------------
123
+ function optionArgs(input) {
124
+ const args = [];
125
+ const lang = input.lang?.trim();
126
+ if (lang)
127
+ args.push("--lang", lang);
128
+ const strictness = input.strictness?.trim();
129
+ if (strictness && STRICTNESS_VALUES.includes(strictness))
130
+ args.push("--strictness", strictness);
131
+ for (const glob of input.globs ?? [])
132
+ if (glob.trim())
133
+ args.push("--globs", glob.trim());
134
+ return args;
135
+ }
136
+ function targetArgs(input) {
137
+ const paths = (input.paths ?? []).map((path) => path.trim()).filter(Boolean);
138
+ return ["--", ...(paths.length > 0 ? paths : ["."])];
139
+ }
140
+ function formatMatch(match) {
141
+ const file = typeof match.file === "string" ? match.file : "?";
142
+ const line = Number(match.range?.start?.line ?? 0) + 1;
143
+ const column = Number(match.range?.start?.column ?? 0) + 1;
144
+ const text = String(match.lines ?? match.text ?? "").split("\n")[0].trim();
145
+ return `${file}:${line}:${column}: ${truncate(text, 160)}`;
146
+ }
147
+ /**
148
+ * Files in ast-grep's diff output. File headers are bare paths; every other line is a hunk
149
+ * header (`@@`), a change (`+`/`-`), or a numbered context line (`N N│ ...`).
150
+ */
151
+ export function countDiffFiles(diff) {
152
+ let files = 0;
153
+ for (const line of diff.split("\n")) {
154
+ if (!line)
155
+ continue;
156
+ if (line.startsWith("@@") || line.startsWith("+") || line.startsWith("-"))
157
+ continue;
158
+ if (line.startsWith(" ") || line.startsWith("\\") || /^\d/.test(line))
159
+ continue;
160
+ if (line.includes("│"))
161
+ continue;
162
+ files++;
163
+ }
164
+ return files;
165
+ }
166
+ function run(bin, args, cwd, timeoutMs, signal) {
167
+ if (signal?.aborted)
168
+ return Promise.resolve({ code: -1, stdout: "", stderr: "", spawnError: "cancelled" });
169
+ return new Promise((resolve) => {
170
+ let child;
171
+ try {
172
+ child = spawn(bin, args, { cwd, windowsHide: true, signal });
173
+ }
174
+ catch (error) {
175
+ return resolve({ code: -1, stdout: "", stderr: "", spawnError: String(error?.message ?? error) });
176
+ }
177
+ const out = new TextDecoder();
178
+ const err = new TextDecoder();
179
+ let stdout = "";
180
+ let stderr = "";
181
+ let timedOut = false;
182
+ const timer = setTimeout(() => {
183
+ timedOut = true;
184
+ child.kill("SIGKILL");
185
+ }, timeoutMs);
186
+ timer.unref();
187
+ child.stdout?.on("data", (chunk) => (stdout += out.decode(chunk, { stream: true })));
188
+ child.stderr?.on("data", (chunk) => (stderr += err.decode(chunk, { stream: true })));
189
+ child.on("error", (error) => {
190
+ clearTimeout(timer);
191
+ resolve({ code: -1, stdout: "", stderr: "", spawnError: error.message });
192
+ });
193
+ child.on("close", (code) => {
194
+ clearTimeout(timer);
195
+ resolve({ code: code ?? 1, stdout: stdout + out.decode(), stderr: stderr + err.decode(), timedOut });
196
+ });
197
+ });
198
+ }
199
+ function clamp(value, min, max, fallback) {
200
+ const n = typeof value === "number" ? value : Number.parseInt(String(value ?? ""), 10);
201
+ return Number.isFinite(n) ? Math.min(max, Math.max(min, Math.trunc(n))) : fallback;
202
+ }
203
+ function truncate(text, max) {
204
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
205
+ }
206
+ function clampOutput(text) {
207
+ return text.length <= MAX_OUTPUT_CHARS
208
+ ? text
209
+ : `${text.slice(0, MAX_OUTPUT_CHARS)}\n… truncated (${text.length - MAX_OUTPUT_CHARS} more characters; narrow the search).`;
210
+ }
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ast-grep-edit-mcp: ast-grep structural search and rewrite as MCP tools, over stdio.
4
+ *
5
+ * Paths are relative to AST_GREP_ROOT, else the directory the client started the server in.
6
+ */
7
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
8
+ import { dirname, join, relative } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { McpServer } from "@modelcontextprotocol/server";
11
+ import { memorySkillFiles, SkillsExtension } from "@modelcontextprotocol/server/ext/skills";
12
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
13
+ import { z } from "zod";
14
+ import { DEFAULT_SEARCH_LIMIT, edit, search, STRICTNESS_VALUES } from "./astgrep.js";
15
+ export const NAME = "ast-grep";
16
+ export const VERSION = "0.1.0";
17
+ export const INSTRUCTIONS = `ast-grep searches and rewrites code by its syntax tree, not by text.
18
+ - ast_grep_search: when the question is about code shape (calls with certain arguments, JSX, declarations, nesting, missing guards, patterns over several lines). Use plain grep for text.
19
+ - ast_grep_edit: repo-wide mechanical changes (rename call sites, migrate an API). It returns a diff first; call it again with apply=true to write.
20
+ Patterns are code with metavariables: $A one node, $$$ many, $_ without capturing. Example: console.log($$$ARGS) → logger.info($$$ARGS). The skill ast-grep has more patterns.`;
21
+ const root = () => process.env.AST_GREP_ROOT || process.cwd();
22
+ const options = {
23
+ lang: z.string().optional().describe("Language id (ts, tsx, js, py, rust, go, java, csharp...). Inferred from file extensions when omitted."),
24
+ paths: z.array(z.string()).optional().describe("Files or directories relative to the project. Defaults to the whole project."),
25
+ globs: z.array(z.string()).optional().describe("Include/exclude patterns, e.g. `**/*.ts` or `!**/node_modules/**`."),
26
+ strictness: z.enum(STRICTNESS_VALUES).optional().describe("How strictly the pattern must match an AST node (default: smart)."),
27
+ };
28
+ async function createServerFactory() {
29
+ const skills = await loadSkills();
30
+ return () => {
31
+ const mcp = new McpServer({ name: NAME, version: VERSION }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
32
+ mcp.registerTool("ast_grep_search", {
33
+ title: "Structural code search",
34
+ description: "Structural (syntax-aware) code search with ast-grep. Use when the query is about code shape, not text: calls with " +
35
+ "specific arguments, JSX, declarations, nesting, missing guards, or patterns that span lines. The pattern is code with " +
36
+ "metavariables: `console.log($$$ARGS)`, `$A && $A()`, `async function $F($$$) { $$$ }`, `$X.method($A)`. Returns " +
37
+ "matches as file:line:col. Use grep for plain text; use this for structure.",
38
+ inputSchema: z.object({
39
+ pattern: z.string().describe("AST pattern, e.g. `console.log($$$ARGS)`. `$A` one node, `$$$` many, `$_` without capturing."),
40
+ ...options,
41
+ context: z.number().int().min(0).max(10).optional().describe("Lines of context around each match (0-10)."),
42
+ limit: z.number().int().min(1).max(500).optional().describe(`Maximum matches to print (default ${DEFAULT_SEARCH_LIMIT}).`),
43
+ }),
44
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
45
+ }, async (args, ctx) => ({ content: [{ type: "text", text: await search(args, root(), ctx.mcpReq.signal) }] }));
46
+ mcp.registerTool("ast_grep_edit", {
47
+ title: "Structural multi-file rewrite",
48
+ description: "Structural multi-file rewrite with ast-grep. Finds code matching a syntax pattern and replaces it with a rewrite " +
49
+ "template, preserving surrounding formatting. Dry run by default (returns a diff); set apply=true to write. Use for " +
50
+ "repo-wide mechanical refactors (call-site renames, API migrations such as `$A && $A()` -> `$A?.()`), not for " +
51
+ "one-off single-file edits.",
52
+ inputSchema: z.object({
53
+ pattern: z.string().describe("AST pattern to find, e.g. `console.log($$$ARGS)`. Metavariables are reused in the rewrite."),
54
+ rewrite: z.string().describe("Replacement template using the same metavariables, e.g. `logger.info($$$ARGS)`."),
55
+ ...options,
56
+ apply: z.boolean().optional().describe("Write the changes. Default false returns the dry-run diff only."),
57
+ }),
58
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
59
+ }, async (args, ctx) => ({ content: [{ type: "text", text: await edit(args, root(), ctx.mcpReq.signal) }] }));
60
+ skills?.attach(mcp);
61
+ return mcp;
62
+ };
63
+ }
64
+ async function loadSkills() {
65
+ let dir = dirname(fileURLToPath(import.meta.url));
66
+ let skillsDir = null;
67
+ for (let i = 0; i < 4 && !skillsDir; i++) {
68
+ if (existsSync(join(dir, "skills", NAME, "SKILL.md")))
69
+ skillsDir = join(dir, "skills");
70
+ dir = dirname(dir);
71
+ }
72
+ if (!skillsDir)
73
+ return null;
74
+ const files = {};
75
+ const walk = (current) => {
76
+ for (const name of readdirSync(current)) {
77
+ const path = join(current, name);
78
+ if (statSync(path).isDirectory())
79
+ walk(path);
80
+ else
81
+ files[relative(skillsDir, path).split("\\").join("/")] = readFileSync(path, "utf8");
82
+ }
83
+ };
84
+ walk(skillsDir);
85
+ try {
86
+ return await SkillsExtension.load(memorySkillFiles(files), { onWarning: () => undefined });
87
+ }
88
+ catch {
89
+ return null;
90
+ }
91
+ }
92
+ const handle = serveStdio(await createServerFactory(), {
93
+ onerror: (error) => process.stderr.write(`ast-grep-edit-mcp: ${error.message}\n`),
94
+ });
95
+ const stop = async () => {
96
+ await handle.close?.();
97
+ process.exit(0);
98
+ };
99
+ process.on("SIGINT", () => void stop());
100
+ process.on("SIGTERM", () => void stop());
101
+ process.stdin.on("end", () => void stop());
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "ast-grep-edit-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "MCP server (stdio): ast-grep structural code search and multi-file rewrite (dry-run diff, then apply) as tools, with instructions and a skill for agents",
5
+ "license": "MIT",
6
+ "author": "Antonio Orizondo Leyva",
7
+ "contributors": [
8
+ "Don Bowman (opencode-ast-grep)"
9
+ ],
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/aorizondo/ast-grep-edit-mcp.git"
13
+ },
14
+ "homepage": "https://github.com/aorizondo/ast-grep-edit-mcp#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/aorizondo/ast-grep-edit-mcp/issues"
17
+ },
18
+ "keywords": [
19
+ "mcp",
20
+ "model-context-protocol",
21
+ "ast-grep",
22
+ "structural-search",
23
+ "codemod",
24
+ "refactoring",
25
+ "opencode",
26
+ "claude-code"
27
+ ],
28
+ "type": "module",
29
+ "bin": {
30
+ "ast-grep-edit-mcp": "dist/src/index.js"
31
+ },
32
+ "files": [
33
+ "dist/src",
34
+ "skills",
35
+ "README.md",
36
+ "CHANGELOG.md",
37
+ "LICENSE"
38
+ ],
39
+ "engines": {
40
+ "node": ">=22"
41
+ },
42
+ "scripts": {
43
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && chmod +x dist/src/index.js",
44
+ "typecheck": "tsc --noEmit -p .",
45
+ "test": "npm run build && node test/smoke.test.mjs",
46
+ "prepublishOnly": "npm run typecheck && npm test"
47
+ },
48
+ "dependencies": {
49
+ "@modelcontextprotocol/server": "2.4.0",
50
+ "zod": "^4.2.0"
51
+ },
52
+ "devDependencies": {
53
+ "@modelcontextprotocol/client": "2.4.0",
54
+ "@types/node": "^22.0.0",
55
+ "bun-types": "^1.1.0",
56
+ "typescript": "^5.5.0"
57
+ }
58
+ }
@@ -0,0 +1,60 @@
1
+ ---
2
+ name: ast-grep
3
+ description: Search and rewrite code by its syntax tree with ast-grep (ast_grep_search, ast_grep_edit). Use for questions about code shape and for repo-wide mechanical refactors; plain grep stays better for text.
4
+ ---
5
+
6
+ # ast-grep: code by shape
7
+
8
+ `ast_grep_search` finds code that has a given **syntax shape**; `ast_grep_edit` rewrites it in every
9
+ matching file. A pattern is ordinary code with **metavariables**:
10
+
11
+ | Metavariable | Matches |
12
+ | ------------ | -------------------------------------------------- |
13
+ | `$A` | exactly one node (an expression, an identifier...) |
14
+ | `$$$` | any number of nodes (arguments, statements) |
15
+ | `$$$ARGS` | the same, captured as `ARGS` for the rewrite |
16
+ | `$_` | one node, not captured |
17
+
18
+ The same name twice must match the same code: `$A && $A()` finds `cb && cb()` but not `a && b()`.
19
+
20
+ ## When to use which
21
+
22
+ - Text, names, comments, strings: `grep`.
23
+ - Shape (a call with these arguments, a missing `await`, a JSX prop, nested ifs): `ast_grep_search`.
24
+ - The same change in many places: `ast_grep_edit`. One place: the normal edit tool.
25
+
26
+ ## Search examples
27
+
28
+ ```json
29
+ { "pattern": "console.log($$$ARGS)", "lang": "ts", "paths": ["src"] }
30
+ { "pattern": "useEffect($F, [])", "lang": "tsx" }
31
+ { "pattern": "fetch($URL)", "globs": ["!**/node_modules/**"], "limit": 50 }
32
+ { "pattern": "except: $$$", "lang": "py" }
33
+ { "pattern": "unwrap()", "lang": "rust", "strictness": "relaxed" }
34
+ ```
35
+
36
+ ## Rewrite: preview, then apply
37
+
38
+ 1. Preview (writes nothing, returns a diff):
39
+
40
+ ```json
41
+ { "pattern": "console.log($$$ARGS)", "rewrite": "logger.info($$$ARGS)", "lang": "ts" }
42
+ ```
43
+
44
+ 2. Read the diff. If it is right, the same call with `"apply": true` writes it.
45
+
46
+ More rewrites:
47
+
48
+ ```json
49
+ { "pattern": "$A && $A()", "rewrite": "$A?.()", "lang": "ts" }
50
+ { "pattern": "assertEquals($A, $B)", "rewrite": "assertEqual($A, $B)", "lang": "py" }
51
+ { "pattern": "oldApi($$$ARGS)", "rewrite": "newApi($$$ARGS)", "paths": ["src", "test"] }
52
+ ```
53
+
54
+ ## When nothing matches
55
+
56
+ - A pattern matches a **whole node**: `env::var($X)` does not match `std::env::var($X)`; try both forms.
57
+ - Set `lang` when the file extension does not tell (`.js` with JSX: `tsx` or `jsx`).
58
+ - Absorb the rest with `$$$`: `function $F($$$) { $$$ }`.
59
+ - `strictness: "relaxed"` ignores comments and some trivia; `"ast"` ignores more.
60
+ - Zero matches is a normal answer, not an error.