localmcp-cli 0.0.0-stage → 0.0.11

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.
@@ -0,0 +1,591 @@
1
+ import { execFile, spawn, spawnSync } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { existsSync } from "node:fs";
4
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { promisify } from "node:util";
8
+ import { childEnvironment, platformLabel } from "../core/config.js";
9
+ import { buildDefaultHints, discoverLocalSkills, loadGuideState } from "../core/context-discovery.js";
10
+ import { CONTROL_SECURITY_SCHEMES, okResult, toolMeta, truncateText } from "../core/protocol.js";
11
+ import { invokeSelfUpdate } from "../core/updater-client.js";
12
+
13
+ const execFileAsync = promisify(execFile);
14
+
15
+ let cachedPwshBinary = null;
16
+
17
+ function resolvePowerShellBinary() {
18
+ if (cachedPwshBinary) return cachedPwshBinary;
19
+ const candidates = [
20
+ path.join(process.env.ProgramFiles || "C:\\Program Files", "PowerShell", "7", "pwsh.exe"),
21
+ process.env.LOCALAPPDATA
22
+ ? path.join(process.env.LOCALAPPDATA, "Microsoft", "WindowsApps", "pwsh.exe")
23
+ : "",
24
+ ].filter(Boolean);
25
+
26
+ for (const bin of candidates) {
27
+ if (existsSync(bin)) {
28
+ const check = spawnSync(bin, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", "exit 0"], {
29
+ timeout: 3000,
30
+ windowsHide: true,
31
+ stdio: "ignore",
32
+ });
33
+ if (check.status === 0) {
34
+ cachedPwshBinary = { bin, edition: "pwsh" };
35
+ return cachedPwshBinary;
36
+ }
37
+ }
38
+ }
39
+
40
+ const wherePwsh = spawnSync("where.exe", ["pwsh.exe"], {
41
+ timeout: 2000,
42
+ windowsHide: true,
43
+ encoding: "utf8",
44
+ });
45
+ if (wherePwsh.status === 0 && wherePwsh.stdout) {
46
+ const first = wherePwsh.stdout.split(/\r?\n/).map((s) => s.trim()).find(Boolean);
47
+ if (first && existsSync(first)) {
48
+ cachedPwshBinary = { bin: first, edition: "pwsh" };
49
+ return cachedPwshBinary;
50
+ }
51
+ }
52
+
53
+ cachedPwshBinary = { bin: "powershell.exe", edition: "powershell" };
54
+ return cachedPwshBinary;
55
+ }
56
+
57
+ function resolvePosixShellBinary() {
58
+ for (const candidate of ["/bin/bash", "/usr/bin/bash", "/bin/zsh", "/bin/sh"]) {
59
+ if (existsSync(candidate)) {
60
+ return { bin: candidate, shell: path.basename(candidate) };
61
+ }
62
+ }
63
+ return { bin: "sh", shell: "sh" };
64
+ }
65
+
66
+ function killSpawnedTree(child, platform) {
67
+ const pid = child?.pid;
68
+ if (!pid) return;
69
+ if (platform === "win32") {
70
+ try {
71
+ spawnSync("taskkill.exe", ["/PID", String(pid), "/T", "/F"], {
72
+ stdio: "ignore",
73
+ windowsHide: true,
74
+ timeout: 4000,
75
+ });
76
+ } catch {
77
+ try { child.kill("SIGKILL"); } catch {}
78
+ }
79
+ return;
80
+ }
81
+ try {
82
+ process.kill(-pid, "SIGKILL");
83
+ } catch {
84
+ try { child.kill("SIGKILL"); } catch {}
85
+ }
86
+ }
87
+
88
+ function spawnCollected(bin, args, { cwd, env, timeoutMs, maxOutputChars, platform }) {
89
+ return new Promise((resolve, reject) => {
90
+ const maxBytes = Math.max(maxOutputChars * 4, 1024 * 1024);
91
+ const detached = platform !== "win32";
92
+ const child = spawn(bin, args, {
93
+ cwd,
94
+ env,
95
+ detached,
96
+ windowsHide: true,
97
+ stdio: ["ignore", "pipe", "pipe"],
98
+ });
99
+
100
+ const outChunks = [];
101
+ const errChunks = [];
102
+ let outLen = 0;
103
+ let errLen = 0;
104
+ let timedOut = false;
105
+
106
+ child.stdout?.on("data", (chunk) => {
107
+ if (outLen < maxBytes) {
108
+ outChunks.push(chunk);
109
+ outLen += chunk.length;
110
+ }
111
+ });
112
+ child.stderr?.on("data", (chunk) => {
113
+ if (errLen < maxBytes) {
114
+ errChunks.push(chunk);
115
+ errLen += chunk.length;
116
+ }
117
+ });
118
+
119
+ const timer = setTimeout(() => {
120
+ timedOut = true;
121
+ killSpawnedTree(child, platform);
122
+ }, timeoutMs);
123
+
124
+ child.once("error", (err) => {
125
+ clearTimeout(timer);
126
+ reject(err);
127
+ });
128
+
129
+ child.once("close", (code) => {
130
+ clearTimeout(timer);
131
+ const stdoutRaw = Buffer.concat(outChunks).toString("utf8");
132
+ const stderrRaw = Buffer.concat(errChunks).toString("utf8");
133
+ resolve({
134
+ exitCode: timedOut ? 124 : typeof code === "number" ? code : 1,
135
+ timedOut,
136
+ stdout: truncateText(stdoutRaw, maxOutputChars),
137
+ stderr: truncateText(
138
+ timedOut && !stderrRaw ? `Command timed out after ${timeoutMs}ms.` : stderrRaw,
139
+ maxOutputChars
140
+ ),
141
+ });
142
+ });
143
+ });
144
+ }
145
+
146
+ export async function runPowerShell(script, { config, cwd, timeoutMs, env = {}, sta = false } = {}) {
147
+ if (config.state.platform !== "win32") {
148
+ throw new Error("PowerShell automation is only supported on Windows. Use run_shell on macOS/Linux.");
149
+ }
150
+ const effectiveTimeout = Math.min(Math.max(Number(timeoutMs ?? config.state.commandTimeoutMs) || 15000, 1000), 120000);
151
+ const workDir = cwd || config.state.allowedRoots[0] || config.state.cwd;
152
+ const { bin, edition } = resolvePowerShellBinary();
153
+
154
+ const mergedEnv = {
155
+ ...childEnvironment(),
156
+ PYTHONIOENCODING: "utf-8",
157
+ ...env,
158
+ };
159
+
160
+ // Append GNU coreutils bin path as fallback if installed on Windows (per Codex powershell-windows skill).
161
+ const coreutilsBin = "C:\\Program Files\\coreutils\\bin";
162
+ if (existsSync(coreutilsBin)) {
163
+ const pathKey = Object.keys(mergedEnv).find((k) => k.toLowerCase() === "path") || "Path";
164
+ const curPath = String(mergedEnv[pathKey] || "");
165
+ if (!curPath.toLowerCase().includes(coreutilsBin.toLowerCase())) {
166
+ mergedEnv[pathKey] = curPath ? `${curPath};${coreutilsBin}` : coreutilsBin;
167
+ }
168
+ }
169
+
170
+ // Write script to a temporary UTF-8 BOM .ps1 file so both pwsh 7 and powershell 5.1 parse Unicode/Chinese
171
+ // losslessly without command-line length limits, quote mangling, or premature $variable expansion.
172
+ const tempScriptPath = path.join(os.tmpdir(), `local-mcp-ps-${randomUUID()}.ps1`);
173
+ mergedEnv.__LOCAL_MCP_PS1 = tempScriptPath;
174
+ const bomScript = `\uFEFF${String(script ?? "")}\r\n`;
175
+ await writeFile(tempScriptPath, bomScript, "utf8");
176
+
177
+ const bootstrap =
178
+ "[Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = [System.Text.Encoding]::UTF8; " +
179
+ "$global:LASTEXITCODE = 0; " +
180
+ "& $env:__LOCAL_MCP_PS1; " +
181
+ "if ($null -ne $LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE }";
182
+
183
+ const args = [
184
+ ...(sta ? ["-STA"] : []),
185
+ "-NoLogo",
186
+ "-NoProfile",
187
+ "-NonInteractive",
188
+ "-ExecutionPolicy",
189
+ "Bypass",
190
+ "-Command",
191
+ bootstrap,
192
+ ];
193
+
194
+ try {
195
+ const res = await spawnCollected(bin, args, {
196
+ cwd: workDir,
197
+ env: mergedEnv,
198
+ timeoutMs: effectiveTimeout,
199
+ maxOutputChars: config.state.maxCommandOutputChars,
200
+ platform: "win32",
201
+ });
202
+ return {
203
+ shell: edition,
204
+ cwd: workDir,
205
+ ...res,
206
+ };
207
+ } finally {
208
+ await rm(tempScriptPath, { force: true }).catch(() => {});
209
+ }
210
+ }
211
+
212
+ export async function runPosixShell(script, { config, cwd, timeoutMs, env = {} } = {}) {
213
+ const effectiveTimeout = Math.min(Math.max(Number(timeoutMs ?? config.state.commandTimeoutMs) || 15000, 1000), 120000);
214
+ const workDir = cwd || config.state.allowedRoots[0] || config.state.cwd;
215
+ const { bin, shell } = resolvePosixShellBinary();
216
+ const baseEnv = childEnvironment();
217
+ const mergedEnv = {
218
+ ...baseEnv,
219
+ LANG: baseEnv.LANG || "en_US.UTF-8",
220
+ PYTHONIOENCODING: "utf-8",
221
+ LOCAL_MCP_WORKDIR: workDir,
222
+ ...env,
223
+ };
224
+
225
+ const wrappedScript = `cd "$LOCAL_MCP_WORKDIR" || exit 1\n${String(script ?? "")}`;
226
+ const res = await spawnCollected(bin, ["-lc", wrappedScript], {
227
+ cwd: workDir,
228
+ env: mergedEnv,
229
+ timeoutMs: effectiveTimeout,
230
+ maxOutputChars: config.state.maxCommandOutputChars,
231
+ platform: config.state.platform,
232
+ });
233
+ return {
234
+ shell,
235
+ cwd: workDir,
236
+ ...res,
237
+ };
238
+ }
239
+
240
+ export function createSystemTools({ config, auth }) {
241
+ return [
242
+ {
243
+ name: "computer_status",
244
+ title: "Computer status",
245
+ description:
246
+ "Return status for this LocalMCP server, including device name, allowed roots, enabled capabilities, GUIDE.md instructions, and discovered local skill directories.",
247
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
248
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
249
+ _meta: toolMeta("Checking LocalMCP status", "LocalMCP status ready"),
250
+ async handler(_args, { authContext }) {
251
+ auth.requireReadAuth(authContext);
252
+ const guide = loadGuideState(config.state.guideFilePath);
253
+ const localSkills = discoverLocalSkills({ primarySkillDir: config.state.primarySkillDir });
254
+ const hints = [
255
+ ...guide.rules.map((line) => `[用户引导] ${line}`),
256
+ ...buildDefaultHints(config.state.platform),
257
+ ];
258
+ const payload = {
259
+ name: config.state.serverName,
260
+ version: config.state.version,
261
+ platform: config.state.platform,
262
+ platformLabel: platformLabel(config.state.platform),
263
+ arch: process.arch,
264
+ hostname: os.hostname(),
265
+ cwd: config.state.cwd,
266
+ allowedRoots: config.state.allowedRoots,
267
+ capabilities: config.getCapabilities(),
268
+ guide: {
269
+ path: guide.path,
270
+ exists: guide.exists,
271
+ rules: guide.rules,
272
+ },
273
+ localSkills,
274
+ hints,
275
+ uptimeSeconds: Math.round(process.uptime()),
276
+ };
277
+ return okResult(JSON.stringify(payload, null, 2), payload);
278
+ },
279
+ },
280
+ {
281
+ name: "self_update",
282
+ title: "Self update LocalMCP",
283
+ description:
284
+ "Check for new LocalMCP releases or trigger an in-place zero-drop hot-update (~270 KB) directly over MCP without disconnecting active temporary tunnels or rotating the secret key.",
285
+ inputSchema: {
286
+ type: "object",
287
+ properties: {
288
+ action: {
289
+ type: "string",
290
+ enum: ["check", "apply"],
291
+ description: "'check' queries latest version metadata; 'apply' verifies SHA-256 & ABI, replies 200 OK first, then hot-swaps LocalMCP in ~300ms without dropping the tunnel.",
292
+ },
293
+ force: {
294
+ type: "boolean",
295
+ description: "Re-apply hot patch even if version matches (optional, default false).",
296
+ },
297
+ control_pin: {
298
+ type: "string",
299
+ description: "Optional fallback PIN when not authenticated by secret-key or OAuth.",
300
+ },
301
+ },
302
+ additionalProperties: false,
303
+ },
304
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true, idempotentHint: true },
305
+ _meta: toolMeta("Managing LocalMCP self-update", "LocalMCP self-update handled", CONTROL_SECURITY_SCHEMES),
306
+ async handler(args, { authContext }) {
307
+ const action = args.action === "apply" ? "apply" : "check";
308
+ if (action === "apply") {
309
+ auth.requireControlAuth(args.control_pin, authContext);
310
+ } else {
311
+ auth.requireReadAuth(authContext);
312
+ }
313
+ const payload = await invokeSelfUpdate(action, {
314
+ currentVersion: config.state.version,
315
+ force: Boolean(args.force),
316
+ });
317
+ return okResult(JSON.stringify(payload, null, 2), payload);
318
+ },
319
+ },
320
+ {
321
+ name: "run_shell",
322
+ title: "Run shell",
323
+ description:
324
+ "Run a shell command or script inside LOCAL_CONTROL_ROOTS (Codex/DSH style): automatically uses native bash/zsh on macOS/Linux and UTF-8 PowerShell (pwsh 7 preferred) on Windows.",
325
+ inputSchema: {
326
+ type: "object",
327
+ properties: {
328
+ command: { type: "string", minLength: 1, description: "Shell command or multi-line script to execute." },
329
+ cwd: { type: "string", description: "Working directory inside LOCAL_CONTROL_ROOTS." },
330
+ workdir: { type: "string", description: "Alias for cwd (Codex/DSH compatibility)." },
331
+ timeoutMs: { type: "integer", minimum: 1000, maximum: 120000 },
332
+ control_pin: { type: "string", description: "Optional fallback PIN." },
333
+ },
334
+ required: ["command"],
335
+ additionalProperties: false,
336
+ },
337
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true, idempotentHint: false },
338
+ _meta: toolMeta("Running shell command", "Shell command finished", CONTROL_SECURITY_SCHEMES),
339
+ async handler(args, { authContext }) {
340
+ auth.requireCapability(
341
+ "ALLOW_SHELL + ALLOW_UNSAFE_SHELL",
342
+ config.state.allowShell && config.state.allowUnsafeShell,
343
+ args.control_pin,
344
+ authContext
345
+ );
346
+ const rawCwd = args.cwd || args.workdir || config.state.allowedRoots[0] || ".";
347
+ const workDir = await config.resolveAllowedPath(rawCwd, { mustExist: true });
348
+ const payload =
349
+ config.state.platform === "win32"
350
+ ? await runPowerShell(String(args.command || ""), { config, cwd: workDir, timeoutMs: args.timeoutMs })
351
+ : await runPosixShell(String(args.command || ""), { config, cwd: workDir, timeoutMs: args.timeoutMs });
352
+ return okResult(JSON.stringify(payload, null, 2), payload);
353
+ },
354
+ },
355
+ {
356
+ name: "run_command",
357
+ title: "Run command",
358
+ description: "Run a local executable directly without a shell inside LOCAL_CONTROL_ROOTS.",
359
+ inputSchema: {
360
+ type: "object",
361
+ properties: {
362
+ command: {
363
+ type: "array",
364
+ items: { type: "string" },
365
+ minItems: 1,
366
+ description: "Executable and arguments, for example ['git', 'status', '--short'].",
367
+ },
368
+ cwd: { type: "string", description: "Working directory inside LOCAL_CONTROL_ROOTS." },
369
+ timeoutMs: { type: "integer", minimum: 1000, maximum: 120000 },
370
+ control_pin: { type: "string", description: "Optional fallback PIN." },
371
+ },
372
+ required: ["command"],
373
+ additionalProperties: false,
374
+ },
375
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true, idempotentHint: false },
376
+ _meta: toolMeta("Running local command", "Local command finished", CONTROL_SECURITY_SCHEMES),
377
+ async handler(args, { authContext }) {
378
+ auth.requireCapability("ALLOW_SHELL", config.state.allowShell, args.control_pin, authContext);
379
+ if (!Array.isArray(args.command) || args.command.length === 0) {
380
+ throw new Error("command must be a non-empty array of strings.");
381
+ }
382
+ const [executable, ...cmdArgs] = args.command.map(String);
383
+ if (!config.state.allowUnsafeShell && !config.state.safeExecutables.has(executable)) {
384
+ throw new Error(`Executable "${executable}" is not in SAFE_EXECUTABLES. Enable ALLOW_UNSAFE_SHELL=1 for trusted sessions.`);
385
+ }
386
+ const workDir = await config.resolveAllowedPath(args.cwd || config.state.allowedRoots[0] || ".", { mustExist: true });
387
+ const timeoutMs = Math.min(Math.max(Number(args.timeoutMs ?? config.state.commandTimeoutMs) || 15000, 1000), 120000);
388
+
389
+ let result;
390
+ try {
391
+ const out = await execFileAsync(executable, cmdArgs, {
392
+ cwd: workDir,
393
+ timeout: timeoutMs,
394
+ maxBuffer: Math.max(config.state.maxCommandOutputChars * 4, 1024 * 1024),
395
+ env: childEnvironment(),
396
+ });
397
+ result = {
398
+ command: args.command,
399
+ cwd: workDir,
400
+ exitCode: 0,
401
+ stdout: truncateText(out.stdout ?? "", config.state.maxCommandOutputChars),
402
+ stderr: truncateText(out.stderr ?? "", config.state.maxCommandOutputChars),
403
+ };
404
+ } catch (error) {
405
+ if (error && typeof error === "object" && "stdout" in error) {
406
+ result = {
407
+ command: args.command,
408
+ cwd: workDir,
409
+ exitCode: typeof error.code === "number" ? error.code : 1,
410
+ stdout: truncateText(error.stdout ?? "", config.state.maxCommandOutputChars),
411
+ stderr: truncateText(error.stderr ?? String(error.message ?? ""), config.state.maxCommandOutputChars),
412
+ };
413
+ } else {
414
+ throw error;
415
+ }
416
+ }
417
+ return okResult(JSON.stringify(result, null, 2), result);
418
+ },
419
+ },
420
+ {
421
+ name: "take_screenshot",
422
+ title: "Take screenshot",
423
+ description: "Capture the local screen and return it as a PNG MCP image.",
424
+ inputSchema: {
425
+ type: "object",
426
+ properties: {
427
+ control_pin: { type: "string", description: "Optional fallback PIN." },
428
+ },
429
+ additionalProperties: false,
430
+ },
431
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: false },
432
+ _meta: toolMeta("Taking screenshot", "Screenshot ready", CONTROL_SECURITY_SCHEMES),
433
+ async handler(args, { authContext }) {
434
+ auth.requireCapability("ALLOW_SCREENSHOT", config.state.allowScreenshot, args.control_pin, authContext);
435
+ await mkdir(config.state.artifactDir, { recursive: true });
436
+ const outFile = path.join(config.state.artifactDir, `screenshot-${Date.now()}.png`);
437
+ try {
438
+ if (config.state.platform === "darwin") {
439
+ await execFileAsync("screencapture", ["-x", outFile], { timeout: 15000 });
440
+ } else if (config.state.platform === "win32") {
441
+ const capRes = await runPowerShell(
442
+ `
443
+ $ErrorActionPreference = 'Stop'
444
+ Add-Type -AssemblyName System.Windows.Forms
445
+ Add-Type -AssemblyName System.Drawing
446
+ $bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen
447
+ $bitmap = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height)
448
+ $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
449
+ $graphics.CopyFromScreen($bounds.Location, [System.Drawing.Point]::Empty, $bounds.Size)
450
+ $bitmap.Save($env:LOCAL_MCP_SCREENSHOT_PATH, [System.Drawing.Imaging.ImageFormat]::Png)
451
+ $graphics.Dispose()
452
+ $bitmap.Dispose()
453
+ `,
454
+ { config, timeoutMs: 15000, sta: true, env: { LOCAL_MCP_SCREENSHOT_PATH: outFile } }
455
+ );
456
+ if (capRes.exitCode !== 0) {
457
+ throw new Error(capRes.stderr.text || "Screenshot PowerShell script failed.");
458
+ }
459
+ } else {
460
+ throw new Error(`Screenshot capture is not supported on ${config.state.platform}.`);
461
+ }
462
+ const bytes = await readFile(outFile);
463
+ return {
464
+ content: [
465
+ { type: "image", data: bytes.toString("base64"), mimeType: "image/png" },
466
+ { type: "text", text: `Captured screenshot (${bytes.length} bytes).` },
467
+ ],
468
+ structuredContent: { mimeType: "image/png", bytes: bytes.length },
469
+ };
470
+ } finally {
471
+ await rm(outFile, { force: true }).catch(() => {});
472
+ }
473
+ },
474
+ },
475
+ {
476
+ name: "open_target",
477
+ title: "Open target",
478
+ description: "Open a URL, allowed local file, folder, or application on the local computer.",
479
+ inputSchema: {
480
+ type: "object",
481
+ properties: {
482
+ target: { type: "string", minLength: 1, description: "URL, file/folder path, or application name." },
483
+ control_pin: { type: "string", description: "Optional fallback PIN." },
484
+ },
485
+ required: ["target"],
486
+ additionalProperties: false,
487
+ },
488
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true, idempotentHint: false },
489
+ _meta: toolMeta("Opening local target", "Local target opened", CONTROL_SECURITY_SCHEMES),
490
+ async handler(args, { authContext }) {
491
+ auth.requireCapability("ALLOW_OPEN", config.state.allowOpen, args.control_pin, authContext);
492
+ const rawTarget = String(args.target || "").trim();
493
+ if (!rawTarget) throw new Error("target is required.");
494
+ const isUrl = /^https?:\/\//i.test(rawTarget);
495
+ const resolvedTarget = isUrl
496
+ ? rawTarget
497
+ : rawTarget.includes("/") || rawTarget.includes("\\") || rawTarget.startsWith(".") || rawTarget.startsWith("~")
498
+ ? await config.resolveAllowedPath(rawTarget, { mustExist: true })
499
+ : rawTarget;
500
+
501
+ if (config.state.platform === "darwin") {
502
+ await execFileAsync("open", [resolvedTarget], { timeout: 10000 });
503
+ } else if (config.state.platform === "win32") {
504
+ const openRes = await runPowerShell("$ErrorActionPreference = 'Stop'; Start-Process -FilePath $env:LOCAL_MCP_OPEN_TARGET", {
505
+ config,
506
+ timeoutMs: 10000,
507
+ env: { LOCAL_MCP_OPEN_TARGET: resolvedTarget },
508
+ });
509
+ if (openRes.exitCode !== 0) {
510
+ throw new Error(openRes.stderr.text || "Failed to open target.");
511
+ }
512
+ } else {
513
+ await execFileAsync("xdg-open", [resolvedTarget], { timeout: 10000 });
514
+ }
515
+ const payload = { ok: true, target: resolvedTarget };
516
+ return okResult(JSON.stringify(payload, null, 2), payload);
517
+ },
518
+ },
519
+ {
520
+ name: "run_applescript",
521
+ title: "Run AppleScript",
522
+ description: "Run an AppleScript snippet on macOS for native GUI automation.",
523
+ inputSchema: {
524
+ type: "object",
525
+ properties: {
526
+ script: { type: "string", minLength: 1 },
527
+ timeoutMs: { type: "integer", minimum: 1000, maximum: 60000 },
528
+ control_pin: { type: "string", description: "Optional fallback PIN." },
529
+ },
530
+ required: ["script"],
531
+ additionalProperties: false,
532
+ },
533
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true, idempotentHint: false },
534
+ _meta: toolMeta("Running AppleScript", "AppleScript finished", CONTROL_SECURITY_SCHEMES),
535
+ async handler(args, { authContext }) {
536
+ auth.requireCapability("ALLOW_APPLESCRIPT", config.state.allowAppleScript, args.control_pin, authContext);
537
+ if (config.state.platform !== "darwin") {
538
+ throw new Error("AppleScript automation is only supported on macOS.");
539
+ }
540
+ const timeoutMs = Math.min(Math.max(Number(args.timeoutMs ?? config.state.commandTimeoutMs) || 15000, 1000), 60000);
541
+ const lineArgs = String(args.script || "").split("\n").flatMap((line) => ["-e", line]);
542
+ const out = await execFileAsync("osascript", lineArgs, {
543
+ timeout: timeoutMs,
544
+ maxBuffer: Math.max(config.state.maxCommandOutputChars * 4, 1024 * 1024),
545
+ });
546
+ const payload = {
547
+ exitCode: 0,
548
+ stdout: truncateText(out.stdout ?? "", config.state.maxCommandOutputChars),
549
+ stderr: truncateText(out.stderr ?? "", config.state.maxCommandOutputChars),
550
+ };
551
+ return okResult(JSON.stringify(payload, null, 2), payload);
552
+ },
553
+ },
554
+ {
555
+ name: "run_powershell",
556
+ title: "Run PowerShell",
557
+ description:
558
+ "Run a Windows PowerShell script (pwsh 7 preferred, UTF-8 .ps1 execution). Avoid Bash <<EOF heredocs or \\\" escaping; use @'...'@ here-strings, & $exe @argList, -LiteralPath, and curl.exe.",
559
+ inputSchema: {
560
+ type: "object",
561
+ properties: {
562
+ script: { type: "string", minLength: 1 },
563
+ cwd: { type: "string", description: "Optional working directory inside LOCAL_CONTROL_ROOTS." },
564
+ timeoutMs: { type: "integer", minimum: 1000, maximum: 120000 },
565
+ control_pin: { type: "string", description: "Optional fallback PIN." },
566
+ },
567
+ required: ["script"],
568
+ additionalProperties: false,
569
+ },
570
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true, idempotentHint: false },
571
+ _meta: toolMeta("Running PowerShell", "PowerShell finished", CONTROL_SECURITY_SCHEMES),
572
+ async handler(args, { authContext }) {
573
+ auth.requireCapability(
574
+ "ALLOW_SHELL + ALLOW_UNSAFE_SHELL",
575
+ config.state.allowShell && config.state.allowUnsafeShell,
576
+ args.control_pin,
577
+ authContext
578
+ );
579
+ const workDir = args.cwd
580
+ ? await config.resolveAllowedPath(args.cwd, { mustExist: true })
581
+ : await config.resolveAllowedPath(config.state.allowedRoots[0] || ".", { mustExist: true });
582
+ const payload = await runPowerShell(String(args.script || ""), {
583
+ config,
584
+ cwd: workDir,
585
+ timeoutMs: args.timeoutMs,
586
+ });
587
+ return okResult(JSON.stringify(payload, null, 2), payload);
588
+ },
589
+ },
590
+ ];
591
+ }