@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.
- package/README.md +59 -20
- package/dist/ast-mcp.js +232 -130
- package/dist/ast-mcp.js.map +107 -27
- package/package.json +2 -1
- package/src/ast-bro/capability.ts +3 -8
- package/src/ast-bro/client.ts +18 -2
- package/src/ast-bro/result.ts +5 -12
- package/src/cli.ts +70 -95
- package/src/config-cli.ts +54 -0
- package/src/config.ts +886 -0
- package/src/helpers/aider.ts +252 -0
- package/src/helpers/ast-bro.ts +64 -0
- package/src/helpers/config.ts +149 -0
- package/src/helpers/hook.ts +60 -0
- package/src/helpers/installer.ts +249 -0
- package/src/helpers/json.ts +19 -0
- package/src/helpers/mcp-schema.ts +31 -0
- package/src/helpers/process.ts +31 -0
- package/src/helpers/string.ts +97 -0
- package/src/hook.ts +135 -40
- package/src/http-entry.ts +1 -1
- package/src/http.ts +118 -103
- package/src/installer-transport.ts +190 -0
- package/src/installer.ts +579 -242
- package/src/mcp-cli.ts +104 -0
- package/src/patch/aider.ts +6 -199
- package/src/patch/engine.ts +271 -197
- package/src/runtime/dependencies.ts +48 -29
- package/src/runtime/file-delete.ts +13 -9
- package/src/runtime/file-read.ts +91 -57
- package/src/runtime/file-rename.ts +158 -0
- package/src/runtime/format.ts +57 -34
- package/src/runtime/paths.ts +30 -16
- package/src/runtime/policy.ts +21 -0
- package/src/runtime/process-input.ts +14 -4
- package/src/service.ts +219 -0
- package/src/shell-policy.ts +331 -0
- package/src/stdio.ts +47 -35
- package/src/tools/ast-bro.ts +12 -6
- package/src/tools/configured.ts +28 -0
- package/src/tools/files.ts +24 -27
- package/src/tools/index.ts +5 -3
- package/src/tools/lifecycle.ts +69 -55
- package/templates/skills/ast-mcp/SKILL.md +7 -6
- package/templates/skills/ast-mcp/evals/batch.evals.json +48 -0
- package/templates/skills/ast-mcp/evals/evals.json +1 -0
- package/templates/skills/ast-mcp/evals/score.test.ts +175 -0
- package/templates/skills/ast-mcp/evals/score.ts +304 -267
- package/templates/skills/ast-mcp/evals/semantic.test.ts +322 -0
- package/templates/skills/ast-mcp/evals/semantic.ts +390 -135
- package/templates/skills/ast-mcp/evals/shell-policy.ts +252 -0
- package/templates/skills/ast-mcp/evals/source.test.ts +46 -0
- package/templates/skills/ast-mcp/evals/source.ts +164 -0
- package/templates/skills/ast-mcp/evals/trigger-queries.json +1 -1
- package/templates/skills/ast-mcp/references/installation.md +9 -8
- package/templates/skills/ast-mcp/references/patch-state-machine.md +5 -5
- package/templates/skills/ast-mcp/references/tool-catalog.md +4 -2
- package/templates/skills/ast-mcp/scripts/check-install.ts +312 -110
package/src/service.ts
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstat, mkdir, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { createServer } from "node:net";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import type { HttpEndpoint } from "./installer-transport";
|
|
6
|
+
|
|
7
|
+
export type ServiceScope = "local" | "global";
|
|
8
|
+
export type ServiceCommandRunner = (
|
|
9
|
+
command: string[],
|
|
10
|
+
ignoreFailure?: boolean,
|
|
11
|
+
) => Promise<void>;
|
|
12
|
+
|
|
13
|
+
export interface ServiceOptions {
|
|
14
|
+
cliEntry: string;
|
|
15
|
+
endpoint: HttpEndpoint;
|
|
16
|
+
home: string;
|
|
17
|
+
platform?: NodeJS.Platform;
|
|
18
|
+
root: string;
|
|
19
|
+
runner?: ServiceCommandRunner;
|
|
20
|
+
scope: ServiceScope;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ServicePlan {
|
|
24
|
+
content: string;
|
|
25
|
+
file: string;
|
|
26
|
+
id: string;
|
|
27
|
+
installCommands: string[][];
|
|
28
|
+
removeCommands: string[][];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function xml(value: string) {
|
|
32
|
+
return value
|
|
33
|
+
.replaceAll("&", "&")
|
|
34
|
+
.replaceAll("<", "<")
|
|
35
|
+
.replaceAll(">", ">")
|
|
36
|
+
.replaceAll('"', """)
|
|
37
|
+
.replaceAll("'", "'");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function systemd(value: string) {
|
|
41
|
+
return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function serviceIdentity(scope: ServiceScope, root: string) {
|
|
45
|
+
if (scope === "global") return "ast-mcp";
|
|
46
|
+
const digest = createHash("sha256")
|
|
47
|
+
.update(path.resolve(root))
|
|
48
|
+
.digest("hex")
|
|
49
|
+
.slice(0, 12);
|
|
50
|
+
return `ast-mcp-${digest}`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function createServicePlan(options: ServiceOptions): ServicePlan {
|
|
54
|
+
const platform = options.platform ?? process.platform;
|
|
55
|
+
if (platform === "win32")
|
|
56
|
+
throw new Error(
|
|
57
|
+
"Managed ast-mcp services are not supported on Windows; start `ast-mcp mcp --transport http` manually",
|
|
58
|
+
);
|
|
59
|
+
if (platform !== "darwin" && platform !== "linux")
|
|
60
|
+
throw new Error(
|
|
61
|
+
`Managed ast-mcp services are not supported on ${platform}; start the HTTP transport manually`,
|
|
62
|
+
);
|
|
63
|
+
const id = serviceIdentity(options.scope, options.root);
|
|
64
|
+
const args = [
|
|
65
|
+
options.cliEntry,
|
|
66
|
+
"mcp",
|
|
67
|
+
"--transport",
|
|
68
|
+
"http",
|
|
69
|
+
"--host",
|
|
70
|
+
options.endpoint.host,
|
|
71
|
+
"--port",
|
|
72
|
+
String(options.endpoint.port),
|
|
73
|
+
];
|
|
74
|
+
const environment =
|
|
75
|
+
options.scope === "local"
|
|
76
|
+
? { AST_MCP_PROJECT_ROOT: path.resolve(options.root) }
|
|
77
|
+
: {};
|
|
78
|
+
if (platform === "darwin") {
|
|
79
|
+
const label = `com.mwillbanks.${id}`;
|
|
80
|
+
const file = path.join(
|
|
81
|
+
options.home,
|
|
82
|
+
"Library/LaunchAgents",
|
|
83
|
+
`${label}.plist`,
|
|
84
|
+
);
|
|
85
|
+
const state = path.join(options.home, ".local/state/ast-mcp");
|
|
86
|
+
const programArguments = [process.execPath, ...args]
|
|
87
|
+
.map((value) => ` <string>${xml(value)}</string>`)
|
|
88
|
+
.join("\n");
|
|
89
|
+
const environmentVariables = Object.entries(environment)
|
|
90
|
+
.map(
|
|
91
|
+
([name, value]) =>
|
|
92
|
+
` <key>${xml(name)}</key>\n <string>${xml(value)}</string>`,
|
|
93
|
+
)
|
|
94
|
+
.join("\n");
|
|
95
|
+
const environmentBlock = environmentVariables
|
|
96
|
+
? `\n <key>EnvironmentVariables</key>\n <dict>\n${environmentVariables}\n </dict>`
|
|
97
|
+
: "";
|
|
98
|
+
const content = `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n <key>Label</key>\n <string>${label}</string>\n <key>ProgramArguments</key>\n <array>\n${programArguments}\n </array>${environmentBlock}\n <key>WorkingDirectory</key>\n <string>${xml(options.scope === "local" ? path.resolve(options.root) : options.home)}</string>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <true/>\n <key>StandardOutPath</key>\n <string>${xml(path.join(state, `${id}.out.log`))}</string>\n <key>StandardErrorPath</key>\n <string>${xml(path.join(state, `${id}.err.log`))}</string>\n</dict>\n</plist>\n`;
|
|
99
|
+
const domain = `gui/${typeof process.getuid === "function" ? process.getuid() : 501}`;
|
|
100
|
+
return {
|
|
101
|
+
content,
|
|
102
|
+
file,
|
|
103
|
+
id,
|
|
104
|
+
installCommands: [
|
|
105
|
+
["launchctl", "bootout", domain, file],
|
|
106
|
+
["launchctl", "bootstrap", domain, file],
|
|
107
|
+
["launchctl", "kickstart", "-k", `${domain}/${label}`],
|
|
108
|
+
],
|
|
109
|
+
removeCommands: [["launchctl", "bootout", domain, file]],
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
const file = path.join(options.home, ".config/systemd/user", `${id}.service`);
|
|
113
|
+
const environmentLines = Object.entries(environment)
|
|
114
|
+
.map(([name, value]) => `Environment="${name}=${systemd(value)}"`)
|
|
115
|
+
.join("\n");
|
|
116
|
+
const command = [process.execPath, ...args]
|
|
117
|
+
.map((value) => `"${systemd(value)}"`)
|
|
118
|
+
.join(" ");
|
|
119
|
+
const workingDirectory = systemd(
|
|
120
|
+
options.scope === "local" ? path.resolve(options.root) : options.home,
|
|
121
|
+
);
|
|
122
|
+
const content = `[Unit]\nDescription=ast-mcp Streamable HTTP (${id})\nAfter=network.target\n\n[Service]\nType=simple\nWorkingDirectory="${workingDirectory}"\n${environmentLines ? `${environmentLines}\n` : ""}ExecStart=${command}\nRestart=on-failure\nRestartSec=2\n\n[Install]\nWantedBy=default.target\n`;
|
|
123
|
+
return {
|
|
124
|
+
content,
|
|
125
|
+
file,
|
|
126
|
+
id,
|
|
127
|
+
installCommands: [
|
|
128
|
+
["systemctl", "--user", "daemon-reload"],
|
|
129
|
+
["systemctl", "--user", "enable", "--now", `${id}.service`],
|
|
130
|
+
],
|
|
131
|
+
removeCommands: [
|
|
132
|
+
["systemctl", "--user", "disable", "--now", `${id}.service`],
|
|
133
|
+
],
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function assertPortAvailable(endpoint: HttpEndpoint) {
|
|
138
|
+
const server = createServer();
|
|
139
|
+
try {
|
|
140
|
+
await new Promise<void>((resolve, reject) => {
|
|
141
|
+
server.once("error", reject);
|
|
142
|
+
server.listen(endpoint.port, endpoint.host, resolve);
|
|
143
|
+
});
|
|
144
|
+
} catch (error) {
|
|
145
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
146
|
+
throw new Error(
|
|
147
|
+
code === "EADDRINUSE"
|
|
148
|
+
? `Cannot install the managed service because ${endpoint.host}:${endpoint.port} is already in use`
|
|
149
|
+
: `Cannot bind managed service endpoint ${endpoint.host}:${endpoint.port}: ${error instanceof Error ? error.message : String(error)}`,
|
|
150
|
+
);
|
|
151
|
+
} finally {
|
|
152
|
+
if (server.listening)
|
|
153
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export const runServiceCommand: ServiceCommandRunner = async (
|
|
158
|
+
command,
|
|
159
|
+
ignoreFailure,
|
|
160
|
+
) => {
|
|
161
|
+
const child = Bun.spawn(command, { stderr: "pipe", stdout: "pipe" });
|
|
162
|
+
const [exitCode, stderr] = await Promise.all([
|
|
163
|
+
child.exited,
|
|
164
|
+
new Response(child.stderr).text(),
|
|
165
|
+
]);
|
|
166
|
+
if (exitCode !== 0 && !ignoreFailure)
|
|
167
|
+
throw new Error(
|
|
168
|
+
`Service command failed (${command.join(" ")}): ${stderr.trim() || `exit ${exitCode}`}`,
|
|
169
|
+
);
|
|
170
|
+
};
|
|
171
|
+
const defaultRunner = runServiceCommand;
|
|
172
|
+
|
|
173
|
+
export async function waitForService(url: string) {
|
|
174
|
+
for (let attempt = 0; attempt < 25; attempt += 1) {
|
|
175
|
+
try {
|
|
176
|
+
const response = await fetch(url);
|
|
177
|
+
if (response.status < 500) return;
|
|
178
|
+
} catch {
|
|
179
|
+
// The service may still be starting.
|
|
180
|
+
}
|
|
181
|
+
await Bun.sleep(100);
|
|
182
|
+
}
|
|
183
|
+
throw new Error(`Managed ast-mcp service did not become ready at ${url}`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function preflightService(options: ServiceOptions) {
|
|
187
|
+
const plan = createServicePlan(options);
|
|
188
|
+
if (!(await lstat(plan.file).catch(() => undefined)))
|
|
189
|
+
await assertPortAvailable(options.endpoint);
|
|
190
|
+
return plan;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export async function installService(options: ServiceOptions) {
|
|
194
|
+
const plan = await preflightService(options);
|
|
195
|
+
const runner = options.runner ?? defaultRunner;
|
|
196
|
+
await mkdir(path.dirname(plan.file), { recursive: true });
|
|
197
|
+
if ((options.platform ?? process.platform) === "darwin")
|
|
198
|
+
await mkdir(path.join(options.home, ".local/state/ast-mcp"), {
|
|
199
|
+
recursive: true,
|
|
200
|
+
});
|
|
201
|
+
await writeFile(plan.file, plan.content);
|
|
202
|
+
for (let index = 0; index < plan.installCommands.length; index += 1)
|
|
203
|
+
await runner(
|
|
204
|
+
plan.installCommands[index],
|
|
205
|
+
index === 0 && plan.installCommands[index][0] === "launchctl",
|
|
206
|
+
);
|
|
207
|
+
if (!options.runner) await waitForService(options.endpoint.url);
|
|
208
|
+
return plan;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export async function removeService(options: ServiceOptions) {
|
|
212
|
+
const plan = createServicePlan(options);
|
|
213
|
+
const runner = options.runner ?? defaultRunner;
|
|
214
|
+
for (const command of plan.removeCommands) await runner(command, true);
|
|
215
|
+
await rm(plan.file, { force: true });
|
|
216
|
+
if ((options.platform ?? process.platform) === "linux")
|
|
217
|
+
await runner(["systemctl", "--user", "daemon-reload"], true);
|
|
218
|
+
return plan;
|
|
219
|
+
}
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { type Command, parse } from "unbash";
|
|
2
|
+
|
|
3
|
+
const mutators = new Set([
|
|
4
|
+
"apply_patch",
|
|
5
|
+
"patch",
|
|
6
|
+
"truncate",
|
|
7
|
+
"touch",
|
|
8
|
+
"rm",
|
|
9
|
+
"unlink",
|
|
10
|
+
"mv",
|
|
11
|
+
"rename",
|
|
12
|
+
"ed",
|
|
13
|
+
"set-content",
|
|
14
|
+
"add-content",
|
|
15
|
+
"clear-content",
|
|
16
|
+
"out-file",
|
|
17
|
+
"remove-item",
|
|
18
|
+
"move-item",
|
|
19
|
+
"new-item",
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
const wrappers = new Set([
|
|
23
|
+
"env",
|
|
24
|
+
"command",
|
|
25
|
+
"builtin",
|
|
26
|
+
"exec",
|
|
27
|
+
"sudo",
|
|
28
|
+
"doas",
|
|
29
|
+
"nice",
|
|
30
|
+
"nohup",
|
|
31
|
+
"stdbuf",
|
|
32
|
+
"busybox",
|
|
33
|
+
"timeout",
|
|
34
|
+
"chrt",
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
const wrapperValueOptions: Record<string, Set<string>> = {
|
|
38
|
+
doas: new Set([
|
|
39
|
+
"-u",
|
|
40
|
+
"-g",
|
|
41
|
+
"-p",
|
|
42
|
+
"-r",
|
|
43
|
+
"-t",
|
|
44
|
+
"-C",
|
|
45
|
+
"-D",
|
|
46
|
+
"-R",
|
|
47
|
+
"-T",
|
|
48
|
+
"--user",
|
|
49
|
+
"--group",
|
|
50
|
+
"--prompt",
|
|
51
|
+
"--role",
|
|
52
|
+
"--type",
|
|
53
|
+
"--close-from",
|
|
54
|
+
"--chdir",
|
|
55
|
+
"--chroot",
|
|
56
|
+
"--command-timeout",
|
|
57
|
+
]),
|
|
58
|
+
env: new Set(["-u", "-C", "--unset", "--chdir"]),
|
|
59
|
+
nice: new Set(["-n", "--adjustment"]),
|
|
60
|
+
sudo: new Set([
|
|
61
|
+
"-u",
|
|
62
|
+
"-g",
|
|
63
|
+
"-p",
|
|
64
|
+
"-r",
|
|
65
|
+
"-t",
|
|
66
|
+
"-C",
|
|
67
|
+
"-D",
|
|
68
|
+
"-R",
|
|
69
|
+
"-T",
|
|
70
|
+
"--user",
|
|
71
|
+
"--group",
|
|
72
|
+
"--prompt",
|
|
73
|
+
"--role",
|
|
74
|
+
"--type",
|
|
75
|
+
"--close-from",
|
|
76
|
+
"--chdir",
|
|
77
|
+
"--chroot",
|
|
78
|
+
"--command-timeout",
|
|
79
|
+
]),
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
function commandName(value = "") {
|
|
83
|
+
return value.split("/").at(-1)?.toLowerCase() ?? "";
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function skipWrapper(values: string[], index: number) {
|
|
87
|
+
const wrapper = commandName(values[index]);
|
|
88
|
+
let cursor = index + 1;
|
|
89
|
+
while (values[cursor]?.startsWith("-")) {
|
|
90
|
+
const option = values[cursor] as string;
|
|
91
|
+
cursor += wrapperValueOptions[wrapper]?.has(option) ? 2 : 1;
|
|
92
|
+
}
|
|
93
|
+
if (wrapper === "env")
|
|
94
|
+
while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(values[cursor] ?? "")) cursor += 1;
|
|
95
|
+
if ((wrapper === "timeout" || wrapper === "chrt") && cursor < values.length)
|
|
96
|
+
cursor += 1;
|
|
97
|
+
return cursor;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function executable(command: Command) {
|
|
101
|
+
const values = [command.name, ...command.suffix].map(
|
|
102
|
+
(word) => word?.value ?? "",
|
|
103
|
+
);
|
|
104
|
+
let index = 0;
|
|
105
|
+
while (wrappers.has(commandName(values[index])))
|
|
106
|
+
index = skipWrapper(values, index);
|
|
107
|
+
return { args: values.slice(index + 1), name: commandName(values[index]) };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function inlineMutates(source: string) {
|
|
111
|
+
const value = source.toLowerCase();
|
|
112
|
+
if (
|
|
113
|
+
[
|
|
114
|
+
"writefile(",
|
|
115
|
+
"writefilesync(",
|
|
116
|
+
"appendfile(",
|
|
117
|
+
"appendfilesync(",
|
|
118
|
+
"bun.write(",
|
|
119
|
+
"deno.write",
|
|
120
|
+
".write_text(",
|
|
121
|
+
".write_bytes(",
|
|
122
|
+
"unlink(",
|
|
123
|
+
"unlinksync(",
|
|
124
|
+
"rmsync(",
|
|
125
|
+
"truncate(",
|
|
126
|
+
"truncatesync(",
|
|
127
|
+
"mkdir(",
|
|
128
|
+
"rename(",
|
|
129
|
+
"renamesync(",
|
|
130
|
+
].some((marker) => value.includes(marker))
|
|
131
|
+
)
|
|
132
|
+
return true;
|
|
133
|
+
const opens = value.includes("open(") || value.includes("opensync(");
|
|
134
|
+
return (
|
|
135
|
+
opens &&
|
|
136
|
+
([', "w', ", 'w", ', "a', ", 'a", ', "x', ", 'x", ', "r+', ", 'r+"].some(
|
|
137
|
+
(marker) => value.includes(marker),
|
|
138
|
+
) ||
|
|
139
|
+
/\bmode\s*=\s*["'](?:[wax]|r\+)/.test(value))
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function payloadAfter(args: string[], flags: string[]) {
|
|
144
|
+
const index = args.findIndex(
|
|
145
|
+
(arg) =>
|
|
146
|
+
flags.includes(arg) || flags.some((flag) => arg.startsWith(`${flag}=`)),
|
|
147
|
+
);
|
|
148
|
+
if (index < 0) return undefined;
|
|
149
|
+
const argument = args[index];
|
|
150
|
+
const separator = argument.indexOf("=");
|
|
151
|
+
return separator >= 0 ? argument.slice(separator + 1) : args[index + 1];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
type CommandMutationHandler = (args: string[]) => boolean;
|
|
155
|
+
|
|
156
|
+
function sedMutates(args: string[]) {
|
|
157
|
+
return args.some(
|
|
158
|
+
(arg) =>
|
|
159
|
+
arg === "--in-place" ||
|
|
160
|
+
arg.startsWith("--in-place=") ||
|
|
161
|
+
/^-[^-]*i/.test(arg),
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function astGrepMutates(args: string[]) {
|
|
166
|
+
const rewrites = args.some(
|
|
167
|
+
(arg) => arg === "--rewrite" || arg.startsWith("--rewrite="),
|
|
168
|
+
);
|
|
169
|
+
return rewrites && args.some((arg) => arg === "-U" || arg === "--update-all");
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function findMutates(args: string[]) {
|
|
173
|
+
if (args.includes("-delete")) return true;
|
|
174
|
+
const action = args.findIndex((arg) =>
|
|
175
|
+
["-exec", "-execdir", "-ok", "-okdir"].includes(arg),
|
|
176
|
+
);
|
|
177
|
+
return action >= 0 && shellMutates(args.slice(action + 1).join(" "));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function shellInterpreterMutates(args: string[]) {
|
|
181
|
+
const grouped = args.findIndex((arg) => /^-[A-Za-z]*c[A-Za-z]*$/.test(arg));
|
|
182
|
+
const payload =
|
|
183
|
+
payloadAfter(args, ["-c", "--command", "-Command"]) ??
|
|
184
|
+
(grouped >= 0 ? args[grouped + 1] : undefined);
|
|
185
|
+
return payload ? shellMutates(payload) : false;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function inlineInterpreterMutates(name: string, args: string[]) {
|
|
189
|
+
const flags = name.startsWith("python") ? ["-c"] : ["-e", "--eval"];
|
|
190
|
+
const payload = payloadAfter(args, flags);
|
|
191
|
+
return payload ? inlineMutates(payload) : false;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const shellInterpreters = new Set([
|
|
195
|
+
"bash",
|
|
196
|
+
"sh",
|
|
197
|
+
"zsh",
|
|
198
|
+
"dash",
|
|
199
|
+
"ksh",
|
|
200
|
+
"fish",
|
|
201
|
+
"pwsh",
|
|
202
|
+
"powershell",
|
|
203
|
+
]);
|
|
204
|
+
const mutationHandlers: Record<string, CommandMutationHandler> = {
|
|
205
|
+
"ast-grep": astGrepMutates,
|
|
206
|
+
eval: (args) => shellMutates(args.join(" ")),
|
|
207
|
+
find: findMutates,
|
|
208
|
+
sed: sedMutates,
|
|
209
|
+
xargs: (args) => shellMutates(args.join(" ")),
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
function originalCommandDecision(
|
|
213
|
+
original: string,
|
|
214
|
+
args: string[],
|
|
215
|
+
): boolean | undefined {
|
|
216
|
+
if (
|
|
217
|
+
original === "command" &&
|
|
218
|
+
args.some((arg) => arg === "-v" || arg === "-V")
|
|
219
|
+
)
|
|
220
|
+
return false;
|
|
221
|
+
if (original !== "env") return undefined;
|
|
222
|
+
const dispatched = payloadAfter(args, ["-S", "--split-string"]);
|
|
223
|
+
return dispatched ? shellMutates(dispatched) : undefined;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function commandMutates(command: Command) {
|
|
227
|
+
const original = commandName(command.name?.value);
|
|
228
|
+
const originalArgs = command.suffix.map((word) => word.value);
|
|
229
|
+
const originalDecision = originalCommandDecision(original, originalArgs);
|
|
230
|
+
if (originalDecision !== undefined) return originalDecision;
|
|
231
|
+
const { args, name } = executable(command);
|
|
232
|
+
if (name === "git") return false;
|
|
233
|
+
if (mutators.has(name)) return true;
|
|
234
|
+
const handler = mutationHandlers[name];
|
|
235
|
+
if (handler) return handler(args);
|
|
236
|
+
if (shellInterpreters.has(name)) return shellInterpreterMutates(args);
|
|
237
|
+
if (/^(?:node|python\d*(?:\.\d+)*|ruby|perl|php|bun|deno)$/.test(name))
|
|
238
|
+
return inlineInterpreterMutates(name, args);
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function nodeChildren(value: Record<string, unknown>) {
|
|
243
|
+
const node = value as {
|
|
244
|
+
command?: unknown;
|
|
245
|
+
commands?: unknown[];
|
|
246
|
+
parts?: unknown[];
|
|
247
|
+
script?: unknown;
|
|
248
|
+
};
|
|
249
|
+
return [
|
|
250
|
+
node.script,
|
|
251
|
+
node.command,
|
|
252
|
+
...(node.commands ?? []),
|
|
253
|
+
...(node.parts ?? []),
|
|
254
|
+
];
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function visit(value: unknown): boolean {
|
|
258
|
+
if (!value || typeof value !== "object") return false;
|
|
259
|
+
if (Array.isArray(value)) return value.some(visit);
|
|
260
|
+
const node = value as { type?: string };
|
|
261
|
+
if (node.type === "Command" && commandMutates(value as Command)) return true;
|
|
262
|
+
if (nodeChildren(value as Record<string, unknown>).some(visit)) return true;
|
|
263
|
+
return Object.values(value).some(visit);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function shellMutates(source: string) {
|
|
267
|
+
if (source.length > 100_000) return false;
|
|
268
|
+
try {
|
|
269
|
+
const script = parse(source);
|
|
270
|
+
return script.errors?.length ? false : visit(script);
|
|
271
|
+
} catch {
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const embeddedKeys = new Set(["cmd", "command", "script", "source", "code"]);
|
|
277
|
+
|
|
278
|
+
function stringLiteral(source: string, start: number) {
|
|
279
|
+
const quote = source[start];
|
|
280
|
+
if (quote !== '"' && quote !== "'" && quote !== "`") return undefined;
|
|
281
|
+
let value = "";
|
|
282
|
+
for (let index = start + 1; index < source.length; index++) {
|
|
283
|
+
const character = source[index];
|
|
284
|
+
if (character === "\\" && index + 1 < source.length) {
|
|
285
|
+
value += source[++index];
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (character === quote) return { end: index + 1, value };
|
|
289
|
+
value += character;
|
|
290
|
+
}
|
|
291
|
+
return undefined;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
interface EmbeddedKey {
|
|
295
|
+
end: number;
|
|
296
|
+
key: string;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function embeddedKey(source: string, index: number): EmbeddedKey | undefined {
|
|
300
|
+
const literal = stringLiteral(source, index);
|
|
301
|
+
if (literal) return { end: literal.end, key: literal.value };
|
|
302
|
+
if (!/[A-Za-z_$]/.test(source[index] ?? "")) return undefined;
|
|
303
|
+
let end = index;
|
|
304
|
+
while (/[A-Za-z0-9_$]/.test(source[end] ?? "")) end += 1;
|
|
305
|
+
return { end, key: source.slice(index, end) };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function skipWhitespace(source: string, index: number) {
|
|
309
|
+
while (/\s/.test(source[index] ?? "")) index += 1;
|
|
310
|
+
return index;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function embeddedPayload(source: string, key: EmbeddedKey) {
|
|
314
|
+
let index = skipWhitespace(source, key.end);
|
|
315
|
+
if (source[index] !== ":") return undefined;
|
|
316
|
+
index = skipWhitespace(source, index + 1);
|
|
317
|
+
return stringLiteral(source, index)?.value;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export function embeddedShellMutates(source: string) {
|
|
321
|
+
if (source.length > 100_000) return false;
|
|
322
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
323
|
+
const key = embeddedKey(source, index);
|
|
324
|
+
if (!key) continue;
|
|
325
|
+
index = key.end - 1;
|
|
326
|
+
if (!embeddedKeys.has(key.key)) continue;
|
|
327
|
+
const payload = embeddedPayload(source, key);
|
|
328
|
+
if (payload && shellMutates(payload)) return true;
|
|
329
|
+
}
|
|
330
|
+
return false;
|
|
331
|
+
}
|
package/src/stdio.ts
CHANGED
|
@@ -68,43 +68,55 @@ export class BatchingStdioServerTransport implements Transport {
|
|
|
68
68
|
});
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
private takeLine() {
|
|
72
|
+
const newline = this.buffer.indexOf(10);
|
|
73
|
+
if (newline === -1) return;
|
|
74
|
+
const line = this.buffer
|
|
75
|
+
.subarray(0, newline)
|
|
76
|
+
.toString("utf8")
|
|
77
|
+
.replace(/\r$/, "");
|
|
78
|
+
this.buffer = this.buffer.subarray(newline + 1);
|
|
79
|
+
return line;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private deserializeItem(message: unknown) {
|
|
83
|
+
try {
|
|
84
|
+
return deserializeMessage(JSON.stringify(message));
|
|
85
|
+
} catch (error) {
|
|
86
|
+
this.reportInvalidRequest(
|
|
87
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
private deserializeBatch(parsed: unknown) {
|
|
93
|
+
if (Array.isArray(parsed) && parsed.length === 0) {
|
|
94
|
+
this.reportInvalidRequest(
|
|
95
|
+
new Error("JSON-RPC batches must not be empty"),
|
|
96
|
+
);
|
|
97
|
+
return [];
|
|
98
|
+
}
|
|
99
|
+
return (Array.isArray(parsed) ? parsed : [parsed])
|
|
100
|
+
.map((message) => this.deserializeItem(message))
|
|
101
|
+
.filter((message): message is JSONRPCMessage => message !== undefined);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private processLine(line: string) {
|
|
105
|
+
try {
|
|
106
|
+
const messages = this.deserializeBatch(JSON.parse(line));
|
|
107
|
+
for (const message of messages) this.onmessage?.(message);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
this.reportInvalidRequest(
|
|
110
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
71
115
|
private processReadBuffer() {
|
|
72
116
|
while (true) {
|
|
73
|
-
const
|
|
74
|
-
if (
|
|
75
|
-
|
|
76
|
-
const line = this.buffer
|
|
77
|
-
.subarray(0, newline)
|
|
78
|
-
.toString("utf8")
|
|
79
|
-
.replace(/\r$/, "");
|
|
80
|
-
this.buffer = this.buffer.subarray(newline + 1);
|
|
81
|
-
|
|
82
|
-
try {
|
|
83
|
-
const parsed: unknown = JSON.parse(line);
|
|
84
|
-
if (Array.isArray(parsed) && parsed.length === 0) {
|
|
85
|
-
this.reportInvalidRequest(
|
|
86
|
-
new Error("JSON-RPC batches must not be empty"),
|
|
87
|
-
);
|
|
88
|
-
continue;
|
|
89
|
-
}
|
|
90
|
-
const messages = (Array.isArray(parsed) ? parsed : [parsed]).flatMap(
|
|
91
|
-
(message) => {
|
|
92
|
-
try {
|
|
93
|
-
return [deserializeMessage(JSON.stringify(message))];
|
|
94
|
-
} catch (error) {
|
|
95
|
-
this.reportInvalidRequest(
|
|
96
|
-
error instanceof Error ? error : new Error(String(error)),
|
|
97
|
-
);
|
|
98
|
-
return [];
|
|
99
|
-
}
|
|
100
|
-
},
|
|
101
|
-
);
|
|
102
|
-
for (const message of messages) this.onmessage?.(message);
|
|
103
|
-
} catch (error) {
|
|
104
|
-
this.reportInvalidRequest(
|
|
105
|
-
error instanceof Error ? error : new Error(String(error)),
|
|
106
|
-
);
|
|
107
|
-
}
|
|
117
|
+
const line = this.takeLine();
|
|
118
|
+
if (line === undefined) return;
|
|
119
|
+
this.processLine(line);
|
|
108
120
|
}
|
|
109
121
|
}
|
|
110
122
|
|
package/src/tools/ast-bro.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { replaceFileAtomically } from "../runtime/atomic";
|
|
|
15
15
|
import { assertFormattable, formatFileAtomically } from "../runtime/format";
|
|
16
16
|
import { withFileLocks } from "../runtime/locks";
|
|
17
17
|
import { primaryRoot, resolveWritablePath } from "../runtime/paths";
|
|
18
|
+
import { type ConfiguredExecution, localExecution } from "./configured";
|
|
18
19
|
|
|
19
20
|
function upstreamSchema(
|
|
20
21
|
jsonSchema: Record<string, unknown>,
|
|
@@ -135,7 +136,10 @@ async function callAstBroWithFormatting(
|
|
|
135
136
|
});
|
|
136
137
|
}
|
|
137
138
|
|
|
138
|
-
export default function registerAstBroTools(
|
|
139
|
+
export default function registerAstBroTools(
|
|
140
|
+
server: McpServer,
|
|
141
|
+
execute: ConfiguredExecution = localExecution,
|
|
142
|
+
) {
|
|
139
143
|
for (const toolName of AST_BRO_TOOLS) {
|
|
140
144
|
const definition = metadata[toolName];
|
|
141
145
|
server.registerTool(
|
|
@@ -150,11 +154,13 @@ export default function registerAstBroTools(server: McpServer) {
|
|
|
150
154
|
},
|
|
151
155
|
async (args) => {
|
|
152
156
|
try {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
157
|
+
return await execute(args, async () => {
|
|
158
|
+
const root = await primaryRoot();
|
|
159
|
+
await validateAstBroPaths(args, root);
|
|
160
|
+
return toolName === "run"
|
|
161
|
+
? await callAstBroWithFormatting(args, root)
|
|
162
|
+
: await callAstBro(toolName, args, root);
|
|
163
|
+
});
|
|
158
164
|
} catch (error) {
|
|
159
165
|
return {
|
|
160
166
|
content: [
|