@mwillbanks/ast-mcp 0.6.6 → 0.7.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 (55) hide show
  1. package/CONTRIBUTING.md +6 -0
  2. package/dist/ast-mcp.js +358 -337
  3. package/dist/ast-mcp.js.map +45 -32
  4. package/dist/workers/sql-postgres-worker.js +5 -0
  5. package/dist/workers/sql-postgres-worker.js.map +10 -0
  6. package/package.json +3 -2
  7. package/src/cli/doctor.ts +103 -0
  8. package/src/cli/index.ts +9 -1
  9. package/src/config/index.ts +61 -6
  10. package/src/config/registry.ts +209 -67
  11. package/src/config/v2-schema.ts +2 -0
  12. package/src/helpers/installer.ts +10 -1
  13. package/src/http/index.ts +12 -5
  14. package/src/installer/codex.ts +237 -0
  15. package/src/installer/diagnostics.ts +387 -0
  16. package/src/installer/directory-ancestry.ts +55 -0
  17. package/src/installer/index.ts +386 -119
  18. package/src/installer/ownership.ts +165 -0
  19. package/src/installer/service-state.ts +151 -0
  20. package/src/installer/service.ts +131 -7
  21. package/src/installer/transaction.ts +342 -0
  22. package/src/installer/transport.ts +22 -31
  23. package/src/intelligence/mutation/locks.ts +4 -1
  24. package/src/patch/engine.ts +157 -11
  25. package/src/runtime/approval.ts +427 -66
  26. package/src/runtime/config-write.ts +27 -1
  27. package/src/runtime/diagnostics.ts +115 -0
  28. package/src/runtime/file-capabilities.ts +2 -0
  29. package/src/runtime/hosts/codex.ts +16 -0
  30. package/src/runtime/path-policy.ts +2 -0
  31. package/src/runtime/release.ts +220 -0
  32. package/src/runtime/sql-assistance.ts +439 -0
  33. package/src/runtime/sql-options-schema.ts +31 -0
  34. package/src/runtime/sql-postgres-worker.ts +72 -0
  35. package/src/runtime/sql-postgres.ts +245 -0
  36. package/src/server/index.ts +35 -5
  37. package/src/server/lifecycle.ts +1 -1
  38. package/src/tools/configuration.ts +2 -0
  39. package/src/tools/diagnostics.ts +85 -0
  40. package/src/tools/files.ts +2 -0
  41. package/src/tools/index.ts +9 -0
  42. package/templates/skills/ast-mcp/SKILL.md +20 -1
  43. package/templates/skills/ast-mcp/evals/evals.json +274 -0
  44. package/templates/skills/ast-mcp/evals/semantic.ts +2 -0
  45. package/templates/skills/ast-mcp/evals/trigger-queries.json +4 -1
  46. package/templates/skills/ast-mcp/references/cli.md +97 -0
  47. package/templates/skills/ast-mcp/references/configuration.md +11 -3
  48. package/templates/skills/ast-mcp/references/diagnostics.md +106 -0
  49. package/templates/skills/ast-mcp/references/host-context.md +85 -0
  50. package/templates/skills/ast-mcp/references/installation.md +37 -0
  51. package/templates/skills/ast-mcp/references/issue-reporting.md +80 -0
  52. package/templates/skills/ast-mcp/references/patch-state-machine.md +10 -0
  53. package/templates/skills/ast-mcp/references/tool-catalog.md +120 -50
  54. package/templates/skills/ast-mcp/scripts/check-install.ts +223 -24
  55. package/templates/skills/ast-mcp/scripts/release.ts +220 -0
@@ -16,6 +16,10 @@ import type { CliOutputFormat } from "../config/schema-common";
16
16
  import { grantUnrestrictedFilesystem } from "./approval";
17
17
  import { withFileLocks } from "./locks";
18
18
  import { assertPolicy, evaluatePolicy, PathPolicyError } from "./path-policy";
19
+ import {
20
+ mergeSqlAssistanceDefaults,
21
+ type SqlAssistanceOptions,
22
+ } from "./sql-assistance";
19
23
 
20
24
  export type ConfigTarget = "global" | "project";
21
25
 
@@ -35,6 +39,7 @@ export interface ConfigCorePatch {
35
39
  "diff-match-patch" | "exact" | "relative-indentation" | "whitespace"
36
40
  >;
37
41
  strategies?: Array<"aider_block" | "ast">;
42
+ sql?: SqlAssistanceOptions;
38
43
  };
