@mwillbanks/ast-mcp 0.1.3 → 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 +59 -20
  2. package/dist/ast-mcp.js +232 -130
  3. package/dist/ast-mcp.js.map +107 -27
  4. package/package.json +2 -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 +70 -95
  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 +579 -242
  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 +48 -29
  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 +9 -8
  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
  }
@@ -152,11 +218,15 @@ async function instructions(file: string) {
152
218
  );
153
219
  }
154
220
 
155
- async function removeInstructions(file: string) {
156
- const old = await readFile(file, "utf8").catch((error) => {
221
+ async function optionalText(file: string) {
222
+ return readFile(file, "utf8").catch((error) => {
157
223
  if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
158
224
  throw error;
159
225
  });
226
+ }
227
+
228
+ async function removeInstructions(file: string) {
229
+ const old = await optionalText(file);
160
230
  if (old === undefined) return;
161
231
  await writeText(file, old.replace(instructionsPattern, ""));
162
232
  }
@@ -177,10 +247,7 @@ async function removeJsonMcp(file: string, section = "mcpServers") {
177
247
  }
178
248
 
179
249
  async function removeCodexMcp(file: string) {
180
- const old = await readFile(file, "utf8").catch((error) => {
181
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
182
- throw error;
183
- });
250
+ const old = await optionalText(file);
184
251
  if (old === undefined) return;
185
252
  await writeText(
186
253
  file,
@@ -226,58 +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
307
  class InstallerUsageError extends Error {
235
308
  override name = "InstallerUsageError";
236
309
  }
237
310
 
238
- function targetPaths(
311
+ async function targetTransport(
239
312
  target: Target,
240
313
  global: boolean,
241
314
  root: string,
242
315
  home: string,
243
- ) {
316
+ ): Promise<McpTransport | undefined> {
244
317
  if (target === "codex") {
245
318
  const base = global ? path.join(home, ".codex") : path.join(root, ".codex");
246
- return [
319
+ const content = await readFile(
247
320
  path.join(base, "config.toml"),
248
- path.join(base, "hooks.json"),
249
- path.join(base, "hooks/ast-mcp.ts"),
250
- path.join(base, "skills/ast-mcp"),
251
- global ? path.join(base, "AGENTS.md") : path.join(root, "AGENTS.md"),
252
- ];
321
+ "utf8",
322
+ ).catch(() => "");
323
+ return codexTransport(content);
253
324
  }
254
- if (target === "claude") {
255
- const base = global
256
- ? path.join(home, ".claude")
257
- : path.join(root, ".claude");
258
- return [
259
- global ? path.join(home, ".claude.json") : path.join(root, ".mcp.json"),
260
- path.join(base, "settings.json"),
261
- path.join(base, "hooks/ast-mcp.ts"),
262
- path.join(base, "skills/ast-mcp"),
263
- global ? path.join(base, "CLAUDE.md") : path.join(root, "AGENTS.md"),
264
- ];
265
- }
266
- const base = global
267
- ? path.join(home, ".copilot")
268
- : path.join(root, ".github");
269
- return [
270
- global
271
- ? path.join(base, "mcp-config.json")
272
- : path.join(root, ".github/mcp.json"),
273
- ...(global ? [] : [path.join(root, ".vscode/mcp.json")]),
274
- path.join(base, "hooks/ast-mcp.json"),
275
- path.join(base, "hooks/ast-mcp.ts"),
276
- path.join(base, "skills/ast-mcp"),
277
- global
278
- ? path.join(base, "copilot-instructions.md")
279
- : path.join(root, "AGENTS.md"),
280
- ];
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);
281
387
  }
282
388
 
283
389
  async function snapshot(paths: string[]) {
@@ -304,88 +410,388 @@ function changedFiles(before: Map<string, string>, after: Map<string, string>) {
304
410
  .sort();
305
411
  }
306
412
 
307
- async function reconcile(options: InstallOptions) {
308
- 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));
309
672
  const root = path.resolve(options.root);
310
673
  const home = options.home ?? os.homedir();
311
674
  const global = options.scope === "global";
312
- const paths = options.targets.flatMap((target) =>
313
- 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,
314
685
  );
315
686
  const before = await snapshot(paths);
316
- for (const target of options.targets) {
317
- if (target === "codex") {
318
- const base = global
319
- ? path.join(home, ".codex")
320
- : path.join(root, ".codex");
321
- await codexMcp(path.join(base, "config.toml"), global ? undefined : root);
322
- await hook(
323
- path.join(base, "hooks.json"),
324
- "PreToolUse",
325
- path.join(base, "hooks/ast-mcp.ts"),
326
- global
327
- ? path.join(base, "hooks/ast-mcp.ts")
328
- : ".codex/hooks/ast-mcp.ts",
329
- );
330
- await skills(path.join(base, "skills"));
331
- await instructions(
332
- global ? path.join(base, "AGENTS.md") : path.join(root, "AGENTS.md"),
333
- );
334
- } else if (target === "claude") {
335
- const base = global
336
- ? path.join(home, ".claude")
337
- : path.join(root, ".claude");
338
- await jsonMcp(
339
- global ? path.join(home, ".claude.json") : path.join(root, ".mcp.json"),
340
- global ? undefined : root,
341
- );
342
- await hook(
343
- path.join(base, "settings.json"),
344
- "PreToolUse",
345
- path.join(base, "hooks/ast-mcp.ts"),
346
- global
347
- ? path.join(base, "hooks/ast-mcp.ts")
348
- : `\${CLAUDE_PROJECT_DIR}/.claude/hooks/ast-mcp.ts`,
349
- );
350
- await skills(path.join(base, "skills"));
351
- await instructions(
352
- global ? path.join(base, "CLAUDE.md") : path.join(root, "AGENTS.md"),
353
- );
354
- } else {
355
- const base = global
356
- ? path.join(home, ".copilot")
357
- : path.join(root, ".github");
358
- if (global)
359
- await jsonMcp(path.join(base, "mcp-config.json"), undefined, true);
360
- else {
361
- await jsonMcp(path.join(root, ".github/mcp.json"), root, true);
362
- await vscodeMcp(path.join(root, ".vscode/mcp.json"), root);
363
- }
364
- await hook(
365
- path.join(base, "hooks/ast-mcp.json"),
366
- "preToolUse",
367
- path.join(base, "hooks/ast-mcp.ts"),
368
- global
369
- ? path.join(base, "hooks/ast-mcp.ts")
370
- : ".github/hooks/ast-mcp.ts",
371
- );
372
- await skills(path.join(base, "skills"));
373
- await instructions(
374
- global
375
- ? path.join(base, "copilot-instructions.md")
376
- : path.join(root, "AGENTS.md"),
377
- );
378
- }
379
- }
687
+ for (const target of options.targets)
688
+ await installTarget(target, global, root, home, transport, endpoint);
689
+ await reconcileService(options, endpoint);
380
690
  return changedFiles(before, await snapshot(paths));
381
691
  }
382
692
 
383
693
  export async function install(options: InstallOptions) {
384
- return reconcile(options);
694
+ return reconcile(options, "install");
385
695
  }
386
696
 
387
697
  export async function update(options: InstallOptions) {
388
- 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);
389
795
  }
390
796
 
391
797
  export async function uninstall(options: InstallOptions) {
@@ -396,132 +802,63 @@ export async function uninstall(options: InstallOptions) {
396
802
  targetPaths(target, global, root, home),
397
803
  );
398
804
  const before = await snapshot(paths);
399
- for (const target of options.targets) {
400
- if (target === "codex") {
401
- const base = global
402
- ? path.join(home, ".codex")
403
- : path.join(root, ".codex");
404
- await removeCodexMcp(path.join(base, "config.toml"));
405
- await removeHook(
406
- path.join(base, "hooks.json"),
407
- "PreToolUse",
408
- global
409
- ? path.join(base, "hooks/ast-mcp.ts")
410
- : ".codex/hooks/ast-mcp.ts",
411
- );
412
- await rm(path.join(base, "hooks/ast-mcp.ts"), { force: true });
413
- await rm(path.join(base, "skills/ast-mcp"), {
414
- force: true,
415
- recursive: true,
416
- });
417
- if (global) await removeInstructions(path.join(base, "AGENTS.md"));
418
- } else if (target === "claude") {
419
- const base = global
420
- ? path.join(home, ".claude")
421
- : path.join(root, ".claude");
422
- await removeJsonMcp(
423
- global ? path.join(home, ".claude.json") : path.join(root, ".mcp.json"),
424
- );
425
- await removeHook(
426
- path.join(base, "settings.json"),
427
- "PreToolUse",
428
- global
429
- ? path.join(base, "hooks/ast-mcp.ts")
430
- : `\${CLAUDE_PROJECT_DIR}/.claude/hooks/ast-mcp.ts`,
431
- );
432
- await rm(path.join(base, "hooks/ast-mcp.ts"), { force: true });
433
- await rm(path.join(base, "skills/ast-mcp"), {
434
- force: true,
435
- recursive: true,
436
- });
437
- if (global) await removeInstructions(path.join(base, "CLAUDE.md"));
438
- } else {
439
- const base = global
440
- ? path.join(home, ".copilot")
441
- : path.join(root, ".github");
442
- if (global) await removeJsonMcp(path.join(base, "mcp-config.json"));
443
- else {
444
- await removeJsonMcp(path.join(root, ".github/mcp.json"));
445
- await removeJsonMcp(path.join(root, ".vscode/mcp.json"), "servers");
446
- }
447
- await removeHook(
448
- path.join(base, "hooks/ast-mcp.json"),
449
- "preToolUse",
450
- global
451
- ? path.join(base, "hooks/ast-mcp.ts")
452
- : ".github/hooks/ast-mcp.ts",
453
- );
454
- await rm(path.join(base, "hooks/ast-mcp.ts"), { force: true });
455
- await rm(path.join(base, "skills/ast-mcp"), {
456
- force: true,
457
- recursive: true,
458
- });
459
- if (global)
460
- await removeInstructions(path.join(base, "copilot-instructions.md"));
461
- }
462
- }
463
- if (options.scope === "local" && !(await hasLocalInstallation(root)))
464
- 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);
465
808
  return changedFiles(before, await snapshot(paths));
466
809
  }
467
810
 
468
811
  export async function runInstallerCli(
469
812
  args = process.argv.slice(2),
470
813
  ): Promise<void> {
471
- const tokens = args.flatMap((token) => {
472
- const match = /^(--(?:scope|root|target))=(.*)$/.exec(token);
473
- return match ? [match[1], match[2]] : [token];
474
- });
475
- type Operation = "install" | "update" | "uninstall";
476
- let operation: Operation = "install";
477
- if (["install", "update", "uninstall"].includes(tokens[0] ?? ""))
478
- operation = tokens.shift() as Operation;
479
- let scope: "local" | "global" = "local";
480
- let root = process.cwd();
481
- let selected: Target[] = [...targets];
482
- const valueAfter = (index: number) => {
483
- const value = tokens[index + 1];
484
- if (!value || value.startsWith("-"))
485
- throw new InstallerUsageError(
486
- `Missing value for ${tokens[index] ?? "option"}`,
487
- );
488
- return value;
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,
489
861
  };
490
- for (let index = 0; index < tokens.length; index += 1) {
491
- if (["--scope", "-s"].includes(tokens[index] ?? "")) {
492
- scope = valueAfter(index) as typeof scope;
493
- index += 1;
494
- } else if (["--root", "-r"].includes(tokens[index] ?? "")) {
495
- root = valueAfter(index);
496
- index += 1;
497
- } else if (["--target", "-t"].includes(tokens[index] ?? "")) {
498
- const value = valueAfter(index);
499
- selected = value === "all" ? [...targets] : [value as Target];
500
- index += 1;
501
- } else throw new InstallerUsageError(`Unknown option: ${tokens[index]}`);
502
- }
503
- if (!["local", "global"].includes(scope))
504
- throw new InstallerUsageError(
505
- `Invalid scope "${scope}"; expected local or global`,
506
- );
507
- const invalidTarget = selected.find((item) => !targets.includes(item));
508
- if (invalidTarget)
509
- throw new InstallerUsageError(
510
- `Invalid target "${invalidTarget}"; expected codex, claude, copilot, or all`,
511
- );
512
- const options = { root, scope, targets: selected };
513
- const changed =
514
- operation === "install"
515
- ? await install(options)
516
- : operation === "update"
517
- ? await update(options)
518
- : await uninstall(options);
519
- const _label =
520
- operation === "install"
521
- ? "Installed"
522
- : operation === "update"
523
- ? "Updated"
524
- : "Uninstalled";
525
- process.stdout.write(`${JSON.stringify({ changed, operation })}\n`);
862
+ process.stdout.write(`${JSON.stringify(result)}\n`);
526
863
  }
527
864
  if (import.meta.main) await runInstallerCli();