@mwillbanks/ast-mcp 0.6.5 → 0.7.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 (55) hide show
  1. package/CONTRIBUTING.md +6 -0
  2. package/dist/ast-mcp.js +358 -337
  3. package/dist/ast-mcp.js.map +45 -32
  4. package/dist/workers/sql-postgres-worker.js +5 -0
  5. package/dist/workers/sql-postgres-worker.js.map +10 -0
  6. package/package.json +3 -2
  7. package/src/cli/doctor.ts +103 -0
  8. package/src/cli/index.ts +9 -1
  9. package/src/config/index.ts +61 -6
  10. package/src/config/registry.ts +209 -67
  11. package/src/config/v2-schema.ts +2 -0
  12. package/src/helpers/installer.ts +10 -1
  13. package/src/http/index.ts +12 -5
  14. package/src/installer/codex.ts +237 -0
  15. package/src/installer/diagnostics.ts +387 -0
  16. package/src/installer/directory-ancestry.ts +55 -0
  17. package/src/installer/index.ts +386 -119
  18. package/src/installer/ownership.ts +165 -0
  19. package/src/installer/service-state.ts +151 -0
  20. package/src/installer/service.ts +131 -7
  21. package/src/installer/transaction.ts +342 -0
  22. package/src/installer/transport.ts +22 -31
  23. package/src/intelligence/mutation/locks.ts +4 -1
  24. package/src/patch/engine.ts +157 -11
  25. package/src/runtime/approval.ts +427 -66
  26. package/src/runtime/config-write.ts +27 -1
  27. package/src/runtime/diagnostics.ts +115 -0
  28. package/src/runtime/file-capabilities.ts +2 -0
  29. package/src/runtime/hosts/codex.ts +16 -0
  30. package/src/runtime/path-policy.ts +2 -0
  31. package/src/runtime/release.ts +220 -0
  32. package/src/runtime/sql-assistance.ts +439 -0
  33. package/src/runtime/sql-options-schema.ts +31 -0
  34. package/src/runtime/sql-postgres-worker.ts +72 -0
  35. package/src/runtime/sql-postgres.ts +245 -0
  36. package/src/server/index.ts +35 -5
  37. package/src/server/lifecycle.ts +1 -1
  38. package/src/tools/configuration.ts +2 -0
  39. package/src/tools/diagnostics.ts +85 -0
  40. package/src/tools/files.ts +2 -0
  41. package/src/tools/index.ts +9 -0
  42. package/templates/skills/ast-mcp/SKILL.md +20 -1
  43. package/templates/skills/ast-mcp/evals/evals.json +274 -0
  44. package/templates/skills/ast-mcp/evals/semantic.ts +2 -0
  45. package/templates/skills/ast-mcp/evals/trigger-queries.json +4 -1
  46. package/templates/skills/ast-mcp/references/cli.md +97 -0
  47. package/templates/skills/ast-mcp/references/configuration.md +11 -3
  48. package/templates/skills/ast-mcp/references/diagnostics.md +106 -0
  49. package/templates/skills/ast-mcp/references/host-context.md +85 -0
  50. package/templates/skills/ast-mcp/references/installation.md +37 -0
  51. package/templates/skills/ast-mcp/references/issue-reporting.md +80 -0
  52. package/templates/skills/ast-mcp/references/patch-state-machine.md +10 -0
  53. package/templates/skills/ast-mcp/references/tool-catalog.md +120 -50
  54. package/templates/skills/ast-mcp/scripts/check-install.ts +223 -24
  55. package/templates/skills/ast-mcp/scripts/release.ts +220 -0
@@ -1,5 +1,6 @@
1
1
  import { type FSWatcher, watch } from "node:fs";
2
- import { stat } from "node:fs/promises";
2
+ import { realpath, stat } from "node:fs/promises";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
 
5
6
  import { setApprovalConfigInvalidator } from "../runtime/approval";
