@mwillbanks/ast-mcp 0.1.3 → 0.2.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 (58) hide show
  1. package/README.md +59 -20
  2. package/dist/ast-mcp.js +232 -130
  3. package/dist/ast-mcp.js.map +107 -27
  4. package/package.json +2 -1
  5. package/src/ast-bro/capability.ts +3 -8
  6. package/src/ast-bro/client.ts +18 -2
  7. package/src/ast-bro/result.ts +5 -12
  8. package/src/cli.ts +70 -95
  9. package/src/config-cli.ts +54 -0
  10. package/src/config.ts +886 -0
  11. package/src/helpers/aider.ts +252 -0
  12. package/src/helpers/ast-bro.ts +64 -0
  13. package/src/helpers/config.ts +149 -0
  14. package/src/helpers/hook.ts +60 -0
  15. package/src/helpers/installer.ts +249 -0
  16. package/src/helpers/json.ts +19 -0
  17. package/src/helpers/mcp-schema.ts +31 -0
  18. package/src/helpers/process.ts +31 -0
  19. package/src/helpers/string.ts +97 -0
  20. package/src/hook.ts +135 -40
  21. package/src/http-entry.ts +1 -1
  22. package/src/http.ts +118 -103
  23. package/src/installer-transport.ts +190 -0
  24. package/src/installer.ts +579 -242
  25. package/src/mcp-cli.ts +104 -0
  26. package/src/patch/aider.ts +6 -199
  27. package/src/patch/engine.ts +271 -197
  28. package/src/runtime/dependencies.ts +48 -29
  29. package/src/runtime/file-delete.ts +13 -9
  30. package/src/runtime/file-read.ts +91 -57
  31. package/src/runtime/file-rename.ts +158 -0
  32. package/src/runtime/format.ts +57 -34
  33. package/src/runtime/paths.ts +30 -16
  34. package/src/runtime/policy.ts +21 -0
  35. package/src/runtime/process-input.ts +14 -4
  36. package/src/service.ts +219 -0
  37. package/src/shell-policy.ts +331 -0
  38. package/src/stdio.ts +47 -35
  39. package/src/tools/ast-bro.ts +12 -6
  40. package/src/tools/configured.ts +28 -0
  41. package/src/tools/files.ts +24 -27
  42. package/src/tools/index.ts +5 -3
  43. package/src/tools/lifecycle.ts +69 -55
  44. package/templates/skills/ast-mcp/SKILL.md +7 -6
  45. package/templates/skills/ast-mcp/evals/batch.evals.json +48 -0
  46. package/templates/skills/ast-mcp/evals/evals.json +1 -0
  47. package/templates/skills/ast-mcp/evals/score.test.ts +175 -0
  48. package/templates/skills/ast-mcp/evals/score.ts +304 -267
  49. package/templates/skills/ast-mcp/evals/semantic.test.ts +322 -0
  50. package/templates/skills/ast-mcp/evals/semantic.ts +390 -135
  51. package/templates/skills/ast-mcp/evals/shell-policy.ts +252 -0
  52. package/templates/skills/ast-mcp/evals/source.test.ts +46 -0
  53. package/templates/skills/ast-mcp/evals/source.ts +164 -0
  54. package/templates/skills/ast-mcp/evals/trigger-queries.json +1 -1
  55. package/templates/skills/ast-mcp/references/installation.md +9 -8
  56. package/templates/skills/ast-mcp/references/patch-state-machine.md +5 -5
  57. package/templates/skills/ast-mcp/references/tool-catalog.md +4 -2
  58. package/templates/skills/ast-mcp/scripts/check-install.ts +312 -110
