@mwillbanks/ast-mcp 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/CONTRIBUTING.md +60 -0
- package/LICENSE +21 -0
- package/README.md +109 -0
- package/dist/ast-mcp-hook.js +7 -0
- package/dist/ast-mcp-hook.js.map +11 -0
- package/dist/ast-mcp-install.js +22 -0
- package/dist/ast-mcp-install.js.map +12 -0
- package/dist/ast-mcp.js +115 -0
- package/dist/ast-mcp.js.map +89 -0
- package/dprint.json +37 -0
- package/logo.svg +1 -0
- package/package.json +89 -0
- package/src/ast-bro/capability.ts +21 -0
- package/src/ast-bro/client.ts +47 -0
- package/src/ast-bro/result.ts +42 -0
- package/src/ast-bro/rewrite-capability.ts +9 -0
- package/src/ast-bro/tools.json +603 -0
- package/src/hook.ts +79 -0
- package/src/http-entry.ts +3 -0
- package/src/http.ts +138 -0
- package/src/index.ts +8 -0
- package/src/installer.ts +501 -0
- package/src/lifecycle.ts +10 -0
- package/src/managed-hook.ts +4 -0
- package/src/patch/aider.ts +224 -0
- package/src/patch/engine.ts +446 -0
- package/src/patch/languages.ts +36 -0
- package/src/runtime/atomic.ts +26 -0
- package/src/runtime/attributes.ts +70 -0
- package/src/runtime/file-delete.ts +96 -0
- package/src/runtime/file-read.ts +178 -0
- package/src/runtime/format.ts +56 -0
- package/src/runtime/hash.ts +11 -0
- package/src/runtime/locks.ts +87 -0
- package/src/runtime/paths.ts +73 -0
- package/src/runtime/process-input.ts +25 -0
- package/src/runtime/signals.ts +47 -0
- package/src/server.ts +13 -0
- package/src/stdio.ts +154 -0
- package/src/tools/ast-bro.ts +172 -0
- package/src/tools/files.ts +173 -0
- package/src/tools/index.ts +11 -0
- package/src/tools/lifecycle.ts +124 -0
- package/templates/AGENTS.md +56 -0
- package/templates/skills/ast-mcp/SKILL.md +96 -0
- package/templates/skills/ast-mcp/agents/openai.yaml +4 -0
- package/templates/skills/ast-mcp/evals/batch.evals.json +274 -0
- package/templates/skills/ast-mcp/evals/evals.json +1209 -0
- package/templates/skills/ast-mcp/evals/file-hash.evals.json +50 -0
- package/templates/skills/ast-mcp/evals/measure.ts +18 -0
- package/templates/skills/ast-mcp/evals/results.md +17 -0
- package/templates/skills/ast-mcp/evals/score.ts +417 -0
- package/templates/skills/ast-mcp/evals/semantic.ts +332 -0
- package/templates/skills/ast-mcp/evals/trigger-queries.json +22 -0
- package/templates/skills/ast-mcp/evals/validate.ts +99 -0
- package/templates/skills/ast-mcp/references/installation.md +40 -0
- package/templates/skills/ast-mcp/references/managed-hook.ts +3 -0
- package/templates/skills/ast-mcp/references/patch-state-machine.md +39 -0
- package/templates/skills/ast-mcp/references/tool-catalog.md +46 -0
- package/templates/skills/ast-mcp/scripts/check-install.ts +269 -0
- package/templates/skills/ast-mcp/scripts/managed-hook.ts +22 -0
package/src/stdio.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// fallow-ignore-file unused-class-member -- start and send are required Transport interface methods
|
|
2
|
+
// fallow-ignore-file unused-class-member -- start and send are required Transport interface methods
|
|
3
|
+
// fallow-ignore-file stale-suppression -- Fallow cannot model external MCP Transport dispatch
|
|
4
|
+
|
|
5
|
+
import type { Readable, Writable } from "node:stream";
|
|
6
|
+
import {
|
|
7
|
+
deserializeMessage,
|
|
8
|
+
type JSONRPCMessage,
|
|
9
|
+
serializeMessage,
|
|
10
|
+
type Transport,
|
|
11
|
+
} from "@modelcontextprotocol/server";
|
|
12
|
+
|
|
13
|
+
const MAX_BUFFER_SIZE = 10 * 1024 * 1024;
|
|
14
|
+
|
|
15
|
+
export class BatchingStdioServerTransport implements Transport {
|
|
16
|
+
private buffer = Buffer.alloc(0);
|
|
17
|
+
private started = false;
|
|
18
|
+
private closed = false;
|
|
19
|
+
|
|
20
|
+
constructor(
|
|
21
|
+
private readonly stdin: Readable = process.stdin,
|
|
22
|
+
private readonly stdout: Writable = process.stdout,
|
|
23
|
+
) {}
|
|
24
|
+
|
|
25
|
+
onclose?: () => void;
|
|
26
|
+
onerror?: (error: Error) => void;
|
|
27
|
+
onmessage?: (message: JSONRPCMessage) => void;
|
|
28
|
+
|
|
29
|
+
private readonly onData = (chunk: Buffer | string) => {
|
|
30
|
+
try {
|
|
31
|
+
const next = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
32
|
+
if (this.buffer.length + next.length > MAX_BUFFER_SIZE) {
|
|
33
|
+
this.buffer = Buffer.alloc(0);
|
|
34
|
+
throw new Error(
|
|
35
|
+
`Stdio input exceeded maximum size of ${MAX_BUFFER_SIZE} bytes`,
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
this.buffer = Buffer.concat([this.buffer, next]);
|
|
39
|
+
this.processReadBuffer();
|
|
40
|
+
} catch (error) {
|
|
41
|
+
this.onerror?.(error instanceof Error ? error : new Error(String(error)));
|
|
42
|
+
void this.close();
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
private readonly onError = (error: Error) => {
|
|
47
|
+
this.onerror?.(error);
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
async start() {
|
|
51
|
+
if (this.started) throw new Error("Stdio transport already started");
|
|
52
|
+
this.started = true;
|
|
53
|
+
this.stdin.on("data", this.onData);
|
|
54
|
+
this.stdin.on("error", this.onError);
|
|
55
|
+
this.stdout.on("error", this.onError);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
private reportInvalidRequest(error: Error) {
|
|
59
|
+
this.onerror?.(error);
|
|
60
|
+
void this.send({
|
|
61
|
+
error: { code: -32600, message: "Invalid Request" },
|
|
62
|
+
id: null,
|
|
63
|
+
jsonrpc: "2.0",
|
|
64
|
+
} as unknown as JSONRPCMessage).catch((sendError) => {
|
|
65
|
+
this.onerror?.(
|
|
66
|
+
sendError instanceof Error ? sendError : new Error(String(sendError)),
|
|
67
|
+
);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private processReadBuffer() {
|
|
72
|
+
while (true) {
|
|
73
|
+
const newline = this.buffer.indexOf(10);
|
|
74
|
+
if (newline === -1) return;
|
|
75
|
+
|
|
76
|
+
const line = this.buffer
|
|
77
|
+
.subarray(0, newline)
|
|
78
|
+
.toString("utf8")
|
|
79
|
+
.replace(/\r$/, "");
|
|
80
|
+
this.buffer = this.buffer.subarray(newline + 1);
|
|
81
|
+
|
|
82
|
+
try {
|
|
83
|
+
const parsed: unknown = JSON.parse(line);
|
|
84
|
+
if (Array.isArray(parsed) && parsed.length === 0) {
|
|
85
|
+
this.reportInvalidRequest(
|
|
86
|
+
new Error("JSON-RPC batches must not be empty"),
|
|
87
|
+
);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const messages = (Array.isArray(parsed) ? parsed : [parsed]).flatMap(
|
|
91
|
+
(message) => {
|
|
92
|
+
try {
|
|
93
|
+
return [deserializeMessage(JSON.stringify(message))];
|
|
94
|
+
} catch (error) {
|
|
95
|
+
this.reportInvalidRequest(
|
|
96
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
97
|
+
);
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
);
|
|
102
|
+
for (const message of messages) this.onmessage?.(message);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
this.reportInvalidRequest(
|
|
105
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async close() {
|
|
112
|
+
if (this.closed) return;
|
|
113
|
+
this.closed = true;
|
|
114
|
+
this.stdin.off("data", this.onData);
|
|
115
|
+
this.stdin.off("error", this.onError);
|
|
116
|
+
this.stdout.off("error", this.onError);
|
|
117
|
+
if (this.stdin.listenerCount("data") === 0) this.stdin.pause();
|
|
118
|
+
this.buffer = Buffer.alloc(0);
|
|
119
|
+
this.onclose?.();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
send(message: JSONRPCMessage) {
|
|
123
|
+
if (this.closed)
|
|
124
|
+
return Promise.reject(new Error("Stdio transport is closed"));
|
|
125
|
+
|
|
126
|
+
return new Promise<void>((resolve, reject) => {
|
|
127
|
+
let settled = false;
|
|
128
|
+
const onError = (error: Error) => {
|
|
129
|
+
if (settled) return;
|
|
130
|
+
settled = true;
|
|
131
|
+
this.stdout.off("error", onError);
|
|
132
|
+
this.stdout.off("drain", onDrain);
|
|
133
|
+
reject(error);
|
|
134
|
+
};
|
|
135
|
+
const onDrain = () => {
|
|
136
|
+
if (settled) return;
|
|
137
|
+
settled = true;
|
|
138
|
+
this.stdout.off("error", onError);
|
|
139
|
+
this.stdout.off("drain", onDrain);
|
|
140
|
+
resolve();
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
this.stdout.once("error", onError);
|
|
144
|
+
if (this.stdout.write(serializeMessage(message))) {
|
|
145
|
+
if (settled) return;
|
|
146
|
+
settled = true;
|
|
147
|
+
this.stdout.off("error", onError);
|
|
148
|
+
resolve();
|
|
149
|
+
} else {
|
|
150
|
+
this.stdout.once("drain", onDrain);
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { lstat, readFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import type {
|
|
4
|
+
McpServer,
|
|
5
|
+
StandardSchemaWithJSON,
|
|
6
|
+
} from "@modelcontextprotocol/server";
|
|
7
|
+
import { AST_BRO_TOOLS, callAstBro } from "../ast-bro/client";
|
|
8
|
+
import {
|
|
9
|
+
astBroMatchFiles,
|
|
10
|
+
astBroRewrittenFiles,
|
|
11
|
+
parseAstBroJson,
|
|
12
|
+
} from "../ast-bro/result";
|
|
13
|
+
import metadata from "../ast-bro/tools.json";
|
|
14
|
+
import { replaceFileAtomically } from "../runtime/atomic";
|
|
15
|
+
import { assertFormattable, formatFileAtomically } from "../runtime/format";
|
|
16
|
+
import { withFileLocks } from "../runtime/locks";
|
|
17
|
+
import { primaryRoot, resolveWritablePath } from "../runtime/paths";
|
|
18
|
+
|
|
19
|
+
function upstreamSchema(
|
|
20
|
+
jsonSchema: Record<string, unknown>,
|
|
21
|
+
): StandardSchemaWithJSON<Record<string, unknown>> {
|
|
22
|
+
return {
|
|
23
|
+
"~standard": {
|
|
24
|
+
jsonSchema: {
|
|
25
|
+
input: () => jsonSchema,
|
|
26
|
+
output: () => ({ type: "object" }),
|
|
27
|
+
},
|
|
28
|
+
validate(value) {
|
|
29
|
+
return value !== null &&
|
|
30
|
+
typeof value === "object" &&
|
|
31
|
+
!Array.isArray(value)
|
|
32
|
+
? { value: value as Record<string, unknown> }
|
|
33
|
+
: { issues: [{ message: "Expected an object" }] };
|
|
34
|
+
},
|
|
35
|
+
vendor: "ast-mcp",
|
|
36
|
+
version: 1,
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
async function boundedPath(root: string, value: string): Promise<string> {
|
|
41
|
+
return resolveWritablePath(
|
|
42
|
+
path.isAbsolute(value) ? value : path.resolve(root, value),
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const pathArguments = ["file", "path", "root"] as const;
|
|
47
|
+
|
|
48
|
+
async function validateAstBroPaths(
|
|
49
|
+
args: Record<string, unknown>,
|
|
50
|
+
root: string,
|
|
51
|
+
): Promise<void> {
|
|
52
|
+
for (const name of pathArguments) {
|
|
53
|
+
const value = args[name];
|
|
54
|
+
if (typeof value === "string") await boundedPath(root, value);
|
|
55
|
+
}
|
|
56
|
+
if (!Array.isArray(args.paths)) return;
|
|
57
|
+
for (const value of args.paths)
|
|
58
|
+
if (typeof value === "string") await boundedPath(root, value);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function callAstBroWithFormatting(
|
|
62
|
+
args: Record<string, unknown>,
|
|
63
|
+
root: string,
|
|
64
|
+
) {
|
|
65
|
+
const paths = Array.isArray(args.paths)
|
|
66
|
+
? args.paths.filter((value): value is string => typeof value === "string")
|
|
67
|
+
: [];
|
|
68
|
+
for (const value of paths.length ? paths : [root])
|
|
69
|
+
await boundedPath(root, value);
|
|
70
|
+
if (args.write !== true || typeof args.rewrite !== "string")
|
|
71
|
+
return callAstBro("run", args, root);
|
|
72
|
+
|
|
73
|
+
const previewArgs: Record<string, unknown> = {
|
|
74
|
+
json: true,
|
|
75
|
+
paths: args.paths,
|
|
76
|
+
pattern: args.pattern,
|
|
77
|
+
};
|
|
78
|
+
for (const key of ["glob", "lang"])
|
|
79
|
+
if (args[key] !== undefined) previewArgs[key] = args[key];
|
|
80
|
+
const initialPreview = await callAstBro("run", previewArgs, root);
|
|
81
|
+
const preview = parseAstBroJson(initialPreview);
|
|
82
|
+
if (preview.capped)
|
|
83
|
+
throw new Error(
|
|
84
|
+
"ast-bro run preview was capped; narrow paths or pattern before writing",
|
|
85
|
+
);
|
|
86
|
+
const initialFiles = await Promise.all(
|
|
87
|
+
astBroMatchFiles(initialPreview).map((file) => boundedPath(root, file)),
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
return withFileLocks(initialFiles, async () => {
|
|
91
|
+
const previewResult = await callAstBro("run", previewArgs, root);
|
|
92
|
+
const lockedPreview = parseAstBroJson(previewResult);
|
|
93
|
+
if (lockedPreview.capped)
|
|
94
|
+
throw new Error(
|
|
95
|
+
"ast-bro run preview was capped; narrow paths or pattern before writing",
|
|
96
|
+
);
|
|
97
|
+
const lockedFiles = await Promise.all(
|
|
98
|
+
astBroMatchFiles(previewResult).map((file) => boundedPath(root, file)),
|
|
99
|
+
);
|
|
100
|
+
if (
|
|
101
|
+
initialFiles.length !== lockedFiles.length ||
|
|
102
|
+
initialFiles.some((filePath, index) => filePath !== lockedFiles[index])
|
|
103
|
+
)
|
|
104
|
+
throw new Error(
|
|
105
|
+
"ast-bro run targets changed while waiting for the write lock; preview again",
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
const snapshots = new Map<string, { content: string; mode: number }>();
|
|
109
|
+
for (const filePath of lockedFiles) {
|
|
110
|
+
await assertFormattable(filePath);
|
|
111
|
+
snapshots.set(filePath, {
|
|
112
|
+
content: await readFile(filePath, "utf8"),
|
|
113
|
+
mode: (await lstat(filePath)).mode,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
const result = await callAstBro("run", { ...args, json: true }, root);
|
|
117
|
+
const rewritten = await Promise.all(
|
|
118
|
+
astBroRewrittenFiles(result).map((file) => boundedPath(root, file)),
|
|
119
|
+
);
|
|
120
|
+
try {
|
|
121
|
+
for (const filePath of rewritten) await formatFileAtomically(filePath);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
for (const filePath of rewritten) {
|
|
124
|
+
const snapshot = snapshots.get(filePath);
|
|
125
|
+
if (snapshot)
|
|
126
|
+
await replaceFileAtomically(
|
|
127
|
+
filePath,
|
|
128
|
+
snapshot.content,
|
|
129
|
+
snapshot.mode,
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
return result;
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export default function registerAstBroTools(server: McpServer) {
|
|
139
|
+
for (const toolName of AST_BRO_TOOLS) {
|
|
140
|
+
const definition = metadata[toolName];
|
|
141
|
+
server.registerTool(
|
|
142
|
+
toolName,
|
|
143
|
+
{
|
|
144
|
+
description:
|
|
145
|
+
toolName === "run"
|
|
146
|
+
? "AST structural search and rewrite. Use for bounded inspection and previews; direct write is a lower-level escape hatch for exceptional cases. Normal agent edits belong in keyed file_patch, which supports ordered AST rules and Aider blocks."
|
|
147
|
+
: definition.description,
|
|
148
|
+
inputSchema: upstreamSchema(definition.inputSchema),
|
|
149
|
+
title: `ast-bro ${toolName}`,
|
|
150
|
+
},
|
|
151
|
+
async (args) => {
|
|
152
|
+
try {
|
|
153
|
+
const root = await primaryRoot();
|
|
154
|
+
await validateAstBroPaths(args, root);
|
|
155
|
+
return toolName === "run"
|
|
156
|
+
? await callAstBroWithFormatting(args, root)
|
|
157
|
+
: await callAstBro(toolName, args, root);
|
|
158
|
+
} catch (error) {
|
|
159
|
+
return {
|
|
160
|
+
content: [
|
|
161
|
+
{
|
|
162
|
+
text: error instanceof Error ? error.message : String(error),
|
|
163
|
+
type: "text",
|
|
164
|
+
},
|
|
165
|
+
],
|
|
166
|
+
isError: true,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import type { McpServer } from "@modelcontextprotocol/server";
|
|
2
|
+
import * as z from "zod/v4";
|
|
3
|
+
import { patchFiles, writeFilesSafely } from "../patch/engine";
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
FILE_READ_MAX_BATCH,
|
|
7
|
+
FILE_READ_MAX_BYTES,
|
|
8
|
+
FILE_READ_MAX_LINES,
|
|
9
|
+
hashFilesSafely,
|
|
10
|
+
readFilesSafely,
|
|
11
|
+
} from "../runtime/file-read";
|
|
12
|
+
|
|
13
|
+
const failure = (error: unknown) => ({
|
|
14
|
+
content: [
|
|
15
|
+
{
|
|
16
|
+
text: error instanceof Error ? error.message : String(error),
|
|
17
|
+
type: "text" as const,
|
|
18
|
+
},
|
|
19
|
+
],
|
|
20
|
+
isError: true,
|
|
21
|
+
});
|
|
22
|
+
export default function registerFileTools(server: McpServer) {
|
|
23
|
+
const lineRange = z
|
|
24
|
+
.tuple([z.number().int().nonnegative(), z.number().int().positive()])
|
|
25
|
+
.describe("Zero-based, end-exclusive [start, end] line range");
|
|
26
|
+
const readTarget = z.object({
|
|
27
|
+
filePath: z.string(),
|
|
28
|
+
lines: lineRange.optional(),
|
|
29
|
+
maxBytes: z.number().int().positive().max(FILE_READ_MAX_BYTES).optional(),
|
|
30
|
+
});
|
|
31
|
+
const aiderBlock = z.object({
|
|
32
|
+
replace: z.string(),
|
|
33
|
+
search: z.string(),
|
|
34
|
+
});
|
|
35
|
+
const astRule = z.object({
|
|
36
|
+
expectedMatches: z.number().int().positive().optional(),
|
|
37
|
+
fix: z.string(),
|
|
38
|
+
pattern: z.string().min(1),
|
|
39
|
+
});
|
|
40
|
+
const chattr = z.object({
|
|
41
|
+
chmod: z.number().int().min(0).max(0o777).optional(),
|
|
42
|
+
chown: z
|
|
43
|
+
.object({
|
|
44
|
+
gid: z.number().int().nonnegative(),
|
|
45
|
+
uid: z.number().int().nonnegative(),
|
|
46
|
+
})
|
|
47
|
+
.optional(),
|
|
48
|
+
});
|
|
49
|
+
const writeTarget = z.object({
|
|
50
|
+
chattr: chattr.optional(),
|
|
51
|
+
content: z.string(),
|
|
52
|
+
expectedSha256: z.string().length(64).optional(),
|
|
53
|
+
});
|
|
54
|
+
const boundedBatch = <T extends z.ZodType>(schema: T, label: string) =>
|
|
55
|
+
z
|
|
56
|
+
.record(z.string().min(1), schema)
|
|
57
|
+
.refine(
|
|
58
|
+
(value) =>
|
|
59
|
+
Object.keys(value).length > 0 &&
|
|
60
|
+
Object.keys(value).length <= FILE_READ_MAX_BATCH,
|
|
61
|
+
label,
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
server.registerTool(
|
|
65
|
+
"file_read",
|
|
66
|
+
{
|
|
67
|
+
description: `Batches bounded line slices from non-AST files only. AST-capable files are rejected and must use map/show/search/context/run. Each slice defaults to lines [0, 100], is capped at ${FILE_READ_MAX_LINES} lines and ${FILE_READ_MAX_BYTES} bytes, and includes a streaming whole-file SHA-256.`,
|
|
68
|
+
inputSchema: z.object({
|
|
69
|
+
files: z.array(readTarget).min(1).max(FILE_READ_MAX_BATCH),
|
|
70
|
+
}),
|
|
71
|
+
title: "Read Bounded Non-AST File Slices",
|
|
72
|
+
},
|
|
73
|
+
async ({ files }) => {
|
|
74
|
+
try {
|
|
75
|
+
return {
|
|
76
|
+
content: [
|
|
77
|
+
{
|
|
78
|
+
text: JSON.stringify({ files: await readFilesSafely(files) }),
|
|
79
|
+
type: "text",
|
|
80
|
+
},
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
} catch (error) {
|
|
84
|
+
return failure(error);
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
server.registerTool(
|
|
90
|
+
"file_hash",
|
|
91
|
+
{
|
|
92
|
+
description: `Batches streaming whole-file SHA-256 calculations without loading file contents into memory. Use this for fresh patch hashes, including AST-capable files. Accepts up to ${FILE_READ_MAX_BATCH} paths.`,
|
|
93
|
+
inputSchema: z.object({
|
|
94
|
+
filePaths: z.array(z.string()).min(1).max(FILE_READ_MAX_BATCH),
|
|
95
|
+
}),
|
|
96
|
+
title: "Hash Files Without Reading Content",
|
|
97
|
+
},
|
|
98
|
+
async ({ filePaths }) => {
|
|
99
|
+
try {
|
|
100
|
+
return {
|
|
101
|
+
content: [
|
|
102
|
+
{
|
|
103
|
+
text: JSON.stringify({
|
|
104
|
+
files: await hashFilesSafely(filePaths),
|
|
105
|
+
}),
|
|
106
|
+
type: "text",
|
|
107
|
+
},
|
|
108
|
+
],
|
|
109
|
+
};
|
|
110
|
+
} catch (error) {
|
|
111
|
+
return failure(error);
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
);
|
|
115
|
+
|
|
116
|
+
server.registerTool(
|
|
117
|
+
"file_write",
|
|
118
|
+
{
|
|
119
|
+
description:
|
|
120
|
+
"Creates or replaces multiple files in one keyed batch. Each key is a file path and each value contains content plus an optional fresh expectedSha256 for existing non-structurally-rewritable files.",
|
|
121
|
+
inputSchema: boundedBatch(
|
|
122
|
+
writeTarget,
|
|
123
|
+
"file_write requires between 1 and 50 files",
|
|
124
|
+
),
|
|
125
|
+
title: "Write Files Safely",
|
|
126
|
+
},
|
|
127
|
+
async (args) => {
|
|
128
|
+
try {
|
|
129
|
+
return {
|
|
130
|
+
content: [
|
|
131
|
+
{
|
|
132
|
+
text: JSON.stringify(await writeFilesSafely(args)),
|
|
133
|
+
type: "text",
|
|
134
|
+
},
|
|
135
|
+
],
|
|
136
|
+
};
|
|
137
|
+
} catch (error) {
|
|
138
|
+
return failure(error);
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
);
|
|
142
|
+
|
|
143
|
+
server.registerTool(
|
|
144
|
+
"file_patch",
|
|
145
|
+
{
|
|
146
|
+
description:
|
|
147
|
+
"Patches multiple files in one keyed batch. Each key is a file path and each value contains one expectedSha256, a patchStrategy, ordered aiderBlocks or astRules, and optional preview mode. Preview runs the complete guarded operation and returns a bounded diff without committing.",
|
|
148
|
+
inputSchema: boundedBatch(
|
|
149
|
+
z.object({
|
|
150
|
+
aiderBlocks: z.array(aiderBlock).max(FILE_READ_MAX_BATCH).optional(),
|
|
151
|
+
astRules: z.array(astRule).max(FILE_READ_MAX_BATCH).optional(),
|
|
152
|
+
chattr: chattr.optional(),
|
|
153
|
+
expectedSha256: z.string().length(64),
|
|
154
|
+
patchStrategy: z.enum(["ast", "aider_block"]),
|
|
155
|
+
preview: z.boolean().optional(),
|
|
156
|
+
}),
|
|
157
|
+
"file_patch requires between 1 and 50 files",
|
|
158
|
+
),
|
|
159
|
+
title: "Patch Files Through the Enforced State Machine",
|
|
160
|
+
},
|
|
161
|
+
async (args) => {
|
|
162
|
+
try {
|
|
163
|
+
return {
|
|
164
|
+
content: [
|
|
165
|
+
{ text: JSON.stringify(await patchFiles(args)), type: "text" },
|
|
166
|
+
],
|
|
167
|
+
};
|
|
168
|
+
} catch (error) {
|
|
169
|
+
return failure(error);
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
);
|
|
173
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { McpServer } from "@modelcontextprotocol/server";
|
|
2
|
+
|
|
3
|
+
import registerAstBroTools from "./ast-bro";
|
|
4
|
+
import registerFileTools from "./files";
|
|
5
|
+
import registerLifecycleTools from "./lifecycle";
|
|
6
|
+
|
|
7
|
+
export default function (server: McpServer) {
|
|
8
|
+
registerFileTools(server);
|
|
9
|
+
registerLifecycleTools(server);
|
|
10
|
+
registerAstBroTools(server);
|
|
11
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { McpServer } from "@modelcontextprotocol/server";
|
|
2
|
+
import * as z from "zod/v4";
|
|
3
|
+
import { applyFileChattr, type FileChattr } from "../runtime/attributes";
|
|
4
|
+
import { deleteFilesSafely } from "../runtime/file-delete";
|
|
5
|
+
import { FILE_READ_MAX_BATCH } from "../runtime/file-read";
|
|
6
|
+
import { sha256 } from "../runtime/hash";
|
|
7
|
+
import { withFileLocks } from "../runtime/locks";
|
|
8
|
+
import { resolveWritablePath } from "../runtime/paths";
|
|
9
|
+
|
|
10
|
+
const chattr = z.object({
|
|
11
|
+
chmod: z.number().int().min(0).max(0o777).optional(),
|
|
12
|
+
chown: z
|
|
13
|
+
.object({
|
|
14
|
+
gid: z.number().int().nonnegative(),
|
|
15
|
+
uid: z.number().int().nonnegative(),
|
|
16
|
+
})
|
|
17
|
+
.optional(),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
const failure = (error: unknown) => ({
|
|
21
|
+
content: [
|
|
22
|
+
{
|
|
23
|
+
text: error instanceof Error ? error.message : String(error),
|
|
24
|
+
type: "text" as const,
|
|
25
|
+
},
|
|
26
|
+
],
|
|
27
|
+
isError: true,
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
export default function registerLifecycleTools(server: McpServer) {
|
|
31
|
+
server.registerTool(
|
|
32
|
+
"file_chattr",
|
|
33
|
+
{
|
|
34
|
+
description:
|
|
35
|
+
"Applies the shared chattr contract to multiple root-bounded files under deterministic locks.",
|
|
36
|
+
inputSchema: z
|
|
37
|
+
.record(
|
|
38
|
+
z.string().min(1),
|
|
39
|
+
z.object({
|
|
40
|
+
chattr,
|
|
41
|
+
expectedSha256: z.string().length(64).optional(),
|
|
42
|
+
}),
|
|
43
|
+
)
|
|
44
|
+
.refine(
|
|
45
|
+
(value) =>
|
|
46
|
+
Object.keys(value).length > 0 &&
|
|
47
|
+
Object.keys(value).length <= FILE_READ_MAX_BATCH,
|
|
48
|
+
"file_chattr requires between 1 and 50 files",
|
|
49
|
+
),
|
|
50
|
+
title: "Change File Attributes Safely",
|
|
51
|
+
},
|
|
52
|
+
async (requests) => {
|
|
53
|
+
try {
|
|
54
|
+
const entries = await Promise.all(
|
|
55
|
+
Object.entries(requests).map(async ([inputPath, request]) => ({
|
|
56
|
+
filePath: await resolveWritablePath(inputPath),
|
|
57
|
+
request,
|
|
58
|
+
})),
|
|
59
|
+
);
|
|
60
|
+
const files: Record<string, unknown> = {};
|
|
61
|
+
await withFileLocks(
|
|
62
|
+
entries.map(({ filePath }) => filePath),
|
|
63
|
+
async () => {
|
|
64
|
+
for (const { filePath, request } of entries) {
|
|
65
|
+
if (request.expectedSha256) {
|
|
66
|
+
const actual = sha256(await Bun.file(filePath).text());
|
|
67
|
+
if (actual !== request.expectedSha256)
|
|
68
|
+
throw new Error(
|
|
69
|
+
`Stale file context: expected ${request.expectedSha256}, found ${actual}`,
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
files[filePath] = {
|
|
73
|
+
chattr: await applyFileChattr(
|
|
74
|
+
filePath,
|
|
75
|
+
request.chattr as FileChattr,
|
|
76
|
+
),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
);
|
|
81
|
+
return { content: [{ text: JSON.stringify({ files }), type: "text" }] };
|
|
82
|
+
} catch (error) {
|
|
83
|
+
return failure(error);
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
);
|
|
87
|
+
|
|
88
|
+
server.registerTool(
|
|
89
|
+
"file_delete",
|
|
90
|
+
{
|
|
91
|
+
description:
|
|
92
|
+
"Deletes hash-guarded files in one reference-preflighted batch and removes empty ancestor directories within configured roots.",
|
|
93
|
+
inputSchema: z
|
|
94
|
+
.record(
|
|
95
|
+
z.string().min(1),
|
|
96
|
+
z.object({
|
|
97
|
+
expectedSha256: z.string().length(64),
|
|
98
|
+
forceReferences: z.boolean().optional(),
|
|
99
|
+
}),
|
|
100
|
+
)
|
|
101
|
+
.refine(
|
|
102
|
+
(value) =>
|
|
103
|
+
Object.keys(value).length > 0 &&
|
|
104
|
+
Object.keys(value).length <= FILE_READ_MAX_BATCH,
|
|
105
|
+
"file_delete requires between 1 and 50 files",
|
|
106
|
+
),
|
|
107
|
+
title: "Delete Files Safely",
|
|
108
|
+
},
|
|
109
|
+
async (requests) => {
|
|
110
|
+
try {
|
|
111
|
+
return {
|
|
112
|
+
content: [
|
|
113
|
+
{
|
|
114
|
+
text: JSON.stringify(await deleteFilesSafely(requests)),
|
|
115
|
+
type: "text",
|
|
116
|
+
},
|
|
117
|
+
],
|
|
118
|
+
};
|
|
119
|
+
} catch (error) {
|
|
120
|
+
return failure(error);
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
);
|
|
124
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# AST MCP isolated environment
|
|
2
|
+
|
|
3
|
+
CRITICAL INSTRUCTION: You are operating in an AST-isolated environment.
|
|
4
|
+
|
|
5
|
+
- Load and follow the `$ast-mcp` skill before exploring or changing repository files.
|
|
6
|
+
- You have zero permission to create, overwrite, patch, move, or delete files through direct editor tools, `apply_patch`, unified patches, shell utilities, or interpreter scripts.
|
|
7
|
+
- For repository structure, source, dependencies, callers, and exact file content, use only ast-mcp tools.
|
|
8
|
+
- AST-capable files must be inspected with AST intelligence tools, never `file_read`.
|
|
9
|
+
- Use `file_read` only for bounded slices of non-AST content, and batch multiple files in one call.
|
|
10
|
+
- Use `file_hash` for fresh whole-file SHA-256 values without retrieving content.
|
|
11
|
+
- For new files, use only `file_write`.
|
|
12
|
+
- For existing files, call `file_hash` immediately before a guarded `file_patch`; use its path-keyed batch shape for both AST and Aider operations.
|
|
13
|
+
- Parseable rewrite-supported files use `file_patch` with `patchStrategy: "ast"` and ordered `astRules`; unsupported, unparseable, or inspection-only formats use `patchStrategy: "aider_block"` and ordered `aiderBlocks`.
|
|
14
|
+
|
|
15
|
+
## Available ast-mcp tools
|
|
16
|
+
|
|
17
|
+
File boundary: `file_hash`, `file_read`, `file_write`, `file_patch`, `file_chattr`, `file_delete`.
|
|
18
|
+
|
|
19
|
+
Code intelligence: `digest`, `map`, `show`, `search`, `find_related`, `surface`, `deps`, `reverse_deps`, `cycles`, `graph`, `callers`, `callees`, `trace`, `impact`, `context`, `implements`, `index`, `run`, `squeeze`.
|
|
20
|
+
|
|
21
|
+
Call every intelligence tool directly by name. There is no proxy tool. Use `run` for bounded AST searches and previews. Direct `run` rewrites with `write: true` are a lower-level escape hatch for intentionally bounded cases; they remain first-match-per-file and are not the normal agent patch route. All `file_patch`, `file_write`, `file_chattr`, and `file_delete` batches are root-bounded, SHA-guarded where required, and atomically committed per keyed path. `file_write` and `file_patch` share the `file_chattr` contract rather than independent chmod/chown keys; `file_delete` is the only directory cleanup capability and only removes empty ancestors after a successful file deletion.
|
|
22
|
+
|
|
23
|
+
## Forbidden mutation paths
|
|
24
|
+
|
|
25
|
+
Never use `apply_patch`, `patch`, direct Edit/Write/Create tools, output redirection, heredoc writes, `cat`, `echo`, `printf`, `tee`, `sed -i`, `awk`, `ed`, `touch`, `truncate`, `dd`, file-writing PowerShell commands, or interpreter one-liners to mutate files. Repository scripts invoked through Bun, Node, or another package runner are allowed when the task authorizes them; their writes are best-effort monitored rather than pre-execution provable. Never use `git apply`, destructive Git worktree commands, or `dprint fmt` as an editing bypass. Hooks deny known manual paths.
|
|
26
|
+
|
|
27
|
+
Shell commands are limited to read-only inspection that ast-mcp cannot provide and repository-defined validation. Package-manager mutation is allowed only for an explicitly authorized dependency or ast-mcp installation, never as a content-editing mechanism.
|
|
28
|
+
|
|
29
|
+
## Repository search routing
|
|
30
|
+
|
|
31
|
+
Use ast-mcp intelligence tools as the primary repository search surface: `digest`, `map`, `show`, `search`, `find_related`, `callers`, `callees`, `trace`, `impact`, and bounded `run`. Do not invoke `ast-grep` directly; ast-mcp owns structural search and rewrites. `sed` is prohibited for repository reads and edits. `rg` is a fallback only for exact literals, identifiers, non-AST formats, or discovery that ast-mcp cannot provide; do not use it as the primary search route. External transcript/session analysis, Git metadata, repository-defined validation, and live runtime reproduction remain permitted exceptions.
|
|
32
|
+
|
|
33
|
+
## Required write workflow
|
|
34
|
+
|
|
35
|
+
1. Explore AST-capable content with the smallest direct intelligence call; use `impact` before shared API changes. Use batched, bounded `file_read` slices only for non-AST content.
|
|
36
|
+
2. Preview structural matches with `run({ pattern, paths, lang?, json: true })`, bounded to explicit paths. Use `file_patch` with `preview: true` when you need the full guarded and formatted dry-run contract.
|
|
37
|
+
3. Call `file_hash({ filePaths })` immediately before a SHA-guarded patch.
|
|
38
|
+
4. Call one keyed `file_patch` batch with one fresh hash and ordered operations per path:
|
|
39
|
+
- AST targets: `{ expectedSha256, patchStrategy: "ast", astRules: [...] }`
|
|
40
|
+
- Unsupported targets: `{ expectedSha256, patchStrategy: "aider_block", aiderBlocks: [...] }`
|
|
41
|
+
Each keyed path is locked and atomically committed once; preview every AST rule before the batch.
|
|
42
|
+
5. Use one keyed `file_write` batch for new files or SHA-guarded replacement of existing non-structurally-rewritable files.
|
|
43
|
+
6. Use direct `run` with `rewrite` and `write: true` only when an intentionally bounded lower-level rewrite is required; do not use it instead of `file_patch` for normal agent edits.
|
|
44
|
+
7. Verify keyed results with `show`, `map`, `run`, or bounded `file_read` slices, then run repository validation and review the final diff without mutating through Git.
|
|
45
|
+
|
|
46
|
+
A stale hash, ambiguous Aider block, unexpected match count, capped run preview, capped file slice, dprint preflight failure, missing MCP, or lost MCP connection is a safe stop. Refresh `file_hash`, re-inspect through the correct route, or restore ast-mcp and rebuild the operation; never switch to a forbidden writer.
|
|
47
|
+
|
|
48
|
+
## Transport and transcript evidence
|
|
49
|
+
|
|
50
|
+
A JSON-RPC transport batch may contain requests and notifications. Stdio emits one framed response per request; live streamable HTTP uses SSE by default and emits one event per request. Notifications never receive responses. Preserve every request ID and do not assume the live HTTP response is a JSON array unless `enableJsonResponse` is configured.
|
|
51
|
+
|
|
52
|
+
`evals:measure` inventories direct MCP records and statically visible `tools.mcp__ast_mcp__*` calls inside top-level Codex `exec` source. Put exactly one `ast-mcp-eval:<id>` marker in the user evaluation prompt, or in a direct record input supplied by an evaluation harness, to associate following direct MCP records with that case. Marked nested `exec` evidence and multi-marker evidence fail closed because an outer result cannot prove each nested call. Scoring requires schema-relevant inputs, workspace-root compliance from transcript context, required sequencing, expected output evidence, fixture assertions, and a successful output bound to each direct call.
|
|
53
|
+
|
|
54
|
+
## Missing MCP
|
|
55
|
+
|
|
56
|
+
If the skill is present but tools are absent, stop all mutation and follow the skill's `references/installation.md`. Diagnose with `scripts/check-install.ts`, install `@mwillbanks/ast-mcp` for the required local or global host surface, reconnect the MCP server, and verify all file and direct intelligence tools before continuing. Obtain authorization before downloading a package that is not already available.
|