@mwillbanks/ast-mcp 0.1.2 → 0.2.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 (58) hide show
  1. package/README.md +71 -22
  2. package/dist/ast-mcp.js +301 -101
  3. package/dist/ast-mcp.js.map +107 -27
  4. package/package.json +3 -1
  5. package/src/ast-bro/capability.ts +3 -8
  6. package/src/ast-bro/client.ts +18 -2
  7. package/src/ast-bro/result.ts +5 -12
  8. package/src/cli.ts +112 -13
  9. package/src/config-cli.ts +54 -0
  10. package/src/config.ts +886 -0
  11. package/src/helpers/aider.ts +252 -0
  12. package/src/helpers/ast-bro.ts +64 -0
  13. package/src/helpers/config.ts +149 -0
  14. package/src/helpers/hook.ts +60 -0
  15. package/src/helpers/installer.ts +249 -0
  16. package/src/helpers/json.ts +19 -0
  17. package/src/helpers/mcp-schema.ts +31 -0
  18. package/src/helpers/process.ts +31 -0
  19. package/src/helpers/string.ts +97 -0
  20. package/src/hook.ts +135 -40
  21. package/src/http-entry.ts +1 -1
  22. package/src/http.ts +118 -103
  23. package/src/installer-transport.ts +190 -0
  24. package/src/installer.ts +596 -235
  25. package/src/mcp-cli.ts +104 -0
  26. package/src/patch/aider.ts +6 -199
  27. package/src/patch/engine.ts +271 -197
  28. package/src/runtime/dependencies.ts +161 -8
  29. package/src/runtime/file-delete.ts +13 -9
  30. package/src/runtime/file-read.ts +91 -57
  31. package/src/runtime/file-rename.ts +158 -0
  32. package/src/runtime/format.ts +57 -34
  33. package/src/runtime/paths.ts +30 -16
  34. package/src/runtime/policy.ts +21 -0
  35. package/src/runtime/process-input.ts +14 -4
  36. package/src/service.ts +219 -0
  37. package/src/shell-policy.ts +331 -0
  38. package/src/stdio.ts +47 -35
  39. package/src/tools/ast-bro.ts +12 -6
  40. package/src/tools/configured.ts +28 -0
  41. package/src/tools/files.ts +24 -27
  42. package/src/tools/index.ts +5 -3
  43. package/src/tools/lifecycle.ts +69 -55
  44. package/templates/skills/ast-mcp/SKILL.md +7 -6
  45. package/templates/skills/ast-mcp/evals/batch.evals.json +48 -0
  46. package/templates/skills/ast-mcp/evals/evals.json +1 -0
  47. package/templates/skills/ast-mcp/evals/score.test.ts +175 -0
  48. package/templates/skills/ast-mcp/evals/score.ts +304 -267
  49. package/templates/skills/ast-mcp/evals/semantic.test.ts +322 -0
  50. package/templates/skills/ast-mcp/evals/semantic.ts +390 -135
  51. package/templates/skills/ast-mcp/evals/shell-policy.ts +252 -0
  52. package/templates/skills/ast-mcp/evals/source.test.ts +46 -0
  53. package/templates/skills/ast-mcp/evals/source.ts +164 -0
  54. package/templates/skills/ast-mcp/evals/trigger-queries.json +1 -1
  55. package/templates/skills/ast-mcp/references/installation.md +24 -11
  56. package/templates/skills/ast-mcp/references/patch-state-machine.md +5 -5
  57. package/templates/skills/ast-mcp/references/tool-catalog.md +4 -2
  58. package/templates/skills/ast-mcp/scripts/check-install.ts +312 -110
package/src/installer.ts CHANGED
@@ -9,8 +9,30 @@ import {
9
9
  } from "node:fs/promises";
10
10
  import os from "node:os";
11
11
  import path from "node:path";
12
+ import { globalConfigPath, resolveConfig } from "./config";
13
+ import {
14
+ codexTransport,
15
+ installerTargetPaths,
16
+ jsonTargetConfig,
17
+ jsonTransport,
18
+ parseInstallerArguments,
19
+ } from "./helpers/installer";
20
+ import {
21
+ type HttpEndpoint,
22
+ httpEndpoint,
23
+ type McpTransport,
24
+ resolveInstallerEndpoint,
25
+ transports,
26
+ } from "./installer-transport";
12
27
  import { isManagedHook } from "./managed-hook";
13
- import { assertAstBroAvailable } from "./runtime/dependencies";
28
+ import { AST_BRO_BINARY, assertAstBroAvailable } from "./runtime/dependencies";
29
+ import {
30
+ createServicePlan,
31
+ installService,
32
+ preflightService,
33
+ removeService,
34
+ type ServiceCommandRunner,
35
+ } from "./service";
14
36
 
15
37
  const packageRoot = path.resolve(import.meta.dir, "..");
16
38
  const cliEntry = path.join(packageRoot, "dist/ast-mcp.js");
@@ -31,40 +53,84 @@ async function save(file: string, value: unknown) {
31
53
  await mkdir(path.dirname(file), { recursive: true });
32
54
  await writeFile(file, `${JSON.stringify(value, null, 2)}\n`);
33
55
  }