package/src/mcp-cli.ts ADDED
@@ -0,0 +1,104 @@
1
+ import {
2
+ transports,
3
+ validateHttpHost,
4
+ validateHttpPort,
5
+ } from "./installer-transport";
6
+
7
+ export interface McpCliRuntime {
8
+ http?(options: { host?: string; port?: number }): Promise<{ url: URL }>;
9
+ stdio?(): Promise<void>;
10
+ }
11
+
12
+ function mcpUsageError(message: string) {
13
+ const error = new Error(message);
14
+ error.name = "McpUsageError";
15
+ return error;
16
+ }
17
+
18
+ function valueAfter(args: string[], index: number) {
19
+ const value = args[index + 1];
20
+ if (!value || value.startsWith("-"))
21
+ throw mcpUsageError(`Missing value for ${args[index] ?? "option"}`);
22
+ return value;
23
+ }
24
+
25
+ interface ParsedMcpOptions {
26
+ host?: string;
27
+ port?: number;
28
+ transport: "stdio" | "http";
29
+ }
30
+
31
+ function normalizedMcpTokens(args: string[]) {
32
+ return args.flatMap((token) => {
33
+ const match = /^(--(?:transport|host|port))=(.*)$/.exec(token);
34
+ return match ? [match[1] as string, match[2] as string] : [token];
35
+ });
36
+ }
37
+
38
+ function parsedPort(raw: string) {
39
+ if (!/^\d+$/.test(raw))
40
+ throw mcpUsageError(
41
+ `Invalid HTTP port "${raw}"; expected an integer from 1 through 65535`,
42
+ );
43
+ return validateHttpPort(Number(raw));
44
+ }
45
+
46
+ function parseMcpOptions(args: string[]): ParsedMcpOptions {
47
+ const tokens = normalizedMcpTokens(args);
48
+ const options: ParsedMcpOptions = { transport: "stdio" };
49
+ for (let index = 0; index < tokens.length; index += 1) {
50
+ const token = tokens[index];
51
+ if (token === "--transport") {
52
+ options.transport = valueAfter(
53
+ tokens,
54
+ index,
55
+ ) as ParsedMcpOptions["transport"];
56
+ index += 1;
57
+ } else if (token === "--host") {
58
+ options.host = valueAfter(tokens, index);
59
+ index += 1;
60
+ } else if (token === "--port") {
61
+ options.port = parsedPort(valueAfter(tokens, index));
62
+ index += 1;
63
+ } else throw mcpUsageError(`Unknown option: ${token}`);
64
+ }
65
+ return options;
66
+ }
67
+
68
+ function validateMcpOptions(options: ParsedMcpOptions) {
69
+ if (!transports.includes(options.transport))
70
+ throw mcpUsageError(
71
+ `Invalid transport "${options.transport}"; expected stdio or http`,
72
+ );
73
+ if (
74
+ options.transport === "stdio" &&
75
+ (options.host !== undefined || options.port !== undefined)
76
+ )
77
+ throw mcpUsageError("--host and --port require --transport http");
78
+ }
79
+
80
+ async function startStdio(runtime: McpCliRuntime) {
81
+ if (runtime.stdio) await runtime.stdio();
82
+ else await import("./index");
83
+ }
84
+
85
+ async function startHttp(options: ParsedMcpOptions, runtime: McpCliRuntime) {
86
+ const host =
87
+ options.host === undefined ? undefined : validateHttpHost(options.host);
88
+ if (runtime.http) return await runtime.http({ host, port: options.port });
89
+ const { startHttpServer } = await import("./http");
90
+ return await startHttpServer({ host, port: options.port });
91
+ }
92
+
93
+ export async function runMcpCli(args: string[], runtime: McpCliRuntime = {}) {
94
+ const options = parseMcpOptions(args);
95
+ validateMcpOptions(options);
96
+ if (options.transport === "stdio") {
97
+ await startStdio(runtime);
98
+ return;
99
+ }
100
+ const server = await startHttp(options, runtime);
101
+ const endpoint = new URL("/mcp", server.url);
102
+ process.stderr.write(`ast-mcp: listening on ${endpoint.toString()}\n`);
103
+ return server;
104
+ }
@@ -1,4 +1,7 @@
1
- import { DiffMatchPatch } from "diff-match-patch-ts";
1
+ import {
2
+ applyAiderBlockCascade as applyAiderBlockHelper,
3
+ parseAiderBlocksFromOutput as parseAiderBlocksHelper,
4
+ } from "../helpers/aider";
2
5
 
