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