@mwillbanks/ast-mcp 0.1.2 → 0.1.3

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.
package/package.json CHANGED
@@ -48,6 +48,7 @@
48
48
  "license": "MIT",
49
49
  "name": "@mwillbanks/ast-mcp",
50
50
  "packageManager": "bun@1.3.14",
51
+ "preferUnplugged": true,
51
52
  "publishConfig": {
52
53
  "access": "public"
53
54
  },
@@ -84,5 +85,5 @@
84
85
  "dprint"
85
86
  ],
86
87
  "type": "module",
87
- "version": "0.1.2"
88
+ "version": "0.1.3"
88
89
  }
package/src/cli.ts CHANGED
@@ -2,6 +2,98 @@ export interface CliHandlers {
2
2
  hook(): Promise<number>;
3
3
  installer(args: string[]): Promise<void>;
4
4
  mcp(): Promise<void>;
5
+ stderr?(text: string): void;
6
+ stdout?(text: string): void;
7
+ }
8
+
9
+ const rootHelp = `ast-mcp - AST-aware Model Context Protocol server
10
+
11
+ Usage:
12
+ ast-mcp <command> [options]
13
+
14
+ Commands:
15
+ install Configure ast-mcp for one or more supported hosts
16
+ update Refresh an existing ast-mcp configuration
17
+ uninstall Remove ast-mcp-managed configuration
18
+ mcp Start the stdio MCP server
19
+ hook Run the pre-tool-use filesystem guard
20
+ help Display help for a command
21
+
22
+ Options:
23
+ -h, --help Display help
24
+
25
+ Run "ast-mcp help <command>" for command-specific help.
26
+ `;
27
+
28
+ const installerOptions = `Options:
29
+ -s, --scope <scope> Installation scope: local or global (default: local)
30
+ -t, --target <target> Host: codex, claude, copilot, or all (default: all)
31
+ -r, --root <path> Project root for local scope (default: current directory)
32
+ -h, --help Display help
33
+ `;
34
+
35
+ const commandHelp: Record<string, string> = {
36
+ hook: `Usage:
37
+ ast-mcp hook
38
+
39
+ Run the pre-tool-use filesystem guard. Hook input is read from stdin.
40
+
41
+ Options:
42
+ -h, --help Display help
43
+ `,
44
+ install: `Usage:
45
+ ast-mcp install [options]
46
+
47
+ Configure ast-mcp for supported hosts.
48
+
49
+ ${installerOptions}`,
50
+ mcp: `Usage:
51
+ ast-mcp mcp
52
+
53
+ Start the stdio MCP server. Protocol messages are read from stdin and written to stdout.
54
+
55
+ Options:
56
+ -h, --help Display help
57
+ `,
58
+ uninstall: `Usage:
59
+ ast-mcp uninstall [options]
60
+
61
+ Remove ast-mcp-managed configuration while preserving shared host files.
62
+
63
+ ${installerOptions}`,
64
+ update: `Usage:
65
+ ast-mcp update [options]
66
+
67
+ Refresh managed configuration and installed skill content.
68
+
69
+ ${installerOptions}`,
70
+ };
71
+
72
+ export function getCliHelp(): string;
73
+ export function getCliHelp(command: keyof typeof commandHelp): string;
74
+ export function getCliHelp(command: string): string | undefined;
75
+ export function getCliHelp(command?: string) {
76
+ return command && Object.hasOwn(commandHelp, command)
77
+ ? commandHelp[command]
78
+ : command
79
+ ? undefined
80
+ : rootHelp;
81
+ }
82
+
83
+ function writeHelp(handlers: CliHandlers, command?: string) {
84
+ const output =
85
+ command === undefined ? getCliHelp() : (getCliHelp(command) ?? rootHelp);
86
+ if (handlers.stdout) handlers.stdout(output);
87
+ else process.stdout.write(output);
88
+ }
89
+
90
+ function usageError(handlers: CliHandlers, message: string, command?: string) {
91
+ const help =
92
+ command === undefined ? getCliHelp() : (getCliHelp(command) ?? rootHelp);
93
+ const output = `ast-mcp: ${message}\n\n${help}`;
94
+ if (handlers.stderr) handlers.stderr(output);
95
+ else process.stderr.write(output);
96
+ return 1;
5
97
  }
6
98
 
