@mwillbanks/ast-mcp 0.2.2 → 0.4.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 (62) hide show
  1. package/CONTRIBUTING.md +13 -0
  2. package/README.md +18 -16
  3. package/dist/ast-mcp.js +209 -147
  4. package/dist/ast-mcp.js.map +70 -50
  5. package/package.json +21 -15
  6. package/src/ast-bro/capability.ts +20 -10
  7. package/src/ast-bro/client.ts +12 -6
  8. package/src/ast-bro/result.ts +79 -0
  9. package/src/ast-bro/tools.json +29 -4
  10. package/src/cli.ts +10 -7
  11. package/src/config-cli.ts +166 -19
  12. package/src/config-edit.ts +236 -0
  13. package/src/config-migrate.ts +206 -0
  14. package/src/config-registry.ts +329 -0
  15. package/src/config-schema-common.ts +88 -0
  16. package/src/config-v2-schema.ts +109 -0
  17. package/src/config.ts +523 -170
  18. package/src/helpers/ast-bro.ts +1 -7
  19. package/src/helpers/config.ts +16 -3
  20. package/src/helpers/installer.ts +8 -0
  21. package/src/helpers/mcp-schema.ts +98 -4
  22. package/src/host-smoke.ts +182 -0
  23. package/src/http.ts +8 -3
  24. package/src/installer-transport.ts +6 -4
  25. package/src/installer.ts +242 -54
  26. package/src/patch/engine.ts +575 -280
  27. package/src/patch/languages.ts +9 -0
  28. package/src/patch/strategy/aiderBlock.ts +110 -0
  29. package/src/patch/strategy/ast.ts +170 -0
  30. package/src/patch/strategy.ts +61 -0
  31. package/src/runtime/approval.ts +438 -0
  32. package/src/runtime/config-write.ts +327 -0
  33. package/src/runtime/dependencies.ts +14 -78
  34. package/src/runtime/document-inspection.ts +78 -0
  35. package/src/runtime/file-capabilities.ts +250 -0
  36. package/src/runtime/file-delete.ts +110 -37
  37. package/src/runtime/file-read.ts +134 -15
  38. package/src/runtime/file-rename.ts +5 -2
  39. package/src/runtime/format.ts +90 -30
  40. package/src/runtime/git-worktrees.ts +179 -0
  41. package/src/runtime/path-policy.ts +643 -0
  42. package/src/runtime/path-utils.ts +80 -0
  43. package/src/runtime/paths.ts +171 -47
  44. package/src/server.ts +2 -1
  45. package/src/tools/ast-bro.ts +294 -75
  46. package/src/tools/configuration.ts +668 -0
  47. package/src/tools/configured.ts +49 -21
  48. package/src/tools/files.ts +169 -62
  49. package/src/tools/index.ts +2 -0
  50. package/src/tools/lifecycle.ts +82 -38
  51. package/templates/AGENTS.md +17 -15
  52. package/templates/skills/ast-mcp/SKILL.md +57 -20
  53. package/templates/skills/ast-mcp/evals/evals.json +319 -9
  54. package/templates/skills/ast-mcp/evals/score.ts +80 -0
  55. package/templates/skills/ast-mcp/evals/semantic.ts +3 -1
  56. package/templates/skills/ast-mcp/references/installation.md +12 -12
  57. package/templates/skills/ast-mcp/references/patch-state-machine.md +15 -14
  58. package/templates/skills/ast-mcp/references/tool-catalog.md +18 -8
  59. package/templates/skills/ast-mcp/scripts/binary-resolution.ts +112 -0
  60. package/templates/skills/ast-mcp/scripts/check-install.ts +165 -51
  61. package/templates/skills/ast-mcp/scripts/managed-hook.ts +34 -2
  62. package/src/ast-bro/rewrite-capability.ts +0 -9