@@ -7,6 +8,7 @@ import { canonicalPathWithin } from "../runtime/path-utils";
7
8
  import {
8
9
  clearConfigCache,
9
10
  globalConfigPath,
11
+ hostProjectRootCandidate,
10
12
  type ResolveConfigOptions,
11
13
  type ResolvedConfig,
12
14
  resolveConfig,
@@ -24,16 +26,39 @@ export interface ConfigSnapshot {
24
26
 
25
27
  interface RegistryEntry {
26
28
  options: ResolveConfigOptions;
29
+ fingerprintRoles?: Record<string, FingerprintRole>;
27
30
  promise?: Promise<Readonly<ConfigSnapshot>>;
28
31
  reloadTimer?: ReturnType<typeof setTimeout>;
32
+ reloadForce?: boolean;
29
33
  snapshot?: Readonly<ConfigSnapshot>;
30
34
  watchers: FSWatcher[];
31
35
  }
32
36
 
33
- function normalizedClientRoot(value: string): string {
34
- return path.resolve(
35
- value.startsWith("file:") ? Bun.fileURLToPath(new URL(value)) : value,
36
- );
37
+ function capturedOptions(options: ResolveConfigOptions): ResolveConfigOptions {
38
+ const launchCwd = path.resolve(options.launchCwd ?? process.cwd());
39
+ const cwd =
40
+ options.cwd === undefined
41
+ ? undefined
42
+ : path.resolve(launchCwd, options.cwd);
43
+ const env = environmentFingerprint(options.env ?? process.env);
44
+ for (const name of ["APPDATA", "XDG_CONFIG_HOME"] as const) {
45
+ if (env[name] !== undefined) env[name] = path.resolve(launchCwd, env[name]);
46
+ }
47
+ return {
48
+ ...options,
49
+ cwd,
50
+ launchCwd,
51
+ env,
52
+ home: path.resolve(launchCwd, options.home ?? os.homedir()),
53
+ platform: options.platform ?? process.platform,
54
+ clientRoots: options.clientRoots?.map((value) =>
55
+ path.resolve(
56
+ launchCwd,
57
+ value.startsWith("file:") ? Bun.fileURLToPath(new URL(value)) : value,
58
+ ),
59
+ ),
60
+ requestPaths: options.requestPaths ? [...options.requestPaths] : undefined,
61
+ };
37
62
  }
38
63
 
39
64
  function environmentFingerprint(environment: NodeJS.ProcessEnv) {
@@ -43,6 +68,7 @@ function environmentFingerprint(environment: NodeJS.ProcessEnv) {
43
68
  "XDG_CONFIG_HOME",
44
69
  "AST_MCP_PROJECT_ROOT",
45
70
  "AST_MCP_ROOTS",
71
+ "CLAUDE_PROJECT_DIR",
46
72
  "AST_MCP_ALLOW_ANY_PATH",
47
73
  "AST_MCP_ALLOW_EXTERNAL_ROOTS",
48
74
  "AST_MCP_ALLOW_TEMP_DIRECTORY",
@@ -86,9 +112,9 @@ function configuredSelectionRoots(
86
112
  }
87
113
 
88
114
  function keyFor(options: ResolveConfigOptions): string {
89
- const cwd = path.resolve(options.cwd ?? process.cwd());
90
- const env = options.env ?? process.env;
91
- const clientRoots = (options.clientRoots ?? []).map(normalizedClientRoot);
115
+ const cwd = options.cwd ?? options.launchCwd!;
116
+ const env = options.env!;
117
+ const clientRoots = options.clientRoots ?? [];
92
118
  const selectionRoots = configuredSelectionRoots(clientRoots, cwd, env);
93
119
  const requestPaths = (options.requestPaths ?? [])
94
120
  .filter((item) => path.isAbsolute(item))
@@ -96,6 +122,7 @@ function keyFor(options: ResolveConfigOptions): string {
96
122
  return JSON.stringify({
97
123
  clientRoots,
98
124
  cwd,
125
+ explicitCwd: options.cwd !== undefined,
99
126
  env: environmentFingerprint(env),
100
127
  home: options.home,
101
128
  platform: options.platform,
@@ -106,16 +133,36 @@ function keyFor(options: ResolveConfigOptions): string {
106
133
  });
107
134
  }
108
135
 
109
- async function fingerprint(filePath: string): Promise<string> {
136
+ type FingerprintRole = "configuration" | "identity" | "boundary";
137
+
138
+ async function fingerprint(
139
+ filePath: string,
140
+ role: FingerprintRole,
141
+ ): Promise<string> {
110
142
  const metadata = await stat(filePath).catch(() => undefined);
111
- return metadata ? `${metadata.mtimeMs}:${metadata.size}` : "missing";
143
+ if (!metadata) return "missing";
144
+ const physicalPath = await realpath(filePath).catch(() => undefined);
145
+ return JSON.stringify([
146
+ metadata.isDirectory() ? "directory" : "file",
147
+ metadata.dev,
148
+ metadata.ino,
149
+ physicalPath,
150
+ ...(role === "configuration" || (role === "boundary" && metadata.isFile())
151
+ ? [metadata.mtimeMs, metadata.size]
152
+ : []),
153
+ ]);
112
154
  }
113
155
 
114
- async function projectConfigCandidates(projectRoot: string): Promise<string[]> {
115
- const candidates: string[] = [];
156
+ async function projectConfigCandidates(
157
+ projectRoot: string,
158
+ ): Promise<Array<[string, FingerprintRole]>> {
159
+ const candidates: Array<[string, FingerprintRole]> = [];
116
160
  let current = path.resolve(projectRoot);
117
161
  while (true) {
118
- candidates.push(path.join(current, "ast-mcp.toml"));
162
+ candidates.push(
163
+ [path.join(current, "ast-mcp.toml"), "configuration"],
164
+ [path.join(current, ".git"), "boundary"],
165
+ );
119
166
  const boundary = await stat(path.join(current, ".git")).then(
120
167
  () => true,
121
168
  () => false,
@@ -130,24 +177,96 @@ async function projectConfigCandidates(projectRoot: string): Promise<string[]> {
130
177
  async function fingerprints(
131
178
  config: ResolvedConfig | undefined,
132
179
  options: ResolveConfigOptions,
133
- ): Promise<Record<string, string>> {
134
- const projectRoot = config?.projectRoot ?? options.cwd ?? process.cwd();
135
- const sources = [
136
- globalConfigPath(options),
137
- ...(await projectConfigCandidates(projectRoot)),
138
- config?.sources.global,
139
- config?.sources.project,
140
- ].filter(
141
- (item, index, all): item is string =>
142
- Boolean(item) && all.indexOf(item) === index,
180
+ ) {
181
+ const projectRoot = config?.projectRoot ?? options.cwd ?? options.launchCwd!;
182
+ const hostRoot = hostProjectRootCandidate(options);
183
+ const selectionRoots = configuredSelectionRoots(
184
+ options.clientRoots ?? [],
185
+ options.cwd ?? options.launchCwd!,
186
+ options.env!,
143
187
  );
144
- return Object.fromEntries(
145
- await Promise.all(
146
- sources.map(async (source) => [source, await fingerprint(source)]),
188
+ const identityRoots = new Set([
189
+ projectRoot,
190
+ ...selectionRoots,
191
+ ...(config?.trustedRoots ?? []),
192
+ ...(config?.workspace.roots ?? []),
193
+ ]);
194
+ const sources = new Map<string, FingerprintRole>([
195
+ ...[...identityRoots].map((root): [string, FingerprintRole] => [
196
+ root,
197
+ "identity",
198
+ ]),
199
+ ...(hostRoot
200
+ ? [
201
+ [hostRoot, "identity"] as [string, FingerprintRole],
202
+ ...(await projectConfigCandidates(hostRoot)),
203
+ ]
204
+ : []),
205
+ [globalConfigPath(options), "configuration"],
206
+ ...(await projectConfigCandidates(projectRoot)),
207
+ ...(config?.sources.global
208
+ ? [[config.sources.global, "configuration"] as [string, FingerprintRole]]
209
+ : []),
210
+ ...(config?.sources.project
211
+ ? [[config.sources.project, "configuration"] as [string, FingerprintRole]]
212
+ : []),
213
+ ]);
214
+ return {
215
+ roles: Object.fromEntries(sources),
216
+ values: Object.fromEntries(
217
+ await Promise.all(
218
+ [...sources].map(async ([source, role]) => [
219
+ source,
220
+ await fingerprint(source, role),
221
+ ]),
222
+ ),
147
223
  ),
224
+ };
225
+ }
226
+
227
+ function sameFingerprints(
228
+ left: Record<string, string>,
229
+ right: Record<string, string>,
230
+ ): boolean {
231
+ const keys = Object.keys(left);
232
+ return (
233
+ keys.length === Object.keys(right).length &&
234
+ keys.every((key) => left[key] === right[key])
148
235
  );
149
236
  }
150
237
 
238
+ function configurationIdentity(
239
+ config: Readonly<ResolvedConfig> | undefined,
240
+ ): string {
241
+ return JSON.stringify(config ? { ...config, generation: 0 } : null);
242
+ }
243
+
244
+ async function stableResolution(entry: RegistryEntry) {
245
+ let previous = entry.snapshot?.config;
246
+ for (let attempt = 0; ; attempt += 1) {
247
+ const before = await fingerprints(previous, entry.options);
248
+ clearConfigCache();
249
+ let resolved: ResolvedConfig | undefined;
250
+ let error: string | undefined;
251
+ try {
252
+ resolved = await resolveConfig(entry.options);
253
+ } catch (failure) {
254
+ error = failure instanceof Error ? failure.message : String(failure);
255
+ }
256
+ const collected = await fingerprints(resolved ?? previous, entry.options);
257
+ if (sameFingerprints(before.values, collected.values))
258
+ return { collected, error, resolved };
259
+ if (attempt >= 2)
260
+ return {
261
+ collected,
262
+ error:
263
+ "ast-mcp configuration changed during resolution; run config_status again",
264
+ resolved: undefined,
265
+ };
266
+ previous = resolved ?? previous;
267
+ }
268
+ }
269
+
151
270
  export class ConfigRegistry {
152
271
  readonly #entries = new Map<string, RegistryEntry>();
153
272
  readonly #reconcileTimer: ReturnType<typeof setInterval>;
@@ -196,24 +315,24 @@ export class ConfigRegistry {
196
315
  async snapshot(
197
316
  options: ResolveConfigOptions = {},
198
317
  ): Promise<Readonly<ConfigSnapshot>> {
199
- const key = keyFor(options);
200
- const entry = this.#entry(key, options);
318
+ const captured = capturedOptions(options);
319
+ const key = keyFor(captured);
320
+ const entry = this.#entry(key, captured);
201
321
  if (!entry.promise) entry.promise = this.#reload(key, entry);
202
322
  return entry.promise;
203
323
  }
204
324
  invalidate(options: ResolveConfigOptions = {}): void {
205
- const key = keyFor(options);
325
+ const key = keyFor(capturedOptions(options));
206
326
  const entry = this.#entries.get(key);
207
327
  if (Object.keys(options).length === 0) {
208
328
  for (const [entryKey, entryValue] of this.#entries)
209
- this.#queueReload(entryKey, entryValue);
210
- } else if (entry) this.#schedule(key, entry);
329
+ this.#queueReload(entryKey, entryValue, true);
330
+ } else if (entry) this.#schedule(key, entry, true);
211
331
  }
212
332
  async reload(): Promise<Array<Readonly<ConfigSnapshot>>> {
213
- this.invalidate();
214
333
  return Promise.all(
215
- [...this.#entries.values()].flatMap((entry) =>
216
- entry.promise ? [entry.promise] : [],
334
+ [...this.#entries.entries()].map(([key, entry]) =>
335
+ this.#queueReload(key, entry),
217
336
  ),
218
337
  );
219
338
  }
@@ -221,12 +340,14 @@ export class ConfigRegistry {
221
340
  await Promise.all(
222
341
  [...this.#entries.entries()].map(async ([key, entry]) => {
223
342
  const snapshot = entry.snapshot;
224
- if (!snapshot) return;
343
+ const roles = entry.fingerprintRoles;
344
+ if (!snapshot || !roles) return;
225
345
  for (const [source, previous] of Object.entries(
226
346
  snapshot.fingerprints,
227
347
  )) {
228
- if ((await fingerprint(source)) !== previous) {
229
- this.#schedule(key, entry);
348
+ if ((await fingerprint(source, roles[source]!)) !== previous) {
349
+ if (entry.snapshot === snapshot && this.#entries.get(key) === entry)
350
+ this.#schedule(key, entry);
230
351
  break;
231
352
  }
232
353
  }
@@ -242,17 +363,27 @@ export class ConfigRegistry {
242
363
  }
243
364
  this.#entries.clear();
244
365
  }
245
- #queueReload(key: string, entry: RegistryEntry): void {
366
+ #queueReload(
367
+ key: string,
368
+ entry: RegistryEntry,
369
+ force = false,
370
+ ): Promise<Readonly<ConfigSnapshot>> {
371
+ if (entry.reloadTimer) clearTimeout(entry.reloadTimer);
372
+ entry.reloadTimer = undefined;
373
+ const forced = force || entry.reloadForce === true;
374
+ entry.reloadForce = false;
246
375
  const previous = entry.promise;
247
376
  const next = (
248
377
  previous ? previous.catch(() => undefined) : Promise.resolve()
249
- ).then(() => this.#reload(key, entry));
378
+ ).then(() => this.#reload(key, entry, forced));
250
379
  entry.promise = next;
251
380
  void next.catch(() => undefined);
381
+ return next;
252
382
  }
253
383
 
254
- #schedule(key: string, entry: RegistryEntry): void {
384
+ #schedule(key: string, entry: RegistryEntry, force = false): void {
255
385
  if (entry.reloadTimer) clearTimeout(entry.reloadTimer);
386
+ entry.reloadForce = force || entry.reloadForce === true;
256
387
  entry.reloadTimer = setTimeout(() => {
257
388
  this.#queueReload(key, entry);
258
389
  }, this.debounceMs);
@@ -261,32 +392,35 @@ export class ConfigRegistry {
261
392
  async #reload(
262
393
  key: string,
263
394
  entry: RegistryEntry,
395
+ force = false,
264
396
  ): Promise<Readonly<ConfigSnapshot>> {
265
- clearConfigCache();
266
- const generation = (entry.snapshot?.generation ?? 0) + 1;
267
- let snapshot: Readonly<ConfigSnapshot>;
268
- try {
269
- const resolved = await resolveConfig(entry.options);
270
- const config = Object.freeze({ ...resolved, generation });
271
- snapshot = Object.freeze({
272
- config,
273
- fingerprints: await fingerprints(resolved, entry.options),
274
- generation,
275
- healthy: true,
276
- key,
277
- loadedAt: new Date().toISOString(),
278
- });
279
- } catch (error) {
280
- snapshot = Object.freeze({
281
- config: entry.snapshot?.config,
282
- error: error instanceof Error ? error.message : String(error),
283
- fingerprints: await fingerprints(entry.snapshot?.config, entry.options),
284
- generation,
285
- healthy: false,
286
- key,
287
- loadedAt: new Date().toISOString(),
288
- });
289
- }
397
+ const { collected, error, resolved } = await stableResolution(entry);
398
+ const previous = entry.snapshot;
399
+ const healthy = resolved !== undefined;
400
+ entry.fingerprintRoles = collected.roles;
401
+ if (
402
+ !force &&
403
+ previous &&
404
+ previous.healthy === healthy &&
405
+ previous.error === error &&
406
+ sameFingerprints(previous.fingerprints, collected.values) &&
407
+ (!resolved ||
408
+ configurationIdentity(previous.config) ===
409
+ configurationIdentity(resolved))
410
+ )
411
+ return previous;
412
+ const generation = (previous?.generation ?? 0) + 1;
413
+ const snapshot = Object.freeze({
414
+ config: resolved
415
+ ? Object.freeze({ ...resolved, generation })
416
+ : previous?.config,
417
+ ...(error === undefined ? {} : { error }),
418
+ fingerprints: collected.values,
419
+ generation,
420
+ healthy,
421
+ key,
422
+ loadedAt: new Date().toISOString(),
423
+ });
290
424
  entry.snapshot = snapshot;
291
425
  if (!entry.promise) entry.promise = Promise.resolve(snapshot);
292
426
  if (this.#entries.get(key) === entry) this.#watch(key, entry, snapshot);
@@ -307,8 +441,16 @@ export class ConfigRegistry {
307
441
  try {
308
442
  const watcher = watch(directory, (_event, filename) => {
309
443
  if (this.#entries.get(key) !== entry) return;
310
- if (!filename || filename.toString() === "ast-mcp.toml")
311
- this.#schedule(key, entry);
444
+ if (
445
+ !filename ||
446
+ filename.toString() === "ast-mcp.toml" ||
447
+ filename.toString() === ".git" ||
448
+ Object.hasOwn(
449
+ snapshot.fingerprints,
450
+ path.join(directory, filename.toString()),
451
+ )
452
+ )
453
+ void this.reconcile();
312
454
  });
313
455
  watcher.unref?.();
314
456
  entry.watchers.push(watcher);
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
 
3
+ import { sqlAssistanceOptionsSchema } from "../runtime/sql-options-schema";
3
4
  import {
4
5
  cliSchema,
5
6
  createFormatterSchema,
@@ -135,6 +136,7 @@ export const fileV2Schema = z
135
136
  .array(z.enum(["ast", "aider_block"]))
136
137
  .max(2)
137
138
  .optional(),
139
+ sql: sqlAssistanceOptionsSchema.optional(),
138
140
  })
139
141
  .strict()
140
142
  .optional(),
@@ -178,8 +178,17 @@ export function parseInstallerArguments(
178
178
  return { operation, options };
179
179
  }
180
180
 
181
+ export function codexHome(
182
+ home: string,
183
+ env: NodeJS.ProcessEnv = process.env,
184
+ ): string {
185
+ return env.CODEX_HOME
186
+ ? path.resolve(env.CODEX_HOME)
187
+ : path.join(home, ".codex");
188
+ }
189
+
181
190
  function codexPaths(global: boolean, root: string, home: string): string[] {
182
- const base = global ? path.join(home, ".codex") : path.join(root, ".codex");
191
+ const base = global ? codexHome(home) : path.join(root, ".codex");
183
192
  return [
184
193
  path.join(base, "config.toml"),
185
194
  path.join(base, "hooks.json"),
package/src/http/index.ts CHANGED
@@ -52,7 +52,7 @@ function sessionRuntime(config: ResolvedConfig) {
52
52
  const session = sessions.get(sessionId);
53
53
  if (!session) return;
54
54
  sessions.delete(sessionId);
55
- clearSessionApprovals(sessionId);
55
+ clearSessionApprovals(sessionId, session.server);
56
56
  void closeServer(session.server).catch(() => undefined);
57
57
  }
58
58
 
@@ -60,7 +60,7 @@ function sessionRuntime(config: ResolvedConfig) {
60
60
  const session = sessions.get(sessionId);
61
61
  if (!session) return;
62
62
  sessions.delete(sessionId);
63
- clearSessionApprovals(sessionId);
63
+ clearSessionApprovals(sessionId, session.server);
64
64
  await closeServer(session.server);
65
65
  }
66
66
 
@@ -106,7 +106,7 @@ function sessionRuntime(config: ResolvedConfig) {
106
106
  }
107
107
 
108
108
  async function createSession(request: Request) {
109
- const server = createServer();
109
+ const server = createServer({}, {}, {}, { transport: "http" });
110
110
  servers.add(server);
111
111
  const transport = sessionTransport(server);
112
112
  const signal = AbortSignal.any([request.signal, setupAbort.signal]);
@@ -169,7 +169,13 @@ function sessionRuntime(config: ResolvedConfig) {
169
169
  function modernHttpHandler() {
170
170
  const workspaceRegistry = new WorkspaceRegistry();
171
171
  return createMcpHandler(
172
- () => createServer({}, {}, { workspaceRegistry, requestScoped: true }),
172
+ () =>
173
+ createServer(
174
+ {},
175
+ {},
176
+ { workspaceRegistry, requestScoped: true },
177
+ { transport: "http" },
178
+ ),
173
179
  { legacy: "reject", responseMode: "sse" },
174
180
  );
175
181
  }
@@ -198,7 +204,8 @@ function sessionRuntime(config: ResolvedConfig) {
198
204
  httpServer.stop(false);
199
205
  if (sessionSweep) clearInterval(sessionSweep);
200
206
  const activeSessions = [...sessions.entries()];
201
- for (const [sessionId] of activeSessions) clearSessionApprovals(sessionId);
207
+ for (const [sessionId, session] of activeSessions)
208
+ clearSessionApprovals(sessionId, session.server);
202
209
  const results = await Promise.allSettled([
203
210
  ...[...servers].map(closeServer),
204
211
  ...cleanup,