@mwillbanks/ast-mcp 0.2.1 → 0.2.2

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.
@@ -1,3 +1,4 @@
1
+ import os from "node:os";
1
2
  import path from "node:path";
2
3
  import { embeddedShellMutates, shellMutates } from "./shell-policy";
3
4
  import { advanceQuote } from "./source";
@@ -114,20 +115,33 @@ function hasBoolean(input: string, key: string, value: boolean) {
114
115
 
115
116
  type InputValidator = (input: string) => boolean;
116
117
 
117
- const hasKeyedPath = (input: string) => /["'][^"']+["']\s*:/.test(input);
118
+ const fileEntryKeyPattern =
119
+ "(?:aiderBlocks|astRules|chattr|content|destination|expectedSha256|forceReferences|patchStrategy|preview)";
120
+ const declaredFileBatchExpression = new RegExp(
121
+ `^\\s*(?:(?:await\\s+)?tools\\.mcp__ast_mcp__file_(?:chattr|delete|patch|rename|write)\\s*\\(\\s*)?\\{\\s*["']?files["']?\\s*:\\s*\\{\\s*["']([^"']+)["']\\s*:\\s*\\{\\s*["']?${fileEntryKeyPattern}["']?\\s*:`,
122
+ "s",
123
+ );
124
+
125
+ const hasDeclaredFileBatch = (input: string) => {
126
+ declaredFileBatchExpression.lastIndex = 0;
127
+ return declaredFileBatchExpression.test(withoutComments(input));
128
+ };
118
129
  const inputValidators: Record<string, InputValidator> = {
119
- file_chattr: (input) => hasKey(input, "chattr") && hasKeyedPath(input),
130
+ file_chattr: (input) =>
131
+ hasKey(input, "chattr") && hasDeclaredFileBatch(input),
120
132
  file_delete: (input) =>
121
- hasKey(input, "expectedSha256") && hasKeyedPath(input),
133
+ hasKey(input, "expectedSha256") && hasDeclaredFileBatch(input),
122
134
  file_patch: (input) =>
123
135
  hasKey(input, "expectedSha256") &&
124
136
  hasKey(input, "patchStrategy") &&
137
+ hasDeclaredFileBatch(input) &&
125
138
  (hasKey(input, "astRules") || hasKey(input, "aiderBlocks")),
126
139
  file_rename: (input) =>
127
140
  hasKey(input, "expectedSha256") &&
128
141
  hasKey(input, "destination") &&
129
- hasKeyedPath(input),
130
- file_write: (input) => hasKey(input, "content") && hasKeyedPath(input),
142
+ hasDeclaredFileBatch(input),
143
+ file_write: (input) =>
144
+ hasKey(input, "content") && hasDeclaredFileBatch(input),
131
145
  };
132
146
 
133
147
  function meaningfulInput(invocation: Invocation) {
@@ -154,8 +168,10 @@ const singlePathExpression =
154
168
  /["']?(?:filePath|file|path|root|destination)["']?\s*:\s*["']([^"']+)["']/g;
155
169
  const pathArrayExpression =
156
170
  /["']?(?:filePaths|paths)["']?\s*:\s*\[([^\]]*)\]/gs;
157
- const keyedPathExpression =
158
- /["']([^"']+)["']\s*:\s*\{\s*(?:content|expectedSha256|destination|chattr|astRules|aiderBlocks|patchStrategy)\s*:/g;
171
+ const keyedPathExpression = new RegExp(
172
+ `["']([^"']+)["']\\s*:\\s*\\{\\s*["']?${fileEntryKeyPattern}["']?\\s*:`,
173
+ "g",
174
+ );
159
175
 
160
176
  function expressionValues(input: string, expression: RegExp) {
161
177
  expression.lastIndex = 0;
@@ -184,18 +200,80 @@ function escapedPath(candidate: string, roots: string[]) {
184
200
  return pathLike && !pathIsWithinRoot(candidate, roots);
185
201
  }
186
202
 
187
- function pathErrors(invocations: Invocation[], roots: string[]) {
188
- const errors: string[] = [];
189
- for (const invocation of invocations) {
190
- const candidates = pathCandidates(withoutComments(invocation.input));
191
- for (const candidate of candidates) {
192
- if (escapedPath(candidate, roots))
193
- errors.push(
194
- `${invocation.tool} input escapes transcript workspace roots: ${candidate}`,
195
- );
196
- }
197
- }
198
- return errors;
203
+ const fileOperationTools = new Set([
204
+ "file_chattr",
205
+ "file_delete",
206
+ "file_hash",
207
+ "file_patch",
208
+ "file_read",
209
+ "file_rename",
210
+ "file_write",
211
+ ]);
212
+
213
+ export interface FileOperationPolicy {
214
+ allowAnyPath?: boolean;
215
+ allowTempDirectory?: boolean;
216
+ roots?: string[];
217
+ }
218
+
219
+ interface InvocationPathPolicy {
220
+ allowAnyPath: boolean;
221
+ boundary: string;
222
+ roots: string[];
223
+ }
224
+
225
+ function effectiveFileOperationRoots(
226
+ workspaceRoots: string[],
227
+ policy: FileOperationPolicy,
228
+ ) {
229
+ if (policy.roots) return policy.roots;
230
+ return policy.allowTempDirectory === false
231
+ ? workspaceRoots
232
+ : [...workspaceRoots, os.tmpdir()];
233
+ }
234
+
235
+ function invocationPathPolicy(
236
+ invocation: Invocation,
237
+ workspaceRoots: string[],
238
+ fileOperationPolicy: FileOperationPolicy,
239
+ ): InvocationPathPolicy {
240
+ if (!fileOperationTools.has(invocation.tool))
241
+ return {
242
+ allowAnyPath: false,
243
+ boundary: "transcript workspace roots",
244
+ roots: workspaceRoots,
245
+ };
246
+ return {
247
+ allowAnyPath: fileOperationPolicy.allowAnyPath === true,
248
+ boundary: "transcript file-operation roots",
249
+ roots: effectiveFileOperationRoots(workspaceRoots, fileOperationPolicy),
250
+ };
251
+ }
252
+
253
+ function invocationPathErrors(
254
+ invocation: Invocation,
255
+ policy: InvocationPathPolicy,
256
+ ) {
257
+ if (policy.allowAnyPath) return [];
258
+ return pathCandidates(withoutComments(invocation.input))
259
+ .filter((candidate) => escapedPath(candidate, policy.roots))
260
+ .map(
261
+ (candidate) =>
262
+ `${invocation.tool} input escapes ${policy.boundary}: ${candidate}`,
263
+ );
264
+ }
265
+
266
+ function pathErrors(
267
+ invocations: Invocation[],
268
+ workspaceRoots: string[],
269
+ fileOperationPolicy: FileOperationPolicy,
270
+ ) {
271
+ return invocations.flatMap((invocation) =>
272
+ invocationPathErrors(
273
+ invocation,
274
+ invocationPathPolicy(invocation, workspaceRoots, fileOperationPolicy),
275
+ ),
276
+ );
199
277
  }
200
278
 
201
279
  function isBatch(invocation: Invocation) {
@@ -208,8 +286,10 @@ function isBatch(invocation: Invocation) {
208
286
  "file_delete",
209
287
  "file_rename",
210
288
  ].includes(invocation.tool)
211
- )
212
- return (input.match(/["'][^"']+["']\s*:\s*\{/g) ?? []).length > 1;
289
+ ) {
290
+ keyedPathExpression.lastIndex = 0;
291
+ return expressionValues(input, keyedPathExpression).length > 1;
292
+ }
213
293
  if (invocation.tool === "file_hash")
214
294
  return /filePaths\s*:\s*\[[^\]]+,[^\]]+\]/s.test(input);
215
295
  if (invocation.tool === "file_read")
@@ -247,11 +327,13 @@ function renameResultsCoverInputs(
247
327
  roots: string[] = [],
248
328
  ) {
249
329
  try {
250
- const request = JSON.parse(call.input) as Record<string, unknown>;
330
+ const request = JSON.parse(call.input) as {
331
+ files?: Record<string, unknown>;
332
+ };
251
333
  const result = JSON.parse(output) as { files?: RenameFiles };
252
- if (!result.files) return false;
334
+ if (!request.files || !result.files) return false;
253
335
  const workspaceRoot = roots[0] ?? process.cwd();
254
- return Object.entries(request).every((entry) =>
336
+ return Object.entries(request.files).every((entry) =>
255
337
  renameEntryMatches(result.files as RenameFiles, workspaceRoot, entry),
256
338
  );
257
339
  } catch {
@@ -393,23 +475,52 @@ function hashPrecedesMutation(context: AssertionContext) {
393
475
  );
394
476
  }
395
477
 
396
- function workflowAssertion(context: AssertionContext): boolean | undefined {
478
+ function declaredFileBatchAssertion(
479
+ context: AssertionContext,
480
+ ): boolean | undefined {
397
481
  const { invocations, normalized } = context;
482
+ if (!normalized.includes("declared") || !normalized.includes("files"))
483
+ return undefined;
484
+ const requireBatch = normalized.includes("batch");
485
+ return invocations.some(
486
+ (invocation) =>
487
+ [
488
+ "file_patch",
489
+ "file_write",
490
+ "file_chattr",
491
+ "file_delete",
492
+ "file_rename",
493
+ ].includes(invocation.tool) &&
494
+ hasDeclaredFileBatch(invocation.input) &&
495
+ (!requireBatch || isBatch(invocation)),
496
+ );
497
+ }
498
+
499
+ function previewAssertion(context: AssertionContext): boolean | undefined {
398
500
  const patchCalls = calls(context, "file_patch");
501
+ if (context.normalized.includes("preview true"))
502
+ return patchCalls.some((call) => hasBoolean(call.input, "preview", true));
503
+ if (
504
+ !context.normalized.includes("preview") &&
505
+ !context.normalized.includes("dry run")
506
+ )
507
+ return undefined;
508
+ return (
509
+ calls(context, "run").some(
510
+ (call) => !hasBoolean(call.input, "write", true),
511
+ ) || patchCalls.some((call) => hasBoolean(call.input, "preview", true))
512
+ );
513
+ }
514
+
515
+ function workflowAssertion(context: AssertionContext): boolean | undefined {
516
+ const declaredBatch = declaredFileBatchAssertion(context);
517
+ if (declaredBatch !== undefined) return declaredBatch;
518
+ const { invocations, normalized } = context;
399
519
  if (normalized.includes("batch") || normalized.includes("one keyed"))
400
520
  return invocations.some(isBatch);
401
521
  if (normalized.includes("fresh") && normalized.includes("hash"))
402
522
  return hashPrecedesMutation(context);
403
- if (normalized.includes("preview true"))
404
- return patchCalls.some((call) => hasBoolean(call.input, "preview", true));
405
- if (normalized.includes("preview") || normalized.includes("dry run")) {
406
- return (
407
- calls(context, "run").some(
408
- (call) => !hasBoolean(call.input, "write", true),
409
- ) || patchCalls.some((call) => hasBoolean(call.input, "preview", true))
410
- );
411
- }
412
- return undefined;
523
+ return previewAssertion(context);
413
524
  }
414
525
 
415
526
  function strategyAssertion(context: AssertionContext): boolean | undefined {
@@ -561,11 +672,12 @@ export function verifyEvaluation(
561
672
  invocations: Invocation[],
562
673
  output: string,
563
674
  roots: string[],
675
+ fileOperationPolicy: FileOperationPolicy = {},
564
676
  ) {
565
677
  const errors = [
566
678
  ...toolContractErrors(evaluation, invocations),
567
679
  ...sequenceErrors(evaluation, invocations),
568
- ...pathErrors(invocations, roots),
680
+ ...pathErrors(invocations, roots, fileOperationPolicy),
569
681
  ...fileEvidenceErrors(evaluation, invocations, output),
570
682
  ];
571
683
  if (
@@ -56,6 +56,6 @@ The pinned `@ast-bro/cli@3.0.0` package has a precompiled binary only for macOS
56
56
  2. Restart or reconnect MCP servers in the host; a skill file alone cannot make MCP tools callable. A supervised ast-mcp process may receive `SIGHUP`, which performs graceful cleanup and exits 0 so the host can restart it from refreshed code and configuration.
57
57
  3. Confirm `file_hash`, `file_read`, `file_write`, and `file_patch` are present.
58
58
  4. Confirm direct intelligence tools such as `digest`, `map`, `show`, `context`, and `impact` are present; there is no proxy tool.
59
- 5. Verify that `file_read` accepts batched `files`, `file_hash` accepts batched `filePaths`, and `file_write`/`file_patch` accept path-keyed batches with ordered per-file operations; the legacy whole-file `file_read({ filePath })` schema is stale.
59
+ 5. Verify that `file_read` accepts batched `files`, `file_hash` accepts batched `filePaths`, and every mutation tool accepts a declared `files` object containing path-keyed per-file operations; dictionary-only top-level mutation schemas and the legacy whole-file `file_read({ filePath })` schema are stale.
60
60
  6. Rerun `check-install.ts` if the tool list remains incomplete.
61
61
  7. If configuration is correct but startup fails, run the package's `bun run tools:check` from its checkout and report the missing dependency or startup error. Do not bypass the write boundary.
@@ -6,9 +6,9 @@ The server distinguishes AST inspection from structural rewrite support. AST-cap
6
6
 
7
7
  1. Inspect AST-capable content with intelligence tools. Inspect unsupported content with batched, bounded `file_read` slices.
8
8
  2. Preview every ordered structural rule with ast-bro `run`; for the full guarded and formatted dry run, use the same keyed `file_patch` entry with `preview: true`, then obtain one fresh `file_hash` per keyed path immediately before mutation.
9
- 3. Use one path-keyed `file_patch` object for one or more files. Each value has one `patchStrategy`, ordered `astRules` or `aiderBlocks` arrays, optional `preview`, and normally one fresh `expectedSha256`.
10
- 4. Use one path-keyed `file_write` object for new files or existing non-structurally-rewritable files; existing replacements normally receive their own fresh `expectedSha256`. Use the shared `chattr` object for chmod/chown metadata. Missing parents are created only after a guarded write returns `ENOENT`, followed by path revalidation.
11
- 5. Use `file_rename` with a fresh byte hash for root-bounded moves; preflight every source and destination, reject duplicate destinations, lock all endpoints, use no-replace moves, and roll back prior moves when a later move fails. The contract is recoverable on ordinary failures, not crash-atomic. Use `file_chattr` for metadata-only changes. Use `file_delete` with a fresh hash for deletion; it preflights all targets and AST import references before any deletion, rejects referenced source unless `forceReferences` is explicit, then removes empty ancestor directories after releasing locks. `safety.require_hash = false` makes hashes optional for patch, existing write, rename, and delete, but any supplied hash remains enforced.
9
+ 3. Use one `file_patch({ files: { ... } })` object for one or more files. The declared `files` property contains path keys; each value has one `patchStrategy`, ordered `astRules` or `aiderBlocks` arrays, optional `preview`, and normally one fresh `expectedSha256`.
10
+ 4. Use one `file_write({ files: { ... } })` object for new files or existing non-structurally-rewritable files; existing replacements normally receive their own fresh `expectedSha256`. Use the shared `chattr` object for chmod/chown metadata. Missing parents are created only after a guarded write returns `ENOENT`, followed by path revalidation.
11
+ 5. Use `file_rename({ files: { ... } })` with a fresh byte hash for file-operation-root-bounded moves; preflight every source and destination, reject duplicate destinations, lock all endpoints, use no-replace moves, and roll back prior moves when a later move fails. The contract is recoverable on ordinary failures, not crash-atomic. Use `file_chattr` for metadata-only changes. Use `file_delete` with a fresh hash for deletion; it preflights all targets and AST import references before any deletion, rejects referenced source unless `forceReferences` is explicit, then removes empty ancestor directories after releasing locks. `safety.require_hash = false` makes hashes optional for patch, existing write, rename, and delete, but any supplied hash remains enforced.
12
12
  6. Operations for one path are serialized under one lock and one atomic commit. A preview returns a bounded diff and leaves that path unchanged; a failed rule also leaves it unchanged.
13
13
  7. Use direct `run` with `rewrite` and `write: true` only for an intentionally bounded lower-level rewrite; normal agent mutations belong to `file_patch`.
14
14
  8. New files use `file_write`.
@@ -36,4 +36,4 @@ The native TypeScript matcher attempts exact, whitespace-normalized, relative-in
36
36
  - `first match per file`: reduce file_patch to one match or use a bounded direct run across files.
37
37
  - capped preview or read: narrow paths, glob, pattern, line ranges, or byte caps.
38
38
  - formatter preflight failure: the selected external formatter or dprint fallback does not support the target; no write occurs. Formatting is skipped only when `[formatting].enabled = false`.
39
- - path or symlink rejection: use a real path under an effective workspace root. Final symlinks are followed only when `safety.follow_symlinks = true`, and their resolved targets must remain root-bounded.
39
+ - path or symlink rejection: use a real path under an effective workspace root or the OS temporary directory. Set `safety.allow_temp_directory = false` to remove the default temporary-directory allowance. `safety.allow_any_path = true` explicitly disables path protection for file tools. Final symlinks are followed only when `safety.follow_symlinks = true`, and their resolved targets must remain inside an allowed file-operation root unless unrestricted mode is enabled.
@@ -6,13 +6,13 @@ All tools are exposed directly by ast-mcp. Do not wrap ast-bro calls in a proxy
6
6
 
7
7
  - `file_hash({ filePaths })`: batch up to 50 AST or non-AST paths and stream each whole file into SHA-256 without returning source content.
8
8
  - `file_read({ files })`: batch up to 50 non-AST files. Each request accepts a zero-based, end-exclusive `lines` tuple and `maxBytes`; defaults are `[0, 100]` and 1 MiB, with hard caps of 1,000 lines and 1 MiB per slice. AST-capable files are rejected and routed to intelligence tools.
9
- - `file_chattr({ "/repo/a.txt": { chattr, expectedSha256? } })`: applies the shared `chattr` contract (`chmod?`, same-owner `chown?`) under deterministic locks and reports the effective attributes.
10
- - `file_write({ "/repo/a.txt": { content, chattr? }, "/repo/b.txt": { content, expectedSha256?, chattr? } })`: create or replace multiple files in one keyed batch; existing replacements remain limited to non-AST-rewritable files. Missing parents are created only after the write attempt returns `ENOENT`, then the path is revalidated.
11
- - `file_patch({ "/repo/src/a.ts": { expectedSha256?, patchStrategy: "ast", astRules: [...], chattr? } })`: patch one or more files in one keyed batch. Use ordered `astRules` or `aiderBlocks`; every path has one atomic commit.
12
- - `file_rename({ "/repo/a.txt": { destination, expectedSha256? } })`: renames multiple regular files in one root-bounded batch, locks every source and destination, rejects cross-root and duplicate/existing destinations, uses no-replace moves, rolls back prior moves when a later move fails, and reports a per-file result. Crash-atomic recovery is not guaranteed.
13
- - `file_delete({ "/repo/a.txt": { expectedSha256?, forceReferences? } })`: preflights all targets and AST import references before any deletion, rejects referenced source unless explicitly overridden, and removes empty ancestor directories within the configured root.
9
+ - `file_chattr({ files: { "/repo/a.txt": { chattr, expectedSha256? } } })`: applies the shared `chattr` contract (`chmod?`, same-owner `chown?`) under deterministic locks and reports the effective attributes.
10
+ - `file_write({ files: { "/repo/a.txt": { content, chattr? }, "/repo/b.txt": { content, expectedSha256?, chattr? } } })`: create or replace multiple files in one declared batch; existing replacements remain limited to non-AST-rewritable files. Missing parents are created only after the write attempt returns `ENOENT`, then the path is revalidated.
11
+ - `file_patch({ files: { "/repo/src/a.ts": { expectedSha256?, patchStrategy: "ast", astRules: [...], chattr? } } })`: patch one or more files in one declared batch. Use ordered `astRules` or `aiderBlocks`; every path has one atomic commit.
12
+ - `file_rename({ files: { "/repo/a.txt": { destination, expectedSha256? } } })`: renames multiple regular files in one file-operation-root-bounded batch, locks every source and destination, rejects cross-root and duplicate/existing destinations, uses no-replace moves, rolls back prior moves when a later move fails, and reports a per-file result. Crash-atomic recovery is not guaranteed.
13
+ - `file_delete({ files: { "/repo/a.txt": { expectedSha256?, forceReferences? } } })`: preflights all targets and AST import references before any deletion, rejects referenced source unless explicitly overridden, and removes empty ancestor directories within the allowed operation root.
14
14
  - `expectedSha256` is required by the secure default for patch, existing-file write, rename, and delete. `safety.require_hash = false` makes it optional; supplied hashes are always verified.
15
- - The keyed mutation tools return a `files` result map. MCP transport also accepts JSON-RPC request/notification arrays and returns one response per request ID.
15
+ - Mutation tools use a declared `files` input object and return a `files` result map. The OS temporary directory is allowed by default; configure `safety.allow_temp_directory = false` to disable it or `safety.allow_any_path = true` for explicit unrestricted file access. MCP transport also accepts JSON-RPC request/notification arrays and returns one response per request ID.
16
16
 
17
17
  ## Shape and source
18
18