package/src/installer.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import {
2
3
  cp,
3
4
  lstat,
@@ -9,7 +10,8 @@ import {
9
10
  } from "node:fs/promises";
10
11
  import os from "node:os";
11
12
  import path from "node:path";
12
- import { globalConfigPath, resolveConfig } from "./config";
13
+ import { clearConfigCache, globalConfigPath, resolveConfig } from "./config";
14
+ import { migrateConfigSource, writeMigratedConfig } from "./config-migrate";
13
15
  import {
14
16
  codexTransport,
15
17
  installerTargetPaths,
@@ -25,7 +27,12 @@ import {
25
27
  transports,
26
28
  } from "./installer-transport";
27
29
  import { isManagedHook } from "./managed-hook";
28
- import { AST_BRO_BINARY, assertAstBroAvailable } from "./runtime/dependencies";
30
+ import {
31
+ AST_BRO_BINARY,
32
+ assertAstBroAvailable,
33
+ globalBinDirectories,
34
+ resolveGlobalBinaryAlias,
35
+ } from "./runtime/dependencies";
29
36
  import {
30
37
  createServicePlan,
31
38
  installService,
@@ -36,9 +43,66 @@ import {
36
43
 
37
44
  const packageRoot = path.resolve(import.meta.dir, "..");
38
45
  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");
46
+ const installerRuntime = new AsyncLocalStorage<{ cliEntry: string }>();
47
+ function stableGlobalCliEntry(
48
+ value: string | undefined,
49
+ directories: string[],
50
+ platform: NodeJS.Platform,
51
+ ) {
52
+ if (!value) return undefined;
53
+ const resolved = path.resolve(value);
54
+ const basename = path.basename(resolved).toLowerCase();
55
+ const astMcpNames =
56
+ platform === "win32"
57
+ ? ["ast-mcp", "ast-mcp.cmd", "ast-mcp.exe"]
58
+ : ["ast-mcp"];
59
+ if (!astMcpNames.includes(basename)) return undefined;
60
+ const candidateDirectory = path.dirname(resolved);
61
+ const normalize = (entry: string) =>
62
+ platform === "win32"
63
+ ? path.resolve(entry).toLowerCase()
64
+ : path.resolve(entry);
65
+ if (
66
+ !directories.some(
67
+ (directory) => normalize(directory) === normalize(candidateDirectory),
68
+ )
69
+ )
70
+ return undefined;
71
+ return resolveGlobalBinaryAlias("ast-mcp", {
72
+ globalBinDirectories: [candidateDirectory],
73
+ platform,
74
+ });
75
+ }
76
+
77
+ function configuredCliEntry(
78
+ options: InstallOptions,
79
+ root: string,
80
+ home: string,
81
+ ) {
82
+ if (options.scope === "local")
83
+ return path.join(root, "node_modules/.bin/ast-mcp");
84
+ const platform = options.platform ?? process.platform;
85
+ const directories =
86
+ options.globalBinDirectories ??
87
+ globalBinDirectories("ast-mcp", platform, home);
88
+ const resolved =
89
+ stableGlobalCliEntry(options.cliEntry, directories, platform) ??
90
+ resolveGlobalBinaryAlias("ast-mcp", {
91
+ globalBinDirectories: directories,
92
+ platform,
93
+ });
94
+ if (resolved) return resolved;
95
+ throw new Error(
96
+ "No executable global ast-mcp package-manager alias was found. Install @mwillbanks/ast-mcp globally with Bun, npm, pnpm, or Yarn, then rerun the installer.",
97
+ );
98
+ }
99
+ function cliEntryFor(root: string | undefined, _home: string) {
100
+ const entry = installerRuntime.getStore()?.cliEntry ?? cliEntry;
101
+ if (!root) return entry;
102
+ const relative = path.relative(root, entry);
103
+ if (relative && !relative.startsWith("..") && !path.isAbsolute(relative))
104
+ return `./${relative.split(path.sep).join("/")}`;
105
+ return entry;
42
106
  }
43
107
  const hookEntry = path.join(packageRoot, "src/hook.ts");
44
108
  const targets = ["codex", "claude", "copilot"] as const;
@@ -59,13 +123,9 @@ async function save(file: string, value: unknown) {
59
123
  }
60
124
  async function installerAstBroBinary(options: InstallOptions) {
61
125
  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
126
  const config = await resolveConfig({
67
127
  cwd: root,
68
- env,
128
+ env: installerConfigEnvironment(options),
69
129
  home: options.home,
70
130
  });
71
131
  return (
@@ -80,11 +140,7 @@ function definition(
80
140
  endpoint?: HttpEndpoint,
81
141
  ) {
82
142
  if (transport === "http") return { type: "http", url: endpoint?.url };
83
- return {
84
- args: ["mcp"],
85
- command: cliEntryFor(root, home),
86
- env: root ? { AST_MCP_PROJECT_ROOT: root } : {},
87
- };
143
+ return { args: ["mcp"], command: cliEntryFor(root, home) };
88
144
  }
89
145
  async function codexMcp(
90
146
  file: string,
@@ -97,13 +153,10 @@ async function codexMcp(
97
153
  const clean = old
98
154
  .replace(/# ast-mcp:begin[\s\S]*?# ast-mcp:end\n?/g, "")
99
155
  .trimEnd();
100
- const environment = root
101
- ? `env = { AST_MCP_PROJECT_ROOT = ${JSON.stringify(root)} }\n`
102
- : "";
103
156
  const block =
104
157
  transport === "http"
105
158
  ? `# 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`;
159
+ : `# ast-mcp:begin\n[mcp_servers.ast-mcp]\ncommand = ${JSON.stringify(cliEntryFor(root, home))}\nargs = ["mcp"]\n# ast-mcp:end`;
107
160
  await mkdir(path.dirname(file), { recursive: true });
108
161
  await writeFile(file, `${clean ? `${clean}\n\n` : ""}${block}\n`);
109
162
  }
@@ -155,10 +208,8 @@ async function hook(
155
208
  value.hooks ??= {};
156
209
  const prior = Array.isArray(value.hooks[event]) ? value.hooks[event] : [];
157
210
  const command = `${JSON.stringify(commandPath)} hook`;
158
- const managedCommands = [command, `bun ${JSON.stringify(cliEntry)} hook`];
159
211
  const kept = prior.filter(
160
- (item: unknown) =>
161
- !managedCommands.some((managed) => isManagedHook(item, event, managed)),
212
+ (item: unknown) => !isManagedHook(item, event, command),
162
213
  );
163
214
  const item =
164
215
  event === "preToolUse"
@@ -304,6 +355,9 @@ async function hasLocalInstallation(root: string) {
304
355
 
305
356
  export interface InstallOptions {
306
357
  astBroBinary?: string;
358
+ cliEntry?: string;
359
+ deprecatedRoot?: boolean;
360
+ globalBinDirectories?: string[];
307
361
  home?: string;
308
362
  host?: string;
309
363
  platform?: NodeJS.Platform;
@@ -606,6 +660,108 @@ function installerConfigEnvironment(options: InstallOptions) {
606
660
  : { ...process.env, APPDATA: undefined, XDG_CONFIG_HOME: undefined };
607
661
  }
608
662
 
663
+ function installerConfigPath(
664
+ options: InstallOptions,
665
+ root: string,
666
+ home: string,
667
+ ) {
668
+ return options.scope === "local"
669
+ ? path.join(root, "ast-mcp.toml")
670
+ : globalConfigPath({ env: installerConfigEnvironment(options), home });
671
+ }
672
+
673
+ function installerConfigSeed(local: boolean) {
674
+ const common = [
675
+ "version = 2",
676
+ "",
677
+ "[files.read]",
678
+ 'modes = ["ast", "text"]',
679
+ "",
680
+ "[files.patch]",
681
+ 'strategies = ["ast", "aider_block"]',
682
+ 'aider_matchers = ["exact", "whitespace", "relative-indentation", "diff-match-patch"]',
683
+ "",
684
+ "[formatting]",
685
+ "enabled = true",
686
+ 'fallback = "preserve"',
687
+ "",
688
+ "[safety]",
689
+ "require_hash = true",
690
+ "",
691
+ "[safety.hook]",
692
+ "enabled = true",
693
+ "allow_tools = []",
694
+ "block_tools = []",
695
+ "",
696
+ "[http]",
697
+ 'host = "127.0.0.1"',
698
+ "port = 3768",
699
+ "session_timeout_ms = 1800000",
700
+ "session_sweep_interval_ms = 60000",
701
+ "",
702
+ "[mcp.configuration]",
703
+ "enabled = true",
704
+ "require_approval = true",
705
+ ];
706
+ if (!local) return `${common.join("\n")}\n`;
707
+ return `${[
708
+ "version = 2",
709
+ "",
710
+ "[workspace]",
711
+ 'roots = ["."]',
712
+ 'worktrees = "include"',
713
+ "",
714
+ ...common.slice(2),
715
+ "",
716
+ "[[paths]]",
717
+ 'id = "workspace"',
718
+ 'path = "."',
719
+ 'policies = { read = "allow", write = "allow", delete = "deny" }',
720
+ "follow_symlinks = false",
721
+ 'includes = ["**/*"]',
722
+ 'excludes = [".git/**"]',
723
+ ].join("\n")}\n`;
724
+ }
725
+
726
+ async function ensureInstallerConfig(
727
+ options: InstallOptions,
728
+ root: string,
729
+ home: string,
730
+ ) {
731
+ const file = installerConfigPath(options, root, home);
732
+ const existing = await readFile(file, "utf8").catch((error) => {
733
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
734
+ throw error;
735
+ });
736
+ clearConfigCache();
737
+ await resolveConfig({
738
+ cwd: options.scope === "local" ? root : home,
739
+ env: installerConfigEnvironment(options),
740
+ home,
741
+ });
742
+ if (existing === undefined) {
743
+ await mkdir(path.dirname(file), { recursive: true });
744
+ await writeFile(file, installerConfigSeed(options.scope === "local"), {
745
+ flag: "wx",
746
+ });
747
+ } else {
748
+ try {
749
+ const migration = migrateConfigSource(existing, file);
750
+ if (migration.changed) await writeMigratedConfig(file, migration.source);
751
+ } catch (error) {
752
+ throw new Error(
753
+ `invalid configuration: ${error instanceof Error ? error.message : String(error)}`,
754
+ );
755
+ }
756
+ }
757
+ clearConfigCache();
758
+ await resolveConfig({
759
+ cwd: options.scope === "local" ? root : home,
760
+ env: installerConfigEnvironment(options),
761
+ home,
762
+ });
763
+ }
764
+
609
765
  async function reconcileEndpoint(
610
766
  options: InstallOptions,
611
767
  transport: McpTransport,
@@ -642,18 +798,13 @@ function reconcilePaths(
642
798
  global: boolean,
643
799
  root: string,
644
800
  home: string,
645
- transport: McpTransport,
801
+ _transport: McpTransport,
646
802
  endpoint?: HttpEndpoint,
647
803
  ) {
648
804
  const paths = options.targets.flatMap((target) =>
649
805
  targetPaths(target, global, root, home),
650
806
  );
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
- );
807
+ paths.push(installerConfigPath(options, root, home));
657
808
  if (options.service !== undefined)
658
809
  paths.push(
659
810
  createServicePlan(
@@ -685,26 +836,44 @@ async function reconcile(
685
836
  options: InstallOptions,
686
837
  operation: "install" | "update",
687
838
  ) {
688
- assertAstBroAvailable(await installerAstBroBinary(options));
689
839
  const root = path.resolve(options.root);
690
840
  const home = options.home ?? os.homedir();
691
841
  const global = options.scope === "global";
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,
842
+ return installerRuntime.run(
843
+ { cliEntry: configuredCliEntry(options, root, home) },
844
+ async () => {
845
+ const transport = await selectedTransport(options, operation);
846
+ validateReconcileOptions(options, transport);
847
+ const paths = reconcilePaths(
848
+ options,
849
+ global,
850
+ root,
851
+ home,
852
+ transport,
853
+ undefined,
854
+ );
855
+ const before = await snapshot(paths);
856
+ if (transport === "http" && options.service === true) {
857
+ const endpoint = await resolveInstallerEndpoint({
858
+ env: installerConfigEnvironment(options),
859
+ home,
860
+ host: options.host,
861
+ persist: false,
862
+ port: options.port,
863
+ root,
864
+ scope: options.scope,
865
+ });
866
+ await preflightService(serviceConfiguration(options, endpoint));
867
+ }
868
+ assertAstBroAvailable(await installerAstBroBinary(options));
869
+ await ensureInstallerConfig(options, root, home);
870
+ const endpoint = await reconcileEndpoint(options, transport, root, home);
871
+ for (const target of options.targets)
872
+ await installTarget(target, global, root, home, transport, endpoint);
873
+ await reconcileService(options, endpoint);
874
+ return changedFiles(before, await snapshot(paths));
875
+ },
702
876
  );
703
- const before = await snapshot(paths);
704
- for (const target of options.targets)
705
- await installTarget(target, global, root, home, transport, endpoint);
706
- await reconcileService(options, endpoint);
707
- return changedFiles(before, await snapshot(paths));
708
877
  }
709
878
 
710
879
  export async function install(options: InstallOptions) {
@@ -817,15 +986,20 @@ async function removeUnusedService(options: InstallOptions, root: string) {
817
986
  export async function uninstall(options: InstallOptions) {
818
987
  const root = path.resolve(options.root);
819
988
  const home = options.home ?? os.homedir();
820
- const global = options.scope === "global";
821
- const paths = options.targets.flatMap((target) =>
822
- targetPaths(target, global, root, home),
989
+ return installerRuntime.run(
990
+ { cliEntry: configuredCliEntry(options, root, home) },
991
+ async () => {
992
+ const global = options.scope === "global";
993
+ const paths = options.targets.flatMap((target) =>
994
+ targetPaths(target, global, root, home),
995
+ );
996
+ const before = await snapshot(paths);
997
+ for (const target of options.targets)
998
+ await uninstallTarget(target, global, root, home);
999
+ await removeUnusedService(options, root);
1000
+ return changedFiles(before, await snapshot(paths));
1001
+ },
823
1002
  );
824
- const before = await snapshot(paths);
825
- for (const target of options.targets)
826
- await uninstallTarget(target, global, root, home);
827
- await removeUnusedService(options, root);
828
- return changedFiles(before, await snapshot(paths));
829
1003
  }
830
1004
 
831
1005
  export async function runInstallerCli(
@@ -836,6 +1010,10 @@ export async function runInstallerCli(
836
1010
  process.cwd(),
837
1011
  );
838
1012
  const options: InstallOptions = parsedOptions;
1013
+ if (options.deprecatedRoot)
1014
+ process.stderr.write(
1015
+ "ast-mcp: --root is deprecated; run this command from the project root.\n",
1016
+ );
839
1017
  const operationHandlers = { install, uninstall, update };
840
1018
  const changed = await operationHandlers[operation](options);
841
1019
  const root = path.resolve(options.root);
@@ -867,7 +1045,17 @@ export async function runInstallerCli(
867
1045
  : undefined;
868
1046
  const manualStart =
869
1047
  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}`
1048
+ ? installerRuntime.run(
1049
+ {
1050
+ cliEntry: configuredCliEntry(
1051
+ options,
1052
+ root,
1053
+ options.home ?? os.homedir(),
1054
+ ),
1055
+ },
1056
+ () =>
1057
+ `${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}`,
1058
+ )
871
1059
  : undefined;
872
1060
  const result = {
873
1061
  changed,