3
6
  export interface SearchReplaceBlock {
4
7
  filename: string;
@@ -16,52 +19,7 @@ export interface AiderReplacement {
16
19
  }
17
20
 
18
21
  export function parseAiderBlocks(output: string): SearchReplaceBlock[] {
19
- const blocks: SearchReplaceBlock[] = [];
20
- const lines = output.split(/\r?\n/);
21
- let filename = "";
22
- let mode: "outside" | "search" | "replace" = "outside";
23
- let search: string[] = [];
24
- let replace: string[] = [];
25
- for (let index = 0; index < lines.length; index += 1) {
26
- const line = lines[index];
27
- if (line.startsWith("<<<<<<< SEARCH")) {
28
- const prior = lines[index - 1]?.trim();
29
- if (prior && !prior.includes("```"))
30
- filename = prior.replace(/[:`*]/g, "").trim();
31
- search = [];
32
- replace = [];
33
- mode = "search";
34
- } else if (line.startsWith("=======")) mode = "replace";
35
- else if (line.startsWith(">>>>>>>")) {
36
- if (mode !== "replace")
37
- throw new Error(
38
- "Malformed Aider block: replacement terminator arrived out of order",
39
- );
40
- blocks.push({
41
- filename,
42
- replace: replace.join("\n"),
43
- search: search.join("\n"),
44
- });
45
- mode = "outside";
46
- } else if (mode === "search") search.push(line);
47
- else if (mode === "replace") replace.push(line);
48
- }
49
- if (mode !== "outside")
50
- throw new Error("Malformed Aider block: unterminated SEARCH/REPLACE block");
51
- return blocks;
52
- }
53
-
54
- function replaceLines(
55
- contentLines: string[],
56
- start: number,
57
- count: number,
58
- replacement: string,
59
- ): string {
60
- const before = contentLines.slice(0, start).join("\n");
61
- const after = contentLines.slice(start + count).join("\n");
62
- return (
63
- before + (before ? "\n" : "") + replacement + (after ? "\n" : "") + after
64
- );
22
+ return parseAiderBlocksHelper(output);
65
23
  }
66
24
 
67
25
  export function applyAiderBlock(
@@ -69,156 +27,5 @@ export function applyAiderBlock(
69
27
  searchInput: string,
70
28
  replaceInput: string,
71
29
  ): AiderReplacement {
72
- const content = fileContent.replace(/\r\n/g, "\n");
73
- const search = searchInput.replace(/\r\n/g, "\n");
74
- const replace = replaceInput.replace(/\r\n/g, "\n");
75
- if (!search.trim() && replace.trim())
76
- return {
77
- content: content + (content.endsWith("\n") ? "" : "\n") + replace,
78
- method: "append",
79
- };
80
- if (!search)
81
- throw new Error(
82
- "Aider SEARCH block must not be empty when replacement is empty",
83
- );
84
-
85
- const exact = content.split(search).length - 1;
86
- if (exact === 1)
87
- return { content: content.replace(search, () => replace), method: "exact" };
88
- if (exact > 1) throw new Error("Aider exact match is ambiguous");
89
-
90
- const normalize = (value: string) => {
91
- const indent = value.match(/^[ \t]*/)?.[0] ?? "";
92
- return (
93
- indent.replace(/\t/g, " ") +
94
- value
95
- .slice(indent.length)
96
- .replace(/[ \t]+/g, " ")
97
- .trimEnd()
98
- );
99
- };
100
- const contentLines = content.split("\n");
101
- const searchLines = search.split("\n");
102
- const whitespaceMatches: number[] = [];
103
- for (
104
- let start = 0;
105
- start <= contentLines.length - searchLines.length;
106
- start += 1
107
- ) {
108
- if (
109
- searchLines.every(
110
- (line, offset) =>
111
- normalize(contentLines[start + offset]) === normalize(line),
112
- )
113
- )
114
- whitespaceMatches.push(start);
115
- }
116
- if (whitespaceMatches.length === 1)
117
- return {
118
- content: replaceLines(
119
- contentLines,
120
- whitespaceMatches[0],
121
- searchLines.length,
122
- replace,
123
- ),
124
- method: "whitespace",
125
- };
126
- if (whitespaceMatches.length > 1)
127
- throw new Error("Aider whitespace match is ambiguous");
128
-
129
- const sample = searchLines.find((line) => line.trim());
130
- if (sample) {
131
- const searchIndent = sample.match(/^[ \t]*/)?.[0] ?? "";
132
- const shiftedMatches: Array<{ index: number; length: number }> = [];
133
- for (const line of contentLines) {
134
- if (line.trim() !== sample.trim()) continue;
135
- const fileIndent = line.match(/^[ \t]*/)?.[0] ?? "";
136
- if (fileIndent === searchIndent) continue;
137
- const shifted = searchLines
138
- .map((item) =>
139
- item.startsWith(searchIndent)
140
- ? fileIndent + item.slice(searchIndent.length)
141
- : item,
142
- )
143
- .join("\n");
144
- const index = content.indexOf(shifted);
145
- if (index >= 0 && content.indexOf(shifted, index + 1) < 0)
146
- shiftedMatches.push({ index, length: shifted.length });
147
- }
148
- if (shiftedMatches.length === 1) {
149
- const match = shiftedMatches[0];
150
- return {
151
- content:
152
- content.slice(0, match.index) +
153
- replace +
154
- content.slice(match.index + match.length),
155
- method: "relative-indentation",
156
- };
157
- }
158
- if (shiftedMatches.length > 1)
159
- throw new Error("Aider indentation match is ambiguous");
160
- }
161
-
162
- // Tier 4 (git cherry-pick) is deliberately omitted: this engine never spawns git or Python.
163
- const dmp = new DiffMatchPatch();
164
- dmp.Match_Distance = Math.max(1000, content.length);
165
- dmp.Match_Threshold = 0.5;
166
- const anchor = search.slice(0, dmp.Match_MaxBits);
167
- const locations: number[] = [];
168
- for (
169
- let location = content.indexOf(anchor);
170
- location >= 0;
171
- location = content.indexOf(anchor, location + 1)
172
- )
173
- locations.push(location);
174
- if (!locations.length) {
175
- const matcher = dmp as unknown as {
176
- match_main(text: string, pattern: string, location: number): number;
177
- };
178
- const location = matcher.match_main(content, anchor, 0);
179
- if (location >= 0) locations.push(location);
180
- }
181
- const adjustment = Math.min(64, Math.max(4, Math.ceil(search.length * 0.2)));
182
- const candidates: Array<{ index: number; length: number; ratio: number }> =
183
- [];
184
- for (const index of locations) {
185
- const minimum = Math.max(1, search.length - adjustment);
186
- const maximum = Math.min(
187
- content.length - index,
188
- search.length + adjustment,
189
- );
190
- let best: { index: number; length: number; ratio: number } | undefined;
191
- for (let length = minimum; length <= maximum; length += 1) {
192
- const candidate = content.slice(index, index + length);
193
- const edits = dmp.diff_levenshtein(dmp.diff_main(search, candidate));
194
- const ratio = edits / Math.max(search.length, length);
195
- if (
196
- !best ||
197
- ratio < best.ratio ||
198
- (ratio === best.ratio &&
199
- Math.abs(length - search.length) <
200
- Math.abs(best.length - search.length))
201
- )
202
- best = { index, length, ratio };
203
- }
204
- if (best) candidates.push(best);
205
- }
206
- candidates.sort((left, right) => left.ratio - right.ratio);
207
- const best = candidates[0];
208
- if (!best || best.ratio > 0.5)
209
- throw new Error(
210
- "Aider cascade match failed: SEARCH block was not found with sufficient confidence",
211
- );
212
- if (
213
- candidates[1] &&
214
- Math.abs(candidates[1].ratio - best.ratio) < Number.EPSILON
215
- )
216
- throw new Error("Aider diff-match-patch match is ambiguous");
217
- return {
218
- content:
219
- content.slice(0, best.index) +
220
- replace +
221
- content.slice(best.index + best.length),
222
- method: "diff-match-patch",
223
- };
30
+ return applyAiderBlockHelper(fileContent, searchInput, replaceInput);
224
31
  }