@mwillbanks/ast-mcp 0.2.1 → 0.3.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 (59) hide show
  1. package/CONTRIBUTING.md +13 -0
  2. package/README.md +18 -14
  3. package/dist/ast-mcp.js +183 -137
  4. package/dist/ast-mcp.js.map +58 -42
  5. package/package.json +17 -11
  6. package/src/ast-bro/capability.ts +20 -10
  7. package/src/ast-bro/tools.json +22 -2
  8. package/src/cli.ts +10 -7
  9. package/src/config-cli.ts +166 -19
  10. package/src/config-migrate.ts +223 -0
  11. package/src/config-registry.ts +321 -0
  12. package/src/config-schema-common.ts +81 -0
  13. package/src/config-v2-schema.ts +97 -0
  14. package/src/config.ts +375 -149
  15. package/src/helpers/ast-bro.ts +1 -7
  16. package/src/helpers/config.ts +12 -3
  17. package/src/helpers/installer.ts +8 -0
  18. package/src/helpers/mcp-schema.ts +105 -4
  19. package/src/host-smoke.ts +182 -0
  20. package/src/http.ts +8 -3
  21. package/src/installer-transport.ts +6 -4
  22. package/src/installer.ts +192 -51
  23. package/src/patch/engine.ts +555 -279
  24. package/src/patch/languages.ts +9 -0
  25. package/src/patch/strategy/aiderBlock.ts +110 -0
  26. package/src/patch/strategy/ast.ts +170 -0
  27. package/src/patch/strategy.ts +61 -0
  28. package/src/runtime/approval.ts +438 -0
  29. package/src/runtime/dependencies.ts +1 -1
  30. package/src/runtime/document-inspection.ts +78 -0
  31. package/src/runtime/file-capabilities.ts +250 -0
  32. package/src/runtime/file-delete.ts +122 -20
  33. package/src/runtime/file-read.ts +142 -14
  34. package/src/runtime/file-rename.ts +7 -6
  35. package/src/runtime/format.ts +65 -27
  36. package/src/runtime/path-policy.ts +557 -0
  37. package/src/runtime/path-utils.ts +40 -0
  38. package/src/runtime/paths.ts +204 -43
  39. package/src/server.ts +2 -1
  40. package/src/tools/ast-bro.ts +197 -76
  41. package/src/tools/configuration.ts +450 -0
  42. package/src/tools/configured.ts +49 -21
  43. package/src/tools/files.ts +177 -73
  44. package/src/tools/index.ts +2 -0
  45. package/src/tools/lifecycle.ts +89 -45
  46. package/templates/AGENTS.md +15 -17
  47. package/templates/skills/ast-mcp/SKILL.md +50 -34
  48. package/templates/skills/ast-mcp/evals/batch.evals.json +9 -9
  49. package/templates/skills/ast-mcp/evals/evals.json +221 -9
  50. package/templates/skills/ast-mcp/evals/measure.ts +27 -4
  51. package/templates/skills/ast-mcp/evals/score.test.ts +46 -3
  52. package/templates/skills/ast-mcp/evals/score.ts +87 -0
  53. package/templates/skills/ast-mcp/evals/semantic.test.ts +209 -28
  54. package/templates/skills/ast-mcp/evals/semantic.ts +151 -37
  55. package/templates/skills/ast-mcp/references/installation.md +12 -12
  56. package/templates/skills/ast-mcp/references/patch-state-machine.md +15 -14
  57. package/templates/skills/ast-mcp/references/tool-catalog.md +16 -10
  58. package/templates/skills/ast-mcp/scripts/check-install.ts +8 -17
  59. package/src/ast-bro/rewrite-capability.ts +0 -9
@@ -29,13 +29,7 @@ function appendRelatedArguments(
29
29
  ): void {
30
30
  if (typeof args.path !== "string" || typeof args.line !== "number")
31
31
  throw new Error("ast-bro find_related requires path and line");
32
- command.push(
33
- "--file",
34
- args.path,
35
- "--line",
36
- String(args.line),
37
- stringArgument(args, "root", root),
38
- );
32
+ command.push(`${args.path}:${args.line}`, stringArgument(args, "root", root));
39
33
  }
40
34
 
