@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,250 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, readFile, unlink, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { astErrorCount } from "../ast-bro/capability";
5
+ import { currentConfig, type ResolvedConfig } from "../config";
6
+ import { detectAstLanguage } from "../patch/languages";
7
+ import { parseStructuredDocument } from "./document-inspection";
8
+ import { resolveWritablePath } from "./paths";
9
+
10
+ export type FileReadMode = "auto" | "ast" | "text";
11
+ export type PatchStrategyName = "ast" | "aider_block";
12
+ export type AiderMatcher =
13
+ | "exact"
14
+ | "whitespace"
15
+ | "relative-indentation"
16
+ | "diff-match-patch";
17
+ export type FileKind = "source" | "document" | "text" | "binary";
18
+ export type ParseStatus = "parseable" | "invalid" | "unsupported";
19
+
20
+ export interface FileCapabilities {
21
+ effective: {
22
+ aiderMatchers: AiderMatcher[];
23
+ patch: PatchStrategyName[];
24
+ read: Array<Exclude<FileReadMode, "auto">>;
25
+ };
26
+ filePath: string;
27
+ generation: number;
28
+ intrinsic: {
29
+ patch: PatchStrategyName[];
30
+ read: Array<Exclude<FileReadMode, "auto">>;
31
+ search: Array<"ast">;
32
+ };
33
+ kind: FileKind;
34
+ language?: string;
35
+ parseErrorCount?: number;
36
+ parseStatus: ParseStatus;
37
+ size: number;
38
+ }
39
+
40
+ const documentExtensions = new Set([
41
+ ".json",
42
+ ".jsonc",
43
+ ".toml",
44
+ ".yaml",
45
+ ".yml",
46
+ ]);
47
+ const astPatchDocumentExtensions = new Set([".json", ".yaml", ".yml"]);
48
+
49
+ function configuredMethods(config: ResolvedConfig) {
50
+ return {
51
+ aiderMatchers: config.files.patch.aiderMatchers,
52
+ patch: config.files.patch.strategies,
53
+ read: config.files.read.modes,
54
+ };
55
+ }
56
+
57
+ function intersection<T extends string>(left: T[], right: T[]): T[] {
58
+ const permitted = new Set(right);
59
+ return left.filter((value) => permitted.has(value));
60
+ }
61
+
62
+ async function binaryFile(filePath: string, size: number): Promise<boolean> {
63
+ const bytes = Buffer.from(
64
+ await Bun.file(filePath).slice(0, Math.min(size, 8192)).arrayBuffer(),
65
+ );
66
+ return bytes.includes(0);
67
+ }
68
+
69
+ async function parseState(filePath: string, language: string | undefined) {
70
+ const extension = path.extname(filePath).toLowerCase();
71
+ if (documentExtensions.has(extension)) {
72
+ try {
73
+ parseStructuredDocument(filePath, await readFile(filePath, "utf8"));
74
+ return { errorCount: 0, status: "parseable" as const };
75
+ } catch {
76
+ return { errorCount: 1, status: "invalid" as const };
77
+ }
78
+ }
79
+ if (!language)
80
+ return { errorCount: undefined, status: "unsupported" as const };
81
+ const errorCount = await astErrorCount(filePath, language);
82
+ return errorCount === undefined
83
+ ? { errorCount, status: "unsupported" as const }
84
+ : errorCount === 0
85
+ ? { errorCount, status: "parseable" as const }
86
+ : { errorCount, status: "invalid" as const };
87
+ }
88
+
89
+ async function capabilityParseState(
90
+ isBinary: boolean,
91
+ filePath: string,
92
+ language: string | undefined,
93
+ ) {
94
+ if (isBinary)
95
+ return { errorCount: undefined, status: "unsupported" as const };
96
+ return parseState(filePath, language);
97
+ }
98
+
99
+ function supportsAstRead(
100
+ isBinary: boolean,
101
+ isDocument: boolean,
102
+ language: string | undefined,
103
+ parseStatus: ParseStatus,
104
+ ): boolean {
105
+ if (isBinary || parseStatus !== "parseable") return false;
106
+ return isDocument || Boolean(language);
107
+ }
108
+
109
+ function supportsAstPatch(
110
+ astRead: boolean,
111
+ isDocument: boolean,
112
+ extension: string,
113
+ language: string | undefined,
114
+ ): boolean {
115
+ if (!astRead || language === "markdown") return false;
116
+ return !isDocument || astPatchDocumentExtensions.has(extension);
117
+ }
118
+
119
+ function intrinsicMethods(
120
+ isBinary: boolean,
121
+ isDocument: boolean,
122
+ extension: string,
123
+ language: string | undefined,
124
+ parseStatus: ParseStatus,
125
+ ) {
126
+ const read: Array<"ast" | "text"> = [];
127
+ const patch: PatchStrategyName[] = [];
128
+ const astRead = supportsAstRead(isBinary, isDocument, language, parseStatus);
129
+ const astPatch = supportsAstPatch(astRead, isDocument, extension, language);
130
+ if (astRead) read.push("ast");
131
+ if (!isBinary) read.push("text");
132
+ if (astPatch) patch.push("ast");
133
+ if (!isBinary) patch.push("aider_block");
134
+ return { astRead, patch, read };
135
+ }
136
+
137
+ function classifyFile(
138
+ isBinary: boolean,
139
+ isDocument: boolean,
140
+ language: string | undefined,
141
+ ): FileKind {
142
+ if (isBinary) return "binary";
143
+ if (isDocument) return "document";
144
+ if (language) return "source";
145
+ return "text";
146
+ }
147
+
148
+ export async function inspectFileCapabilities(
149
+ filePath: string,
150
+ languageOverride?: string,
151
+ ): Promise<FileCapabilities> {
152
+ const metadata = await lstat(filePath);
153
+ if (!metadata.isFile()) throw new Error(`Not a regular file: ${filePath}`);
154
+ const config = await currentConfig();
155
+ const configured = configuredMethods(config);
156
+ const language = languageOverride ?? detectAstLanguage(filePath);
157
+ const extension = path.extname(filePath).toLowerCase();
158
+ const isBinary = await binaryFile(filePath, metadata.size);
159
+ const state = await capabilityParseState(isBinary, filePath, language);
160
+ const isDocument = documentExtensions.has(extension);
161
+ const intrinsic = intrinsicMethods(
162
+ isBinary,
163
+ isDocument,
164
+ extension,
165
+ language,
166
+ state.status,
167
+ );
168
+ return {
169
+ effective: {
170
+ aiderMatchers: configured.aiderMatchers,
171
+ patch: intersection(intrinsic.patch, configured.patch),
172
+ read: intersection(intrinsic.read, configured.read),
173
+ },
174
+ filePath,
175
+ generation: config.generation,
176
+ intrinsic: {
177
+ patch: intrinsic.patch,
178
+ read: intrinsic.read,
179
+ search: intrinsic.astRead ? ["ast"] : [],
180
+ },
181
+ kind: classifyFile(isBinary, isDocument, language),
182
+ language,
183
+ parseErrorCount: state.errorCount,
184
+ parseStatus: state.status,
185
+ size: metadata.size,
186
+ };
187
+ }
188
+
189
+ export async function inspectFileCapabilitiesSafely(filePaths: string[]) {
190
+ return Promise.all(
191
+ filePaths.map(async (filePath) =>
192
+ inspectFileCapabilities(await resolveWritablePath(filePath, "read")),
193
+ ),
194
+ );
195
+ }
196
+
197
+ function candidatePath(filePath: string): string {
198
+ const extension = path.extname(filePath);
199
+ const stem = extension ? filePath.slice(0, -extension.length) : filePath;
200
+ return `${stem}.ast-mcp-validate-${process.pid}-${randomUUID()}${extension}`;
201
+ }
202
+
203
+ export async function validateStructuredCandidate(
204
+ capabilities: FileCapabilities,
205
+ candidate: string,
206
+ ): Promise<void> {
207
+ if (capabilities.kind === "document") {
208
+ try {
209
+ parseStructuredDocument(capabilities.filePath, candidate);
210
+ return;
211
+ } catch (error) {
212
+ throw Object.assign(
213
+ new Error(
214
+ `Patch candidate is not valid ${capabilities.language ?? "structured data"}: ${error instanceof Error ? error.message : String(error)}`,
215
+ ),
216
+ { code: "candidate_parse_error", retryable: true },
217
+ );
218
+ }
219
+ }
220
+ if (!capabilities.language || capabilities.kind !== "source") return;
221
+ if (capabilities.parseErrorCount === undefined) return;
222
+ const temporary = candidatePath(capabilities.filePath);
223
+ try {
224
+ await writeFile(temporary, candidate, { encoding: "utf8", flag: "wx" });
225
+ const candidateErrors = await astErrorCount(
226
+ temporary,
227
+ capabilities.language,
228
+ );
229
+ if (
230
+ candidateErrors === undefined ||
231
+ (capabilities.parseErrorCount !== undefined &&
232
+ candidateErrors > capabilities.parseErrorCount)
233
+ )
234
+ throw Object.assign(
235
+ new Error("Patch candidate increases structural parse errors"),
236
+ {
237
+ code: "candidate_parse_error",
238
+ details: {
239
+ before: capabilities.parseErrorCount,
240
+ candidate: candidateErrors,
241
+ },
242
+ retryable: true,
243
+ },
244
+ );
245
+ } finally {
246
+ try {
247
+ await unlink(temporary);
248
+ } catch {}
249
+ }
250
+ }
@@ -3,11 +3,13 @@ import path from "node:path";
3
3
  import { astCapable } from "../ast-bro/capability";
