@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,438 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import {
4
+ existsSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ renameSync,
8
+ statSync,
9
+ unlinkSync,
10
+ writeFileSync,
11
+ } from "node:fs";
12
+ import path from "node:path";
13
+ import {
14
+ type InputRequiredResult,
15
+ inputRequired,
16
+ type McpServer,
17
+ type ServerContext,
18
+ } from "@modelcontextprotocol/server";
19
+ import { z } from "zod";
20
+ import { globalConfigPath } from "../config";
21
+ import type { PolicyDecision } from "./path-policy";
22
+
23
+ interface ApprovalScope {
24
+ context?: ServerContext;
25
+ invocationGrants?: Set<string>;
26
+ server?: McpServer;
27
+ tool: string;
28
+ }
29
+
30
+ const activeApproval = new AsyncLocalStorage<ApprovalScope>();
31
+ const sessionGrants = new Set<string>();
32
+ interface ApprovalChallenge {
33
+ expiresAt: number;
34
+ responseKey: string;
35
+ sessionId: string;
36
+ }
37
+
38
+ const APPROVAL_CHALLENGE_TTL_MS = 5 * 60 * 1000;
39
+ const MAX_APPROVAL_CHALLENGES = 1024;
40
+ const MAX_SESSION_APPROVAL_CHALLENGES = 64;
41
+ const issuedChallenges = new Map<string, ApprovalChallenge>();
42
+ let invalidateConfigRegistry: (() => void) | undefined;
43
+
44
+ export function setApprovalConfigInvalidator(invalidate: () => void): void {
45
+ invalidateConfigRegistry = invalidate;
46
+ }
47
+
48
+ function persistentConfig(globalPath: string): string {
49
+ mkdirSync(path.dirname(globalPath), { mode: 0o700, recursive: true });
50
+ const existing = existsSync(globalPath)
51
+ ? readFileSync(globalPath, "utf8")
52
+ : "";
53
+ if (!existing) return existing;
54
+ const parsed = Bun.TOML.parse(existing) as { version?: unknown };
55
+ if (parsed.version === 2) return existing;
56
+ throw Object.assign(
57
+ new Error(
58
+ "Persistent approvals require a version 2 user-global ast-mcp.toml; migrate it explicitly first",
59
+ ),
60
+ {
61
+ code: "approval_persistence_required",
62
+ retryable: true,
63
+ suggestedNextCall: "config_status",
64
+ },
65
+ );
66
+ }
67
+
68
+ interface StoredPersistentRule {
69
+ id?: string;
70
+ path?: string;
71
+ policies?: Partial<
72
+ Record<PolicyDecision["operation"], "allow" | "deny" | "request">
73
+ >;
74
+ }
75
+
76
+ function storedPersistentApprovals(
77
+ existing: string,
78
+ canonicalPath: string,
79
+ ): StoredPersistentRule[] {
80
+ if (!existing) return [];
81
+ const parsed = Bun.TOML.parse(existing) as {
82
+ paths?: StoredPersistentRule[];
83
+ };
84
+ return (parsed.paths ?? []).filter(
85
+ (rule) => rule.id?.startsWith("approval-") && rule.path === canonicalPath,
86
+ );
87
+ }
88
+
89
+ function persistentPolicy(
90
+ operation: PolicyDecision["operation"],
91
+ existing: StoredPersistentRule[] = [],
92
+ ) {
93
+ const allowed = new Set<PolicyDecision["operation"]>([operation]);
94
+ for (const rule of existing)
95
+ for (const candidate of ["read", "write", "delete"] as const)
96
+ if (rule.policies?.[candidate] === "allow") allowed.add(candidate);
97
+ return {
98
+ delete: allowed.has("delete") ? "allow" : "deny",
99
+ read: allowed.has("read") ? "allow" : "deny",
100
+ write: allowed.has("write") ? "allow" : "deny",
101
+ } as const;
102
+ }
103
+
104
+ function persistentPolicyLine(
105
+ policy: ReturnType<typeof persistentPolicy>,
106
+ ): string {
107
+ return `policies = { read = ${JSON.stringify(policy.read)}, write = ${JSON.stringify(policy.write)}, delete = ${JSON.stringify(policy.delete)} }`;
108
+ }
109
+
110
+ function mergePersistentPolicies(
111
+ source: string,
112
+ rules: StoredPersistentRule[],
113
+ policy: ReturnType<typeof persistentPolicy>,
114
+ ): string {
115
+ const ids = new Set(rules.flatMap((rule) => (rule.id ? [rule.id] : [])));
116
+ const policyLine = persistentPolicyLine(policy);
117
+ return source
118
+ .split(/(?=^\[\[paths\]\]\s*$)/m)
119
+ .map((block) =>
120
+ [...ids].some((id) => block.includes(`id = ${JSON.stringify(id)}`))
121
+ ? block.replace(/^policies = \{.*\}$/m, policyLine)
122
+ : block,
123
+ )
124
+ .join("");
125
+ }
126
+
127
+ function persistentId(decision: PolicyDecision): string {
128
+ return `approval-${createHash("sha256")
129
+ .update(`${decision.operation}\u0000${decision.canonicalPath}`)
130
+ .digest("hex")
131
+ .slice(0, 16)}`;
132
+ }
133
+
134
+ function persistApproval(
135
+ globalPath: string,
136
+ update: (existing: string) => string | undefined,
137
+ ): void {
138
+ mkdirSync(path.dirname(globalPath), { mode: 0o700, recursive: true });
139
+ const lockPath = `${globalPath}.approval.lock`;
140
+ const temporary = path.join(
141
+ path.dirname(globalPath),
142
+ `.${path.basename(globalPath)}.approval-${randomUUID()}`,
143
+ );
144
+ let lockOwned = false;
145
+ try {
146
+ try {
147
+ writeFileSync(lockPath, "", { flag: "wx", mode: 0o600 });
148
+ lockOwned = true;
149
+ } catch (error) {
150
+ if ((error as NodeJS.ErrnoException).code === "EEXIST")
151
+ throw Object.assign(
152
+ new Error("Another persistent approval update is in progress; retry"),
153
+ { code: "approval_persistence_busy", retryable: true },
154
+ );
155
+ throw error;
156
+ }
157
+ const existing = persistentConfig(globalPath);
158
+ const next = update(existing);
159
+ if (next === undefined) return;
160
+ writeFileSync(temporary, next, {
161
+ flag: "wx",
162
+ mode: existsSync(globalPath) ? statSync(globalPath).mode : 0o600,
163
+ });
164
+ if (persistentConfig(globalPath) !== existing)
165
+ throw Object.assign(
166
+ new Error("User-global configuration changed during approval; retry"),
167
+ { code: "approval_persistence_conflict", retryable: true },
168
+ );
169
+ renameSync(temporary, globalPath);
170
+ } finally {
171
+ try {
172
+ unlinkSync(temporary);
173
+ } catch {}
174
+ if (lockOwned)
175
+ try {
176
+ unlinkSync(lockPath);
177
+ } catch {}
178
+ }
179
+ }
180
+
181
+ function persistentRule(decision: PolicyDecision): string {
182
+ const globalPath = globalConfigPath();
183
+ const id = persistentId(decision);
184
+ let changed = false;
185
+ let created = false;
186
+ persistApproval(globalPath, (existing) => {
187
+ const matching = storedPersistentApprovals(
188
+ existing,
189
+ decision.canonicalPath,
190
+ );
191
+ const policy = persistentPolicy(decision.operation, matching);
192
+ if (matching.length > 0) {
193
+ const merged = mergePersistentPolicies(existing, matching, policy);
194
+ if (merged === existing) return undefined;
195
+ changed = true;
196
+ return merged;
197
+ }
198
+ const rule = [
199
+ "[[paths]]",
200
+ `id = ${JSON.stringify(id)}`,
201
+ `path = ${JSON.stringify(decision.canonicalPath)}`,
202
+ persistentPolicyLine(policy),
203
+ "follow_symlinks = false",
204
+ 'includes = ["**/*"]',
205
+ "excludes = []",
206
+ ].join("\n");
207
+ const prefix = existing || "version = 2\n";
208
+ changed = true;
209
+ created = true;
210
+ return `${prefix.trimEnd()}\n\n${rule}\n`;
211
+ });
212
+ if (changed) {
213
+ invalidateConfigRegistry?.();
214
+ console.error(
215
+ `ast-mcp audit: ${created ? "created" : "updated"} persistent approval ${id}`,
216
+ );
217
+ }
218
+ return id;
219
+ }
220
+
221
+ function key(
222
+ decision: PolicyDecision,
223
+ scope: ApprovalScope,
224
+ generation: number,
225
+ ): string {
226
+ return [
227
+ scope.context?.sessionId ?? "connection",
228
+ generation,
229
+ scope.tool,
230
+ decision.ruleId ?? decision.source,
231
+ decision.operation,
232
+ decision.canonicalPath,
233
+ ].join("\u0000");
234
+ }
235
+
236
+ function approvalResponseKey(): string {
237
+ return `approval_${randomUUID().replaceAll("-", "")}`;
238
+ }
239
+
240
+ export class InputRequiredSignal extends Error {
241
+ readonly result: InputRequiredResult;
242
+
243
+ constructor(result: InputRequiredResult) {
244
+ super("User approval is required");
245
+ this.name = "InputRequiredSignal";
246
+ this.result = result;
247
+ }
248
+ }
249
+
250
+ export function withApprovalContext<T>(
251
+ scope: ApprovalScope,
252
+ operation: () => Promise<T>,
253
+ ): Promise<T> {
254
+ return activeApproval.run(
255
+ { ...scope, invocationGrants: new Set<string>() },
256
+ operation,
257
+ );
258
+ }
259
+
260
+ type ApprovalResponse = {
261
+ action?: string;
262
+ content?: { decision?: string };
263
+ };
264
+
265
+ function acceptResponse(
266
+ response: ApprovalResponse | undefined,
267
+ decision: PolicyDecision,
268
+ grantKey: string,
269
+ invocationGrants: Set<string>,
270
+ ): boolean | undefined {
271
+ if (response?.action !== "accept") return undefined;
272
+ switch (response.content?.decision) {
273
+ case "allow_once":
274
+ invocationGrants.add(grantKey);
275
+ return true;
276
+ case "allow_session":
277
+ sessionGrants.add(grantKey);
278
+ return true;
279
+ case "always_allow":
280
+ persistentRule(decision);
281
+ invocationGrants.add(grantKey);
282
+ return true;
283
+ default:
284
+ return undefined;
285
+ }
286
+ }
287
+
288
+ function deniedResponse(response: ApprovalResponse | undefined): boolean {
289
+ return (
290
+ response?.action === "decline" ||
291
+ response?.action === "cancel" ||
292
+ response?.content?.decision === "deny"
293
+ );
294
+ }
295
+
296
+ function approvalRequired(decision: PolicyDecision): Error {
297
+ return Object.assign(
298
+ new Error(
299
+ `Approval required for ${decision.operation} ${decision.canonicalPath}; this client has no elicitation capability. Add a narrow user-global [[paths]] rule or use a capable client.`,
300
+ ),
301
+ {
302
+ code: "approval_required",
303
+ details: decision,
304
+ retryable: true,
305
+ suggestedNextCall: "policy_check",
306
+ },
307
+ );
308
+ }
309
+
310
+ function approvalDenied(decision: PolicyDecision): Error {
311
+ return Object.assign(
312
+ new Error(
313
+ `User denied ${decision.operation} for ${decision.canonicalPath}`,
314
+ ),
315
+ { code: "approval_denied", retryable: false },
316
+ );
317
+ }
318
+
319
+ function requestApproval(
320
+ scope: ApprovalScope,
321
+ decision: PolicyDecision,
322
+ responseKey: string,
323
+ ): InputRequiredSignal {
324
+ return new InputRequiredSignal(
325
+ inputRequired({
326
+ inputRequests: {
327
+ [responseKey]: inputRequired.elicit({
328
+ _meta: {
329
+ codex_approval_kind: "mcp_tool_call",
330
+ persist: ["session", "always"],
331
+ },
332
+ message: [
333
+ `${scope.tool} requests ${decision.operation} access.`,
334
+ `Path: ${decision.canonicalPath}`,
335
+ `Policy: ${decision.reason}`,
336
+ "Choose the narrowest approval that is appropriate.",
337
+ ].join("\n"),
338
+ requestedSchema: z.object({
339
+ decision: z.enum([
340
+ "deny",
341
+ "allow_once",
342
+ "allow_session",
343
+ "always_allow",
344
+ ]),
345
+ }),
346
+ }),
347
+ },
348
+ }),
349
+ );
350
+ }
351
+
352
+ function pruneApprovalChallenges(now = Date.now()): void {
353
+ for (const [grantKey, challenge] of issuedChallenges)
354
+ if (challenge.expiresAt <= now) issuedChallenges.delete(grantKey);
355
+ }
356
+
357
+ function storeApprovalChallenge(
358
+ grantKey: string,
359
+ scope: ApprovalScope,
360
+ responseKey: string,
361
+ ): void {
362
+ pruneApprovalChallenges();
363
+ const sessionId = scope.context?.sessionId ?? "connection";
364
+ const sessionChallenges = [...issuedChallenges.values()].filter(
365
+ (challenge) => challenge.sessionId === sessionId,
366
+ ).length;
367
+ if (
368
+ issuedChallenges.size >= MAX_APPROVAL_CHALLENGES ||
369
+ sessionChallenges >= MAX_SESSION_APPROVAL_CHALLENGES
370
+ )
371
+ throw Object.assign(
372
+ new Error(
373
+ "Approval challenge limit reached; answer or allow existing requests to expire",
374
+ ),
375
+ { code: "approval_challenge_limit", retryable: true },
376
+ );
377
+ issuedChallenges.set(grantKey, {
378
+ expiresAt: Date.now() + APPROVAL_CHALLENGE_TTL_MS,
379
+ responseKey,
380
+ sessionId,
381
+ });
382
+ }
383
+
384
+ export function authorizeRequestedDecision(
385
+ decision: PolicyDecision,
386
+ generation: number,
387
+ ): boolean {
388
+ const scope = activeApproval.getStore();
389
+ if (!scope?.context || !scope.server) return false;
390
+ pruneApprovalChallenges();
391
+ const grantKey = key(decision, scope, generation);
392
+ const invocationGrants = scope.invocationGrants ?? new Set<string>();
393
+ if (invocationGrants.has(grantKey) || sessionGrants.has(grantKey))
394
+ return true;
395
+ const challenge = issuedChallenges.get(grantKey);
396
+ const responseKey = challenge?.responseKey;
397
+ const response = responseKey
398
+ ? (scope.context.mcpReq.inputResponses?.[responseKey] as
399
+ | ApprovalResponse
400
+ | undefined)
401
+ : undefined;
402
+ const accepted = acceptResponse(
403
+ response,
404
+ decision,
405
+ grantKey,
406
+ invocationGrants,
407
+ );
408
+ if (accepted !== undefined) {
409
+ issuedChallenges.delete(grantKey);
410
+ return accepted;
411
+ }
412
+ if (deniedResponse(response)) {
413
+ issuedChallenges.delete(grantKey);
414
+ throw approvalDenied(decision);
415
+ }
416
+ if (!scope.server.server.getClientCapabilities()?.elicitation)
417
+ throw approvalRequired(decision);
418
+ const nextResponseKey = responseKey ?? approvalResponseKey();
419
+ if (!challenge) storeApprovalChallenge(grantKey, scope, nextResponseKey);
420
+ throw requestApproval(scope, decision, nextResponseKey);
421
+ }
422
+
423
+ export function approvalSessionId(): string {
424
+ return activeApproval.getStore()?.context?.sessionId ?? "local";
425
+ }
426
+
427
+ export function clearSessionApprovals(sessionId?: string): void {
428
+ if (!sessionId) {
429
+ sessionGrants.clear();
430
+ issuedChallenges.clear();
431
+ return;
432
+ }
433
+ const prefix = `${sessionId}\u0000`;
434
+ for (const grantKey of sessionGrants)
435
+ if (grantKey.startsWith(prefix)) sessionGrants.delete(grantKey);
436
+ for (const [grantKey, challenge] of issuedChallenges)
437
+ if (challenge.sessionId === sessionId) issuedChallenges.delete(grantKey);
438
+ }