@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
@@ -0,0 +1,327 @@
1
+ import { currentConfig, type ResolvedConfig } from "../config";
2
+ import {
3
+ addPathTable,
4
+ existingPathPolicies,
5
+ pathTableIds,
6
+ readConfigSource,
7
+ removePathTable,
8
+ setTomlSectionKey,
9
+ type TomlValue,
10
+ updatePathTable,
11
+ writeConfigSource,
12
+ } from "../config-edit";
13
+ import { configRegistry } from "../config-registry";
14
+ import { withFileLocks } from "./locks";
15
+ import { assertPolicy, evaluatePolicy, PathPolicyError } from "./path-policy";
16
+
17
+ export type ConfigTarget = "global" | "project";
18
+
19
+ export interface ConfigCorePatch {
20
+ dependencies?: {
21
+ ast_bro_binary?: string;
22
+ dprint_binary?: string;
23
+ };
24
+ files?: {
25
+ patch?: {
26
+ aider_matchers?: Array<
27
+ "diff-match-patch" | "exact" | "relative-indentation" | "whitespace"
28
+ >;
29
+ strategies?: Array<"aider_block" | "ast">;
30
+ };
31
+ read?: { modes?: Array<"ast" | "text"> };
32
+ };
33
+ formatting?: {
34
+ dprint_config?: string;
35
+ enabled?: boolean;
36
+ fallback?: "dprint" | "preserve" | "reject";
37
+ };
38
+ http?: {
39
+ host?: string;
40
+ port?: number;
41
+ session_sweep_interval_ms?: number;
42
+ session_timeout_ms?: number;
43
+ };
44
+ mcp?: { configuration?: { enabled?: boolean; require_approval?: boolean } };
45
+ safety?: {
46
+ hook?: {
47
+ allow_tools?: string[];
48
+ block_tools?: string[];
49
+ enabled?: boolean;
50
+ };
51
+ require_hash?: boolean;
52
+ };
53
+ target?: ConfigTarget;
54
+ workspace?: {
55
+ roots?: string[];
56
+ worktrees?: "ignore" | "include" | "request";
57
+ };
58
+ }
59
+
60
+ export interface ConfigPathRulePatch {
61
+ excludes?: string[];
62
+ follow_symlinks?: boolean;
63
+ includes?: string[];
64
+ path?: string;
65
+ policies?: {
66
+ delete?: "allow" | "deny" | "request";
67
+ read?: "allow" | "deny" | "request";
68
+ write?: "allow" | "deny" | "request";
69
+ };
70
+ }
71
+
72
+ export type ConfigPathOperation =
73
+ | {
74
+ op: "add";
75
+ rule: ConfigPathRulePatch & {
76
+ id: string;
77
+ path: string;
78
+ policies: {
79
+ read: "allow" | "deny" | "request";
80
+ write: "allow" | "deny" | "request";
81
+ };
82
+ };
83
+ }
84
+ | { id: string; op: "remove" }
85
+ | { id: string; op: "update"; rule: ConfigPathRulePatch };
86
+
87
+ export interface ConfigPathsPatch {
88
+ operations: ConfigPathOperation[];
89
+ target?: ConfigTarget;
90
+ }
91
+
92
+ function configurationError(
93
+ code: string,
94
+ message: string,
95
+ suggestedNextCall?: string,
96
+ ): Error {
97
+ return Object.assign(new Error(message), {
98
+ code,
99
+ retryable: true,
100
+ suggestedNextCall,
101
+ });
102
+ }
103
+
104
+ async function targetFilePath(target: ConfigTarget) {
105
+ const config = await currentConfig();
106
+ const filePath =
107
+ target === "global" ? config.sources.global : config.sources.project;
108
+ if (!filePath)
109
+ throw configurationError(
110
+ "configuration_missing",
111
+ `No ${target} ast-mcp.toml exists; create version 2 configuration first`,
112
+ "ast-mcp config migrate",
113
+ );
114
+ return { config, filePath };
115
+ }
116
+
117
+ async function loadTarget(target: ConfigTarget = "project") {
118
+ const { config, filePath } = await targetFilePath(target);
119
+ const source = await readConfigSource(filePath);
120
+ const parsed = Bun.TOML.parse(source) as { version?: unknown };
121
+ if (parsed.version !== 2)
122
+ throw configurationError(
123
+ "configuration_migration_required",
124
+ `${filePath} is not version 2; run ast-mcp config migrate before MCP configuration edits`,
125
+ "ast-mcp config migrate",
126
+ );
127
+ return { config, filePath, source };
128
+ }
129
+
130
+ function authorizeConfigWrite(
131
+ config: ResolvedConfig,
132
+ filePath: string,
133
+ touchesMcpConfiguration: boolean,
134
+ ): void {
135
+ if (!config.mcp.configuration.enabled)
136
+ throw configurationError(
137
+ "configuration_mcp_disabled",
138
+ "MCP configuration tools are disabled (mcp.configuration.enabled = false)",
139
+ "config_status",
140
+ );
141
+ const decision = evaluatePolicy(config, filePath, "write");
142
+ if (decision.policy === "deny") throw new PathPolicyError(decision);
143
+ const required =
144
+ config.mcp.configuration.requireApproval || touchesMcpConfiguration;
145
+ if (!required) return;
146
+ assertPolicy(
147
+ {
148
+ ...decision,
149
+ policy: "request",
150
+ reason: "MCP configuration change requires approval",
151
+ },
152
+ config.generation,
153
+ );
154
+ }
155
+
156
+ function compactEntries(
157
+ value: Record<string, unknown> | undefined,
158
+ ): Array<[string, TomlValue]> {
159
+ if (!value) return [];
160
+ return Object.entries(value).filter(
161
+ (entry): entry is [string, TomlValue] => entry[1] !== undefined,
162
+ );
163
+ }
164
+
165
+ function applyObjectKeys(
166
+ source: string,
167
+ header: string,
168
+ value: Record<string, unknown> | undefined,
169
+ ): string {
170
+ let next = source;
171
+ for (const [key, item] of compactEntries(value))
172
+ next = setTomlSectionKey(next, header, key, item);
173
+ return next;
174
+ }
175
+
176
+ function applyConfigCorePatch(source: string, patch: ConfigCorePatch): string {
177
+ let next = source;
178
+ next = applyObjectKeys(next, "workspace", patch.workspace);
179
+ next = applyObjectKeys(next, "safety", {
180
+ require_hash: patch.safety?.require_hash,
181
+ });
182
+ next = applyObjectKeys(next, "safety.hook", patch.safety?.hook);
183
+ next = applyObjectKeys(next, "files.read", patch.files?.read);
184
+ next = applyObjectKeys(next, "files.patch", patch.files?.patch);
185
+ next = applyObjectKeys(next, "formatting", {
186
+ dprint_config: patch.formatting?.dprint_config,
187
+ enabled: patch.formatting?.enabled,
188
+ fallback: patch.formatting?.fallback,
189
+ });
190
+ next = applyObjectKeys(next, "http", patch.http);
191
+ next = applyObjectKeys(next, "dependencies", patch.dependencies);
192
+ next = applyObjectKeys(next, "mcp.configuration", patch.mcp?.configuration);
193
+ return next;
194
+ }
195
+
196
+ function pathRuleRecord(
197
+ rule: ConfigPathRulePatch & { id?: string },
198
+ ): Record<string, TomlValue> {
199
+ const record: Record<string, TomlValue> = {};
200
+ if (rule.id) record.id = rule.id;
201
+ if (rule.path) record.path = rule.path;
202
+ if (rule.policies) record.policies = rule.policies;
203
+ if (rule.follow_symlinks !== undefined)
204
+ record.follow_symlinks = rule.follow_symlinks;
205
+ if (rule.includes) record.includes = rule.includes;
206
+ if (rule.excludes) record.excludes = rule.excludes;
207
+ return record;
208
+ }
209
+
210
+ function applyConfigPathOperations(
211
+ source: string,
212
+ operations: ConfigPathOperation[],
213
+ ): string {
214
+ let next = source;
215
+ const ids = new Set(pathTableIds(next));
216
+ for (const operation of operations) {
217
+ if (operation.op === "add") {
218
+ if (ids.has(operation.rule.id))
219
+ throw configurationError(
220
+ "configuration_path_duplicate",
221
+ `A [[paths]] rule with id ${operation.rule.id} already exists`,
222
+ );
223
+ next = addPathTable(next, pathRuleRecord(operation.rule));
224
+ ids.add(operation.rule.id);
225
+ continue;
226
+ }
227
+ if (operation.op === "remove") {
228
+ next = removePathTable(next, operation.id);
229
+ ids.delete(operation.id);
230
+ continue;
231
+ }
232
+ const record = pathRuleRecord(operation.rule);
233
+ if (operation.rule.policies)
234
+ record.policies = {
235
+ ...existingPathPolicies(next, operation.id),
236
+ ...operation.rule.policies,
237
+ };
238
+ next = updatePathTable(next, operation.id, record);
239
+ }
240
+ return next;
241
+ }
242
+
243
+ async function commitConfigEdit(
244
+ target: ConfigTarget,
245
+ filePath: string,
246
+ source: string,
247
+ changed: string[],
248
+ ) {
249
+ const current = await currentConfig();
250
+ await writeConfigSource(filePath, source);
251
+ const snapshots = await configRegistry.reload();
252
+ const snapshot =
253
+ snapshots.find(
254
+ (item) =>
255
+ item.config?.projectRoot === current.projectRoot ||
256
+ item.config?.sources.project === filePath ||
257
+ item.config?.sources.global === filePath,
258
+ ) ?? (await configRegistry.snapshot({ cwd: current.projectRoot }));
259
+ return {
260
+ changed,
261
+ filePath,
262
+ generation: snapshot.generation,
263
+ healthy: snapshot.healthy,
264
+ target,
265
+ };
266
+ }
267
+
268
+ function coreSectionChanges(patch: ConfigCorePatch): string[] {
269
+ return [
270
+ patch.workspace ? "workspace" : undefined,
271
+ patch.safety ? "safety" : undefined,
272
+ patch.files ? "files" : undefined,
273
+ patch.formatting ? "formatting" : undefined,
274
+ patch.http ? "http" : undefined,
275
+ patch.dependencies ? "dependencies" : undefined,
276
+ patch.mcp ? "mcp.configuration" : undefined,
277
+ ].filter((item): item is string => Boolean(item));
278
+ }
279
+
280
+ async function editConfigCore(target: ConfigTarget, patch: ConfigCorePatch) {
281
+ const loaded = await loadTarget(target);
282
+ const changed = coreSectionChanges(patch);
283
+ if (changed.length === 0)
284
+ throw configurationError(
285
+ "configuration_empty_patch",
286
+ "config_core requires at least one core section",
287
+ );
288
+ authorizeConfigWrite(
289
+ loaded.config,
290
+ loaded.filePath,
291
+ patch.mcp?.configuration?.enabled !== undefined ||
292
+ patch.mcp?.configuration?.require_approval !== undefined,
293
+ );
294
+ return commitConfigEdit(
295
+ target,
296
+ loaded.filePath,
297
+ applyConfigCorePatch(loaded.source, patch),
298
+ changed,
299
+ );
300
+ }
301
+
302
+ async function editConfigPaths(target: ConfigTarget, patch: ConfigPathsPatch) {
303
+ const loaded = await loadTarget(target);
304
+ authorizeConfigWrite(loaded.config, loaded.filePath, false);
305
+ return commitConfigEdit(
306
+ target,
307
+ loaded.filePath,
308
+ applyConfigPathOperations(loaded.source, patch.operations),
309
+ patch.operations.map((operation) =>
310
+ operation.op === "add"
311
+ ? `paths.add:${operation.rule.id}`
312
+ : `paths.${operation.op}:${operation.id}`,
313
+ ),
314
+ );
315
+ }
316
+
317
+ export async function applyConfigCore(patch: ConfigCorePatch) {
318
+ const target = patch.target ?? "project";
319
+ const { filePath } = await targetFilePath(target);
320
+ return withFileLocks([filePath], () => editConfigCore(target, patch));
321
+ }
322
+
323
+ export async function applyConfigPaths(patch: ConfigPathsPatch) {
324
+ const target = patch.target ?? "project";
325
+ const { filePath } = await targetFilePath(target);
326
+ return withFileLocks([filePath], () => editConfigPaths(target, patch));
327
+ }
@@ -1,9 +1,17 @@
1
- import { accessSync, constants, readFileSync } from "node:fs";
1
+ import { readFileSync } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
- import os from "node:os";
4
3
  import path from "node:path";