34
- function definition(root?: string) {
56
+ async function installerAstBroBinary(options: InstallOptions) {
57
+ const root = path.resolve(options.root);
58
+ const env =
59
+ options.scope === "local"
60
+ ? { ...process.env, AST_MCP_PROJECT_ROOT: root }
61
+ : process.env;
62
+ const config = await resolveConfig({
63
+ cwd: root,
64
+ env,
65
+ home: options.home,
66
+ });
67
+ return (
68
+ options.astBroBinary ?? config.dependencies.astBroBinary ?? AST_BRO_BINARY
69
+ );
70
+ }
71
+
72
+ function definition(
73
+ root: string | undefined,
74
+ transport: McpTransport,
75
+ endpoint?: HttpEndpoint,
76
+ ) {
77
+ if (transport === "http") return { type: "http", url: endpoint?.url };
35
78
  return {
36
79
  args: [cliEntry, "mcp"],
37
80
  command: "bun",
38
- env: root ? { AST_MCP_ALLOW_EXTERNAL_ROOTS: "1", AST_MCP_ROOTS: root } : {},
81
+ env: root ? { AST_MCP_PROJECT_ROOT: root } : {},
39
82
  };
40
83
  }
41
- async function codexMcp(file: string, root?: string) {
84
+ async function codexMcp(
85
+ file: string,
86
+ root: string | undefined,
87
+ transport: McpTransport,
88
+ endpoint?: HttpEndpoint,
89
+ ) {
42
90
  const old = await readFile(file, "utf8").catch(() => "");
43
91
  const clean = old
44
92
  .replace(/# ast-mcp:begin[\s\S]*?# ast-mcp:end\n?/g, "")
45
93
  .trimEnd();
46
94
  const environment = root
47
- ? `env = { AST_MCP_ALLOW_EXTERNAL_ROOTS = "1", AST_MCP_ROOTS = ${JSON.stringify(root)} }\n`
95
+ ? `env = { AST_MCP_PROJECT_ROOT = ${JSON.stringify(root)} }\n`
48
96
  : "";
49
- const block = `# ast-mcp:begin\n[mcp_servers.ast-mcp]\ncommand = "bun"\nargs = [${JSON.stringify(cliEntry)}, "mcp"]\n${environment}# ast-mcp:end`;
97
+ const block =
98
+ transport === "http"
99
+ ? `# ast-mcp:begin\n[mcp_servers.ast-mcp]\nurl = ${JSON.stringify(endpoint?.url)}\n# ast-mcp:end`
100
+ : `# ast-mcp:begin\n[mcp_servers.ast-mcp]\ncommand = "bun"\nargs = [${JSON.stringify(cliEntry)}, "mcp"]\n${environment}# ast-mcp:end`;
50
101
  await mkdir(path.dirname(file), { recursive: true });
51
102
  await writeFile(file, `${clean ? `${clean}\n\n` : ""}${block}\n`);
52
103
  }
53
- async function jsonMcp(file: string, root?: string, copilot = false) {
104
+ async function jsonMcp(
105
+ file: string,
106
+ root: string | undefined,
107
+ copilot: boolean,
108
+ transport: McpTransport,
109
+ endpoint?: HttpEndpoint,
110
+ ) {
54
111
  const value = await json(file);
112
+ const entry = definition(root, transport, endpoint);
55
113
  value.mcpServers = {
56
114
  ...(value.mcpServers ?? {}),
57
115
  "ast-mcp": copilot
58
- ? { type: "local", ...definition(root), tools: ["*"] }
59
- : definition(root),
116
+ ? transport === "stdio"
117
+ ? { type: "local", ...entry, tools: ["*"] }
118
+ : { ...entry, tools: ["*"] }
119
+ : entry,
60
120
  };
61
121
  await save(file, value);
62
122
  }
63
- async function vscodeMcp(file: string, root: string) {
123
+ async function vscodeMcp(
124
+ file: string,
125
+ root: string,
126
+ transport: McpTransport,
127
+ endpoint?: HttpEndpoint,
128
+ ) {
64
129
  const value = await json(file);
130
+ const entry = definition(root, transport, endpoint);
65
131
  value.servers = {
66
132
  ...(value.servers ?? {}),
67
- "ast-mcp": { type: "stdio", ...definition(root) },
133
+ "ast-mcp": transport === "stdio" ? { type: "stdio", ...entry } : entry,
68
134
  };
69
135
  await save(file, value);
70
136
  }
@@ -134,14 +200,10 @@ const instructionsEnd = "<!-- ast-mcp:end -->";
134
200
  const instructionsPattern =
135
201
  /<!-- ast-mcp:begin -->[\s\S]*?<!-- ast-mcp:end -->\n?/g;
136
202
 
137
- async function writeTextOrRemove(file: string, content: string) {
203
+ async function writeText(file: string, content: string) {
138
204
  const normalized = content.trimEnd();
139
- if (!normalized) {
140
- await rm(file, { force: true });
141
- return;
142
- }
143
205
  await mkdir(path.dirname(file), { recursive: true });
144
- await writeFile(file, `${normalized}\n`);
206
+ await writeFile(file, normalized ? `${normalized}\n` : "");
145
207
  }
146
208
 
147
209
  async function instructions(file: string) {
@@ -150,23 +212,27 @@ async function instructions(file: string) {
150
212
  ).trim();
151
213
  const old = await readFile(file, "utf8").catch(() => "");
152
214
  const clean = old.replace(instructionsPattern, "").trimEnd();
153
- await writeTextOrRemove(
215
+ await writeText(
154
216
  file,
155
217
  `${clean ? `${clean}\n\n` : ""}${instructionsBegin}\n\n${block}\n\n${instructionsEnd}`,
156
218
  );
157
219
  }
158
220
 
221
+ async function optionalText(file: string) {
222
+ return readFile(file, "utf8").catch((error) => {
223
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
224
+ throw error;
225
+ });
226
+ }
227
+
159
228
  async function removeInstructions(file: string) {
160
- const old = await readFile(file, "utf8").catch(() => "");
161
- await writeTextOrRemove(file, old.replace(instructionsPattern, ""));
229
+ const old = await optionalText(file);
230
+ if (old === undefined) return;
231
+ await writeText(file, old.replace(instructionsPattern, ""));
162
232
  }
163
233
 
164
234
  // biome-ignore lint/suspicious/noExplicitAny: Host configuration JSON is intentionally dynamic.
165
- async function saveJsonOrRemove(file: string, value: Record<string, any>) {
166
- if (Object.keys(value).length === 0) {
167
- await rm(file, { force: true });
168
- return;
169
- }
235
+ async function saveRemainingJson(file: string, value: Record<string, any>) {
170
236
  await save(file, value);
171
237
  }
172
238
 
@@ -177,12 +243,13 @@ async function removeJsonMcp(file: string, section = "mcpServers") {
177
243
  return;
178
244
  delete entries["ast-mcp"];
179
245
  if (Object.keys(entries).length === 0) delete value[section];
180
- await saveJsonOrRemove(file, value);
246
+ await saveRemainingJson(file, value);
181
247
  }
182
248
 
183
249
  async function removeCodexMcp(file: string) {
184
- const old = await readFile(file, "utf8").catch(() => "");
185
- await writeTextOrRemove(
250
+ const old = await optionalText(file);
251
+ if (old === undefined) return;
252
+ await writeText(
186
253
  file,
187
254
  old.replace(/# ast-mcp:begin[\s\S]*?# ast-mcp:end\n?/g, ""),
188
255
  );
@@ -206,7 +273,7 @@ async function removeHook(
206
273
  );
207
274
  if (hooks[event].length === 0) delete hooks[event];
208
275
  if (Object.keys(hooks).length === 0) delete value.hooks;
209
- await saveJsonOrRemove(file, value);
276
+ await saveRemainingJson(file, value);
210
277
  }
211
278
 
212
279
  async function hasLocalInstallation(root: string) {
@@ -226,54 +293,97 @@ async function hasLocalInstallation(root: string) {
226
293
  export interface InstallOptions {
227
294
  astBroBinary?: string;
228
295
  home?: string;
296
+ host?: string;
297
+ platform?: NodeJS.Platform;
298
+ port?: number;
229
299
  root: string;
230
300
  scope: "local" | "global";
301
+ service?: boolean;
302
+ serviceRunner?: ServiceCommandRunner;
231
303
  targets: Target[];
304
+ transport?: McpTransport;
232
305
  }
233
306
 
234
- function targetPaths(
307
+ class InstallerUsageError extends Error {
308
+ override name = "InstallerUsageError";
309
+ }
310
+
311
+ async function targetTransport(
235
312
  target: Target,
236
313
  global: boolean,
237
314
  root: string,
238
315
  home: string,
239
- ) {
316
+ ): Promise<McpTransport | undefined> {
240
317
  if (target === "codex") {
241
318
  const base = global ? path.join(home, ".codex") : path.join(root, ".codex");
242
- return [
319
+ const content = await readFile(
243
320
  path.join(base, "config.toml"),
244
- path.join(base, "hooks.json"),
245
- path.join(base, "hooks/ast-mcp.ts"),
246
- path.join(base, "skills/ast-mcp"),
247
- global ? path.join(base, "AGENTS.md") : path.join(root, "AGENTS.md"),
248
- ];
249
- }
250
- if (target === "claude") {
251
- const base = global
252
- ? path.join(home, ".claude")
253
- : path.join(root, ".claude");
254
- return [
255
- global ? path.join(home, ".claude.json") : path.join(root, ".mcp.json"),
256
- path.join(base, "settings.json"),
257
- path.join(base, "hooks/ast-mcp.ts"),
258
- path.join(base, "skills/ast-mcp"),
259
- global ? path.join(base, "CLAUDE.md") : path.join(root, "AGENTS.md"),
260
- ];
321
+ "utf8",
322
+ ).catch(() => "");
323
+ return codexTransport(content);
261
324
  }
262
- const base = global
263
- ? path.join(home, ".copilot")
264
- : path.join(root, ".github");
265
- return [
266
- global
267
- ? path.join(base, "mcp-config.json")
268
- : path.join(root, ".github/mcp.json"),
269
- ...(global ? [] : [path.join(root, ".vscode/mcp.json")]),
270
- path.join(base, "hooks/ast-mcp.json"),
271
- path.join(base, "hooks/ast-mcp.ts"),
272
- path.join(base, "skills/ast-mcp"),
273
- global
274
- ? path.join(base, "copilot-instructions.md")
275
- : path.join(root, "AGENTS.md"),
276
- ];
325
+ const file = jsonTargetConfig(target, global, root, home);
326
+ const entry = (await json(file)).mcpServers?.["ast-mcp"] as
327
+ | Record<string, unknown>
328
+ | undefined;
329
+ return jsonTransport(entry);
330
+ }
331
+
332
+ async function selectedTransport(
333
+ options: InstallOptions,
334
+ operation: "install" | "update",
335
+ ) {
336
+ if (options.transport) return options.transport;
337
+ if (operation === "install") return "stdio" as const;
338
+ const root = path.resolve(options.root);
339
+ const home = options.home ?? os.homedir();
340
+ const global = options.scope === "global";
341
+ const found = new Set(
342
+ (
343
+ await Promise.all(
344
+ options.targets.map((target) =>
345
+ targetTransport(target, global, root, home),
346
+ ),
347
+ )
348
+ ).filter((value): value is McpTransport => value !== undefined),
349
+ );
350
+ if (found.size > 1)
351
+ throw new InstallerUsageError(
352
+ "Selected targets use mixed transports; pass --transport stdio or --transport http",
353
+ );
354
+ return found.values().next().value ?? "stdio";
355
+ }
356
+
357
+ function serviceConfiguration(options: InstallOptions, endpoint: HttpEndpoint) {
358
+ return {
359
+ cliEntry,
360
+ endpoint,
361
+ home: options.home ?? os.homedir(),
362
+ platform: options.platform,
363
+ root: path.resolve(options.root),
364
+ runner: options.serviceRunner,
365
+ scope: options.scope,
366
+ };
367
+ }
368
+
369
+ async function hasHttpInstallation(options: InstallOptions) {
370
+ const root = path.resolve(options.root);
371
+ const home = options.home ?? os.homedir();
372
+ const global = options.scope === "global";
373
+ return (
374
+ await Promise.all(
375
+ targets.map((target) => targetTransport(target, global, root, home)),
376
+ )
377
+ ).includes("http");
378
+ }
379
+
380
+ function targetPaths(
381
+ target: Target,
382
+ global: boolean,
383
+ root: string,
384
+ home: string,
385
+ ) {
386
+ return installerTargetPaths(target, global, root, home);
277
387
  }
278
388
 
279
389
  async function snapshot(paths: string[]) {
@@ -300,88 +410,388 @@ function changedFiles(before: Map<string, string>, after: Map<string, string>) {
300
410
  .sort();
301
411
  }
302
412
 
303
- async function reconcile(options: InstallOptions) {
304
- assertAstBroAvailable(options.astBroBinary);
413
+ async function installTargetAssets(base: string, instructionsPath: string) {
414
+ await skills(path.join(base, "skills"));
415
+ await instructions(instructionsPath);
416
+ }
417
+
418
+ async function installCodexTarget(
419
+ global: boolean,
420
+ root: string,
421
+ home: string,
422
+ transport: McpTransport,
423
+ endpoint?: HttpEndpoint,
424
+ ) {
425
+ const base = global ? path.join(home, ".codex") : path.join(root, ".codex");
426
+ await codexMcp(
427
+ path.join(base, "config.toml"),
428
+ global ? undefined : root,
429
+ transport,
430
+ endpoint,
431
+ );
432
+ await hook(
433
+ path.join(base, "hooks.json"),
434
+ "PreToolUse",
435
+ path.join(base, "hooks/ast-mcp.ts"),
436
+ global ? path.join(base, "hooks/ast-mcp.ts") : ".codex/hooks/ast-mcp.ts",
437
+ );
438
+ await installTargetAssets(
439
+ base,
440
+ global ? path.join(base, "AGENTS.md") : path.join(root, "AGENTS.md"),
441
+ );
442
+ }
443
+
444
+ async function installClaudeTarget(
445
+ global: boolean,
446
+ root: string,
447
+ home: string,
448
+ transport: McpTransport,
449
+ endpoint?: HttpEndpoint,
450
+ ) {
451
+ const base = global ? path.join(home, ".claude") : path.join(root, ".claude");
452
+ await jsonMcp(
453
+ global ? path.join(home, ".claude.json") : path.join(root, ".mcp.json"),
454
+ global ? undefined : root,
455
+ false,
456
+ transport,
457
+ endpoint,
458
+ );
459
+ await hook(
460
+ path.join(base, "settings.json"),
461
+ "PreToolUse",
462
+ path.join(base, "hooks/ast-mcp.ts"),
463
+ global
464
+ ? path.join(base, "hooks/ast-mcp.ts")
465
+ : `\${CLAUDE_PROJECT_DIR}/.claude/hooks/ast-mcp.ts`,
466
+ );
467
+ await installTargetAssets(
468
+ base,
469
+ global ? path.join(base, "CLAUDE.md") : path.join(root, "AGENTS.md"),
470
+ );
471
+ }
472
+
473
+ async function installCopilotTarget(
474
+ global: boolean,
475
+ root: string,
476
+ home: string,
477
+ transport: McpTransport,
478
+ endpoint?: HttpEndpoint,
479
+ ) {
480
+ const base = global
481
+ ? path.join(home, ".copilot")
482
+ : path.join(root, ".github");
483
+ if (global)
484
+ await jsonMcp(
485
+ path.join(base, "mcp-config.json"),
486
+ undefined,
487
+ true,
488
+ transport,
489
+ endpoint,
490
+ );
491
+ else {
492
+ await jsonMcp(
493
+ path.join(root, ".github/mcp.json"),
494
+ root,
495
+ true,
496
+ transport,
497
+ endpoint,
498
+ );
499
+ await vscodeMcp(
500
+ path.join(root, ".vscode/mcp.json"),
501
+ root,
502
+ transport,
503
+ endpoint,
504
+ );
505
+ }
506
+ await hook(
507
+ path.join(base, "hooks/ast-mcp.json"),
508
+ "preToolUse",
509
+ path.join(base, "hooks/ast-mcp.ts"),
510
+ global ? path.join(base, "hooks/ast-mcp.ts") : ".github/hooks/ast-mcp.ts",
511
+ );
512
+ await installTargetAssets(
513
+ base,
514
+ global
515
+ ? path.join(base, "copilot-instructions.md")
516
+ : path.join(root, "AGENTS.md"),
517
+ );
518
+ }
519
+
520
+ async function installTarget(
521
+ target: Target,
522
+ global: boolean,
523
+ root: string,
524
+ home: string,
525
+ transport: McpTransport,
526
+ endpoint?: HttpEndpoint,
527
+ ) {
528
+ if (target === "codex")
529
+ return installCodexTarget(global, root, home, transport, endpoint);
530
+ if (target === "claude")
531
+ return installClaudeTarget(global, root, home, transport, endpoint);
532
+ return installCopilotTarget(global, root, home, transport, endpoint);
533
+ }
534
+
535
+ function validateTransport(transport: McpTransport) {
536
+ if (!transports.includes(transport))
537
+ throw new InstallerUsageError(
538
+ `Invalid transport "${transport}"; expected stdio or http`,
539
+ );
540
+ }
541
+
542
+ function validateTransportAddress(
543
+ options: InstallOptions,
544
+ transport: McpTransport,
545
+ ) {
546
+ if (
547
+ transport === "stdio" &&
548
+ (options.host !== undefined || options.port !== undefined)
549
+ )
550
+ throw new InstallerUsageError("--host and --port require --transport http");
551
+ }
552
+
553
+ function validateServiceTransport(
554
+ options: InstallOptions,
555
+ transport: McpTransport,
556
+ ) {
557
+ if (options.service === true && transport !== "http")
558
+ throw new InstallerUsageError("--service requires --transport http");
559
+ }
560
+
561
+ function validateLocalServicePort(options: InstallOptions) {
562
+ if (
563
+ options.service === true &&
564
+ options.scope === "local" &&
565
+ options.port === undefined
566
+ )
567
+ throw new InstallerUsageError(
568
+ "Local managed HTTP services require an explicit --port",
569
+ );
570
+ }
571
+
572
+ function validateReconcileOptions(
573
+ options: InstallOptions,
574
+ transport: McpTransport,
575
+ ) {
576
+ validateTransport(transport);
577
+ validateTransportAddress(options, transport);
578
+ validateServiceTransport(options, transport);
579
+ validateLocalServicePort(options);
580
+ }
581
+
582
+ function hasExplicitEndpoint(options: InstallOptions) {
583
+ return options.host !== undefined || options.port !== undefined;
584
+ }
585
+
586
+ function installerConfigEnvironment(options: InstallOptions) {
587
+ return options.home === undefined
588
+ ? process.env
589
+ : { ...process.env, APPDATA: undefined, XDG_CONFIG_HOME: undefined };
590
+ }
591
+
592
+ async function reconcileEndpoint(
593
+ options: InstallOptions,
594
+ transport: McpTransport,
595
+ root: string,
596
+ home: string,
597
+ ) {
598
+ if (transport !== "http") return undefined;
599
+ const env = installerConfigEnvironment(options);
600
+ const endpoint = await resolveInstallerEndpoint({
601
+ env,
602
+ home: home,
603
+ host: options.host,
604
+ persist: false,
605
+ port: options.port,
606
+ root: root,
607
+ scope: options.scope,
608
+ });
609
+ if (options.service === true)
610
+ await preflightService(serviceConfiguration(options, endpoint));
611
+ if (hasExplicitEndpoint(options))
612
+ await resolveInstallerEndpoint({
613
+ env,
614
+ home: home,
615
+ host: options.host,
616
+ port: options.port,
617
+ root: root,
618
+ scope: options.scope,
619
+ });
620
+ return endpoint;
621
+ }
622
+
623
+ function reconcilePaths(
624
+ options: InstallOptions,
625
+ global: boolean,
626
+ root: string,
627
+ home: string,
628
+ transport: McpTransport,
629
+ endpoint?: HttpEndpoint,
630
+ ) {
631
+ const paths = options.targets.flatMap((target) =>
632
+ targetPaths(target, global, root, home),
633
+ );
634
+ if (transport === "http" && hasExplicitEndpoint(options))
635
+ paths.push(
636
+ options.scope === "local"
637
+ ? path.join(root, "ast-mcp.toml")
638
+ : globalConfigPath({ env: installerConfigEnvironment(options), home }),
639
+ );
640
+ if (options.service !== undefined)
641
+ paths.push(
642
+ createServicePlan(
643
+ serviceConfiguration(
644
+ options,
645
+ endpoint ?? httpEndpoint("127.0.0.1", 3768),
646
+ ),
647
+ ).file,
648
+ );
649
+ return paths;
650
+ }
651
+
652
+ async function reconcileService(
653
+ options: InstallOptions,
654
+ endpoint?: HttpEndpoint,
655
+ ) {
656
+ if (options.service === true && endpoint)
657
+ await installService(serviceConfiguration(options, endpoint));
658
+ else if (options.service === false)
659
+ await removeService(
660
+ serviceConfiguration(
661
+ options,
662
+ endpoint ?? httpEndpoint("127.0.0.1", 3768),
663
+ ),
664
+ );
665
+ }
666
+
667
+ async function reconcile(
668
+ options: InstallOptions,
669
+ operation: "install" | "update",
670
+ ) {
671
+ assertAstBroAvailable(await installerAstBroBinary(options));
305
672
  const root = path.resolve(options.root);
306
673
  const home = options.home ?? os.homedir();
307
674
  const global = options.scope === "global";
308
- const paths = options.targets.flatMap((target) =>
309
- targetPaths(target, global, root, home),
675
+ const transport = await selectedTransport(options, operation);
676
+ validateReconcileOptions(options, transport);
677
+ const endpoint = await reconcileEndpoint(options, transport, root, home);
678
+ const paths = reconcilePaths(
679
+ options,
680
+ global,
681
+ root,
682
+ home,
683
+ transport,
684
+ endpoint,
310
685
  );
311
686
  const before = await snapshot(paths);
312
- for (const target of options.targets) {
313
- if (target === "codex") {
314
- const base = global
315
- ? path.join(home, ".codex")
316
- : path.join(root, ".codex");
317
- await codexMcp(path.join(base, "config.toml"), global ? undefined : root);
318
- await hook(
319
- path.join(base, "hooks.json"),
320
- "PreToolUse",
321
- path.join(base, "hooks/ast-mcp.ts"),
322
- global
323
- ? path.join(base, "hooks/ast-mcp.ts")
324
- : ".codex/hooks/ast-mcp.ts",
325
- );
326
- await skills(path.join(base, "skills"));
327
- await instructions(
328
- global ? path.join(base, "AGENTS.md") : path.join(root, "AGENTS.md"),
329
- );
330
- } else if (target === "claude") {
331
- const base = global
332
- ? path.join(home, ".claude")
333
- : path.join(root, ".claude");
334
- await jsonMcp(
335
- global ? path.join(home, ".claude.json") : path.join(root, ".mcp.json"),
336
- global ? undefined : root,
337
- );
338
- await hook(
339
- path.join(base, "settings.json"),
340
- "PreToolUse",
341
- path.join(base, "hooks/ast-mcp.ts"),
342
- global
343
- ? path.join(base, "hooks/ast-mcp.ts")
344
- : `\${CLAUDE_PROJECT_DIR}/.claude/hooks/ast-mcp.ts`,
345
- );
346
- await skills(path.join(base, "skills"));
347
- await instructions(
348
- global ? path.join(base, "CLAUDE.md") : path.join(root, "AGENTS.md"),
349
- );
350
- } else {
351
- const base = global
352
- ? path.join(home, ".copilot")
353
- : path.join(root, ".github");
354
- if (global)
355
- await jsonMcp(path.join(base, "mcp-config.json"), undefined, true);
356
- else {
357
- await jsonMcp(path.join(root, ".github/mcp.json"), root, true);
358
- await vscodeMcp(path.join(root, ".vscode/mcp.json"), root);
359
- }
360
- await hook(
361
- path.join(base, "hooks/ast-mcp.json"),
362
- "preToolUse",
363
- path.join(base, "hooks/ast-mcp.ts"),
364
- global
365
- ? path.join(base, "hooks/ast-mcp.ts")
366
- : ".github/hooks/ast-mcp.ts",
367
- );
368
- await skills(path.join(base, "skills"));
369
- await instructions(
370
- global
371
- ? path.join(base, "copilot-instructions.md")
372
- : path.join(root, "AGENTS.md"),
373
- );
374
- }
375
- }
687
+ for (const target of options.targets)
688
+ await installTarget(target, global, root, home, transport, endpoint);
689
+ await reconcileService(options, endpoint);
376
690
  return changedFiles(before, await snapshot(paths));
377
691
  }
378
692
 
379
693
  export async function install(options: InstallOptions) {
380
- return reconcile(options);
694
+ return reconcile(options, "install");
381
695
  }
382
696
 
383
697
  export async function update(options: InstallOptions) {
384
- return reconcile(options);
698
+ return reconcile(options, "update");
699
+ }
700
+
701
+ async function removeTargetAssets(base: string, instructionsPath?: string) {
702
+ await rm(path.join(base, "hooks/ast-mcp.ts"), { force: true });
703
+ await rm(path.join(base, "skills/ast-mcp"), { force: true, recursive: true });
704
+ if (instructionsPath) await removeInstructions(instructionsPath);
705
+ }
706
+
707
+ async function uninstallCodexTarget(
708
+ global: boolean,
709
+ root: string,
710
+ home: string,
711
+ ) {
712
+ const base = global ? path.join(home, ".codex") : path.join(root, ".codex");
713
+ await removeCodexMcp(path.join(base, "config.toml"));
714
+ await removeHook(
715
+ path.join(base, "hooks.json"),
716
+ "PreToolUse",
717
+ global ? path.join(base, "hooks/ast-mcp.ts") : ".codex/hooks/ast-mcp.ts",
718
+ );
719
+ await removeTargetAssets(
720
+ base,
721
+ global ? path.join(base, "AGENTS.md") : undefined,
722
+ );
723
+ }
724
+
725
+ async function uninstallClaudeTarget(
726
+ global: boolean,
727
+ root: string,
728
+ home: string,
729
+ ) {
730
+ const base = global ? path.join(home, ".claude") : path.join(root, ".claude");
731
+ await removeJsonMcp(
732
+ global ? path.join(home, ".claude.json") : path.join(root, ".mcp.json"),
733
+ );
734
+ await removeHook(
735
+ path.join(base, "settings.json"),
736
+ "PreToolUse",
737
+ global
738
+ ? path.join(base, "hooks/ast-mcp.ts")
739
+ : `\${CLAUDE_PROJECT_DIR}/.claude/hooks/ast-mcp.ts`,
740
+ );
741
+ await removeTargetAssets(
742
+ base,
743
+ global ? path.join(base, "CLAUDE.md") : undefined,
744
+ );
745
+ }
746
+
747
+ async function uninstallCopilotTarget(
748
+ global: boolean,
749
+ root: string,
750
+ home: string,
751
+ ) {
752
+ const base = global
753
+ ? path.join(home, ".copilot")
754
+ : path.join(root, ".github");
755
+ if (global) await removeJsonMcp(path.join(base, "mcp-config.json"));
756
+ else {
757
+ await removeJsonMcp(path.join(root, ".github/mcp.json"));
758
+ await removeJsonMcp(path.join(root, ".vscode/mcp.json"), "servers");
759
+ }
760
+ await removeHook(
761
+ path.join(base, "hooks/ast-mcp.json"),
762
+ "preToolUse",
763
+ global ? path.join(base, "hooks/ast-mcp.ts") : ".github/hooks/ast-mcp.ts",
764
+ );
765
+ await removeTargetAssets(
766
+ base,
767
+ global ? path.join(base, "copilot-instructions.md") : undefined,
768
+ );
769
+ }
770
+
771
+ async function uninstallTarget(
772
+ target: Target,
773
+ global: boolean,
774
+ root: string,
775
+ home: string,
776
+ ) {
777
+ if (target === "codex") return uninstallCodexTarget(global, root, home);
778
+ if (target === "claude") return uninstallClaudeTarget(global, root, home);
779
+ return uninstallCopilotTarget(global, root, home);
780
+ }
781
+
782
+ async function removeUnusedService(options: InstallOptions, root: string) {
783
+ if (options.scope === "local" && !(await hasLocalInstallation(root)))
784
+ await removeInstructions(path.join(root, "AGENTS.md"));
785
+ const platform = options.platform ?? process.platform;
786
+ if (platform !== "darwin" && platform !== "linux") return;
787
+ if (await hasHttpInstallation(options)) return;
788
+ const service = serviceConfiguration(
789
+ options,
790
+ httpEndpoint("127.0.0.1", 3768),
791
+ );
792
+ const plan = createServicePlan(service);
793
+ if (await lstat(plan.file).catch(() => undefined))
794
+ await removeService(service);
385
795
  }
386
796
 
387
797
  export async function uninstall(options: InstallOptions) {
@@ -392,112 +802,63 @@ export async function uninstall(options: InstallOptions) {
392
802
  targetPaths(target, global, root, home),
393
803
  );
394
804
  const before = await snapshot(paths);
395
- for (const target of options.targets) {
396
- if (target === "codex") {
397
- const base = global
398
- ? path.join(home, ".codex")
399
- : path.join(root, ".codex");
400
- await removeCodexMcp(path.join(base, "config.toml"));
401
- await removeHook(
402
- path.join(base, "hooks.json"),
403
- "PreToolUse",
404
- global
405
- ? path.join(base, "hooks/ast-mcp.ts")
406
- : ".codex/hooks/ast-mcp.ts",
407
- );
408
- await rm(path.join(base, "hooks/ast-mcp.ts"), { force: true });
409
- await rm(path.join(base, "skills/ast-mcp"), {
410
- force: true,
411
- recursive: true,
412
- });
413
- if (global) await removeInstructions(path.join(base, "AGENTS.md"));
414
- } else if (target === "claude") {
415
- const base = global
416
- ? path.join(home, ".claude")
417
- : path.join(root, ".claude");
418
- await removeJsonMcp(
419
- global ? path.join(home, ".claude.json") : path.join(root, ".mcp.json"),
420
- );
421
- await removeHook(
422
- path.join(base, "settings.json"),
423
- "PreToolUse",
424
- global
425
- ? path.join(base, "hooks/ast-mcp.ts")
426
- : `\${CLAUDE_PROJECT_DIR}/.claude/hooks/ast-mcp.ts`,
427
- );
428
- await rm(path.join(base, "hooks/ast-mcp.ts"), { force: true });
429
- await rm(path.join(base, "skills/ast-mcp"), {
430
- force: true,
431
- recursive: true,
432
- });
433
- if (global) await removeInstructions(path.join(base, "CLAUDE.md"));
434
- } else {
435
- const base = global
436
- ? path.join(home, ".copilot")
437
- : path.join(root, ".github");
438
- if (global) await removeJsonMcp(path.join(base, "mcp-config.json"));
439
- else {
440
- await removeJsonMcp(path.join(root, ".github/mcp.json"));
441
- await removeJsonMcp(path.join(root, ".vscode/mcp.json"), "servers");
442
- }
443
- await removeHook(
444
- path.join(base, "hooks/ast-mcp.json"),
445
- "preToolUse",
446
- global
447
- ? path.join(base, "hooks/ast-mcp.ts")
448
- : ".github/hooks/ast-mcp.ts",
449
- );
450
- await rm(path.join(base, "hooks/ast-mcp.ts"), { force: true });
451
- await rm(path.join(base, "skills/ast-mcp"), {
452
- force: true,
453
- recursive: true,
454
- });
455
- if (global)
456
- await removeInstructions(path.join(base, "copilot-instructions.md"));
457
- }
458
- }
459
- if (options.scope === "local" && !(await hasLocalInstallation(root)))
460
- await removeInstructions(path.join(root, "AGENTS.md"));
805
+ for (const target of options.targets)
806
+ await uninstallTarget(target, global, root, home);
807
+ await removeUnusedService(options, root);
461
808
  return changedFiles(before, await snapshot(paths));
462
809
  }
463
810
 
464
811
  export async function runInstallerCli(
465
812
  args = process.argv.slice(2),
466
813
  ): Promise<void> {
467
- const tokens = [...args];
468
- type Operation = "install" | "update" | "uninstall";
469
- let operation: Operation = "install";
470
- if (["install", "update", "uninstall"].includes(tokens[0] ?? ""))
471
- operation = tokens.shift() as Operation;
472
- let scope: "local" | "global" = "local";
473
- let root = process.cwd();
474
- let selected: Target[] = [...targets];
475
- for (let index = 0; index < tokens.length; index += 1) {
476
- if (tokens[index] === "--scope") scope = tokens[++index] as typeof scope;
477
- else if (tokens[index] === "--root") root = tokens[++index];
478
- else if (tokens[index] === "--target") {
479
- const value = tokens[++index];
480
- selected = value === "all" ? [...targets] : [value as Target];
481
- } else throw new Error(`Unknown argument: ${tokens[index]}`);
482
- }
483
- if (
484
- !["local", "global"].includes(scope) ||
485
- selected.some((item) => !targets.includes(item))
486
- )
487
- throw new Error("Invalid install scope or target");
488
- const options = { root, scope, targets: selected };
489
- const changed =
490
- operation === "install"
491
- ? await install(options)
492
- : operation === "update"
493
- ? await update(options)
494
- : await uninstall(options);
495
- const _label =
496
- operation === "install"
497
- ? "Installed"
498
- : operation === "update"
499
- ? "Updated"
500
- : "Uninstalled";
501
- process.stdout.write(`${JSON.stringify({ changed, operation })}\n`);
814
+ const { operation, options: parsedOptions } = parseInstallerArguments(
815
+ args,
816
+ process.cwd(),
817
+ );
818
+ const options: InstallOptions = parsedOptions;
819
+ const operationHandlers = { install, uninstall, update };
820
+ const changed = await operationHandlers[operation](options);
821
+ const root = path.resolve(options.root);
822
+ const global = options.scope === "global";
823
+ const effectiveTransport =
824
+ operation === "uninstall"
825
+ ? (options.transport ?? "stdio")
826
+ : ((await targetTransport(
827
+ options.targets[0],
828
+ global,
829
+ root,
830
+ os.homedir(),
831
+ )) ??
832
+ options.transport ??
833
+ "stdio");
834
+ const endpoint =
835
+ effectiveTransport === "http"
836
+ ? await resolveInstallerEndpoint({
837
+ home: os.homedir(),
838
+ host: options.host,
839
+ port: options.port,
840
+ root,
841
+ scope: options.scope,
842
+ })
843
+ : undefined;
844
+ const servicePlan =
845
+ options.service === true && endpoint
846
+ ? createServicePlan(serviceConfiguration(options, endpoint))
847
+ : undefined;
848
+ const manualStart =
849
+ endpoint && options.service !== true
850
+ ? `${global ? "" : `cd ${JSON.stringify(root)} && `}bun ${JSON.stringify(cliEntry)} mcp --transport http --host ${JSON.stringify(endpoint.host)} --port ${endpoint.port}`
851
+ : undefined;
852
+ const result = {
853
+ changed,
854
+ endpoint: endpoint?.url,
855
+ manualStart,
856
+ operation,
857
+ service: servicePlan
858
+ ? { id: servicePlan.id, managed: true }
859
+ : { managed: false },
860
+ transport: effectiveTransport,
861
+ };
862
+ process.stdout.write(`${JSON.stringify(result)}\n`);
502
863
  }
503
864
  if (import.meta.main) await runInstallerCli();