4
4
  import { callAstBro } from "../ast-bro/client";
5
5
  import { parseAstBroJson } from "../ast-bro/result";
6
+ import { currentConfig } from "../config";
6
7
  import { detectAstLanguage } from "../patch/languages";
7
8
  import { sha256File } from "./hash";
8
9
  import { withFileLocks } from "./locks";
10
+ import { assertReadableTree } from "./path-policy";
9
11
  import {
10
- configuredRootForPath,
12
+ referenceRootForPath,
11
13
  resolveWritablePath,
12
14
  rootForPath,
13
15
  } from "./paths";
@@ -35,8 +37,8 @@ async function importersFor(filePath: string, root: string): Promise<string[]> {
35
37
  .filter((file: unknown): file is string => typeof file === "string");
36
38
  }
37
39
 
38
- async function emptyParents(filePath: string, root: string) {
39
- const removedDirectories: string[] = [];
40
+ function ancestorPaths(filePath: string, root: string): string[] {
41
+ const ancestors: string[] = [];
40
42
  let directory = path.dirname(filePath);
41
43
  while (true) {
42
44
  const relative = path.relative(root, directory);
@@ -46,6 +48,31 @@ async function emptyParents(filePath: string, root: string) {
46
48
  path.isAbsolute(relative)
47
49
  )
48
50
  break;
51
+ ancestors.push(directory);
52
+ directory = path.dirname(directory);
53
+ }
54
+ return ancestors;
55
+ }
56
+
57
+ async function authorizedAncestors(filePath: string, root: string) {
58
+ return new Set(
59
+ await Promise.all(
60
+ ancestorPaths(filePath, root).map((directory) =>
61
+ resolveWritablePath(directory, "delete"),
62
+ ),
63
+ ),
64
+ );
65
+ }
66
+
67
+ async function emptyParents(
68
+ filePath: string,
69
+ root: string,
70
+ authorized: Set<string>,
71
+ ) {
72
+ const removedDirectories: string[] = [];
73
+ for (const directory of ancestorPaths(filePath, root)) {
74
+ if (!authorized.has(directory))
75
+ throw new Error(`Directory deletion was not preflighted: ${directory}`);
49
76
  const contents = await readdir(directory).catch(
50
77
  (error: NodeJS.ErrnoException) => {
51
78
  if (error.code === "ENOENT") return undefined;
@@ -55,44 +82,86 @@ async function emptyParents(filePath: string, root: string) {
55
82
  if (contents?.length !== 0) break;
56
83
  await rmdir(directory);
57
84
  removedDirectories.push(directory);
58
- directory = path.dirname(directory);
59
85
  }
60
86
  return removedDirectories;
61
87
  }
62
88
 
89
+ function requireVerifiableReferences(
90
+ referenceRoot: string | undefined,
91
+ capable: boolean,
92
+ inputPath: string,
93
+ forceReferences: boolean | undefined,
94
+ ): void {
95
+ if (referenceRoot || !capable || forceReferences) return;
96
+ throw new Error(
97
+ `file_delete rejected ${inputPath}: references cannot be verified outside configured file-operation roots; set forceReferences to override`,
98
+ );
99
+ }
100
+
101
+ async function authorizedImporters(
102
+ filePath: string,
103
+ referenceRoot: string | undefined,
104
+ capable: boolean,
105
+ ) {
106
+ if (!referenceRoot || !capable) return [];
107
+ assertReadableTree(await currentConfig(), referenceRoot);
108
+ return importersFor(filePath, referenceRoot);
109
+ }
110
+
111
+ function requireUnreferenced(
112
+ importers: string[],
113
+ inputPath: string,
114
+ forceReferences: boolean | undefined,
115
+ ): void {
116
+ if (importers.length === 0 || forceReferences) return;
117
+ throw new Error(
118
+ `file_delete rejected ${inputPath}: referenced by ${importers.join(", ")}; set forceReferences to override`,
119
+ );
120
+ }
121
+
122
+ async function referenceStatus(
123
+ filePath: string,
124
+ inputPath: string,
125
+ request: FileDeleteRequest,
126
+ ) {
127
+ const referenceRoot = await referenceRootForPath(filePath);
128
+ const language = detectAstLanguage(filePath);
129
+ const capable = await astCapable(filePath, language);
130
+ requireVerifiableReferences(
131
+ referenceRoot,
132
+ capable,
133
+ inputPath,
134
+ request.forceReferences,
135
+ );
136
+ const importers = await authorizedImporters(filePath, referenceRoot, capable);
137
+ requireUnreferenced(importers, inputPath, request.forceReferences);
138
+ return { importers, referencesVerified: referenceRoot !== undefined };
139
+ }
140
+
141
+ async function prepareDeleteEntry(
142
+ inputPath: string,
143
+ request: FileDeleteRequest,
144
+ ) {
145
+ const filePath = await resolveWritablePath(inputPath, "delete");
146
+ const metadata = await lstat(filePath);
147
+ if (!metadata.isFile())
148
+ throw new Error(`file_delete accepts files only: ${inputPath}`);
149
+ const root = await rootForPath(filePath);
150
+ const removableDirectories = await authorizedAncestors(filePath, root);
151
+ return {
152
+ filePath,
153
+ ...(await referenceStatus(filePath, inputPath, request)),
154
+ removableDirectories,
155
+ request,
156
+ root,
157
+ };
158
+ }
159
+
63
160
  export async function deleteFilesSafely(requests: FileDeleteBatch) {
64
161
  const entries = await Promise.all(
65
- Object.entries(requests).map(async ([inputPath, request]) => {
66
- const filePath = await resolveWritablePath(inputPath);
67
- const metadata = await lstat(filePath);
68
- if (!metadata.isFile())
69
- throw new Error(`file_delete accepts files only: ${inputPath}`);
70
- const root = await rootForPath(filePath);
71
- const referenceRoot = await configuredRootForPath(filePath);
72
- const language = detectAstLanguage(filePath);
73
- if (
74
- !referenceRoot &&
75
- (await astCapable(filePath, language)) &&
76
- !request.forceReferences
77
- )
78
- throw new Error(
79
- `file_delete rejected ${inputPath}: references cannot be verified outside configured file-operation roots; set forceReferences to override`,
80
- );
81
- const importers = referenceRoot
82
- ? await importersFor(filePath, referenceRoot)
83
- : [];
84
- if (importers.length > 0 && !request.forceReferences)
85
- throw new Error(
86
- `file_delete rejected ${inputPath}: referenced by ${importers.join(", ")}; set forceReferences to override`,
87
- );
88
- return {
89
- filePath,
90
- importers,
91
- referencesVerified: referenceRoot !== undefined,
92
- request,
93
- root,
94
- };
95
- }),
162
+ Object.entries(requests).map(([inputPath, request]) =>
163
+ prepareDeleteEntry(inputPath, request),
164
+ ),
96
165
  );
97
166
  const files = await withFileLocks(
98
167
  entries.map(({ filePath }) => filePath),
@@ -122,8 +191,12 @@ export async function deleteFilesSafely(requests: FileDeleteBatch) {
122
191
  },
123
192
  );
124
193
  const removedDirectories = new Set<string>();
125
- for (const { filePath, root } of entries)
126
- for (const directory of await emptyParents(filePath, root))
194
+ for (const { filePath, removableDirectories, root } of entries)
195
+ for (const directory of await emptyParents(
196
+ filePath,
197
+ root,
198
+ removableDirectories,
199
+ ))
127
200
  removedDirectories.add(directory);
128
201
  return { files, removedDirectories: [...removedDirectories].sort() };
129
202
  }
@@ -1,10 +1,15 @@
1
1
  import { createReadStream } from "node:fs";
2
- import { stat } from "node:fs/promises";
2
+ import { readFile, stat } from "node:fs/promises";
3
3
 
4
- import { astCapable } from "../ast-bro/capability";
5
- import { detectAstLanguage } from "../patch/languages";
4
+ import { callAstBro } from "../ast-bro/client";
5
+ import { selectDocumentValues } from "./document-inspection";
6
+ import {
7
+ type FileCapabilities,
8
+ type FileReadMode,
9
+ inspectFileCapabilities,
10
+ } from "./file-capabilities";
6
11
  import { sha256File } from "./hash";
7
- import { resolveWritablePath } from "./paths";
12
+ import { intelligenceRoot, resolveWritablePath } from "./paths";
8
13
 
9
14
  const FILE_READ_DEFAULT_LINES = [0, 100] as const;
10
15
  export const FILE_READ_MAX_BATCH = 50;
@@ -13,8 +18,26 @@ export const FILE_READ_MAX_LINES = 1000;
13
18
 
14
19
  export interface FileReadRequest {
15
20
  filePath: string;
21
+ language?: string;
16
22
  lines?: [number, number];
17
23
  maxBytes?: number;
24
+ mode?: FileReadMode;
25
+ selectors?: string[];
26
+ symbols?: string[];
27
+ }
28
+
29
+ export interface FileReadResult {
30
+ ast?: unknown;
31
+ capabilities?: FileCapabilities;
32
+ content: string;
33
+ filePath: string;
34
+ hasMore: boolean;
35
+ lines: { requested: [number, number]; returned: number[] };
36
+ requestedMode?: FileReadMode;
37
+ resolvedMode?: Exclude<FileReadMode, "auto">;
38
+ sha256: string;
39
+ size: number;
40
+ truncated: boolean;
18
41
  }
19
42
 
20
43
  async function mapConcurrently<Input, Output>(
@@ -161,7 +184,7 @@ async function readLineRange(
161
184
  }
162
185
 
163
186
  async function hashFileSafely(filePath: string) {
164
- const resolved = await resolveWritablePath(filePath);
187
+ const resolved = await resolveWritablePath(filePath, "read");
165
188
  const metadata = await stat(resolved);
166
189
  if (!metadata.isFile()) throw new Error(`Not a regular file: ${filePath}`);
167
190
  return {
@@ -179,25 +202,121 @@ export async function hashFilesSafely(filePaths: string[]) {
179
202
  return mapConcurrently(filePaths, hashFileSafely);
180
203
  }
181
204
 
182
- export async function readFileSafely(request: FileReadRequest) {
183
- const resolved = await resolveWritablePath(request.filePath);
184
- const language = detectAstLanguage(resolved);
185
- if (await astCapable(resolved, language))
186
- throw new Error(
187
- "REJECTED: AST-capable files must use map, show, search, context, or run; use file_hash when only SHA-256 is required",
205
+ function resolveReadMode(
206
+ requestedMode: FileReadMode,
207
+ capabilities: FileCapabilities,
208
+ ): Exclude<FileReadMode, "auto"> {
209
+ if (requestedMode !== "auto") return requestedMode;
210
+ return capabilities.effective.read.includes("ast") ? "ast" : "text";
211
+ }
212
+
213
+ function assertReadMode(
214
+ resolved: string,
215
+ requestedMode: FileReadMode,
216
+ resolvedMode: Exclude<FileReadMode, "auto">,
217
+ capabilities: FileCapabilities,
218
+ ): void {
219
+ if (capabilities.effective.read.includes(resolvedMode)) return;
220
+ throw Object.assign(
221
+ new Error(
222
+ `file_read mode '${resolvedMode}' is unavailable for ${resolved}; available modes: ${capabilities.effective.read.join(", ") || "none"}`,
223
+ ),
224
+ {
225
+ code: "read_mode_unavailable",
226
+ details: { capabilities, requestedMode, resolvedMode },
227
+ retryable: true,
228
+ suggestedNextCall: "file_capabilities",
229
+ },
230
+ );
231
+ }
232
+
233
+ async function readDocumentAst(
234
+ resolved: string,
235
+ size: number,
236
+ selectors: string[] | undefined,
237
+ ): Promise<unknown> {
238
+ if (size > FILE_READ_MAX_BYTES)
239
+ throw Object.assign(
240
+ new Error(
241
+ `Structured document exceeds the ${FILE_READ_MAX_BYTES}-byte inspection limit; use bounded text mode`,
242
+ ),
243
+ {
244
+ code: "document_source_too_large",
245
+ retryable: true,
246
+ suggestedNextCall: "file_read",
247
+ },
188
248
  );
249
+ const source = await readFile(resolved, "utf8");
250
+ return {
251
+ schema: "ast-mcp.document-read.v1",
252
+ values: selectDocumentValues(
253
+ resolved,
254
+ source,
255
+ selectors?.length ? selectors : [""],
256
+ ),
257
+ };
258
+ }
259
+
260
+ async function readSourceAst(
261
+ resolved: string,
262
+ symbols: string[] | undefined,
263
+ ): Promise<unknown> {
264
+ const root = await intelligenceRoot([resolved]);
265
+ if (symbols?.length)
266
+ return callAstBro("show", { json: true, path: resolved, symbols }, root);
267
+ return callAstBro("map", { json: true, paths: [resolved] }, root);
268
+ }
269
+
270
+ async function readAst(
271
+ request: FileReadRequest,
272
+ resolved: string,
273
+ size: number,
274
+ capabilities: FileCapabilities,
275
+ ): Promise<unknown> {
276
+ if (capabilities.kind === "document")
277
+ return readDocumentAst(resolved, size, request.selectors);
278
+ return readSourceAst(resolved, request.symbols);
279
+ }
189
280
 
281
+ export async function readFileSafely(
282
+ request: FileReadRequest,
283
+ ): Promise<FileReadResult> {
284
+ const resolved = await resolveWritablePath(request.filePath, "read");
190
285
  const metadata = await stat(resolved);
191
286
  if (!metadata.isFile())
192
287
  throw new Error(`Not a regular file: ${request.filePath}`);
288
+ const capabilities = await inspectFileCapabilities(
289
+ resolved,
290
+ request.language,
291
+ );
292
+ const requestedMode = request.mode ?? "auto";
293
+ const resolvedMode = resolveReadMode(requestedMode, capabilities);
294
+ assertReadMode(resolved, requestedMode, resolvedMode, capabilities);
295
+ const sha256 = await sha256File(resolved);
296
+ if (resolvedMode === "ast") {
297
+ const ast = await readAst(request, resolved, metadata.size, capabilities);
298
+ return {
299
+ ast,
300
+ capabilities,
301
+ content: JSON.stringify(ast),
302
+ filePath: resolved,
303
+ hasMore: false,
304
+ lines: { requested: [0, 0], returned: [0, 0] },
305
+ requestedMode,
306
+ resolvedMode,
307
+ sha256,
308
+ size: metadata.size,
309
+ truncated: false,
310
+ };
311
+ }
193
312
  const { lines, maxBytes } = validateRequest(request);
194
- const [slice, sha256] = await Promise.all([
195
- readLineRange(resolved, metadata.size, lines, maxBytes),
196
- sha256File(resolved),
197
- ]);
313
+ const slice = await readLineRange(resolved, metadata.size, lines, maxBytes);
198
314
  return {
199
315
  ...slice,
316
+ capabilities,
200
317
  filePath: resolved,
318
+ requestedMode,
319
+ resolvedMode,
201
320
  sha256,
202
321
  size: metadata.size,
203
322
  };
@@ -103,8 +103,11 @@ export async function renameFilesSafely(requests: FileRenameBatch) {
103
103
 
104
104
  const entries = await Promise.all(
105
105
  Object.entries(requests).map(async ([inputPath, request]) => {
106
- const filePath = await resolveWritablePath(inputPath);
107
- const destinationPath = await resolveWritablePath(request.destination);
106
+ const filePath = await resolveWritablePath(inputPath, "delete");
107
+ const destinationPath = await resolveWritablePath(
108
+ request.destination,
109
+ "write",
110
+ );
108
111
  const metadata = await lstat(filePath);
109
112
  if (!metadata.isFile())
110
113
  throw new Error(`file_rename accepts files only: ${inputPath}`);