@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.
Files changed (61) hide show
  1. package/CONTRIBUTING.md +60 -0
  2. package/LICENSE +21 -0
  3. package/README.md +109 -0
  4. package/dist/ast-mcp-hook.js +7 -0
  5. package/dist/ast-mcp-hook.js.map +11 -0
  6. package/dist/ast-mcp-install.js +22 -0
  7. package/dist/ast-mcp-install.js.map +12 -0
  8. package/dist/ast-mcp.js +115 -0
  9. package/dist/ast-mcp.js.map +89 -0
  10. package/dprint.json +37 -0
  11. package/logo.svg +1 -0
  12. package/package.json +89 -0
  13. package/src/ast-bro/capability.ts +21 -0
  14. package/src/ast-bro/client.ts +47 -0
  15. package/src/ast-bro/result.ts +42 -0
  16. package/src/ast-bro/rewrite-capability.ts +9 -0
  17. package/src/ast-bro/tools.json +603 -0
  18. package/src/hook.ts +79 -0
  19. package/src/http-entry.ts +3 -0
  20. package/src/http.ts +138 -0
  21. package/src/index.ts +8 -0
  22. package/src/installer.ts +501 -0
  23. package/src/lifecycle.ts +10 -0
  24. package/src/managed-hook.ts +4 -0
  25. package/src/patch/aider.ts +224 -0
  26. package/src/patch/engine.ts +446 -0
  27. package/src/patch/languages.ts +36 -0
  28. package/src/runtime/atomic.ts +26 -0
  29. package/src/runtime/attributes.ts +70 -0
  30. package/src/runtime/file-delete.ts +96 -0
  31. package/src/runtime/file-read.ts +178 -0
  32. package/src/runtime/format.ts +56 -0
  33. package/src/runtime/hash.ts +11 -0
  34. package/src/runtime/locks.ts +87 -0
  35. package/src/runtime/paths.ts +73 -0
  36. package/src/runtime/process-input.ts +25 -0
  37. package/src/runtime/signals.ts +47 -0
  38. package/src/server.ts +13 -0
  39. package/src/stdio.ts +154 -0
  40. package/src/tools/ast-bro.ts +172 -0
  41. package/src/tools/files.ts +173 -0
  42. package/src/tools/index.ts +11 -0
  43. package/src/tools/lifecycle.ts +124 -0
  44. package/templates/AGENTS.md +56 -0
  45. package/templates/skills/ast-mcp/SKILL.md +96 -0
  46. package/templates/skills/ast-mcp/agents/openai.yaml +4 -0
  47. package/templates/skills/ast-mcp/evals/batch.evals.json +274 -0
  48. package/templates/skills/ast-mcp/evals/evals.json +1209 -0
  49. package/templates/skills/ast-mcp/evals/file-hash.evals.json +50 -0
  50. package/templates/skills/ast-mcp/evals/measure.ts +18 -0
  51. package/templates/skills/ast-mcp/evals/results.md +17 -0
  52. package/templates/skills/ast-mcp/evals/score.ts +417 -0
  53. package/templates/skills/ast-mcp/evals/semantic.ts +332 -0
  54. package/templates/skills/ast-mcp/evals/trigger-queries.json +22 -0
  55. package/templates/skills/ast-mcp/evals/validate.ts +99 -0
  56. package/templates/skills/ast-mcp/references/installation.md +40 -0
  57. package/templates/skills/ast-mcp/references/managed-hook.ts +3 -0
  58. package/templates/skills/ast-mcp/references/patch-state-machine.md +39 -0
  59. package/templates/skills/ast-mcp/references/tool-catalog.md +46 -0
  60. package/templates/skills/ast-mcp/scripts/check-install.ts +269 -0
  61. package/templates/skills/ast-mcp/scripts/managed-hook.ts +22 -0
