@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
@@ -0,0 +1,249 @@
1
+ import path from "node:path";
2
+ import type { McpTransport } from "../installer-transport";
3
+
4
+ const installerTargets = ["codex", "claude", "copilot"] as const;
5
+ export type InstallerTarget = (typeof installerTargets)[number];
6
+ export type InstallerOperation = "install" | "update" | "uninstall";
7
+
8
+ export interface ParsedInstallerCommand {
9
+ operation: InstallerOperation;
10
+ options: {
11
+ host?: string;
12
+ port?: number;
13
+ root: string;
14
+ scope: "local" | "global";
15
+ service?: boolean;
16
+ targets: InstallerTarget[];
17
+ transport?: McpTransport;
18
+ };
19
+ }
20
+
21
+ function usageError(message: string): Error {
22
+ const error = new Error(message);
23
+ error.name = "InstallerUsageError";
24
+ return error;
25
+ }
26
+
27
+ function expandedTokens(args: string[]): string[] {
28
+ return args.flatMap((token) => {
29
+ const match = /^(--(?:scope|root|target|transport|host|port))=(.*)$/.exec(
30
+ token,
31
+ );
32
+ return match ? [match[1], match[2]] : [token];
33
+ });
34
+ }
35
+
36
+ function requiredValue(tokens: string[], index: number): string {
37
+ const value = tokens[index + 1];
38
+ if (!value || value.startsWith("-"))
39
+ throw usageError(`Missing value for ${tokens[index] ?? "option"}`);
40
+ return value;
41
+ }
42
+
43
+ function httpPort(value: string): number {
44
+ if (!/^\d+$/.test(value))
45
+ throw usageError(
46
+ `Invalid HTTP port "${value}"; expected an integer from 1 through 65535`,
47
+ );
48
+ const port = Number(value);
49
+ if (!Number.isInteger(port) || port < 1 || port > 65_535)
50
+ throw usageError(
51
+ `Invalid HTTP port "${value}"; expected an integer from 1 through 65535`,
52
+ );
53
+ return port;
54
+ }
55
+
56
+ function operationFrom(tokens: string[]): InstallerOperation {
57
+ const first = tokens[0];
58
+ if (first === "install" || first === "update" || first === "uninstall") {
59
+ tokens.shift();
60
+ return first;
61
+ }
62
+ return "install";
63
+ }
64
+
65
+ type MutableOptions = ParsedInstallerCommand["options"];
66
+
67
+ type ValueOptionHandler = (value: string, options: MutableOptions) => void;
68
+
69
+ const valueOptionHandlers: Record<string, ValueOptionHandler> = {
70
+ "--host": (value, options) => {
71
+ options.host = value;
72
+ },
73
+ "--port": (value, options) => {
74
+ options.port = httpPort(value);
75
+ },
76
+ "--root": (value, options) => {
77
+ options.root = value;
78
+ },
79
+ "--scope": (value, options) => {
80
+ options.scope = value as "local" | "global";
81
+ },
82
+ "--target": (value, options) => {
83
+ options.targets =
84
+ value === "all" ? [...installerTargets] : [value as InstallerTarget];
85
+ },
86
+ "--transport": (value, options) => {
87
+ options.transport = value as McpTransport;
88
+ },
89
+ };
90
+
91
+ valueOptionHandlers["-r"] = valueOptionHandlers["--root"] as ValueOptionHandler;
92
+ valueOptionHandlers["-s"] = valueOptionHandlers[
93
+ "--scope"
94
+ ] as ValueOptionHandler;
95
+ valueOptionHandlers["-t"] = valueOptionHandlers[
96
+ "--target"
97
+ ] as ValueOptionHandler;
98
+
99
+ function applyValueOption(
100
+ token: string,
101
+ value: string,
102
+ options: MutableOptions,
103
+ ): void {
104
+ const handler = valueOptionHandlers[token];
105
+ if (!handler) throw usageError(`Unknown option: ${token}`);
106
+ handler(value, options);
107
+ }
108
+
109
+ function validateOptions(options: MutableOptions): void {
110
+ if (options.scope !== "local" && options.scope !== "global")
111
+ throw usageError(
112
+ `Invalid scope "${options.scope}"; expected local or global`,
113
+ );
114
+ const invalidTarget = options.targets.find(
115
+ (target) => !installerTargets.includes(target),
116
+ );
117
+ if (invalidTarget)
118
+ throw usageError(
119
+ `Invalid target "${invalidTarget}"; expected codex, claude, copilot, or all`,
120
+ );
121
+ if (
122
+ options.transport &&
123
+ options.transport !== "stdio" &&
124
+ options.transport !== "http"
125
+ )
126
+ throw usageError(
127
+ `Invalid transport "${options.transport}"; expected stdio or http`,
128
+ );
129
+ }
130
+
131
+ export function parseInstallerArguments(
132
+ args: string[],
133
+ cwd: string,
134
+ ): ParsedInstallerCommand {
135
+ const tokens = expandedTokens(args);
136
+ const operation = operationFrom(tokens);
137
+ const options: MutableOptions = {
138
+ root: cwd,
139
+ scope: "local",
140
+ targets: [...installerTargets],
141
+ };
142
+ for (let index = 0; index < tokens.length; index += 1) {
143
+ const token = tokens[index] ?? "";
144
+ if (token === "--service" || token === "--no-service") {
145
+ const service = token === "--service";
146
+ if (options.service !== undefined && options.service !== service)
147
+ throw usageError("--service and --no-service cannot be used together");
148
+ options.service = service;
149
+ continue;
150
+ }
151
+ if (
152
+ ![
153
+ "--scope",
154
+ "-s",
155
+ "--root",
156
+ "-r",
157
+ "--target",
158
+ "-t",
159
+ "--transport",
160
+ "--host",
161
+ "--port",
162
+ ].includes(token)
163
+ )
164
+ throw usageError(`Unknown option: ${token}`);
165
+ applyValueOption(token, requiredValue(tokens, index), options);
166
+ index += 1;
167
+ }
168
+ validateOptions(options);
169
+ return { operation, options };
170
+ }
171
+
172
+ function codexPaths(global: boolean, root: string, home: string): string[] {
173
+ const base = global ? path.join(home, ".codex") : path.join(root, ".codex");
174
+ return [
175
+ path.join(base, "config.toml"),
176
+ path.join(base, "hooks.json"),
177
+ path.join(base, "hooks/ast-mcp.ts"),
178
+ path.join(base, "skills/ast-mcp"),
179
+ global ? path.join(base, "AGENTS.md") : path.join(root, "AGENTS.md"),
180
+ ];
181
+ }
182
+
183
+ function claudePaths(global: boolean, root: string, home: string): string[] {
184
+ const base = global ? path.join(home, ".claude") : path.join(root, ".claude");
185
+ return [
186
+ global ? path.join(home, ".claude.json") : path.join(root, ".mcp.json"),
187
+ path.join(base, "settings.json"),
188
+ path.join(base, "hooks/ast-mcp.ts"),
189
+ path.join(base, "skills/ast-mcp"),
190
+ global ? path.join(base, "CLAUDE.md") : path.join(root, "AGENTS.md"),
191
+ ];
192
+ }
193
+
194
+ function copilotPaths(global: boolean, root: string, home: string): string[] {
195
+ const base = global
196
+ ? path.join(home, ".copilot")
197
+ : path.join(root, ".github");
198
+ return [
199
+ global
200
+ ? path.join(base, "mcp-config.json")
201
+ : path.join(root, ".github/mcp.json"),
202
+ ...(global ? [] : [path.join(root, ".vscode/mcp.json")]),
203
+ path.join(base, "hooks/ast-mcp.json"),
204
+ path.join(base, "hooks/ast-mcp.ts"),
205
+ path.join(base, "skills/ast-mcp"),
206
+ global
207
+ ? path.join(base, "copilot-instructions.md")
208
+ : path.join(root, "AGENTS.md"),
209
+ ];
210
+ }
211
+
212
+ export function installerTargetPaths(
213
+ target: InstallerTarget,
214
+ global: boolean,
215
+ root: string,
216
+ home: string,
217
+ ): string[] {
218
+ if (target === "codex") return codexPaths(global, root, home);
219
+ if (target === "claude") return claudePaths(global, root, home);
220
+ return copilotPaths(global, root, home);
221
+ }
222
+
223
+ export function codexTransport(content: string): McpTransport | undefined {
224
+ const block = content.match(/# ast-mcp:begin\n([\s\S]*?)# ast-mcp:end/)?.[1];
225
+ if (!block) return undefined;
226
+ return /^\s*url\s*=/m.test(block) ? "http" : "stdio";
227
+ }
228
+
229
+ export function jsonTransport(
230
+ entry: Record<string, unknown> | undefined,
231
+ ): McpTransport | undefined {
232
+ if (!entry) return undefined;
233
+ return typeof entry.url === "string" ? "http" : "stdio";
234
+ }
235
+
236
+ export function jsonTargetConfig(
237
+ target: Exclude<InstallerTarget, "codex">,
238
+ global: boolean,
239
+ root: string,
240
+ home: string,
241
+ ): string {
242
+ if (target === "claude")
243
+ return global
244
+ ? path.join(home, ".claude.json")
245
+ : path.join(root, ".mcp.json");
246
+ return global
247
+ ? path.join(home, ".copilot/mcp-config.json")
248
+ : path.join(root, ".github/mcp.json");
249
+ }
@@ -0,0 +1,19 @@
1
+ export interface TextResult {
2
+ content: Array<{ type: string; text?: string }>;
3
+ isError?: boolean;
4
+ }
5
+
6
+ // biome-ignore lint/suspicious/noExplicitAny: Upstream JSON schemas are intentionally dynamic at this boundary.
7
+ export function parseTextResultJson(result: TextResult): Record<string, any> {
8
+ const text = result.content
9
+ .filter((item) => item.type === "text" && typeof item.text === "string")
10
+ .map((item) => item.text)
11
+ .join("\n");
12
+ if (result.isError) throw new Error(text || "ast-bro MCP call failed");
13
+ if (!text) throw new Error("ast-bro MCP returned no JSON text");
14
+ try {
15
+ return JSON.parse(text);
16
+ } catch (error) {
17
+ throw new Error(`Invalid ast-bro MCP JSON: ${text}`, { cause: error });
18
+ }
19
+ }
@@ -0,0 +1,31 @@
1
+ import * as z from "zod/v4";
2
+ import { FILE_READ_MAX_BATCH } from "../runtime/file-read";
3
+
4
+ export const chattrSchema = z.object({
5
+ chmod: z.number().int().min(0).max(0o777).optional(),
6
+ chown: z
7
+ .object({
8
+ gid: z.number().int().nonnegative(),
9
+ uid: z.number().int().nonnegative(),
10
+ })
11
+ .optional(),
12
+ });
13
+
14
+ export function boundedRecord<T extends z.ZodType>(schema: T, label: string) {
15
+ return z.record(z.string().min(1), schema).refine((value) => {
16
+ const size = Object.keys(value).length;
17
+ return size > 0 && size <= FILE_READ_MAX_BATCH;
18
+ }, label);
19
+ }
20
+
21
+ export function toolFailure(error: unknown) {
22
+ return {
23
+ content: [
24
+ {
25
+ text: error instanceof Error ? error.message : String(error),
26
+ type: "text" as const,
27
+ },
28
+ ],
29
+ isError: true,
30
+ };
31
+ }
@@ -0,0 +1,31 @@
1
+ type CapturedProcess = {
2
+ exited: Promise<number>;
3
+ stderr: ReadableStream<Uint8Array> | number | null | undefined;
4
+ stdout: ReadableStream<Uint8Array> | number | null | undefined;
5
+ };
6
+
7
+ export async function captureProcess(
8
+ processHandle: CapturedProcess,
9
+ ): Promise<{ exitCode: number; stderr: string; stdout: string }> {
10
+ const [exitCode, stdout, stderr] = await Promise.all([
11
+ processHandle.exited,
12
+ processHandle.stdout instanceof ReadableStream
13
+ ? new Response(processHandle.stdout).text()
14
+ : Promise.resolve(""),
15
+ processHandle.stderr instanceof ReadableStream
16
+ ? new Response(processHandle.stderr).text()
17
+ : Promise.resolve(""),
18
+ ]);
19
+ return { exitCode, stderr, stdout };
20
+ }
21
+
22
+ export function successfulProcessOutput(
23
+ command: string,
24
+ result: { exitCode: number; stderr: string; stdout: string },
25
+ ): string {
26
+ if (result.exitCode !== 0)
27
+ throw new Error(
28
+ result.stderr.trim() || `${command} exited with code ${result.exitCode}`,
29
+ );
30
+ return result.stdout.trimEnd();
31
+ }
@@ -0,0 +1,97 @@
1
+ export function normalizeNewlines(value: string): string {
2
+ return value.replace(/\r\n?/g, "\n");
3
+ }
4
+
5
+ export function normalizeWhitespaceLine(value: string): string {
6
+ const indent = value.match(/^[ \t]*/)?.[0] ?? "";
7
+ const body = value
8
+ .slice(indent.length)
9
+ .replace(/[ \t]+/g, " ")
10
+ .trimEnd();
11
+ return `${indent.replace(/\t/g, " ")}${body}`;
12
+ }
13
+
14
+ type Quote = '"' | "'" | "`";
15
+
16
+ class CompactSourceScanner {
17
+ private escaped = false;
18
+ private index = 0;
19
+ private quote: Quote | undefined;
20
+
21
+ constructor(private readonly source: string) {}
22
+
23
+ read(): string {
24
+ let output = "";
25
+ while (this.index < this.source.length) output += this.readCharacter();
26
+ return output;
27
+ }
28
+
29
+ private readCharacter(): string {
30
+ const character = this.source[this.index] ?? "";
31
+ if (this.quote) return this.readQuoted(character);
32
+ const quote = this.asQuote(character);
33
+ if (quote) return this.beginQuote(quote);
34
+ if (character === "/" && this.source[this.index + 1] === "/") {
35
+ this.skipLineComment();
36
+ return "";
37
+ }
38
+ if (character === "/" && this.source[this.index + 1] === "*") {
39
+ this.skipBlockComment();
40
+ return "";
41
+ }
42
+ this.index += 1;
43
+ return /\s/.test(character) ? "" : character.toLowerCase();
44
+ }
45
+
46
+ private readQuoted(character: string): string {
47
+ this.index += 1;
48
+ if (this.escaped) this.escaped = false;
49
+ else if (character === "\\") this.escaped = true;
50
+ else if (character === this.quote) this.quote = undefined;
51
+ return character.toLowerCase();
52
+ }
53
+
54
+ private asQuote(character: string): Quote | undefined {
55
+ return character === '"' || character === "'" || character === "`"
56
+ ? character
57
+ : undefined;
58
+ }
59
+
60
+ private beginQuote(quote: Quote): string {
61
+ this.quote = quote;
62
+ this.index += 1;
63
+ return quote;
64
+ }
65
+
66
+ private skipLineComment(): void {
67
+ const newline = this.source.indexOf("\n", this.index + 2);
68
+ this.index = newline < 0 ? this.source.length : newline + 1;
69
+ }
70
+
71
+ private skipBlockComment(): void {
72
+ const terminator = this.source.indexOf("*/", this.index + 2);
73
+ this.index = terminator < 0 ? this.source.length : terminator + 2;
74
+ }
75
+ }
76
+
77
+ export function compactCallSyntax(source: string): string {
78
+ return new CompactSourceScanner(source)
79
+ .read()
80
+ .replaceAll("tools?.", "tools.");
81
+ }
82
+ export function containsToolInvocation(
83
+ source: string,
84
+ tools: Iterable<string>,
85
+ ): boolean {
86
+ const value = compactCallSyntax(source);
87
+ return [...tools].some((tool) =>
88
+ [
89
+ `tools.${tool}(`,
90
+ `tools.${tool}?.(`,
91
+ `tools["${tool}"](`,
92
+ `tools["${tool}"]?.(`,
93
+ `tools['${tool}'](`,
94
+ `tools['${tool}']?.(`,
95
+ ].some((syntax) => value.includes(syntax)),
96
+ );
97
+ }
package/src/hook.ts CHANGED
@@ -1,52 +1,145 @@
1
- const direct =
2
- /^(?:apply_patch|edit|editFiles|create|createFile|write|writeFile|replace|str_replace|MultiEdit|Edit|Write|NotebookEdit)$/;
3
- const nestedDirect =
4
- /tools(?:\.(?:apply_patch|edit|editFiles|create|createFile|write|writeFile|replace|str_replace|MultiEdit|Edit|Write|NotebookEdit)|\s*\[\s*["'](?:apply_patch|edit|editFiles|create|createFile|write|writeFile|replace|str_replace|MultiEdit|Edit|Write|NotebookEdit)["']\s*\])\s*\(/;
5
- const shell =
6
- /^(?:bash|shell|terminal|exec|functions\.exec|mcp__functions__exec|codex\.exec|exec_command|functions\.exec_command|Bash|powershell|PowerShell)$/;
7
- const mutation =
8
- /(?:^|[;&|]\s*|["'`]\s*|:\s*["'`]\s*)(?:(?:env(?:\s+(?:--?[^\s"'`]+|[A-Za-z_][A-Za-z0-9_]*=[^\s"'`]+))*|command|sudo(?:\s+--?[^\s"'`]+)*|nice(?:\s+--?[^\s"'`]+)*|nohup|busybox)\s+)*(?:(?:\/[^\s/"'`]+)*\/)?(?:apply_patch|patch|tee|truncate|touch|rm|mv|cp|install|dd|ed|awk|mkdir|rmdir|chmod|chown|python\d*|node|ruby|perl|php|sed|ast-grep)(?=\s|["'`]|$)|(?:^|[;&|]\s*|["'`]\s*|:\s*["'`]\s*)(?:find\b[^\n]*\s-delete\b|xargs\s+(?:[^\n]*\s)?rm\b|git(?:\s+(?:-[A-Za-z]\s+[^\s"'`]+|--?[^\s"'`]+))*\s+(?:apply|checkout|restore|reset|clean)|dprint\s+fmt|bun\s+(?:-e|--eval)|(?:Set|Add)-Content|Out-File|Remove-Item|Move-Item|Copy-Item|New-Item)(?=\s|["'`]|$)|(?:^|[^<\d>])>{1,2}(?!=)|<<[-~]?\s*\w/i;
1
+ import { currentConfig } from "./config";
2
+ import {
3
+ eventCommand,
4
+ type HookPolicy,
5
+ policyMatches,
6
+ toolIdentity,
7
+ } from "./helpers/hook";
8
+ import {
9
+ compactCallSyntax as compactCallSyntaxHelper,
10
+ containsToolInvocation,
11
+ } from "./helpers/string";
12
+ import { embeddedShellMutates, shellMutates } from "./shell-policy";
13
+
14
+ const directTools = new Set([
15
+ "apply_patch",
16
+ "edit",
17
+ "editfiles",
18
+ "create",
19
+ "createfile",
20
+ "write",
21
+ "writefile",
22
+ "replace",
23
+ "rename",
24
+ "renamefile",
25
+ "move",
26
+ "movefile",
27
+ "filerename",
28
+ "str_replace",
29
+ "multiedit",
30
+ "notebookedit",
31
+ ]);
32
+ function _compactCallSyntax(source: string) {
33
+ return compactCallSyntaxHelper(source);
34
+ }
35
+
36
+ function nestedDirect(source: string) {
37
+ return containsToolInvocation(_compactCallSyntax(source), directTools);
38
+ }
39
+ const shellTools = new Set([
40
+ "bash",
41
+ "shell",
42
+ "terminal",
43
+ "exec_command",
44
+ "functions.exec_command",
45
+ "powershell",
46
+ "pwsh",
47
+ ]);
48
+
49
+ const executorTools = new Set([
50
+ "exec",
51
+ "functions.exec",
52
+ "mcp__functions__exec",
53
+ "codex.exec",
54
+ ]);
55
+
56
+ function nestedShellCall(source: string) {
57
+ return containsToolInvocation(source, [
58
+ "exec_command",
59
+ "bash",
60
+ "shell",
61
+ "terminal",
62
+ "powershell",
63
+ "pwsh",
64
+ ]);
65
+ }
9
66
 
10
- const nestedInterpreter =
11
- /(?:bash|sh|zsh|dash|ksh|fish|pwsh|powershell|node|python\d*|ruby|perl|php)(?:["']|\s)+(?:--?[A-Za-z][A-Za-z0-9-]*(?:=[^\s"']+)?(?:["']|\s)+)*(?:-c|--command|-Command|-e|--eval)(?=\s|["']|$)/i;
12
67
  export interface HookDecision {
13
68
  denied: boolean;
14
69
  reason?: string;
15
70
  }
16
- export function evaluateHook(event: Record<string, unknown>): HookDecision {
17
- const name = String(event.tool_name ?? event.toolName ?? event.name ?? "");
18
- if (direct.test(name))
71
+ function policyDecision(
72
+ policy: HookPolicy,
73
+ identity: ReturnType<typeof toolIdentity>,
74
+ ): HookDecision | undefined {
75
+ if (!policy.enabled) return { denied: false };
76
+ if (policyMatches(policy.blockTools, identity))
19
77
  return {
20
78
  denied: true,
21
- reason: "Direct file editing is blocked. Use ast-mcp.",
79
+ reason: `Tool ${identity.name || "<unknown>"} is blocked by ast-mcp hook policy.`,
22
80
  };
23
- if (!shell.test(name)) return { denied: false };
24
- const raw =
25
- event.tool_input ??
26
- event.toolInput ??
27
- event.toolArgs ??
28
- event.input ??
29
- event.args;
30
- const input =
31
- raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
32
- const command =
33
- typeof raw === "string"
34
- ? raw
35
- : String(
36
- input.cmd ??
37
- input.command ??
38
- input.script ??
39
- input.source ??
40
- input.code ??
41
- "",
42
- );
43
- return command &&
44
- (nestedDirect.test(command) ||
45
- mutation.test(command) ||
46
- nestedInterpreter.test(command))
47
- ? { denied: true, reason: "Direct file mutation is blocked. Use ast-mcp." }
81
+ if (policyMatches(policy.allowTools, identity)) return { denied: false };
82
+ return undefined;
83
+ }
84
+ function isDirectTool(identity: ReturnType<typeof toolIdentity>) {
85
+ return (
86
+ directTools.has(identity.normalizedName) ||
87
+ directTools.has(identity.shortName)
88
+ );
89
+ }
90
+ const deniedMutation = (): HookDecision => ({
91
+ denied: true,
92
+ reason: "Route manual file mutation through ast-mcp.",
93
+ });
94
+
95
+ function executorDecision(
96
+ executor: boolean,
97
+ command: string | undefined,
98
+ raw: unknown,
99
+ ): HookDecision | undefined {
100
+ const nestedMutation =
101
+ command &&
102
+ (nestedDirect(command) ||
103
+ (nestedShellCall(command) && embeddedShellMutates(command)));
104
+ if (executor && nestedMutation) return deniedMutation();
105
+ if (executor && typeof raw === "string") return { denied: false };
106
+ return undefined;
107
+ }
108
+
109
+ function shellDecision(command: string | undefined): HookDecision {
110
+ return command && shellMutates(command)
111
+ ? deniedMutation()
48
112
  : { denied: false };
49
113
  }
114
+
115
+ function commandDecision(
116
+ event: Record<string, unknown>,
117
+ identity: ReturnType<typeof toolIdentity>,
118
+ ): HookDecision {
119
+ const { command, raw } = eventCommand(event);
120
+ const executor = executorTools.has(identity.normalizedName);
121
+ const executorResult = executorDecision(executor, command, raw);
122
+ if (executorResult) return executorResult;
123
+ const shell =
124
+ shellTools.has(identity.normalizedName) ||
125
+ shellTools.has(identity.shortName);
126
+ if (!executor && !shell) return { denied: false };
127
+ return shellDecision(command);
128
+ }
129
+ export function evaluateHook(
130
+ event: Record<string, unknown>,
131
+ policy: HookPolicy = { allowTools: [], blockTools: [], enabled: true },
132
+ ): HookDecision {
133
+ const identity = toolIdentity(event);
134
+ const configured = policyDecision(policy, identity);
135
+ if (configured) return configured;
136
+ if (isDirectTool(identity))
137
+ return {
138
+ denied: true,
139
+ reason: "Route direct file editing through ast-mcp.",
140
+ };
141
+ return commandDecision(event, identity);
142
+ }
50
143
  export function decisionPayload(
51
144
  decision: HookDecision,
52
145
  ): Record<string, unknown> {
@@ -65,8 +158,10 @@ export async function runHook(
65
158
  input: Promise<Record<string, unknown>> = Bun.stdin.json(),
66
159
  ): Promise<number> {
67
160
  try {
161
+ const event = await input;
162
+ const policy = (await currentConfig()).safety.hook;
68
163
  process.stdout.write(
69
- `${JSON.stringify(decisionPayload(evaluateHook(await input)))}\n`,
164
+ `${JSON.stringify(decisionPayload(evaluateHook(event, policy)))}\n`,
70
165
  );
71
166
  return 0;
72
167
  } catch (error) {
package/src/http-entry.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { startHttpServer } from "./http";
2
2
 
3
- startHttpServer();
3
+ await startHttpServer();