7
99
  export async function runCli(
@@ -9,18 +101,50 @@ export async function runCli(
9
101
  handlers: CliHandlers,
10
102
  ): Promise<number | undefined> {
11
103
  const [command, ...rest] = args;
104
+ if (!command || command === "--help" || command === "-h") {
105
+ writeHelp(handlers);
106
+ return 0;
107
+ }
108
+ if (command === "help") {
109
+ const [topic, ...extra] = rest;
110
+ if (extra.length > 0)
111
+ return usageError(handlers, `Unexpected argument: ${extra[0]}`);
112
+ if (topic && !Object.hasOwn(commandHelp, topic))
113
+ return usageError(handlers, `Unknown command: ${topic}`);
114
+ writeHelp(handlers, topic);
115
+ return 0;
116
+ }
117
+ if (!Object.hasOwn(commandHelp, command))
118
+ return usageError(handlers, `Unknown command: ${command}`);
119
+ if (rest.includes("--help") || rest.includes("-h")) {
120
+ writeHelp(handlers, command);
121
+ return 0;
122
+ }
12
123
  if (command === "mcp") {
124
+ if (rest.length > 0)
125
+ return usageError(
126
+ handlers,
127
+ `Unexpected argument for mcp: ${rest[0]}`,
128
+ command,
129
+ );
13
130
  await handlers.mcp();
14
131
  return;
15
132
  }
16
133
  if (command === "hook") {
134
+ if (rest.length > 0)
135
+ return usageError(
136
+ handlers,
137
+ `Unexpected argument for hook: ${rest[0]}`,
138
+ command,
139
+ );
17
140
  return handlers.hook();
18
141
  }
19
- if (["install", "update", "uninstall"].includes(command ?? "")) {
20
- await handlers.installer([command as string, ...rest]);
142
+ try {
143
+ await handlers.installer([command, ...rest]);
21
144
  return;
145
+ } catch (error) {
146
+ if (error instanceof Error && error.name === "InstallerUsageError")
147
+ return usageError(handlers, error.message, command);
148
+ throw error;
22
149
  }
23
- throw new Error(
24
- "Usage: ast-mcp <install|update|uninstall|hook|mcp> [options]",
25
- );
26
150
  }
package/src/installer.ts CHANGED
@@ -134,14 +134,10 @@ const instructionsEnd = "<!-- ast-mcp:end -->";
134
134
  const instructionsPattern =
135
135
  /<!-- ast-mcp:begin -->[\s\S]*?<!-- ast-mcp:end -->\n?/g;
136
136
 
137
- async function writeTextOrRemove(file: string, content: string) {
137
+ async function writeText(file: string, content: string) {
138
138
  const normalized = content.trimEnd();
139
- if (!normalized) {
140
- await rm(file, { force: true });
141
- return;
142
- }
143
139
  await mkdir(path.dirname(file), { recursive: true });
144
- await writeFile(file, `${normalized}\n`);
140
+ await writeFile(file, normalized ? `${normalized}\n` : "");
145
141
  }
146
142
 
147
143
  async function instructions(file: string) {
@@ -150,23 +146,23 @@ async function instructions(file: string) {
150
146
  ).trim();
151
147
  const old = await readFile(file, "utf8").catch(() => "");
152
148
  const clean = old.replace(instructionsPattern, "").trimEnd();
153
- await writeTextOrRemove(
149
+ await writeText(
154
150
  file,
155
151
  `${clean ? `${clean}\n\n` : ""}${instructionsBegin}\n\n${block}\n\n${instructionsEnd}`,
156
152
  );
157
153
  }
158
154
 
159
155
  async function removeInstructions(file: string) {
160
- const old = await readFile(file, "utf8").catch(() => "");
161
- await writeTextOrRemove(file, old.replace(instructionsPattern, ""));
156
+ const old = await readFile(file, "utf8").catch((error) => {
157
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
158
+ throw error;
159
+ });
160
+ if (old === undefined) return;
161
+ await writeText(file, old.replace(instructionsPattern, ""));
162
162
  }
163
163
 
164
164
  // 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
- }
165
+ async function saveRemainingJson(file: string, value: Record<string, any>) {
170
166
  await save(file, value);
171
167
  }
172
168
 
@@ -177,12 +173,16 @@ async function removeJsonMcp(file: string, section = "mcpServers") {
177
173
  return;
178
174
  delete entries["ast-mcp"];
179
175
  if (Object.keys(entries).length === 0) delete value[section];
180
- await saveJsonOrRemove(file, value);
176
+ await saveRemainingJson(file, value);
181
177
  }
182
178
 
183
179
  async function removeCodexMcp(file: string) {
184
- const old = await readFile(file, "utf8").catch(() => "");
185
- await writeTextOrRemove(
180
+ const old = await readFile(file, "utf8").catch((error) => {
181
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
182
+ throw error;
183
+ });
184
+ if (old === undefined) return;
185
+ await writeText(
186
186
  file,
187
187
  old.replace(/# ast-mcp:begin[\s\S]*?# ast-mcp:end\n?/g, ""),
188
188
  );
@@ -206,7 +206,7 @@ async function removeHook(
206
206
  );
207
207
  if (hooks[event].length === 0) delete hooks[event];
208
208
  if (Object.keys(hooks).length === 0) delete value.hooks;
209
- await saveJsonOrRemove(file, value);
209
+ await saveRemainingJson(file, value);
210
210
  }
211
211
 
212
212
  async function hasLocalInstallation(root: string) {
@@ -231,6 +231,10 @@ export interface InstallOptions {
231
231
  targets: Target[];
232
232
  }
233
233
 
234
+ class InstallerUsageError extends Error {
235
+ override name = "InstallerUsageError";
236
+ }
237
+
234
238
  function targetPaths(
235
239
  target: Target,
236
240
  global: boolean,
@@ -464,7 +468,10 @@ export async function uninstall(options: InstallOptions) {
464
468
  export async function runInstallerCli(
465
469
  args = process.argv.slice(2),
466
470
  ): Promise<void> {
467
- const tokens = [...args];
471
+ const tokens = args.flatMap((token) => {
472
+ const match = /^(--(?:scope|root|target))=(.*)$/.exec(token);
473
+ return match ? [match[1], match[2]] : [token];
474
+ });
468
475
  type Operation = "install" | "update" | "uninstall";
469
476
  let operation: Operation = "install";
470
477
  if (["install", "update", "uninstall"].includes(tokens[0] ?? ""))
@@ -472,19 +479,36 @@ export async function runInstallerCli(
472
479
  let scope: "local" | "global" = "local";
473
480
  let root = process.cwd();
474
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;
489
+ };
475
490
  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];
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);
480
499
  selected = value === "all" ? [...targets] : [value as Target];
481
- } else throw new Error(`Unknown argument: ${tokens[index]}`);
500
+ index += 1;
501
+ } else throw new InstallerUsageError(`Unknown option: ${tokens[index]}`);
482
502
  }
483
- if (
484
- !["local", "global"].includes(scope) ||
485
- selected.some((item) => !targets.includes(item))
486
- )
487
- throw new Error("Invalid install scope or target");
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
+ );
488
512
  const options = { root, scope, targets: selected };
489
513
  const changed =
490
514
  operation === "install"
@@ -1,5 +1,6 @@
1
- import { realpathSync } from "node:fs";
1
+ import { accessSync, constants, readFileSync } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
 
5
6
  export const PACKAGE_ROOT = path.resolve(
@@ -7,14 +8,146 @@ export const PACKAGE_ROOT = path.resolve(
7
8
  path.basename(import.meta.dir) === "dist" ? ".." : "../..",
8
9
  );
9
10
 
10
- const astBroWrapper = path.join(PACKAGE_ROOT, "node_modules/.bin/ast-bro");
11
- const astBroInstaller = createRequire(import.meta.url)(
12
- path.join(path.dirname(realpathSync(astBroWrapper)), "install.js"),
13
- ) as { getBinaryPath: () => string };
11
+ const require = createRequire(import.meta.url);
12
+
13
+ interface BinaryResolutionOptions {
14
+ globalBinDirectories?: string[];
15
+ packageBinary?: string;
16
+ packageRoot?: string;
17
+ pathValue?: string;
18
+ platform?: NodeJS.Platform;
19
+ }
20
+
21
+ function executableNames(name: string, platform: NodeJS.Platform) {
22
+ if (platform !== "win32") return [name];
23
+ const extensions = (process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM")
24
+ .split(";")
25
+ .filter(Boolean);
26
+ return [name, ...extensions.map((extension) => `${name}${extension}`)];
27
+ }
28
+
29
+ function isExecutable(file: string, platform: NodeJS.Platform) {
30
+ try {
31
+ accessSync(
32
+ file,
33
+ platform === "win32" ? constants.F_OK : constants.F_OK | constants.X_OK,
34
+ );
35
+ return true;
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
41
+ function packageBinary(packageName: string, binaryName: string) {
42
+ try {
43
+ const manifestPath = require.resolve(`${packageName}/package.json`);
44
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as {
45
+ bin?: string | Record<string, string>;
46
+ };
47
+ const relative =
48
+ typeof manifest.bin === "string"
49
+ ? manifest.bin
50
+ : manifest.bin?.[binaryName];
51
+ return relative
52
+ ? path.resolve(path.dirname(manifestPath), relative)
53
+ : undefined;
54
+ } catch {
55
+ return undefined;
56
+ }
57
+ }
58
+
59
+ function commandOutput(command: string, args: string[]) {
60
+ try {
61
+ const result = Bun.spawnSync([command, ...args], {
62
+ stderr: "ignore",
63
+ stdout: "pipe",
64
+ });
65
+ return result.exitCode === 0 ? result.stdout.toString().trim() : "";
66
+ } catch {
67
+ return "";
68
+ }
69
+ }
70
+
71
+ function globalBinDirectories(binaryName: string, platform: NodeJS.Platform) {
72
+ const directories = new Set<string>();
73
+ const add = (value: string | undefined) => {
74
+ if (value) directories.add(path.resolve(value));
75
+ };
76
+ const yarnBinary = commandOutput("yarn", ["bin", binaryName]);
77
+ if (yarnBinary) add(path.dirname(yarnBinary));
78
+ add(process.env.BUN_INSTALL && path.join(process.env.BUN_INSTALL, "bin"));
79
+ add(process.env.PNPM_HOME);
80
+ add(
81
+ process.env.npm_config_prefix &&
82
+ (platform === "win32"
83
+ ? process.env.npm_config_prefix
84
+ : path.join(process.env.npm_config_prefix, "bin")),
85
+ );
86
+ add(path.join(os.homedir(), ".bun/bin"));
87
+ add(path.join(os.homedir(), ".bun/install/global/node_modules/.bin"));
88
+
89
+ add(commandOutput("bun", ["pm", "bin", "-g"]));
90
+ add(commandOutput("pnpm", ["bin", "-g"]));
91
+ add(commandOutput("yarn", ["global", "bin"]));
92
+ const npmPrefix = commandOutput("npm", ["prefix", "-g"]);
93
+ add(
94
+ npmPrefix &&
95
+ (platform === "win32" ? npmPrefix : path.join(npmPrefix, "bin")),
96
+ );
97
+ return [...directories];
98
+ }
99
+
100
+ export function resolveDependencyBinary(
101
+ binaryName: string,
102
+ packageName = binaryName,
103
+ options: BinaryResolutionOptions = {},
104
+ ) {
105
+ const platform = options.platform ?? process.platform;
106
+ const packageRoot = options.packageRoot ?? PACKAGE_ROOT;
107
+ const names = executableNames(binaryName, platform);
108
+ const candidates: string[] = [];
109
+
110
+ for (
111
+ let current = packageRoot;
112
+ path.dirname(current) !== current;
113
+ current = path.dirname(current)
114
+ )
115
+ for (const name of names)
116
+ candidates.push(path.join(current, "node_modules/.bin", name));
117
+
118
+ const directPackageBinary =
119
+ options.packageBinary ?? packageBinary(packageName, binaryName);
120
+ if (directPackageBinary) candidates.push(directPackageBinary);
121
+ const local = candidates.find((candidate) =>
122
+ isExecutable(candidate, platform),
123
+ );
124
+ if (local) return local;
125
+
126
+ const globalDirectories =
127
+ options.globalBinDirectories ?? globalBinDirectories(binaryName, platform);
128
+ candidates.length = 0;
129
+ for (const directory of globalDirectories)
130
+ for (const name of names) candidates.push(path.join(directory, name));
131
+ const global = candidates.find((candidate) =>
132
+ isExecutable(candidate, platform),
133
+ );
134
+ if (global) return global;
135
+
136
+ candidates.length = 0;
137
+ for (const directory of (options.pathValue ?? process.env.PATH ?? "").split(
138
+ path.delimiter,
139
+ ))
140
+ if (directory)
141
+ for (const name of names) candidates.push(path.join(directory, name));
142
+
143
+ return candidates.find((candidate) => isExecutable(candidate, platform));
144
+ }
14
145
 
15
146
  export const AST_BRO_VERSION = "3.0.0";
16
147
  export const AST_BRO_BINARY =
17
- process.env.AST_BRO_BINARY ?? astBroInstaller.getBinaryPath();
148
+ process.env.AST_BRO_BINARY ??
149
+ resolveDependencyBinary("ast-bro", "@ast-bro/cli") ??
150
+ "ast-bro";
18
151
 
19
152
  export function assertAstBroAvailable(
20
153
  binary = AST_BRO_BINARY,
@@ -51,4 +184,5 @@ export function assertAstBroAvailable(
51
184
 
52
185
  export const DPRINT_BINARY =
53
186
  process.env.DPRINT_BINARY ??
54
- path.join(PACKAGE_ROOT, "node_modules/.bin/dprint");
187
+ resolveDependencyBinary("dprint", "dprint") ??
188
+ "dprint";
@@ -26,15 +26,27 @@ Targets are `codex`, `claude`, `copilot`, or `all`.
26
26
 
27
27
  ## Install from the published package
28
28
 
29
- If the package is not already installed, obtain user authorization before allowing Bun to download or install it. Install it into the repository so `@ast-bro/cli` and `dprint` remain available, then run the installed CLI:
29
+ If the package is not already installed, obtain user authorization before allowing a package manager to download or install it. Install it into the repository so `@ast-bro/cli` and `dprint` remain available, then run the installed CLI:
30
30
 
31
- `bun add --dev @mwillbanks/ast-mcp`
31
+ ```npm
32
+ npm install --save-dev @mwillbanks/ast-mcp
33
+ ```
34
+
35
+ When installing with Bun, allow the pinned native installers:
32
36
 
33
37
  `bun pm trust @ast-bro/cli dprint`
34
38
 
35
39
  `./node_modules/.bin/ast-mcp install --scope local --target all --root "$PWD"`
36
40
 
37
- For a global host surface, use `bun add --global --trust @ast-bro/cli dprint @mwillbanks/ast-mcp` followed by `ast-mcp install --scope global --target codex`. Bun blocks transitive lifecycle scripts by default; explicitly trusting `@ast-bro/cli` and `dprint` runs their pinned native installers instead of leaving stale or missing cache paths. Do not use an ephemeral package executor for host installation because its temporary package path can disappear after configuration is written. The installer records the stable installed CLI and uses its `mcp` and `hook` subcommands. For a local installation, run `./node_modules/.bin/ast-mcp update` to refresh managed surfaces and `./node_modules/.bin/ast-mcp uninstall` to remove them; global installations use `ast-mcp update` and `ast-mcp uninstall`.
41
+ For a global host surface, use the package manager's persistent global install:
42
+
43
+ ```npm
44
+ npm install --global @mwillbanks/ast-mcp
45
+ ```
46
+
47
+ Then run `ast-mcp install --scope global --target codex`. Yarn 2+ should use a project-local installation because it does not provide the Yarn Classic global workflow. Bun blocks transitive lifecycle scripts by default; explicitly trusting `@ast-bro/cli` and `dprint` runs their pinned native installers instead of leaving stale or missing cache paths. If another manager blocks dependency build scripts, approve those two packages through that manager.
48
+
49
+ Do not use an ephemeral package executor for host installation because its temporary package path can disappear after configuration is written. The runtime checks ancestor `node_modules/.bin` directories, package metadata, Bun/pnpm/npm/Yarn global bins, and finally `PATH`. The installer records the stable installed CLI and uses its `mcp` and `hook` subcommands. For a local installation, run `./node_modules/.bin/ast-mcp update` to refresh managed surfaces and `./node_modules/.bin/ast-mcp uninstall` to remove them; global installations use `ast-mcp update` and `ast-mcp uninstall`.
38
50
 
39
51
  The pinned `@ast-bro/cli@3.0.0` package has a precompiled binary only for macOS Apple Silicon. On Linux or macOS Intel, install it with `cargo install ast-bro --version 3.0.0 --locked`, set `AST_BRO_BINARY="$HOME/.cargo/bin/ast-bro"`, and persist that export in `~/.profile` or `~/.zprofile`. On Windows, use the same Cargo command and persist `AST_BRO_BINARY` as `$HOME\.cargo\bin\ast-bro.exe` in the user environment. GUI-launched hosts must inherit that variable from their launcher. The ast-mcp installer verifies the binary before modifying host configuration and returns these commands when manual setup is required.
40
52