39
44
  read?: { modes?: Array<"ast" | "text"> };
40
45
  };
@@ -217,6 +222,22 @@ function removeFormatterTables(source: string): string {
217
222
  .join("\n");
218
223
  }
219
224
 
225
+ function applySqlDefaults(source: string, patch: SqlAssistanceOptions): string {
226
+ const parsed = Bun.TOML.parse(source) as {
227
+ files?: { patch?: { sql?: SqlAssistanceOptions } };
228
+ };
229
+ const resolved = mergeSqlAssistanceDefaults(patch, parsed.files?.patch?.sql);
230
+ let next = removeTomlSectionKey(source, "files.patch", "sql");
231
+ for (const key of ["dialect", "policy", "variant", "version"] as const) {
232
+ const value = resolved[key];
233
+ next =
234
+ value === undefined
235
+ ? removeTomlSectionKey(next, "files.patch.sql", key)
236
+ : setTomlSectionKey(next, "files.patch.sql", key, value);
237
+ }
238
+ return next;
239
+ }
240
+
220
241
  function applyConfigCorePatch(source: string, patch: ConfigCorePatch): string {
221
242
  let next = source;
222
243
  next = applyObjectKeys(next, "cli.output", patch.cli?.output);
@@ -228,7 +249,12 @@ function applyConfigCorePatch(source: string, patch: ConfigCorePatch): string {
228
249
  });
229
250
  next = applyObjectKeys(next, "safety.hook", patch.safety?.hook);
230
251
  next = applyObjectKeys(next, "files.read", patch.files?.read);
231
- next = applyObjectKeys(next, "files.patch", patch.files?.patch);
252
+ next = applyObjectKeys(next, "files.patch", {
253
+ aider_matchers: patch.files?.patch?.aider_matchers,
254
+ strategies: patch.files?.patch?.strategies,
255
+ });
256
+ if (patch.files?.patch?.sql !== undefined)
257
+ next = applySqlDefaults(next, patch.files.patch.sql);
232
258
  if (patch.formatting?.formatters !== undefined)
233
259
  next = removeFormatterTables(next);
234
260
  if (patch.formatting?.dprint_config === null)