41
35
  function appendCommonArguments(
@@ -14,6 +14,8 @@ type ConfigLayer = {
14
14
  }>;
15
15
  [key: string]: unknown;
16
16
  };
17
+ paths?: Array<{ path: string; [key: string]: unknown }>;
18
+ safety?: { [key: string]: unknown };
17
19
  workspace?: { roots?: string[] };
18
20
  [key: string]: unknown;
19
21
  };
@@ -73,6 +75,11 @@ export function normalizeConfigLayer<T extends ConfigLayer>(
73
75
  ...value,
74
76
  dependencies: normalizeDependencies(value.dependencies, base),
75
77
  formatting: normalizeFormatting(value.formatting, base),
78
+ paths: value.paths?.map((rule) => ({
79
+ ...rule,
80
+ path: resolvedPath(rule.path, base),
81
+ })),
82
+ safety: value.safety,
76
83
  workspace: value.workspace?.roots
77
84
  ? { roots: value.workspace.roots.map((item) => resolvedPath(item, base)) }
78
85
  : value.workspace,
@@ -139,11 +146,13 @@ function isKeyedBatchPath(
139
146
  childKey: string,
140
147
  child: unknown,
141
148
  ): boolean {
149
+ const isBatchEntry =
150
+ parentKey === "files" ||
151
+ (parentKey === undefined && !keyedBatchExclusions.has(childKey));
142
152
  return (
143
- parentKey === undefined &&
153
+ isBatchEntry &&
144
154
  Boolean(child) &&
145
155
  typeof child === "object" &&
146
- !Array.isArray(child) &&
147
- !keyedBatchExclusions.has(childKey)
156
+ !Array.isArray(child)
148
157
  );
149
158
  }
@@ -8,6 +8,7 @@ export type InstallerOperation = "install" | "update" | "uninstall";
8
8
  export interface ParsedInstallerCommand {
9
9
  operation: InstallerOperation;
10
10
  options: {
11
+ deprecatedRoot?: boolean;
11
12
  host?: string;
12
13
  port?: number;
13
14
  root: string;
@@ -165,6 +166,13 @@ export function parseInstallerArguments(
165
166
  applyValueOption(token, requiredValue(tokens, index), options);
166
167
  index += 1;
167
168
  }
169
+ if (
170
+ args.some(
171
+ (token) =>
172
+ token === "--root" || token === "-r" || token.startsWith("--root="),
173
+ )
174
+ )
175
+ options.deprecatedRoot = true;
168
176
  validateOptions(options);
169
177
  return { operation, options };
170
178
  }
@@ -1,4 +1,5 @@
1
1
  import * as z from "zod/v4";
2
+ import { InputRequiredSignal } from "../runtime/approval";
2
3
  import { FILE_READ_MAX_BATCH } from "../runtime/file-read";
3
4
 
4
5
  export const chattrSchema = z.object({
@@ -18,14 +19,114 @@ export function boundedRecord<T extends z.ZodType>(schema: T, label: string) {
18
19
  }, label);
19
20
  }
20
21
 
22
+ export function boundedFileBatch<T extends z.ZodType>(
23
+ schema: T,
24
+ label: string,
25
+ ) {
26
+ return z.object({ files: boundedRecord(schema, label) }).strict();
27
+ }
28
+
21
29
  export function toolFailure(error: unknown) {
30
+ if (error instanceof InputRequiredSignal) return error.result;
31
+ const value = error as Error & {
32
+ code?: string;
33
+ decision?: unknown;
34
+ details?: unknown;
35
+ retryable?: boolean;
36
+ suggestedNextCall?: string;
37
+ };
38
+ const message = error instanceof Error ? error.message : String(error);
39
+ const code =
40
+ value.code ??
41
+ (/(?:hash|expectedSha256|stale file context)/i.test(message)
42
+ ? "stale_or_missing_hash"
43
+ : /format/i.test(message)
44
+ ? "format_failed"
45
+ : /match/i.test(message)
46
+ ? "match_count"
47
+ : "execution_failed");
48
+ const suggestedNextCall =
49
+ value.suggestedNextCall ??
50
+ (code === "stale_or_missing_hash"
51
+ ? "file_hash"
52
+ : code === "match_count"
53
+ ? "file_patch with preview=true"
54
+ : undefined);
55
+ const structuredContent = {
56
+ error: {
57
+ code,
58
+ details: value.details ?? value.decision,
59
+ message,
60
+ retryable:
61
+ value.retryable ??
62
+ ["stale_or_missing_hash", "match_count", "approval_required"].includes(
63
+ code,
64
+ ),
65
+ suggestedNextCall,
66
+ },
67
+ ok: false,
68
+ };
22
69
  return {
23
70
  content: [
24
- {
25
- text: error instanceof Error ? error.message : String(error),
26
- type: "text" as const,
27
- },
71
+ { text: JSON.stringify(structuredContent), type: "text" as const },
28
72
  ],
29
73
  isError: true,
74
+ structuredContent,
75
+ };
76
+ }
77
+
78
+ export function toolSuccess<T>(data: T) {
79
+ const structuredContent = { data, ok: true as const };
80
+ return {
81
+ content: [{ text: JSON.stringify(data), type: "text" as const }],
82
+ structuredContent,
83
+ };
84
+ }
85
+
86
+ type UpstreamToolResult = {
87
+ content?: Array<{ text?: string; type: string }>;
88
+ isError?: boolean;
89
+ [key: string]: unknown;
90
+ };
91
+
92
+ export function structuredUpstreamToolResult<T extends UpstreamToolResult>(
93
+ result: T,
94
+ suggestedNextCall: string,
95
+ ) {
96
+ if (!result.isError)
97
+ return { ...result, structuredContent: { data: result, ok: true } };
98
+ const message =
99
+ result.content
100
+ ?.filter((item) => item.type === "text")
101
+ .map((item) => item.text ?? "")
102
+ .join("\n") || "Upstream tool failed";
103
+ return {
104
+ ...result,
105
+ structuredContent: {
106
+ error: {
107
+ code: "upstream_tool_error",
108
+ message,
109
+ retryable: true,
110
+ suggestedNextCall,
111
+ },
112
+ ok: false,
113
+ },
30
114
  };
31
115
  }
116
+
117
+ export const toolOutputSchema = z
118
+ .object({
119
+ data: z.unknown().optional(),
120
+ error: z
121
+ .object({
122
+ code: z.string(),
123
+ details: z.unknown().optional(),
124
+ message: z.string(),
125
+ retryable: z.boolean(),
126
+ suggestedNextCall: z.string().optional(),
127
+ })
128
+ .strict()
129
+ .optional(),
130
+ ok: z.boolean(),
131
+ })
132
+ .strict();
@@ -0,0 +1,182 @@
1
+ const HOST_SMOKE_PREFIX = "AST_MCP_HOST_SMOKE_";
2
+ const HOST_SMOKE_TIMEOUT = `${HOST_SMOKE_PREFIX}TIMEOUT_MS`;
3
+ const DEFAULT_TIMEOUT_MS = 60_000;
4
+ const MAX_TIMEOUT_MS = 600_000;
5
+
6
+ export interface HostSmokeCheck {
7
+ command: string[];
8
+ expect: string[];
9
+ name: string;
10
+ timeoutMs: number;
11
+ }
12
+
13
+ export interface HostSmokeCommandResult {
14
+ exitCode: number;
15
+ output: string;
16
+ timedOut?: boolean;
17
+ }
18
+
19
+ export type HostSmokeRunner = (
20
+ check: HostSmokeCheck,
21
+ ) => Promise<HostSmokeCommandResult>;
22
+
23
+ function record(value: unknown): value is Record<string, unknown> {
24
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
25
+ }
26
+
27
+ function timeout(value: unknown, source: string) {
28
+ const parsed = typeof value === "number" ? value : Number(value);
29
+ if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_TIMEOUT_MS)
30
+ throw new Error(
31
+ `${source} must be an integer between 1 and ${MAX_TIMEOUT_MS}`,
32
+ );
33
+ return parsed;
34
+ }
35
+
36
+ function expectedMarkers(value: unknown, source: string) {
37
+ if (value === undefined) return [];
38
+ const values = typeof value === "string" ? [value] : value;
39
+ if (
40
+ !Array.isArray(values) ||
41
+ values.length === 0 ||
42
+ values.some((item) => typeof item !== "string" || item.length === 0)
43
+ )
44
+ throw new Error(
45
+ `${source}.expect must be a non-empty string or string array`,
46
+ );
47
+ return values as string[];
48
+ }
49
+
50
+ function parseCheck(
51
+ environmentName: string,
52
+ raw: string,
53
+ defaultTimeoutMs: number,
54
+ ): HostSmokeCheck {
55
+ let value: unknown;
56
+ try {
57
+ value = JSON.parse(raw);
58
+ } catch {
59
+ throw new Error(`${environmentName} must contain valid JSON`);
60
+ }
61
+ if (!record(value))
62
+ throw new Error(`${environmentName} must contain a JSON object`);
63
+ const unknown = Object.keys(value).filter(
64
+ (key) => !["command", "expect", "timeoutMs"].includes(key),
65
+ );
66
+ if (unknown.length > 0)
67
+ throw new Error(
68
+ `${environmentName} contains unsupported keys: ${unknown.join(", ")}`,
69
+ );
70
+ if (
71
+ !Array.isArray(value.command) ||
72
+ value.command.length === 0 ||
73
+ value.command.some((item) => typeof item !== "string" || item.length === 0)
74
+ )
75
+ throw new Error(
76
+ `${environmentName}.command must be a non-empty string array`,
77
+ );
78
+ const suffix = environmentName.slice(HOST_SMOKE_PREFIX.length);
79
+ return {
80
+ command: value.command as string[],
81
+ expect: expectedMarkers(value.expect, environmentName),
82
+ name: suffix.toLowerCase().replaceAll("_", "-"),
83
+ timeoutMs:
84
+ value.timeoutMs === undefined
85
+ ? defaultTimeoutMs
86
+ : timeout(value.timeoutMs, `${environmentName}.timeoutMs`),
87
+ };
88
+ }
89
+
90
+ export function configuredHostSmokeChecks(
91
+ env: NodeJS.ProcessEnv = process.env,
92
+ ): HostSmokeCheck[] {
93
+ const definitions = Object.entries(env).filter(
94
+ ([name, value]) =>
95
+ name !== HOST_SMOKE_TIMEOUT &&
96
+ name.startsWith(HOST_SMOKE_PREFIX) &&
97
+ /^[A-Z0-9][A-Z0-9_]*$/.test(name.slice(HOST_SMOKE_PREFIX.length)) &&
98
+ value !== undefined,
99
+ );
100
+ if (definitions.length === 0) return [];
101
+ const defaultTimeoutMs =
102
+ env[HOST_SMOKE_TIMEOUT] === undefined
103
+ ? DEFAULT_TIMEOUT_MS
104
+ : timeout(env[HOST_SMOKE_TIMEOUT], HOST_SMOKE_TIMEOUT);
105
+ return definitions
106
+ .map(([name, value]) => parseCheck(name, value as string, defaultTimeoutMs))
107
+ .sort((left, right) => left.name.localeCompare(right.name));
108
+ }
109
+
110
+ async function spawnHostSmoke(
111
+ check: HostSmokeCheck,
112
+ ): Promise<HostSmokeCommandResult> {
113
+ const child = Bun.spawn(check.command, {
114
+ cwd: process.cwd(),
115
+ env: process.env,
116
+ stderr: "pipe",
117
+ stdin: "ignore",
118
+ stdout: "pipe",
119
+ });
120
+ let timedOut = false;
121
+ const timer = setTimeout(() => {
122
+ timedOut = true;
123
+ child.kill();
124
+ }, check.timeoutMs);
125
+ try {
126
+ const [exitCode, stdout, stderr] = await Promise.all([
127
+ child.exited,
128
+ new Response(child.stdout).text(),
129
+ new Response(child.stderr).text(),
130
+ ]);
131
+ return { exitCode, output: `${stdout}\n${stderr}`, timedOut };
132
+ } finally {
133
+ clearTimeout(timer);
134
+ }
135
+ }
136
+
137
+ export async function runHostSmokeChecks(
138
+ checks: HostSmokeCheck[],
139
+ runner: HostSmokeRunner = spawnHostSmoke,
140
+ ): Promise<string[]> {
141
+ await Promise.all(
142
+ checks.map(async (check) => {
143
+ let result: HostSmokeCommandResult;
144
+ try {
145
+ result = await runner(check);
146
+ } catch (error) {
147
+ throw new Error(
148
+ `Host smoke "${check.name}" could not start: ${error instanceof Error ? error.message : String(error)}`,
149
+ );
150
+ }
151
+ if (result.timedOut)
152
+ throw new Error(
153
+ `Host smoke "${check.name}" exceeded ${check.timeoutMs}ms`,
154
+ );
155
+ if (result.exitCode !== 0)
156
+ throw new Error(
157
+ `Host smoke "${check.name}" failed with exit code ${result.exitCode}; external output is suppressed`,
158
+ );
159
+ const missing = check.expect.filter(
160
+ (marker) => !result.output.includes(marker),
161
+ );
162
+ if (missing.length > 0)
163
+ throw new Error(
164
+ `Host smoke "${check.name}" did not emit required markers: ${missing.join(", ")}`,
165
+ );
166
+ }),
167
+ );
168
+ return checks.map((check) => check.name);
169
+ }
170
+
171
+ export async function main(env: NodeJS.ProcessEnv = process.env) {
172
+ const checks = configuredHostSmokeChecks(env);
173
+ if (checks.length === 0) {
174
+ console.log(
175
+ `Host smoke checks skipped; set ${HOST_SMOKE_PREFIX}<NAME> to opt in`,
176
+ );
177
+ return [];
178
+ }
179
+ const completed = await runHostSmokeChecks(checks);
180
+ console.log(`Host smoke checks passed: ${completed.join(", ")}`);
181
+ return completed;
182
+ }
package/src/http.ts CHANGED
@@ -5,6 +5,7 @@ import { serve } from "bun";
5
5
 
6
6
  import { type ResolvedConfig, resolveConfig } from "./config";
7
7
  import { createServer, installProcessSignalHandlers } from "./lifecycle";
8
+ import { clearSessionApprovals } from "./runtime/approval";
8
9
 
9
10
  const configuration = resolveConfig;
10
11
 
@@ -34,15 +35,17 @@ let sessionSweep: ReturnType<typeof setInterval> | undefined;
34
35
  function discardSession(sessionId: string) {
35
36
  const session = sessions.get(sessionId);
36
37
  if (!session) return;
37
- void session.server.close();
38
38
  sessions.delete(sessionId);
39
+ clearSessionApprovals(sessionId);
40
+ void session.server.close().catch(() => undefined);
39
41
  }
40
42
 
41
43
  async function closeSession(sessionId: string) {
42
44
  const session = sessions.get(sessionId);
43
45
  if (!session) return;
44
- await session.server.close();
45
46
  sessions.delete(sessionId);
47
+ clearSessionApprovals(sessionId);
48
+ await session.server.close();
46
49
  }
47
50
 
48
51
  function sweepExpiredSessions() {
@@ -119,8 +122,10 @@ function handleMcpRequest(request: Request) {
119
122
  async function shutdownHttpServer(httpServer: ReturnType<typeof serve>) {
120
123
  httpServer.stop(false);
121
124
  if (sessionSweep) clearInterval(sessionSweep);
125
+ const activeSessions = [...sessions.entries()];
126
+ for (const [sessionId] of activeSessions) clearSessionApprovals(sessionId);
122
127
  const results = await Promise.allSettled(
123
- [...sessions.values()].map((session) => session.server.close()),
128
+ activeSessions.map(([, session]) => session.server.close()),
124
129
  );
125
130
  sessions.clear();
126
131
  httpServer.stop(true);
@@ -166,10 +166,12 @@ export async function resolveInstallerEndpoint(
166
166
  options.persist !== false &&
167
167
  (options.host !== undefined || options.port !== undefined)
168
168
  ) {
169
- const current = await readFile(configFile, "utf8").catch((error) => {
170
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
171
- throw error;
172
- });
169
+ let current = "";
170
+ try {
171
+ current = await readFile(configFile, "utf8");
172
+ } catch (error) {
173
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
174
+ }
173
175
  const updated = updateHttpToml(current, {
174
176
  host: options.host,
175
177
  port: options.port,