@mwillbanks/ast-mcp 0.1.3 → 0.2.1
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/README.md +59 -20
- package/dist/ast-mcp.js +232 -130
- package/dist/ast-mcp.js.map +107 -27
- package/package.json +2 -1
- package/src/ast-bro/capability.ts +3 -8
- package/src/ast-bro/client.ts +18 -2
- package/src/ast-bro/result.ts +5 -12
- package/src/cli.ts +70 -95
- package/src/config-cli.ts +54 -0
- package/src/config.ts +886 -0
- package/src/helpers/aider.ts +252 -0
- package/src/helpers/ast-bro.ts +64 -0
- package/src/helpers/config.ts +149 -0
- package/src/helpers/hook.ts +60 -0
- package/src/helpers/installer.ts +249 -0
- package/src/helpers/json.ts +19 -0
- package/src/helpers/mcp-schema.ts +31 -0
- package/src/helpers/process.ts +31 -0
- package/src/helpers/string.ts +97 -0
- package/src/hook.ts +135 -40
- package/src/http-entry.ts +1 -1
- package/src/http.ts +118 -103
- package/src/installer-transport.ts +190 -0
- package/src/installer.ts +604 -247
- package/src/mcp-cli.ts +104 -0
- package/src/patch/aider.ts +6 -199
- package/src/patch/engine.ts +271 -197
- package/src/runtime/dependencies.ts +48 -29
- package/src/runtime/file-delete.ts +13 -9
- package/src/runtime/file-read.ts +91 -57
- package/src/runtime/file-rename.ts +158 -0
- package/src/runtime/format.ts +57 -34
- package/src/runtime/paths.ts +30 -16
- package/src/runtime/policy.ts +21 -0
- package/src/runtime/process-input.ts +14 -4
- package/src/service.ts +217 -0
- package/src/shell-policy.ts +331 -0
- package/src/stdio.ts +47 -35
- package/src/tools/ast-bro.ts +12 -6
- package/src/tools/configured.ts +28 -0
- package/src/tools/files.ts +24 -27
- package/src/tools/index.ts +5 -3
- package/src/tools/lifecycle.ts +69 -55
- package/templates/skills/ast-mcp/SKILL.md +7 -6
- package/templates/skills/ast-mcp/evals/batch.evals.json +48 -0
- package/templates/skills/ast-mcp/evals/evals.json +1 -0
- package/templates/skills/ast-mcp/evals/score.test.ts +175 -0
- package/templates/skills/ast-mcp/evals/score.ts +304 -267
- package/templates/skills/ast-mcp/evals/semantic.test.ts +322 -0
- package/templates/skills/ast-mcp/evals/semantic.ts +390 -135
- package/templates/skills/ast-mcp/evals/shell-policy.ts +252 -0
- package/templates/skills/ast-mcp/evals/source.test.ts +46 -0
- package/templates/skills/ast-mcp/evals/source.ts +164 -0
- package/templates/skills/ast-mcp/evals/trigger-queries.json +1 -1
- package/templates/skills/ast-mcp/references/installation.md +9 -8
- package/templates/skills/ast-mcp/references/patch-state-machine.md +5 -5
- package/templates/skills/ast-mcp/references/tool-catalog.md +4 -2
- package/templates/skills/ast-mcp/scripts/check-install.ts +323 -131
package/src/config.ts
ADDED
|
@@ -0,0 +1,886 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { stat } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { collectRequestPaths, normalizeConfigLayer } from "./helpers/config";
|
|
8
|
+
|
|
9
|
+
const positiveInteger = z.number().int().positive();
|
|
10
|
+
const toolNameSchema = z
|
|
11
|
+
.string()
|
|
12
|
+
.min(1)
|
|
13
|
+
.max(200)
|
|
14
|
+
.regex(
|
|
15
|
+
/^[a-zA-Z0-9_.:-]+$/,
|
|
16
|
+
"tool names may contain letters, digits, _, ., :, and - only",
|
|
17
|
+
);
|
|
18
|
+
const hookSchema = z
|
|
19
|
+
.object({
|
|
20
|
+
allow_tools: z.array(toolNameSchema).max(64).optional(),
|
|
21
|
+
block_tools: z.array(toolNameSchema).max(64).optional(),
|
|
22
|
+
enabled: z.boolean().optional(),
|
|
23
|
+
})
|
|
24
|
+
.strict()
|
|
25
|
+
.superRefine((value, context) => {
|
|
26
|
+
const allowed = new Set(
|
|
27
|
+
(value.allow_tools ?? []).map((tool) => tool.toLowerCase()),
|
|
28
|
+
);
|
|
29
|
+
for (const tool of value.block_tools ?? [])
|
|
30
|
+
if (allowed.has(tool.toLowerCase()))
|
|
31
|
+
context.addIssue({
|
|
32
|
+
code: "custom",
|
|
33
|
+
message: `hook tool "${tool}" cannot be both allowed and blocked`,
|
|
34
|
+
path: ["block_tools"],
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
const formatterSchema = z
|
|
38
|
+
.object({
|
|
39
|
+
args: z.array(z.string().max(4096)).max(64).optional(),
|
|
40
|
+
command: z.string().min(1).max(4096),
|
|
41
|
+
extensions: z
|
|
42
|
+
.array(
|
|
43
|
+
z.string().regex(/^\.[^./\\]+$/, "extensions must begin with a dot"),
|
|
44
|
+
)
|
|
45
|
+
.max(64)
|
|
46
|
+
.optional(),
|
|
47
|
+
globs: z.array(z.string().min(1).max(4096)).max(64).optional(),
|
|
48
|
+
timeout_ms: positiveInteger.max(120_000).optional(),
|
|
49
|
+
})
|
|
50
|
+
.strict()
|
|
51
|
+
.refine(
|
|
52
|
+
(value) =>
|
|
53
|
+
Boolean(value.extensions?.length) || Boolean(value.globs?.length),
|
|
54
|
+
"formatter requires at least one extension or glob",
|
|
55
|
+
);
|
|
56
|
+
const fileSchema = z
|
|
57
|
+
.object({
|
|
58
|
+
dependencies: z
|
|
59
|
+
.object({
|
|
60
|
+
ast_bro_binary: z.string().min(1).optional(),
|
|
61
|
+
dprint_binary: z.string().min(1).optional(),
|
|
62
|
+
})
|
|
63
|
+
.strict()
|
|
64
|
+
.optional(),
|
|
65
|
+
formatting: z
|
|
66
|
+
.object({
|
|
67
|
+
dprint_config: z.string().min(1).optional(),
|
|
68
|
+
enabled: z.boolean().optional(),
|
|
69
|
+
formatters: z.array(formatterSchema).max(64).optional(),
|
|
70
|
+
})
|
|
71
|
+
.strict()
|
|
72
|
+
.optional(),
|
|
73
|
+
http: z
|
|
74
|
+
.object({
|
|
75
|
+
host: z.string().min(1).optional(),
|
|
76
|
+
port: z.number().int().min(1).max(65_535).optional(),
|
|
77
|
+
session_sweep_interval_ms: positiveInteger.optional(),
|
|
78
|
+
session_timeout_ms: positiveInteger.optional(),
|
|
79
|
+
})
|
|
80
|
+
.strict()
|
|
81
|
+
.optional(),
|
|
82
|
+
safety: z
|
|
83
|
+
.object({
|
|
84
|
+
allow_external_roots: z.boolean().optional(),
|
|
85
|
+
follow_symlinks: z.boolean().optional(),
|
|
86
|
+
hook: hookSchema.optional(),
|
|
87
|
+
require_hash: z.boolean().optional(),
|
|
88
|
+
})
|
|
89
|
+
.strict()
|
|
90
|
+
.optional(),
|
|
91
|
+
version: z.literal(1).optional(),
|
|
92
|
+
workspace: z
|
|
93
|
+
.object({ roots: z.array(z.string().min(1)).min(1).optional() })
|
|
94
|
+
.strict()
|
|
95
|
+
.optional(),
|
|
96
|
+
})
|
|
97
|
+
.strict();
|
|
98
|
+
|
|
99
|
+
type AstMcpFileConfig = z.infer<typeof fileSchema>;
|
|
100
|
+
|
|
101
|
+
export interface ResolvedConfig {
|
|
102
|
+
dependencies: { astBroBinary?: string; dprintBinary?: string };
|
|
103
|
+
formatting: {
|
|
104
|
+
dprintConfig: string;
|
|
105
|
+
enabled: boolean;
|
|
106
|
+
formatters: Array<{
|
|
107
|
+
args: string[];
|
|
108
|
+
command: string;
|
|
109
|
+
extensions: string[];
|
|
110
|
+
globs: string[];
|
|
111
|
+
timeoutMs: number;
|
|
112
|
+
}>;
|
|
113
|
+
};
|
|
114
|
+
http: {
|
|
115
|
+
host: string;
|
|
116
|
+
port: number;
|
|
117
|
+
sessionTimeoutMs: number;
|
|
118
|
+
sessionSweepIntervalMs: number;
|
|
119
|
+
};
|
|
120
|
+
projectRoot: string;
|
|
121
|
+
provenance: Record<string, "default" | "global" | "project" | "environment">;
|
|
122
|
+
safety: {
|
|
123
|
+
allowExternalRoots: boolean;
|
|
124
|
+
followSymlinks: boolean;
|
|
125
|
+
hook: { allowTools: string[]; blockTools: string[]; enabled: boolean };
|
|
126
|
+
requireHash: boolean;
|
|
127
|
+
};
|
|
128
|
+
sources: {
|
|
129
|
+
project?: string;
|
|
130
|
+
global?: string;
|
|
131
|
+
environment: string[];
|
|
132
|
+
};
|
|
133
|
+
trustedRoots: string[];
|
|
134
|
+
version: 1;
|
|
135
|
+
workspace: { roots: string[] };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface ResolveConfigOptions {
|
|
139
|
+
clientRoots?: string[];
|
|
140
|
+
cwd?: string;
|
|
141
|
+
env?: NodeJS.ProcessEnv;
|
|
142
|
+
home?: string;
|
|
143
|
+
platform?: NodeJS.Platform;
|
|
144
|
+
requestPaths?: string[];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
interface LoadedLayer {
|
|
148
|
+
fingerprint: string;
|
|
149
|
+
path: string;
|
|
150
|
+
value?: AstMcpFileConfig;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
interface InternalConfig {
|
|
154
|
+
dependencies?: { ast_bro_binary?: string; dprint_binary?: string };
|
|
155
|
+
formatting?: {
|
|
156
|
+
dprint_config?: string;
|
|
157
|
+
enabled?: boolean;
|
|
158
|
+
formatters?: Array<{
|
|
159
|
+
args?: string[];
|
|
160
|
+
command: string;
|
|
161
|
+
extensions?: string[];
|
|
162
|
+
globs?: string[];
|
|
163
|
+
timeout_ms?: number;
|
|
164
|
+
}>;
|
|
165
|
+
};
|
|
166
|
+
http?: {
|
|
167
|
+
host?: string;
|
|
168
|
+
port?: number;
|
|
169
|
+
session_timeout_ms?: number;
|
|
170
|
+
session_sweep_interval_ms?: number;
|
|
171
|
+
};
|
|
172
|
+
safety?: {
|
|
173
|
+
allow_external_roots?: boolean;
|
|
174
|
+
follow_symlinks?: boolean;
|
|
175
|
+
hook?: {
|
|
176
|
+
allow_tools?: string[];
|
|
177
|
+
block_tools?: string[];
|
|
178
|
+
enabled?: boolean;
|
|
179
|
+
};
|
|
180
|
+
require_hash?: boolean;
|
|
181
|
+
};
|
|
182
|
+
version?: 1;
|
|
183
|
+
workspace?: { roots?: string[] };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
class ConfigurationError extends Error {
|
|
187
|
+
override name = "ConfigurationError";
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const layerCache = new Map<
|
|
191
|
+
string,
|
|
192
|
+
{ fingerprint: string; promise: Promise<LoadedLayer> }
|
|
193
|
+
>();
|
|
194
|
+
const resolvedCache = new Map<
|
|
195
|
+
string,
|
|
196
|
+
{ fingerprint: string; value: ResolvedConfig }
|
|
197
|
+
>();
|
|
198
|
+
const dprintConfigCache = new Map<
|
|
199
|
+
string,
|
|
200
|
+
{ fingerprint: string; promise: Promise<string> }
|
|
201
|
+
>();
|
|
202
|
+
|
|
203
|
+
function packageDprintConfig() {
|
|
204
|
+
return path.resolve(import.meta.dir, "../dprint.json");
|
|
205
|
+
}
|
|
206
|
+
async function validateDprintConfig(filePath: string): Promise<string> {
|
|
207
|
+
const metadata = await stat(filePath).catch((error) => {
|
|
208
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
209
|
+
throw error;
|
|
210
|
+
});
|
|
211
|
+
if (!metadata)
|
|
212
|
+
throw new ConfigurationError(
|
|
213
|
+
`formatting.dprint_config does not exist: ${filePath}`,
|
|
214
|
+
);
|
|
215
|
+
if (!metadata.isFile())
|
|
216
|
+
throw new ConfigurationError(
|
|
217
|
+
`formatting.dprint_config is not a file: ${filePath}`,
|
|
218
|
+
);
|
|
219
|
+
const fingerprint = `${metadata.mtimeMs}:${metadata.size}`;
|
|
220
|
+
const cached = dprintConfigCache.get(filePath);
|
|
221
|
+
if (cached?.fingerprint === fingerprint) return cached.promise;
|
|
222
|
+
const promise = Bun.file(filePath)
|
|
223
|
+
.text()
|
|
224
|
+
.then((source) => {
|
|
225
|
+
let parsed: unknown;
|
|
226
|
+
try {
|
|
227
|
+
parsed = Bun.JSONC.parse(source);
|
|
228
|
+
} catch (error) {
|
|
229
|
+
throw new ConfigurationError(
|
|
230
|
+
`Invalid dprint configuration at ${filePath}: ${error instanceof Error ? error.message : String(error)}`,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
234
|
+
throw new ConfigurationError(
|
|
235
|
+
`Invalid dprint configuration at ${filePath}: expected an object`,
|
|
236
|
+
);
|
|
237
|
+
return fingerprint;
|
|
238
|
+
});
|
|
239
|
+
dprintConfigCache.set(filePath, { fingerprint, promise });
|
|
240
|
+
return promise;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function within(root: string, target: string) {
|
|
244
|
+
const relative = path.relative(root, target);
|
|
245
|
+
return (
|
|
246
|
+
relative === "" ||
|
|
247
|
+
(!relative.startsWith("..") && !path.isAbsolute(relative))
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function resolveFileUri(value: string) {
|
|
252
|
+
if (!value.startsWith("file:")) return value;
|
|
253
|
+
try {
|
|
254
|
+
return fileURLToPath(value);
|
|
255
|
+
} catch (error) {
|
|
256
|
+
throw new ConfigurationError(
|
|
257
|
+
`Invalid MCP workspace root "${value}": ${error instanceof Error ? error.message : String(error)}`,
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async function existingDirectory(value: string) {
|
|
263
|
+
const absolute = path.resolve(value);
|
|
264
|
+
const metadata = await stat(absolute).catch(() => undefined);
|
|
265
|
+
if (!metadata?.isDirectory())
|
|
266
|
+
throw new ConfigurationError(
|
|
267
|
+
`Configuration project root is not a directory: ${absolute}`,
|
|
268
|
+
);
|
|
269
|
+
return absolute;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export function globalConfigPath(options: ResolveConfigOptions = {}) {
|
|
273
|
+
const env = options.env ?? process.env;
|
|
274
|
+
const home = options.home ?? os.homedir();
|
|
275
|
+
const platform = options.platform ?? process.platform;
|
|
276
|
+
if (platform === "win32")
|
|
277
|
+
return path.join(
|
|
278
|
+
env.APPDATA ?? path.join(home, "AppData", "Roaming"),
|
|
279
|
+
"ast-mcp",
|
|
280
|
+
"ast-mcp.toml",
|
|
281
|
+
);
|
|
282
|
+
return path.join(
|
|
283
|
+
env.XDG_CONFIG_HOME ?? path.join(home, ".config"),
|
|
284
|
+
"ast-mcp",
|
|
285
|
+
"ast-mcp.toml",
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function projectConfigPath(projectRoot: string) {
|
|
290
|
+
let current = projectRoot;
|
|
291
|
+
while (true) {
|
|
292
|
+
const candidate = path.join(current, "ast-mcp.toml");
|
|
293
|
+
if (
|
|
294
|
+
await stat(candidate)
|
|
295
|
+
.then(() => true)
|
|
296
|
+
.catch(() => false)
|
|
297
|
+
)
|
|
298
|
+
return candidate;
|
|
299
|
+
if (
|
|
300
|
+
await stat(path.join(current, ".git"))
|
|
301
|
+
.then(() => true)
|
|
302
|
+
.catch(() => false)
|
|
303
|
+
)
|
|
304
|
+
return undefined;
|
|
305
|
+
const parent = path.dirname(current);
|
|
306
|
+
if (parent === current) return undefined;
|
|
307
|
+
current = parent;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function diagnostic(error: z.ZodError) {
|
|
312
|
+
return error.issues
|
|
313
|
+
.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`)
|
|
314
|
+
.join("; ");
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function _pathValue(value: string, base: string) {
|
|
318
|
+
if (path.isAbsolute(value) || (!value.includes("/") && !value.includes("\\")))
|
|
319
|
+
return value;
|
|
320
|
+
return path.resolve(base, value);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function normalizeLayer(
|
|
324
|
+
value: AstMcpFileConfig,
|
|
325
|
+
filePath: string,
|
|
326
|
+
): AstMcpFileConfig {
|
|
327
|
+
return normalizeConfigLayer(value, filePath);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
async function loadLayer(filePath: string): Promise<LoadedLayer> {
|
|
331
|
+
const metadata = await stat(filePath).catch((error) => {
|
|
332
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
333
|
+
throw error;
|
|
334
|
+
});
|
|
335
|
+
const fingerprint = metadata
|
|
336
|
+
? `${metadata.mtimeMs}:${metadata.size}`
|
|
337
|
+
: "missing";
|
|
338
|
+
const cached = layerCache.get(filePath);
|
|
339
|
+
if (cached?.fingerprint === fingerprint) return cached.promise;
|
|
340
|
+
|
|
341
|
+
const promise = (async () => {
|
|
342
|
+
if (!metadata) return { fingerprint, path: filePath };
|
|
343
|
+
let parsed: unknown;
|
|
344
|
+
try {
|
|
345
|
+
parsed = Bun.TOML.parse(await Bun.file(filePath).text());
|
|
346
|
+
} catch (error) {
|
|
347
|
+
throw new ConfigurationError(
|
|
348
|
+
`${filePath}: invalid TOML: ${error instanceof Error ? error.message : String(error)}`,
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
const result = fileSchema.safeParse(parsed);
|
|
352
|
+
if (!result.success)
|
|
353
|
+
throw new ConfigurationError(
|
|
354
|
+
`${filePath}: invalid configuration: ${diagnostic(result.error)}`,
|
|
355
|
+
);
|
|
356
|
+
return {
|
|
357
|
+
fingerprint,
|
|
358
|
+
path: filePath,
|
|
359
|
+
value: normalizeLayer(result.data, filePath),
|
|
360
|
+
};
|
|
361
|
+
})();
|
|
362
|
+
layerCache.set(filePath, { fingerprint, promise });
|
|
363
|
+
return promise;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function integerEnvironment(
|
|
367
|
+
env: NodeJS.ProcessEnv,
|
|
368
|
+
name: string,
|
|
369
|
+
minimum: number,
|
|
370
|
+
maximum = Number.MAX_SAFE_INTEGER,
|
|
371
|
+
) {
|
|
372
|
+
const raw = env[name];
|
|
373
|
+
if (raw === undefined) return undefined;
|
|
374
|
+
const value = Number(raw);
|
|
375
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
|
|
376
|
+
throw new ConfigurationError(
|
|
377
|
+
`Environment variable ${name} must be an integer from ${minimum} to ${maximum}; received "${raw}"`,
|
|
378
|
+
);
|
|
379
|
+
return value;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function booleanEnvironment(env: NodeJS.ProcessEnv, name: string) {
|
|
383
|
+
const raw = env[name];
|
|
384
|
+
if (raw === undefined) return undefined;
|
|
385
|
+
if (raw === "1" || raw === "true") return true;
|
|
386
|
+
if (raw === "0" || raw === "false") return false;
|
|
387
|
+
throw new ConfigurationError(
|
|
388
|
+
`Environment variable ${name} must be 1, 0, true, or false; received "${raw}"`,
|
|
389
|
+
);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
class EnvironmentUsage {
|
|
393
|
+
readonly names: string[] = [];
|
|
394
|
+
|
|
395
|
+
use<T>(name: string, value: T | undefined) {
|
|
396
|
+
if (value !== undefined) this.names.push(name);
|
|
397
|
+
return value;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function environmentRoots(
|
|
402
|
+
env: NodeJS.ProcessEnv,
|
|
403
|
+
cwd: string,
|
|
404
|
+
usage: EnvironmentUsage,
|
|
405
|
+
) {
|
|
406
|
+
const roots = env.AST_MCP_ROOTS?.split(path.delimiter)
|
|
407
|
+
.filter(Boolean)
|
|
408
|
+
.map((item) => path.resolve(cwd, item));
|
|
409
|
+
if (env.AST_MCP_ROOTS !== undefined && !roots?.length)
|
|
410
|
+
throw new ConfigurationError(
|
|
411
|
+
"Environment variable AST_MCP_ROOTS must contain at least one path",
|
|
412
|
+
);
|
|
413
|
+
return usage.use("AST_MCP_ROOTS", roots);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function environmentDependencies(
|
|
417
|
+
env: NodeJS.ProcessEnv,
|
|
418
|
+
usage: EnvironmentUsage,
|
|
419
|
+
) {
|
|
420
|
+
const astBroBinary = usage.use("AST_BRO_BINARY", env.AST_BRO_BINARY);
|
|
421
|
+
const dprintBinary = usage.use("DPRINT_BINARY", env.DPRINT_BINARY);
|
|
422
|
+
return astBroBinary || dprintBinary
|
|
423
|
+
? { ast_bro_binary: astBroBinary, dprint_binary: dprintBinary }
|
|
424
|
+
: undefined;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function environmentFormatting(
|
|
428
|
+
env: NodeJS.ProcessEnv,
|
|
429
|
+
cwd: string,
|
|
430
|
+
usage: EnvironmentUsage,
|
|
431
|
+
) {
|
|
432
|
+
const configured = env.AST_MCP_DPRINT_CONFIG
|
|
433
|
+
? path.resolve(cwd, env.AST_MCP_DPRINT_CONFIG)
|
|
434
|
+
: undefined;
|
|
435
|
+
const dprintConfig = usage.use("AST_MCP_DPRINT_CONFIG", configured);
|
|
436
|
+
return dprintConfig ? { dprint_config: dprintConfig } : undefined;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function environmentHttp(env: NodeJS.ProcessEnv, usage: EnvironmentUsage) {
|
|
440
|
+
const host = usage.use("AST_MCP_HTTP_HOST", env.AST_MCP_HTTP_HOST);
|
|
441
|
+
const port = usage.use("PORT", integerEnvironment(env, "PORT", 1, 65_535));
|
|
442
|
+
const sessionTimeout = usage.use(
|
|
443
|
+
"AST_MCP_SESSION_TIMEOUT_MS",
|
|
444
|
+
integerEnvironment(env, "AST_MCP_SESSION_TIMEOUT_MS", 1),
|
|
445
|
+
);
|
|
446
|
+
const sessionSweep = usage.use(
|
|
447
|
+
"AST_MCP_SESSION_SWEEP_INTERVAL_MS",
|
|
448
|
+
integerEnvironment(env, "AST_MCP_SESSION_SWEEP_INTERVAL_MS", 1),
|
|
449
|
+
);
|
|
450
|
+
if (!host && !port && !sessionTimeout && !sessionSweep) return undefined;
|
|
451
|
+
return {
|
|
452
|
+
host,
|
|
453
|
+
port,
|
|
454
|
+
session_sweep_interval_ms: sessionSweep,
|
|
455
|
+
session_timeout_ms: sessionTimeout,
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function environmentSafety(env: NodeJS.ProcessEnv, usage: EnvironmentUsage) {
|
|
460
|
+
const allowExternal = usage.use(
|
|
461
|
+
"AST_MCP_ALLOW_EXTERNAL_ROOTS",
|
|
462
|
+
booleanEnvironment(env, "AST_MCP_ALLOW_EXTERNAL_ROOTS"),
|
|
463
|
+
);
|
|
464
|
+
return allowExternal === undefined
|
|
465
|
+
? undefined
|
|
466
|
+
: { allow_external_roots: allowExternal };
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function environmentLayer(
|
|
470
|
+
env: NodeJS.ProcessEnv,
|
|
471
|
+
cwd: string,
|
|
472
|
+
): { names: string[]; value: InternalConfig } {
|
|
473
|
+
const usage = new EnvironmentUsage();
|
|
474
|
+
const roots = environmentRoots(env, cwd, usage);
|
|
475
|
+
const safety = environmentSafety(env, usage);
|
|
476
|
+
const formatting = environmentFormatting(env, cwd, usage);
|
|
477
|
+
const dependencies = environmentDependencies(env, usage);
|
|
478
|
+
const http = environmentHttp(env, usage);
|
|
479
|
+
return {
|
|
480
|
+
names: usage.names,
|
|
481
|
+
value: {
|
|
482
|
+
dependencies,
|
|
483
|
+
formatting,
|
|
484
|
+
http,
|
|
485
|
+
safety,
|
|
486
|
+
workspace: roots ? { roots } : undefined,
|
|
487
|
+
},
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
const leaves = [
|
|
492
|
+
"version",
|
|
493
|
+
"workspace.roots",
|
|
494
|
+
"safety.allow_external_roots",
|
|
495
|
+
"safety.follow_symlinks",
|
|
496
|
+
"safety.hook.allow_tools",
|
|
497
|
+
"safety.hook.block_tools",
|
|
498
|
+
"safety.hook.enabled",
|
|
499
|
+
"safety.require_hash",
|
|
500
|
+
"formatting.dprint_config",
|
|
501
|
+
"formatting.enabled",
|
|
502
|
+
"formatting.formatters",
|
|
503
|
+
"dependencies.ast_bro_binary",
|
|
504
|
+
"dependencies.dprint_binary",
|
|
505
|
+
"http.host",
|
|
506
|
+
"http.port",
|
|
507
|
+
"http.session_timeout_ms",
|
|
508
|
+
"http.session_sweep_interval_ms",
|
|
509
|
+
] as const;
|
|
510
|
+
|
|
511
|
+
function leaf(value: InternalConfig, dotted: (typeof leaves)[number]) {
|
|
512
|
+
return dotted
|
|
513
|
+
.split(".")
|
|
514
|
+
.reduce<unknown>(
|
|
515
|
+
(current, key) =>
|
|
516
|
+
current && typeof current === "object"
|
|
517
|
+
? (current as Record<string, unknown>)[key]
|
|
518
|
+
: undefined,
|
|
519
|
+
value,
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function merge(...layers: InternalConfig[]): InternalConfig {
|
|
524
|
+
const result: InternalConfig = {};
|
|
525
|
+
for (const layer of layers) {
|
|
526
|
+
if (layer.version !== undefined) result.version = layer.version;
|
|
527
|
+
for (const section of [
|
|
528
|
+
"workspace",
|
|
529
|
+
"safety",
|
|
530
|
+
"formatting",
|
|
531
|
+
"dependencies",
|
|
532
|
+
"http",
|
|
533
|
+
] as const) {
|
|
534
|
+
const incoming = layer[section];
|
|
535
|
+
if (!incoming) continue;
|
|
536
|
+
const previousHook = result.safety?.hook;
|
|
537
|
+
const defined = Object.fromEntries(
|
|
538
|
+
Object.entries(incoming).filter(([, value]) => value !== undefined),
|
|
539
|
+
);
|
|
540
|
+
result[section] = {
|
|
541
|
+
...(result[section] as object | undefined),
|
|
542
|
+
...defined,
|
|
543
|
+
} as never;
|
|
544
|
+
if (section === "safety") {
|
|
545
|
+
const safetyIncoming = incoming as InternalConfig["safety"];
|
|
546
|
+
if (safetyIncoming?.hook)
|
|
547
|
+
result.safety = {
|
|
548
|
+
...result.safety,
|
|
549
|
+
hook: {
|
|
550
|
+
...previousHook,
|
|
551
|
+
...Object.fromEntries(
|
|
552
|
+
Object.entries(safetyIncoming.hook).filter(
|
|
553
|
+
([, value]) => value !== undefined,
|
|
554
|
+
),
|
|
555
|
+
),
|
|
556
|
+
},
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
return result;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
async function projectRoots(options: ResolveConfigOptions) {
|
|
565
|
+
const env = options.env ?? process.env;
|
|
566
|
+
const cwd = path.resolve(options.cwd ?? process.cwd());
|
|
567
|
+
const clientRoots = await Promise.all(
|
|
568
|
+
(options.clientRoots ?? []).map((item) =>
|
|
569
|
+
existingDirectory(resolveFileUri(item)),
|
|
570
|
+
),
|
|
571
|
+
);
|
|
572
|
+
if (clientRoots.length)
|
|
573
|
+
return { candidates: clientRoots, trustedRoots: clientRoots };
|
|
574
|
+
|
|
575
|
+
if (env.AST_MCP_PROJECT_ROOT) {
|
|
576
|
+
const selected = path.resolve(cwd, env.AST_MCP_PROJECT_ROOT);
|
|
577
|
+
return { candidates: [selected], trustedRoots: [selected] };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
const legacy = env.AST_MCP_ROOTS?.split(path.delimiter).filter(Boolean);
|
|
581
|
+
if (legacy?.length)
|
|
582
|
+
return {
|
|
583
|
+
candidates: legacy.map((item) => path.resolve(cwd, item)),
|
|
584
|
+
trustedRoots: [cwd],
|
|
585
|
+
};
|
|
586
|
+
|
|
587
|
+
return { candidates: [cwd], trustedRoots: [cwd] };
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function matchedProjectRoots(
|
|
591
|
+
candidates: string[],
|
|
592
|
+
requestPaths: string[],
|
|
593
|
+
): string[] {
|
|
594
|
+
const absolute = requestPaths
|
|
595
|
+
.filter((item) => path.isAbsolute(item))
|
|
596
|
+
.map((item) => path.resolve(item));
|
|
597
|
+
const matched = candidates.filter((root) =>
|
|
598
|
+
absolute.some((item) => within(root, item)),
|
|
599
|
+
);
|
|
600
|
+
return matched.length ? matched : [candidates[0] as string];
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function defaultInternalConfig(candidates: string[]): InternalConfig {
|
|
604
|
+
return {
|
|
605
|
+
dependencies: {},
|
|
606
|
+
formatting: {
|
|
607
|
+
dprint_config: packageDprintConfig(),
|
|
608
|
+
enabled: true,
|
|
609
|
+
formatters: [],
|
|
610
|
+
},
|
|
611
|
+
http: {
|
|
612
|
+
host: "127.0.0.1",
|
|
613
|
+
port: 3768,
|
|
614
|
+
session_sweep_interval_ms: 60 * 1000,
|
|
615
|
+
session_timeout_ms: 30 * 60 * 1000,
|
|
616
|
+
},
|
|
617
|
+
safety: {
|
|
618
|
+
allow_external_roots: false,
|
|
619
|
+
follow_symlinks: false,
|
|
620
|
+
hook: { allow_tools: [], block_tools: [], enabled: true },
|
|
621
|
+
require_hash: true,
|
|
622
|
+
},
|
|
623
|
+
version: 1,
|
|
624
|
+
workspace: { roots: candidates },
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
type ConfigLayer = {
|
|
629
|
+
name: "default" | "global" | "project" | "environment";
|
|
630
|
+
value: InternalConfig;
|
|
631
|
+
};
|
|
632
|
+
|
|
633
|
+
function configProvenance(layers: ConfigLayer[]) {
|
|
634
|
+
const provenance: ResolvedConfig["provenance"] = {};
|
|
635
|
+
for (const dotted of leaves)
|
|
636
|
+
for (const layer of layers)
|
|
637
|
+
if (leaf(layer.value, dotted) !== undefined)
|
|
638
|
+
provenance[dotted] = layer.name;
|
|
639
|
+
return provenance;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
function resolvedFormatting(
|
|
643
|
+
value: InternalConfig,
|
|
644
|
+
dprintConfig: string,
|
|
645
|
+
): ResolvedConfig["formatting"] {
|
|
646
|
+
return {
|
|
647
|
+
dprintConfig,
|
|
648
|
+
enabled: value.formatting?.enabled ?? true,
|
|
649
|
+
formatters: (value.formatting?.formatters ?? []).map((formatter) => ({
|
|
650
|
+
args: formatter.args ?? [],
|
|
651
|
+
command: formatter.command,
|
|
652
|
+
extensions: formatter.extensions ?? [],
|
|
653
|
+
globs: formatter.globs ?? [],
|
|
654
|
+
timeoutMs: formatter.timeout_ms ?? 30_000,
|
|
655
|
+
})),
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function resolvedHttp(value: InternalConfig): ResolvedConfig["http"] {
|
|
660
|
+
return {
|
|
661
|
+
host: value.http?.host ?? "127.0.0.1",
|
|
662
|
+
port: value.http?.port ?? 3768,
|
|
663
|
+
sessionSweepIntervalMs: value.http?.session_sweep_interval_ms ?? 60 * 1000,
|
|
664
|
+
sessionTimeoutMs: value.http?.session_timeout_ms ?? 30 * 60 * 1000,
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
function withDefault<T>(value: T | undefined, fallback: T) {
|
|
669
|
+
return value === undefined ? fallback : value;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
function resolvedHook(value: InternalConfig["safety"]) {
|
|
673
|
+
return {
|
|
674
|
+
allowTools: withDefault(value?.hook?.allow_tools, []),
|
|
675
|
+
blockTools: withDefault(value?.hook?.block_tools, []),
|
|
676
|
+
enabled: withDefault(value?.hook?.enabled, true),
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function resolvedSafety(value: InternalConfig): ResolvedConfig["safety"] {
|
|
681
|
+
return {
|
|
682
|
+
allowExternalRoots: withDefault(value.safety?.allow_external_roots, false),
|
|
683
|
+
followSymlinks: withDefault(value.safety?.follow_symlinks, false),
|
|
684
|
+
hook: resolvedHook(value.safety),
|
|
685
|
+
requireHash: withDefault(value.safety?.require_hash, true),
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
function resolvedConfiguration(args: {
|
|
690
|
+
candidates: string[];
|
|
691
|
+
dprintConfig: string;
|
|
692
|
+
environment: ReturnType<typeof environmentLayer>;
|
|
693
|
+
global: LoadedLayer;
|
|
694
|
+
project: LoadedLayer;
|
|
695
|
+
projectRoot: string;
|
|
696
|
+
provenance: ResolvedConfig["provenance"];
|
|
697
|
+
trustedRoots: string[];
|
|
698
|
+
value: InternalConfig;
|
|
699
|
+
}): ResolvedConfig {
|
|
700
|
+
const {
|
|
701
|
+
candidates,
|
|
702
|
+
dprintConfig,
|
|
703
|
+
environment,
|
|
704
|
+
global,
|
|
705
|
+
project,
|
|
706
|
+
projectRoot,
|
|
707
|
+
provenance,
|
|
708
|
+
trustedRoots,
|
|
709
|
+
value,
|
|
710
|
+
} = args;
|
|
711
|
+
return {
|
|
712
|
+
dependencies: {
|
|
713
|
+
astBroBinary: value.dependencies?.ast_bro_binary,
|
|
714
|
+
dprintBinary: value.dependencies?.dprint_binary,
|
|
715
|
+
},
|
|
716
|
+
formatting: resolvedFormatting(value, dprintConfig),
|
|
717
|
+
http: resolvedHttp(value),
|
|
718
|
+
projectRoot,
|
|
719
|
+
provenance,
|
|
720
|
+
safety: resolvedSafety(value),
|
|
721
|
+
sources: {
|
|
722
|
+
environment: environment.names,
|
|
723
|
+
global: global.value ? global.path : undefined,
|
|
724
|
+
project: project.value ? project.path : undefined,
|
|
725
|
+
},
|
|
726
|
+
trustedRoots,
|
|
727
|
+
version: 1,
|
|
728
|
+
workspace: { roots: value.workspace?.roots ?? candidates },
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
function resolutionRuntime(options: ResolveConfigOptions) {
|
|
733
|
+
return {
|
|
734
|
+
cwd: path.resolve(options.cwd ?? process.cwd()),
|
|
735
|
+
env: options.env ?? process.env,
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
function missingProjectLayer(projectRoot: string): LoadedLayer {
|
|
740
|
+
return {
|
|
741
|
+
fingerprint: "missing",
|
|
742
|
+
path: path.join(projectRoot, "ast-mcp.toml"),
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
async function loadResolutionLayers(
|
|
747
|
+
globalPath: string,
|
|
748
|
+
projectPath: string | undefined,
|
|
749
|
+
projectRoot: string,
|
|
750
|
+
) {
|
|
751
|
+
return await Promise.all([
|
|
752
|
+
loadLayer(globalPath),
|
|
753
|
+
projectPath
|
|
754
|
+
? loadLayer(projectPath)
|
|
755
|
+
: Promise.resolve(missingProjectLayer(projectRoot)),
|
|
756
|
+
]);
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
async function resolvedDprint(value: InternalConfig) {
|
|
760
|
+
const enabled = value.formatting?.enabled ?? true;
|
|
761
|
+
const config = value.formatting?.dprint_config ?? packageDprintConfig();
|
|
762
|
+
const fingerprint = enabled ? await validateDprintConfig(config) : "disabled";
|
|
763
|
+
return { config, fingerprint };
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
function resolutionCacheKey(args: {
|
|
767
|
+
candidates: string[];
|
|
768
|
+
cwd: string;
|
|
769
|
+
env: NodeJS.ProcessEnv;
|
|
770
|
+
environment: ReturnType<typeof environmentLayer>;
|
|
771
|
+
globalPath: string;
|
|
772
|
+
projectPath: string | undefined;
|
|
773
|
+
projectRoot: string;
|
|
774
|
+
trustedRoots: string[];
|
|
775
|
+
}) {
|
|
776
|
+
return JSON.stringify({
|
|
777
|
+
candidates: args.candidates,
|
|
778
|
+
cwd: args.cwd,
|
|
779
|
+
environment: args.environment.names.map((name) => [name, args.env[name]]),
|
|
780
|
+
globalPath: args.globalPath,
|
|
781
|
+
projectPath: args.projectPath,
|
|
782
|
+
projectRoot: args.projectRoot,
|
|
783
|
+
trustedRoots: args.trustedRoots,
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
async function resolveForProject(
|
|
788
|
+
projectRoot: string,
|
|
789
|
+
candidates: string[],
|
|
790
|
+
trustedRoots: string[],
|
|
791
|
+
options: ResolveConfigOptions,
|
|
792
|
+
) {
|
|
793
|
+
const { cwd, env } = resolutionRuntime(options);
|
|
794
|
+
const globalPath = globalConfigPath(options);
|
|
795
|
+
const projectPath = await projectConfigPath(projectRoot);
|
|
796
|
+
const [global, project] = await loadResolutionLayers(
|
|
797
|
+
globalPath,
|
|
798
|
+
projectPath,
|
|
799
|
+
projectRoot,
|
|
800
|
+
);
|
|
801
|
+
const environment = environmentLayer(env, cwd);
|
|
802
|
+
const layers: ConfigLayer[] = [
|
|
803
|
+
{ name: "default", value: defaultInternalConfig(candidates) },
|
|
804
|
+
{ name: "global", value: global.value ?? {} },
|
|
805
|
+
{ name: "project", value: project.value ?? {} },
|
|
806
|
+
{ name: "environment", value: environment.value },
|
|
807
|
+
];
|
|
808
|
+
const value = merge(...layers.map((item) => item.value));
|
|
809
|
+
const dprint = await resolvedDprint(value);
|
|
810
|
+
const key = resolutionCacheKey({
|
|
811
|
+
candidates,
|
|
812
|
+
cwd,
|
|
813
|
+
env,
|
|
814
|
+
environment,
|
|
815
|
+
globalPath,
|
|
816
|
+
projectPath,
|
|
817
|
+
projectRoot,
|
|
818
|
+
trustedRoots,
|
|
819
|
+
});
|
|
820
|
+
const fingerprint = `${global.fingerprint}|${project.fingerprint}|${dprint.fingerprint}`;
|
|
821
|
+
const cached = resolvedCache.get(key);
|
|
822
|
+
if (cached?.fingerprint === fingerprint) return cached.value;
|
|
823
|
+
const resolved = resolvedConfiguration({
|
|
824
|
+
candidates,
|
|
825
|
+
dprintConfig: dprint.config,
|
|
826
|
+
environment,
|
|
827
|
+
global,
|
|
828
|
+
project,
|
|
829
|
+
projectRoot,
|
|
830
|
+
provenance: configProvenance(layers),
|
|
831
|
+
trustedRoots,
|
|
832
|
+
value,
|
|
833
|
+
});
|
|
834
|
+
resolvedCache.set(key, { fingerprint, value: resolved });
|
|
835
|
+
return resolved;
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function policy(config: ResolvedConfig) {
|
|
839
|
+
return JSON.stringify({
|
|
840
|
+
dependencies: config.dependencies,
|
|
841
|
+
formatting: config.formatting,
|
|
842
|
+
safety: config.safety,
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
export async function resolveConfig(
|
|
847
|
+
options: ResolveConfigOptions = {},
|
|
848
|
+
): Promise<ResolvedConfig> {
|
|
849
|
+
const { candidates, trustedRoots } = await projectRoots(options);
|
|
850
|
+
const matched = matchedProjectRoots(candidates, options.requestPaths ?? []);
|
|
851
|
+
const configs = await Promise.all(
|
|
852
|
+
matched.map((root) =>
|
|
853
|
+
resolveForProject(root, candidates, trustedRoots, options),
|
|
854
|
+
),
|
|
855
|
+
);
|
|
856
|
+
const first = configs[0] as ResolvedConfig;
|
|
857
|
+
if (configs.some((config) => policy(config) !== policy(first)))
|
|
858
|
+
throw new ConfigurationError(
|
|
859
|
+
`Request spans workspace roots with conflicting ast-mcp policies: ${matched.join(", ")}`,
|
|
860
|
+
);
|
|
861
|
+
return first;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
export function configRequestPaths(value: unknown): string[] {
|
|
865
|
+
return [...new Set(collectRequestPaths(value))];
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
const activeConfig = new AsyncLocalStorage<ResolvedConfig>();
|
|
869
|
+
|
|
870
|
+
export async function currentConfig(): Promise<ResolvedConfig> {
|
|
871
|
+
return activeConfig.getStore() ?? resolveConfig();
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
export async function withConfig<T>(
|
|
875
|
+
options: ResolveConfigOptions,
|
|
876
|
+
operation: () => Promise<T>,
|
|
877
|
+
): Promise<T> {
|
|
878
|
+
const config = await resolveConfig(options);
|
|
879
|
+
return activeConfig.run(config, operation);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
export function clearConfigCache() {
|
|
883
|
+
dprintConfigCache.clear();
|
|
884
|
+
layerCache.clear();
|
|
885
|
+
resolvedCache.clear();
|
|
886
|
+
}
|