@@ -0,0 +1,26 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmod, rename, unlink, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ export async function replaceFileAtomically(
6
+ filePath: string,
7
+ content: string,
8
+ mode: number,
9
+ ): Promise<void> {
10
+ const extension = path.extname(filePath);
11
+ const temporary = path.join(
12
+ path.dirname(filePath),
13
+ `${path.basename(filePath, extension)}.ast-mcp-restore-${randomUUID()}${extension}`,
14
+ );
15
+ try {
16
+ await writeFile(temporary, content, {
17
+ encoding: "utf8",
18
+ flag: "wx",
19
+ mode,
20
+ });
21
+ await chmod(temporary, mode);
22
+ await rename(temporary, filePath);
23
+ } finally {
24
+ await unlink(temporary).catch(() => undefined);
25
+ }
26
+ }
@@ -0,0 +1,70 @@
1
+ import { chmod, chown, lstat } from "node:fs/promises";
2
+
3
+ export interface FileChattr {
4
+ chmod?: number;
5
+ chown?: {
6
+ gid: number;
7
+ uid: number;
8
+ };
9
+ }
10
+
11
+ export function validateFileChattr(
12
+ chattr: FileChattr | undefined,
13
+ ): FileChattr | undefined {
14
+ if (!chattr) return undefined;
15
+ if (
16
+ chattr.chmod !== undefined &&
17
+ (!Number.isInteger(chattr.chmod) ||
18
+ chattr.chmod < 0 ||
19
+ chattr.chmod > 0o777)
20
+ )
21
+ throw new Error("chmod must be an integer between 0 and 0o777");
22
+ if (
23
+ chattr.chown &&
24
+ (!Number.isInteger(chattr.chown.uid) ||
25
+ chattr.chown.uid < 0 ||
26
+ !Number.isInteger(chattr.chown.gid) ||
27
+ chattr.chown.gid < 0)
28
+ )
29
+ throw new Error("chown uid and gid must be non-negative integers");
30
+ const uid = process.getuid?.();
31
+ const gid = process.getgid?.();
32
+ if (
33
+ chattr.chown &&
34
+ (uid === undefined ||
35
+ gid === undefined ||
36
+ chattr.chown.uid !== uid ||
37
+ chattr.chown.gid !== gid)
38
+ )
39
+ throw new Error("chown may only preserve the server process owner");
40
+ return chattr;
41
+ }
42
+
43
+ export async function applyFileChattr(
44
+ filePath: string,
45
+ chattr: FileChattr | undefined,
46
+ ) {
47
+ const validated = validateFileChattr(chattr);
48
+ const before = await resultingFileChattr(filePath);
49
+ if (!validated) return before;
50
+ try {
51
+ if (validated.chown)
52
+ await chown(filePath, validated.chown.uid, validated.chown.gid);
53
+ if (validated.chmod !== undefined) await chmod(filePath, validated.chmod);
54
+ } catch (error) {
55
+ await chown(filePath, before.chown.uid, before.chown.gid).catch(
56
+ () => undefined,
57
+ );
58
+ await chmod(filePath, before.chmod).catch(() => undefined);
59
+ throw error;
60
+ }
61
+ return resultingFileChattr(filePath);
62
+ }
63
+
64
+ export async function resultingFileChattr(filePath: string) {
65
+ const metadata = await lstat(filePath);
66
+ return {
67
+ chmod: metadata.mode & 0o777,
68
+ chown: { gid: metadata.gid, uid: metadata.uid },
69
+ };
70
+ }
@@ -0,0 +1,96 @@
1
+ import { lstat, readdir, rm, rmdir } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { astCapable } from "../ast-bro/capability";
4
+ import { callAstBro } from "../ast-bro/client";
5
+ import { parseAstBroJson } from "../ast-bro/result";
6
+ import { detectAstLanguage } from "../patch/languages";
7
+ import { sha256 } from "./hash";
8
+ import { withFileLocks } from "./locks";
9
+ import { resolveWritablePath, rootForPath } from "./paths";
10
+
11
+ export interface FileDeleteRequest {
12
+ expectedSha256: string;
13
+ forceReferences?: boolean;
14
+ }
15
+
16
+ export type FileDeleteBatch = Record<string, FileDeleteRequest>;
17
+
18
+ async function importersFor(filePath: string, root: string): Promise<string[]> {
19
+ const language = detectAstLanguage(filePath);
20
+ if (!(await astCapable(filePath, language))) return [];
21
+ const result = parseAstBroJson(
22
+ await callAstBro(
23
+ "reverse_deps",
24
+ { file: path.relative(root, filePath), json: true },
25
+ root,
26
+ ),
27
+ );
28
+ return (result.importers ?? [])
29
+ .map((item: { file?: unknown }) => item.file)
30
+ .filter((file: unknown): file is string => typeof file === "string");
31
+ }
32
+
33
+ async function emptyParents(filePath: string, root: string) {
34
+ const removedDirectories: string[] = [];
35
+ let directory = path.dirname(filePath);
36
+ while (true) {
37
+ const relative = path.relative(root, directory);
38
+ if (
39
+ directory === root ||
40
+ relative.startsWith("..") ||
41
+ path.isAbsolute(relative)
42
+ )
43
+ break;
44
+ if ((await readdir(directory)).length !== 0) break;
45
+ await rmdir(directory);
46
+ removedDirectories.push(directory);
47
+ directory = path.dirname(directory);
48
+ }
49
+ return removedDirectories;
50
+ }
51
+
52
+ export async function deleteFilesSafely(requests: FileDeleteBatch) {
53
+ const entries = await Promise.all(
54
+ Object.entries(requests).map(async ([inputPath, request]) => {
55
+ const filePath = await resolveWritablePath(inputPath);
56
+ const metadata = await lstat(filePath);
57
+ if (!metadata.isFile())
58
+ throw new Error(`file_delete accepts files only: ${inputPath}`);
59
+ const root = await rootForPath(filePath);
60
+ const importers = await importersFor(filePath, root);
61
+ if (importers.length > 0 && !request.forceReferences)
62
+ throw new Error(
63
+ `file_delete rejected ${inputPath}: referenced by ${importers.join(", ")}; set forceReferences to override`,
64
+ );
65
+ return { filePath, importers, request, root };
66
+ }),
67
+ );
68
+ const files = await withFileLocks(
69
+ entries.map(({ filePath }) => filePath),
70
+ async () => {
71
+ const deleted: Record<string, unknown> = {};
72
+ for (const { filePath, request } of entries) {
73
+ const content = await Bun.file(filePath).text();
74
+ const actual = sha256(content);
75
+ if (actual !== request.expectedSha256)
76
+ throw new Error(
77
+ `Stale file context: expected ${request.expectedSha256}, found ${actual}`,
78
+ );
79
+ }
80
+ for (const { filePath, importers, request } of entries) {
81
+ await rm(filePath);
82
+ deleted[filePath] = {
83
+ deleted: true,
84
+ forcedReferences:
85
+ importers.length > 0 && request.forceReferences === true,
86
+ };
87
+ }
88
+ return deleted;
89
+ },
90
+ );
91
+ const removedDirectories = new Set<string>();
92
+ for (const { filePath, root } of entries)
93
+ for (const directory of await emptyParents(filePath, root))
94
+ removedDirectories.add(directory);
95
+ return { files, removedDirectories: [...removedDirectories].sort() };
96
+ }
@@ -0,0 +1,178 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { stat } from "node:fs/promises";
3
+
4
+ import { astCapable } from "../ast-bro/capability";
5
+ import { detectAstLanguage } from "../patch/languages";
6
+ import { sha256File } from "./hash";
7
+ import { resolveWritablePath } from "./paths";
8
+
9
+ const FILE_READ_DEFAULT_LINES = [0, 100] as const;
10
+ export const FILE_READ_MAX_BATCH = 50;
11
+ export const FILE_READ_MAX_BYTES = 1024 * 1024;
12
+ export const FILE_READ_MAX_LINES = 1000;
13
+
14
+ export interface FileReadRequest {
15
+ filePath: string;
16
+ lines?: [number, number];
17
+ maxBytes?: number;
18
+ }
19
+
20
+ async function mapConcurrently<Input, Output>(
21
+ inputs: Input[],
22
+ operation: (input: Input) => Promise<Output>,
23
+ ): Promise<Output[]> {
24
+ const output = new Array<Output>(inputs.length);
25
+ let next = 0;
26
+ await Promise.all(
27
+ Array.from({ length: Math.min(4, inputs.length) }, async () => {
28
+ while (next < inputs.length) {
29
+ const index = next;
30
+ next += 1;
31
+ output[index] = await operation(inputs[index] as Input);
32
+ }
33
+ }),
34
+ );
35
+ return output;
36
+ }
37
+
38
+ function validateRequest(request: FileReadRequest) {
39
+ const [start, end] = request.lines ?? FILE_READ_DEFAULT_LINES;
40
+ const maxBytes = request.maxBytes ?? FILE_READ_MAX_BYTES;
41
+ if (!Number.isInteger(start) || start < 0)
42
+ throw new Error("file_read line start must be a non-negative integer");
43
+ if (!Number.isInteger(end) || end <= start)
44
+ throw new Error("file_read line end must be greater than line start");
45
+ if (end - start > FILE_READ_MAX_LINES)
46
+ throw new Error(
47
+ `file_read line ranges are capped at ${FILE_READ_MAX_LINES} lines`,
48
+ );
49
+ if (
50
+ !Number.isInteger(maxBytes) ||
51
+ maxBytes < 1 ||
52
+ maxBytes > FILE_READ_MAX_BYTES
53
+ )
54
+ throw new Error(
55
+ `file_read maxBytes must be between 1 and ${FILE_READ_MAX_BYTES}`,
56
+ );
57
+ return { lines: [start, end] as [number, number], maxBytes };
58
+ }
59
+
60
+ async function readLineRange(
61
+ filePath: string,
62
+ fileSize: number,
63
+ lines: [number, number],
64
+ maxBytes: number,
65
+ ) {
66
+ const [start, end] = lines;
67
+ const selected: Buffer[] = [];
68
+ let selectedBytes = 0;
69
+ let line = 0;
70
+ let moreInChunk = false;
71
+ let truncated = false;
72
+ const stream = createReadStream(filePath);
73
+
74
+ try {
75
+ outer: for await (const raw of stream) {
76
+ const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
77
+ let offset = 0;
78
+ while (offset < chunk.length) {
79
+ const newline = chunk.indexOf(10, offset);
80
+ const segmentEnd = newline < 0 ? chunk.length : newline + 1;
81
+ if (line >= start && line < end) {
82
+ const remaining = maxBytes - selectedBytes;
83
+ const length = segmentEnd - offset;
84
+ if (length > remaining) {
85
+ if (remaining > 0) {
86
+ selected.push(chunk.subarray(offset, offset + remaining));
87
+ selectedBytes += remaining;
88
+ }
89
+ truncated = true;
90
+ moreInChunk = true;
91
+ break outer;
92
+ }
93
+ if (length > 0) {
94
+ selected.push(chunk.subarray(offset, segmentEnd));
95
+ selectedBytes += length;
96
+ }
97
+ }
98
+ offset = segmentEnd;
99
+ if (newline >= 0) {
100
+ line += 1;
101
+ if (line >= end) {
102
+ moreInChunk = offset < chunk.length;
103
+ break outer;
104
+ }
105
+ } else break;
106
+ }
107
+ }
108
+ } finally {
109
+ stream.destroy();
110
+ }
111
+
112
+ const contentBuffer = Buffer.concat(selected, selectedBytes);
113
+ let returnedLineCount = 0;
114
+ for (const byte of contentBuffer) if (byte === 10) returnedLineCount += 1;
115
+ if (contentBuffer.length > 0 && contentBuffer.at(-1) !== 10)
116
+ returnedLineCount += 1;
117
+
118
+ return {
119
+ content: contentBuffer.toString("utf8"),
120
+ hasMore: truncated || moreInChunk || stream.bytesRead < fileSize,
121
+ lines: {
122
+ requested: lines,
123
+ returned: [start, start + returnedLineCount],
124
+ },
125
+ truncated,
126
+ };
127
+ }
128
+
129
+ async function hashFileSafely(filePath: string) {
130
+ const resolved = await resolveWritablePath(filePath);
131
+ const metadata = await stat(resolved);
132
+ if (!metadata.isFile()) throw new Error(`Not a regular file: ${filePath}`);
133
+ return {
134
+ filePath: resolved,
135
+ sha256: await sha256File(resolved),
136
+ size: metadata.size,
137
+ };
138
+ }
139
+
140
+ export async function hashFilesSafely(filePaths: string[]) {
141
+ if (filePaths.length < 1 || filePaths.length > FILE_READ_MAX_BATCH)
142
+ throw new Error(
143
+ `file_hash requires between 1 and ${FILE_READ_MAX_BATCH} paths`,
144
+ );
145
+ return mapConcurrently(filePaths, hashFileSafely);
146
+ }
147
+
148
+ export async function readFileSafely(request: FileReadRequest) {
149
+ const resolved = await resolveWritablePath(request.filePath);
150
+ const language = detectAstLanguage(resolved);
151
+ if (await astCapable(resolved, language))
152
+ throw new Error(
153
+ "REJECTED: AST-capable files must use map, show, search, context, or run; use file_hash when only SHA-256 is required",
154
+ );
155
+
156
+ const metadata = await stat(resolved);
157
+ if (!metadata.isFile())
158
+ throw new Error(`Not a regular file: ${request.filePath}`);
159
+ const { lines, maxBytes } = validateRequest(request);
160
+ const [slice, sha256] = await Promise.all([
161
+ readLineRange(resolved, metadata.size, lines, maxBytes),
162
+ sha256File(resolved),
163
+ ]);
164
+ return {
165
+ ...slice,
166
+ filePath: resolved,
167
+ sha256,
168
+ size: metadata.size,
169
+ };
170
+ }
171
+
172
+ export async function readFilesSafely(requests: FileReadRequest[]) {
173
+ if (requests.length < 1 || requests.length > FILE_READ_MAX_BATCH)
174
+ throw new Error(
175
+ `file_read requires between 1 and ${FILE_READ_MAX_BATCH} files`,
176
+ );
177
+ return mapConcurrently(requests, readFileSafely);
178
+ }
@@ -0,0 +1,56 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ chmod,
4
+ lstat,
5
+ readFile,
6
+ rename,
7
+ unlink,
8
+ writeFile,
9
+ } from "node:fs/promises";
10
+ import path from "node:path";
11
+ import { runCommandInput } from "./process-input";
12
+
13
+ const packageRoot = path.resolve(import.meta.dir, "../..");
14
+ const dprint = path.join(packageRoot, "node_modules/.bin/dprint");
15
+ const dprintConfig =
16
+ process.env.AST_MCP_DPRINT_CONFIG ?? path.join(packageRoot, "dprint.json");
17
+
18
+ export async function formatContent(
19
+ filePath: string,
20
+ content: string,
21
+ ): Promise<string> {
22
+ const result = await runCommandInput(
23
+ dprint,
24
+ ["fmt", "--config", dprintConfig, "--stdin", path.basename(filePath)],
25
+ content,
26
+ );
27
+ return result.stdout;
28
+ }
29
+
30
+ export async function assertFormattable(filePath: string): Promise<void> {
31
+ await formatContent(filePath, await readFile(filePath, "utf8"));
32
+ }
33
+
34
+ export async function formatFileAtomically(filePath: string): Promise<void> {
35
+ const metadata = await lstat(filePath);
36
+ const formatted = await formatContent(
37
+ filePath,
38
+ await readFile(filePath, "utf8"),
39
+ );
40
+ const extension = path.extname(filePath);
41
+ const temporary = path.join(
42
+ path.dirname(filePath),
43
+ `${path.basename(filePath, extension)}.ast-mcp-format-${randomUUID()}${extension}`,
44
+ );
45
+ try {
46
+ await writeFile(temporary, formatted, {
47
+ encoding: "utf8",
48
+ flag: "wx",
49
+ mode: metadata.mode,
50
+ });
51
+ await chmod(temporary, metadata.mode);
52
+ await rename(temporary, filePath);
53
+ } finally {
54
+ await unlink(temporary).catch(() => undefined);
55
+ }
56
+ }
@@ -0,0 +1,11 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ export function sha256(content: string | Uint8Array): string {
4
+ return createHash("sha256").update(content).digest("hex");
5
+ }
6
+
7
+ export async function sha256File(filePath: string): Promise<string> {
8
+ const hash = createHash("sha256");
9
+ for await (const chunk of createReadStream(filePath)) hash.update(chunk);
10
+ return hash.digest("hex");
11
+ }
@@ -0,0 +1,87 @@
1
+ import { lstat, open, rm } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { sha256 } from "./hash";
4
+
5
+ const queues = new Map<string, Promise<void>>();
6
+
7
+ async function lockPath(filePath: string): Promise<string> {
8
+ const targetDirectory = path.dirname(filePath);
9
+ let directory = targetDirectory;
10
+ while (true) {
11
+ try {
12
+ if (!(await lstat(directory)).isDirectory())
13
+ throw new Error(`Lock parent is not a directory: ${directory}`);
14
+ break;
15
+ } catch (error) {
16
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
17
+ const parent = path.dirname(directory);
18
+ if (parent === directory) throw error;
19
+ directory = parent;
20
+ }
21
+ }
22
+ const name =
23
+ directory === targetDirectory
24
+ ? `.${path.basename(filePath)}.ast-mcp.lock`
25
+ : `.${sha256(filePath).slice(0, 24)}.ast-mcp.lock`;
26
+ return path.join(directory, name);
27
+ }
28
+
29
+ async function waitForLock(filePath: string): Promise<() => Promise<void>> {
30
+ const lock = await lockPath(filePath);
31
+ while (true) {
32
+ try {
33
+ const handle = await open(lock, "wx");
34
+ await handle.close();
35
+ return () => rm(lock, { force: true });
36
+ } catch (error) {
37
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
38
+ await new Promise((resolve) => setTimeout(resolve, 10));
39
+ }
40
+ }
41
+ }
42
+
43
+ async function withQueuedLock<Result>(
44
+ filePath: string,
45
+ operation: () => Promise<Result>,
46
+ ): Promise<Result> {
47
+ const previous = queues.get(filePath) ?? Promise.resolve();
48
+ let release!: () => void;
49
+ const current = new Promise<void>((resolve) => {
50
+ release = resolve;
51
+ });
52
+ const queued = previous.then(() => current);
53
+ queues.set(filePath, queued);
54
+ await previous;
55
+ try {
56
+ return await operation();
57
+ } finally {
58
+ release();
59
+ if (queues.get(filePath) === queued) queues.delete(filePath);
60
+ }
61
+ }
62
+
63
+ export async function withFileLock<Result>(
64
+ filePath: string,
65
+ operation: () => Promise<Result>,
66
+ ): Promise<Result> {
67
+ return withQueuedLock(filePath, async () => {
68
+ const release = await waitForLock(filePath);
69
+ try {
70
+ return await operation();
71
+ } finally {
72
+ await release();
73
+ }
74
+ });
75
+ }
76
+
77
+ export async function withFileLocks<Result>(
78
+ filePaths: string[],
79
+ operation: () => Promise<Result>,
80
+ ): Promise<Result> {
81
+ const sorted = [...new Set(filePaths)].sort();
82
+ const acquire = async (index: number): Promise<Result> =>
83
+ index === sorted.length
84
+ ? operation()
85
+ : withFileLock(sorted[index] as string, () => acquire(index + 1));
86
+ return acquire(0);
87
+ }
@@ -0,0 +1,73 @@
1
+ import { lstat, realpath } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ function configuredRoots(): string[] {
5
+ return (
6
+ process.env.AST_MCP_ROOTS?.split(path.delimiter).filter(Boolean) ?? [
7
+ process.cwd(),
8
+ ]
9
+ ).map((item) => path.resolve(item));
10
+ }
11
+ function within(root: string, target: string): boolean {
12
+ const relative = path.relative(root, target);
13
+ return (
14
+ relative === "" ||
15
+ (!relative.startsWith("..") && !path.isAbsolute(relative))
16
+ );
17
+ }
18
+
19
+ async function allowedRoots(): Promise<string[]> {
20
+ const cwd = await realpath(process.cwd()).catch(() => process.cwd());
21
+ const roots = await Promise.all(
22
+ configuredRoots().map(async (root) => realpath(root).catch(() => root)),
23
+ );
24
+ if (
25
+ process.env.AST_MCP_ALLOW_EXTERNAL_ROOTS !== "1" &&
26
+ roots.some((root) => !within(cwd, root))
27
+ )
28
+ throw new Error(
29
+ "AST_MCP_ROOTS contains a root outside the server working directory; set AST_MCP_ALLOW_EXTERNAL_ROOTS=1 to opt in",
30
+ );
31
+ return roots;
32
+ }
33
+
34
+ export async function primaryRoot(): Promise<string> {
35
+ return (await allowedRoots())[0] as string;
36
+ }
37
+
38
+ export async function rootForPath(filePath: string): Promise<string> {
39
+ const root = (await allowedRoots()).find((candidate) =>
40
+ within(candidate, filePath),
41
+ );
42
+ if (!root) throw new Error(`Path is outside AST_MCP_ROOTS: ${filePath}`);
43
+ return root;
44
+ }
45
+ export async function resolveWritablePath(filePath: string): Promise<string> {
46
+ const roots = await allowedRoots();
47
+ const absolute = path.isAbsolute(filePath)
48
+ ? filePath
49
+ : path.resolve(roots[0] as string, filePath);
50
+ let existing = path.dirname(absolute);
51
+ const missing: string[] = [];
52
+ while (true) {
53
+ try {
54
+ existing = await realpath(existing);
55
+ break;
56
+ } catch (error) {
57
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
58
+ const parent = path.dirname(existing);
59
+ if (parent === existing) throw error;
60
+ missing.unshift(path.basename(existing));
61
+ existing = parent;
62
+ }
63
+ }
64
+ const resolved = path.join(existing, ...missing, path.basename(absolute));
65
+ if (!roots.some((root) => within(root, resolved)))
66
+ throw new Error(`Path is outside AST_MCP_ROOTS: ${filePath}`);
67
+ if ((await lstat(resolved).catch(() => undefined))?.isSymbolicLink())
68
+ throw new Error(`Symbolic-link targets are not writable: ${filePath}`);
69
+ return resolved;
70
+ }
71
+ export function rootsForDisplay(): string[] {
72
+ return configuredRoots();
73
+ }
@@ -0,0 +1,25 @@
1
+ import { execFile } from "node:child_process";
2
+ export function runCommandInput(
3
+ command: string,
4
+ args: string[],
5
+ input: string,
6
+ ): Promise<{ stdout: string; stderr: string }> {
7
+ return new Promise((resolve, reject) => {
8
+ const child = execFile(
9
+ command,
10
+ args,
11
+ { encoding: "utf8", maxBuffer: 16 * 1024 * 1024, timeout: 30_000 },
12
+ (error, stdout, stderr) => {
13
+ if (error)
14
+ reject(
15
+ new Error(
16
+ `${command} failed: ${(stderr || stdout || error.message).trim()}`,
17
+ { cause: error },
18
+ ),
19
+ );
20
+ else resolve({ stderr, stdout });
21
+ },
22
+ );
23
+ child.stdin?.end(input);
24
+ });
25
+ }
@@ -0,0 +1,47 @@
1
+ export const PROCESS_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"] as const;
2
+
3
+ export type ProcessSignal = (typeof PROCESS_SIGNALS)[number];
4
+
5
+ export interface SignalHost {
6
+ exit(code: number): unknown;
7
+ off(signal: ProcessSignal, listener: () => void): unknown;
8
+ on(signal: ProcessSignal, listener: () => void): unknown;
9
+ stderr: { write(message: string): unknown };
10
+ }
11
+
12
+ export function installProcessSignalHandlers(
13
+ shutdown: (signal: ProcessSignal) => Promise<void> | void,
14
+ host: SignalHost = process,
15
+ ) {
16
+ let shuttingDown = false;
17
+ const listeners = new Map<ProcessSignal, () => void>();
18
+
19
+ for (const signal of PROCESS_SIGNALS) {
20
+ const listener = () => {
21
+ if (shuttingDown) {
22
+ host.exit(1);
23
+ return;
24
+ }
25
+ shuttingDown = true;
26
+ void Promise.resolve()
27
+ .then(() => shutdown(signal))
28
+ .then(
29
+ () => host.exit(0),
30
+ (error) => {
31
+ const detail =
32
+ error instanceof Error ? error.message : String(error);
33
+ host.stderr.write(
34
+ `ast-mcp shutdown failed after ${signal}: ${detail}\n`,
35
+ );
36
+ host.exit(1);
37
+ },
38
+ );
39
+ };
40
+ listeners.set(signal, listener);
41
+ host.on(signal, listener);
42
+ }
43
+
44
+ return () => {
45
+ for (const [signal, listener] of listeners) host.off(signal, listener);
46
+ };
47
+ }
package/src/server.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { McpServer } from "@modelcontextprotocol/server";
2
+ import tools from "./tools";
3
+
4
+ export function createServer() {
5
+ const server = new McpServer({
6
+ name: "ast-mcp",
7
+ version: "1.0.0",
8
+ });
9
+
10
+ tools(server);
11
+
12
+ return server;
13
+ }