4
+ import {
5
+ directoryBinaryCandidates,
6
+ executableCandidate,
7
+ executableNames,
8
+ globalBinDirectories,
9
+ resolveGlobalBinaryAlias,
10
+ } from "../../templates/skills/ast-mcp/scripts/binary-resolution";
5
11
  import { currentConfig } from "../config";
6
12
 
13
+ export { globalBinDirectories, resolveGlobalBinaryAlias };
14
+
7
15
  const PACKAGE_ROOT = path.resolve(
8
16
  import.meta.dir,
9
17
  path.basename(import.meta.dir) === "dist" ? ".." : "../..",
@@ -13,32 +21,13 @@ const require = createRequire(import.meta.url);
13
21
 
14
22
  interface BinaryResolutionOptions {
15
23
  globalBinDirectories?: string[];
24
+ home?: string;
16
25
  packageBinary?: string;
17
26
  packageRoot?: string;
18
27
  pathValue?: string;
19
28
  platform?: NodeJS.Platform;
20
29
  }
21
30
 
22
- function executableNames(name: string, platform: NodeJS.Platform) {
23
- if (platform !== "win32") return [name];
24
- const extensions = (process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM")
25
- .split(";")
26
- .filter(Boolean);
27
- return [name, ...extensions.map((extension) => `${name}${extension}`)];
28
- }
29
-
30
- function isExecutable(file: string, platform: NodeJS.Platform) {
31
- try {
32
- accessSync(
33
- file,
34
- platform === "win32" ? constants.F_OK : constants.F_OK | constants.X_OK,
35
- );
36
- return true;
37
- } catch {
38
- return false;
39
- }
40
- }
41
-
42
31
  function packageBinary(packageName: string, binaryName: string) {
43
32
  try {
44
33
  const manifestPath = require.resolve(`${packageName}/package.json`);
@@ -57,51 +46,6 @@ function packageBinary(packageName: string, binaryName: string) {
57
46
  }
58
47
  }
59
48
 
60
- function commandOutput(command: string, args: string[]) {
61
- try {
62
- const result = Bun.spawnSync([command, ...args], {
63
- stderr: "ignore",
64
- stdout: "pipe",
65
- });
66
- return result.exitCode === 0 ? result.stdout.toString().trim() : "";
67
- } catch {
68
- return "";
69
- }
70
- }
71
-
72
- function globalBinDirectories(binaryName: string, platform: NodeJS.Platform) {
73
- const directories = new Set<string>();
74
- const add = (value: string | undefined) => {
75
- if (value) directories.add(path.resolve(value));
76
- };
77
- const yarnBinary = commandOutput("yarn", ["bin", binaryName]);
78
- if (yarnBinary) add(path.dirname(yarnBinary));
79
- add(process.env.BUN_INSTALL && path.join(process.env.BUN_INSTALL, "bin"));
80
- add(process.env.PNPM_HOME);
81
- add(
82
- process.env.npm_config_prefix &&
83
- (platform === "win32"
84
- ? process.env.npm_config_prefix
85
- : path.join(process.env.npm_config_prefix, "bin")),
86
- );
87
- add(path.join(os.homedir(), ".bun/bin"));
88
- add(path.join(os.homedir(), ".bun/install/global/node_modules/.bin"));
89
-
90
- add(commandOutput("bun", ["pm", "bin", "-g"]));
91
- add(commandOutput("pnpm", ["bin", "-g"]));
92
- add(commandOutput("yarn", ["global", "bin"]));
93
- const npmPrefix = commandOutput("npm", ["prefix", "-g"]);
94
- add(
95
- npmPrefix &&
96
- (platform === "win32" ? npmPrefix : path.join(npmPrefix, "bin")),
97
- );
98
- return [...directories];
99
- }
100
-
101
- function executableCandidate(candidates: string[], platform: NodeJS.Platform) {
102
- return candidates.find((candidate) => isExecutable(candidate, platform));
103
- }
104
-
105
49
  function ancestorBinaryCandidates(packageRoot: string, names: string[]) {
106
50
  const candidates: string[] = [];
107
51
  for (
@@ -115,15 +59,6 @@ function ancestorBinaryCandidates(packageRoot: string, names: string[]) {
115
59
  return candidates;
116
60
  }
117
61
 
118
- function directoryBinaryCandidates(directories: string[], names: string[]) {
119
- const candidates: string[] = [];
120
- for (const directory of directories) {
121
- if (!directory) continue;
122
- for (const name of names) candidates.push(path.join(directory, name));
123
- }
124
- return candidates;
125
- }
126
-
127
62
  export function resolveDependencyBinary(
128
63
  binaryName: string,
129
64
  packageName = binaryName,
@@ -139,7 +74,8 @@ export function resolveDependencyBinary(
139
74
  const local = executableCandidate(localCandidates, platform);
140
75
  if (local) return local;
141
76
  const globalDirectories =
142
- options.globalBinDirectories ?? globalBinDirectories(binaryName, platform);
77
+ options.globalBinDirectories ??
78
+ globalBinDirectories(binaryName, platform, options.home);
143
79
  const global = executableCandidate(
144
80
  directoryBinaryCandidates(globalDirectories, names),
145
81
  platform,
@@ -154,7 +90,7 @@ export function resolveDependencyBinary(
154
90
  );
155
91
  }
156
92
 
157
- export const AST_BRO_VERSION = "3.0.0";
93
+ export const AST_BRO_VERSION = "4.2.0";
158
94
  export const AST_BRO_BINARY =
159
95
  process.env.AST_BRO_BINARY ??
160
96
  resolveDependencyBinary("ast-bro", "@ast-bro/cli") ??
@@ -0,0 +1,78 @@
1
+ import path from "node:path";
2
+
3
+ export const DOCUMENT_RESULT_MAX_BYTES = 256 * 1024;
4
+
5
+ export interface DocumentSelection {
6
+ selector: string;
7
+ value: unknown;
8
+ }
9
+
10
+ export function parseStructuredDocument(
11
+ filePath: string,
12
+ source: string,
13
+ ): unknown {
14
+ switch (path.extname(filePath).toLowerCase()) {
15
+ case ".json":
16
+ return JSON.parse(source);
17
+ case ".jsonc":
18
+ return Bun.JSONC.parse(source);
19
+ case ".toml":
20
+ return Bun.TOML.parse(source);
21
+ case ".yaml":
22
+ case ".yml":
23
+ return Bun.YAML.parse(source);
24
+ default:
25
+ throw Object.assign(
26
+ new Error(
27
+ "Structured document inspection supports JSON, JSONC, TOML, and YAML files",
28
+ ),
29
+ { code: "document_format_unsupported", retryable: false },
30
+ );
31
+ }
32
+ }
33
+
34
+ export function selectDocumentValue(
35
+ document: unknown,
36
+ selector: string,
37
+ ): unknown {
38
+ if (selector === "") return document;
39
+ if (!selector.startsWith("/"))
40
+ throw Object.assign(new Error(`Invalid RFC 6901 selector: ${selector}`), {
41
+ code: "invalid_document_selector",
42
+ retryable: true,
43
+ });
44
+ return selector
45
+ .slice(1)
46
+ .split("/")
47
+ .map((token) => token.replaceAll("~1", "/").replaceAll("~0", "~"))
48
+ .reduce<unknown>((value, token) => {
49
+ if (Array.isArray(value)) return value[Number(token)];
50
+ if (value && typeof value === "object")
51
+ return (value as Record<string, unknown>)[token];
52
+ return undefined;
53
+ }, document);
54
+ }
55
+
56
+ export function selectDocumentValues(
57
+ filePath: string,
58
+ source: string,
59
+ selectors: string[],
60
+ ): DocumentSelection[] {
61
+ const document = parseStructuredDocument(filePath, source);
62
+ const values = selectors.map((selector) => ({
63
+ selector,
64
+ value: selectDocumentValue(document, selector),
65
+ }));
66
+ if (Buffer.byteLength(JSON.stringify(values)) > DOCUMENT_RESULT_MAX_BYTES)
67
+ throw Object.assign(
68
+ new Error(
69
+ "Structured document result exceeds the 256 KiB limit; use narrower selectors or text mode",
70
+ ),
71
+ {
72
+ code: "document_result_too_large",
73
+ retryable: true,
74
+ suggestedNextCall: "file_read",
75
+ },
76
+ );
77
+ return values;
78
+ }