@@ -0,0 +1,115 @@
1
+ import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
2
+
3
+ import packageJson from "../../package.json" with { type: "json" };
4
+ import type { ResolvedConfig } from "../config";
5
+ import { configRegistry } from "../config/registry";
6
+ import {
7
+ approvalClient,
8
+ approvalDiagnostics,
9
+ supportsApprovalForm,
10
+ } from "./approval";
11
+ import { codexApprovalMetadata } from "./hosts/codex";
12
+
13
+ export { checkLatestVersion } from "./release";
14
+ import { checkLatestVersion } from "./release";
15
+
16
+ export interface DiagnosticsOptions {
17
+ config?: Readonly<ResolvedConfig>;
18
+ context?: ServerContext;
19
+ cwd?: string;
20
+ fetch?: typeof fetch;
21
+ server?: McpServer;
22
+ transport?: "stdio" | "http" | "unknown";
23
+ }
24
+
25
+ function safeIdentity(value: unknown): string {
26
+ return typeof value === "string" && /^[\w .+-]{1,128}$/.test(value)
27
+ ? value
28
+ : "unknown";
29
+ }
30
+
31
+ export async function collectDiagnostics(options: DiagnosticsOptions = {}) {
32
+ const versionCheck = checkLatestVersion(packageJson.version, {
33
+ fetch: options.fetch,
34
+ });
35
+ let config = options.config;
36
+ if (!config) {
37
+ try {
38
+ config = await configRegistry.get({ cwd: options.cwd });
39
+ } catch {
40
+ // Configuration error text can contain private paths or source content.
41
+ }
42
+ }
43
+ const { capabilities, client, protocol } = approvalClient(
44
+ options.server,
45
+ options.context,
46
+ );
47
+ return {
48
+ schemaVersion: 1,
49
+ server: {
50
+ name: "ast-mcp",
51
+ version: packageJson.version,
52
+ runtime: `Bun ${Bun.version}`,
53
+ transport:
54
+ options.transport ?? (options.context?.http ? "http" : "unknown"),
55
+ protocol,
56
+ },
57
+ client: {
58
+ name: safeIdentity(client?.name),
59
+ version: safeIdentity(client?.version),
60
+ activeApprovalPolicy: "unknown",
61
+ backendVersion: "unknown",
62
+ formElicitation: supportsApprovalForm(capabilities),
63
+ capabilities: {
64
+ formElicitation: supportsApprovalForm(capabilities),
65
+ urlElicitation: Boolean(
66
+ capabilities?.elicitation &&
67
+ typeof capabilities.elicitation === "object" &&
68
+ !Array.isArray(capabilities.elicitation) &&
69
+ Object.hasOwn(capabilities.elicitation, "url") &&
70
+ typeof (capabilities.elicitation as { url?: unknown }).url ===
71
+ "object" &&
72
+ (capabilities.elicitation as { url?: unknown }).url !== null &&
73
+ !Array.isArray((capabilities.elicitation as { url?: unknown }).url),
74
+ ),
75
+ roots: Boolean(
76
+ capabilities?.roots &&
77
+ typeof capabilities.roots === "object" &&
78
+ !Array.isArray(capabilities.roots),
79
+ ),
80
+ sampling: Boolean(
81
+ capabilities?.sampling &&
82
+ typeof capabilities.sampling === "object" &&
83
+ !Array.isArray(capabilities.sampling),
84
+ ),
85
+ },
86
+ },
87
+ versionCheck: await versionCheck,
88
+ configuration: {
89
+ healthy: Boolean(config),
90
+ generation: config?.generation ?? null,
91
+ filesystem: config?.safety.filesystem ?? "unknown",
92
+ filesystemSource: config?.provenance["safety.filesystem"] ?? "unknown",
93
+ requireHash: config?.safety.requireHash ?? null,
94
+ hookEnabled: config?.safety.hook.enabled ?? null,
95
+ formattingEnabled: config?.formatting.enabled ?? null,
96
+ sources: {
97
+ global: Boolean(config?.sources.global),
98
+ project: Boolean(config?.sources.project),
99
+ environment: config?.sources.environment?.length ?? 0,
100
+ },
101
+ reason: config ? undefined : "configuration_unavailable",
102
+ },
103
+ approval: approvalDiagnostics(options.server, options.context),
104
+ recovery: [
105
+ "Tool-call approval and server filesystem approval are separate.",
106
+ "A host permission profile or CLI override can supersede disk approval settings.",
107
+ ...(codexApprovalMetadata(client)
108
+ ? [
109
+ "For Codex, use an effective session policy permitting MCP elicitations and answer the real approval form.",
110
+ ]
111
+ : []),
112
+ "Refresh the intended package installation and reconnect; a shell version does not establish the connected server version.",
113
+ ],
114
+ };
115
+ }
@@ -280,6 +280,8 @@ export async function validateStructuredCandidate(
280
280
  }
281
281
  }
282
282
  if (!capabilities.language || capabilities.kind !== "source") return;
283
+ // Generic SQL recovery nodes do not establish dialect syntax validity.
284
+ if (capabilities.language === "sql") return;
283
285
  if (capabilities.parseErrorCount === undefined) return;
284
286
  let candidateErrors: number;
285
287
  try {
@@ -0,0 +1,16 @@
1
+ /** Codex approval display hints never confer server authorization. */
2
+ export function codexApprovalMetadata(
3
+ client: { name?: unknown } | undefined,
4
+ filesystem = false,
5
+ probe = false,
6
+ ) {
7
+ if (
8
+ typeof client?.name !== "string" ||
9
+ !/(?:^|[-_ ])codex(?:$|[-_ ])/i.test(client.name)
10
+ )
11
+ return undefined;
12
+ return {
13
+ codex_approval_kind: "mcp_tool_call",
14
+ persist: probe ? [] : filesystem ? ["session"] : ["session", "always"],
15
+ };
16
+ }
@@ -22,6 +22,8 @@ import {
22
22
  export type PathOperation = "read" | "write" | "delete";
23
23
 
24
24
  export interface PolicyDecision {
25
+ /** Internal synthetic approvals only; never derive this from a path rule ID. */
26
+ approvalKind?: "filesystem" | "probe";
25
27
  canonicalPath: string;
26
28
  operation: PathOperation;
27
29
  policy: PathPolicy;
@@ -0,0 +1,220 @@
1
+ const LATEST_URL = "https://registry.npmjs.org/@mwillbanks%2Fast-mcp/latest";
2
+ const VERSION_PATTERN =
3
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
4
+
5
+ function parsedVersion(value: string) {
6
+ if (value.length > 128) return undefined;
7
+ const matched = VERSION_PATTERN.exec(value);
8
+ if (!matched) return undefined;
9
+ const pre = matched[4]?.split(".");
10
+ if (
11
+ pre?.some(
12
+ (part) => /^\d+$/.test(part) && part.length > 1 && part.startsWith("0"),
13
+ )
14
+ )
15
+ return undefined;
16
+ return { core: matched.slice(1, 4).map(BigInt), pre };
17
+ }
18
+
19
+ export function compareVersions(
20
+ first: string,
21
+ second: string,
22
+ ): number | undefined {
23
+ const a = parsedVersion(first);
24
+ const b = parsedVersion(second);
25
+ if (!a || !b) return undefined;
26
+ for (let index = 0; index < 3; index++) {
27
+ if (a.core[index]! < b.core[index]!) return -1;
28
+ if (a.core[index]! > b.core[index]!) return 1;
29
+ }
30
+ if (!a.pre && !b.pre) return 0;
31
+ if (!a.pre) return 1;
32
+ if (!b.pre) return -1;
33
+ for (let index = 0; index < Math.max(a.pre.length, b.pre.length); index++) {
34
+ const left = a.pre[index];
35
+ const right = b.pre[index];
36
+ if (left === undefined) return -1;
37
+ if (right === undefined) return 1;
38
+ if (left === right) continue;
39
+ const leftNumber = /^\d+$/.test(left);
40
+ const rightNumber = /^\d+$/.test(right);
41
+ if (leftNumber && rightNumber) return BigInt(left) < BigInt(right) ? -1 : 1;
42
+ if (leftNumber !== rightNumber) return leftNumber ? -1 : 1;
43
+ return left < right ? -1 : 1;
44
+ }
45
+ return 0;
46
+ }
47
+
48
+ export interface LatestVersionCheck {
49
+ checkedAt: string;
50
+ latestVersion: string | null;
51
+ runningVersion: string;
52
+ status: "current" | "outdated" | "newer" | "prerelease" | "unavailable";
53
+ comparison?: "older" | "equal" | "newer";
54
+ reason?:
55
+ | "timeout"
56
+ | "registry_unavailable"
57
+ | "invalid_registry_response"
58
+ | "invalid_running_version";
59
+ }
60
+
61
+ /** Validates a complete release report, including status-specific invariants. */
62
+ export function isLatestVersionCheck(
63
+ value: unknown,
64
+ ): value is LatestVersionCheck {
65
+ if (!value || typeof value !== "object") return false;
66
+ const check = value as Record<string, unknown>;
67
+ if (
68
+ typeof check.checkedAt !== "string" ||
69
+ !Number.isFinite(Date.parse(check.checkedAt)) ||
70
+ typeof check.runningVersion !== "string"
71
+ )
72
+ return false;
73
+ const running = parsedVersion(check.runningVersion);
74
+ const latest =
75
+ typeof check.latestVersion === "string"
76
+ ? parsedVersion(check.latestVersion)
77
+ : undefined;
78
+ if (check.status === "unavailable") {
79
+ if (check.comparison !== undefined) return false;
80
+ if (check.reason === "invalid_running_version")
81
+ return !running && latest !== undefined && !latest.pre;
82
+ return (
83
+ typeof check.reason === "string" &&
84
+ ["timeout", "registry_unavailable", "invalid_registry_response"].includes(
85
+ check.reason,
86
+ ) &&
87
+ check.latestVersion === null
88
+ );
89
+ }
90
+ if (!running || !latest || latest.pre || check.reason !== undefined)
91
+ return false;
92
+ const compared = compareVersions(
93
+ check.runningVersion,
94
+ check.latestVersion as string,
95
+ )!;
96
+ const comparison = compared < 0 ? "older" : compared > 0 ? "newer" : "equal";
97
+ const status = running.pre
98
+ ? "prerelease"
99
+ : compared < 0
100
+ ? "outdated"
101
+ : compared > 0
102
+ ? "newer"
103
+ : "current";
104
+ return check.comparison === comparison && check.status === status;
105
+ }
106
+
107
+ async function boundedRegistryVersion(
108
+ response: Response,
109
+ signal: AbortSignal,
110
+ ): Promise<string> {
111
+ if (!response.ok) throw new Error("registry_unavailable");
112
+ if (Number(response.headers.get("content-length")) > 16_384 || !response.body)
113
+ throw new Error("invalid_registry_response");
114
+ const reader = response.body.getReader();
115
+ const abort = () => {
116
+ void reader.cancel().catch(() => {});
117
+ };
118
+ signal.addEventListener("abort", abort, { once: true });
119
+ if (signal.aborted) abort();
120
+ const chunks: Uint8Array[] = [];
121
+ let size = 0;
122
+ try {
123
+ while (true) {
124
+ const chunk = await reader.read();
125
+ if (chunk.done) break;
126
+ size += chunk.value.byteLength;
127
+ if (size > 16_384) throw new Error("invalid_registry_response");
128
+ chunks.push(chunk.value);
129
+ }
130
+ } finally {
131
+ signal.removeEventListener("abort", abort);
132
+ void reader.cancel().catch(() => {});
133
+ reader.releaseLock();
134
+ }
135
+ const bytes = new Uint8Array(size);
136
+ let offset = 0;
137
+ for (const chunk of chunks) {
138
+ bytes.set(chunk, offset);
139
+ offset += chunk.byteLength;
140
+ }
141
+ let value: unknown;
142
+ try {
143
+ value = JSON.parse(new TextDecoder().decode(bytes));
144
+ } catch {
145
+ throw new Error("invalid_registry_response");
146
+ }
147
+ const version = (value as { version?: unknown } | null)?.version;
148
+ if (
149
+ typeof version !== "string" ||
150
+ !parsedVersion(version) ||
151
+ parsedVersion(version)!.pre
152
+ )
153
+ throw new Error("invalid_registry_response");
154
+ return version;
155
+ }
156
+
157
+ /** Always performs a fresh unauthenticated public-registry check. */
158
+ export async function checkLatestVersion(
159
+ runningVersion: string,
160
+ options: { fetch?: typeof fetch; timeoutMs?: number } = {},
161
+ ): Promise<LatestVersionCheck> {
162
+ const result: LatestVersionCheck = {
163
+ checkedAt: new Date().toISOString(),
164
+ latestVersion: null,
165
+ runningVersion,
166
+ status: "unavailable",
167
+ };
168
+ const controller = new AbortController();
169
+ const timeoutMs = Math.max(1, Math.min(options.timeoutMs ?? 5000, 5000));
170
+ let timer: ReturnType<typeof setTimeout> | undefined;
171
+ let timedOut = false;
172
+ try {
173
+ const latest = await Promise.race([
174
+ Promise.resolve().then(async () =>
175
+ boundedRegistryVersion(
176
+ await (options.fetch ?? globalThis.fetch)(LATEST_URL, {
177
+ credentials: "omit",
178
+ headers: { accept: "application/json" },
179
+ redirect: "error",
180
+ signal: controller.signal,
181
+ }),
182
+ controller.signal,
183
+ ),
184
+ ),
185
+ new Promise<never>((_, reject) => {
186
+ timer = setTimeout(() => {
187
+ timedOut = true;
188
+ controller.abort();
189
+ reject(new Error("timeout"));
190
+ }, timeoutMs);
191
+ }),
192
+ ]);
193
+ result.latestVersion = latest;
194
+ const comparison = compareVersions(runningVersion, latest);
195
+ if (comparison === undefined) {
196
+ result.reason = "invalid_running_version";
197
+ return result;
198
+ }
199
+ result.comparison =
200
+ comparison < 0 ? "older" : comparison > 0 ? "newer" : "equal";
201
+ result.status = parsedVersion(runningVersion)?.pre
202
+ ? "prerelease"
203
+ : comparison < 0
204
+ ? "outdated"
205
+ : comparison > 0
206
+ ? "newer"
207
+ : "current";
208
+ return result;
209
+ } catch (error) {
210
+ result.reason = timedOut
211
+ ? "timeout"
212
+ : error instanceof Error && error.message === "invalid_registry_response"
213
+ ? "invalid_registry_response"
214
+ : "registry_unavailable";
215
+ return result;
216
+ } finally {
217
+ clearTimeout(timer);
218
+ controller.abort();
219
+ }
220
+ }