utm-mcp 0.0.0-stage → 0.1.1

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/src/server.mjs ADDED
@@ -0,0 +1,460 @@
1
+ // The MCP server: a broker between an agent and UTM. Every tool maps to a fixed utmctl command or a
2
+ // fixed AppleScript; there is no tool that runs an arbitrary host command or script.
3
+ import { randomBytes } from "node:crypto";
4
+ import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
8
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
+ import { z } from "zod";
10
+ import * as scripts from "./applescript.mjs";
11
+ import { osascript, utmctl, utmctlOk } from "./exec.mjs";
12
+ import { feedbackGuidance, registerUtmFeedback } from "./feedback.mjs";
13
+ import { buildLinuxSeed, buildWindowsSupport, removeMedia } from "./media.mjs";
14
+ import { audit, describePolicy, FILES_DIR, hostPath, isManaged, requireManaged } from "./policy.mjs";
15
+ import * as utm from "./utm.mjs";
16
+
17
+ const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
18
+ const NOTES = `${scripts.MANAGED_MARKER} (created by the utm-mcp server)`;
19
+ const GENERIC_WINDOWS_PRO_KEY = "W269N-WFGWX-YVC9B-4J6C9-T83GX";
20
+
21
+ const vm = z.string().min(1).describe("The VM's UUID or exact name. Prefer the UUID once you have it.");
22
+ const newName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/, "Use letters, digits, dot, dash and underscore, starting with a letter or digit.");
23
+
24
+ const server = new McpServer(
25
+ { name: "utm", version: VERSION },
26
+ {
27
+ instructions:
28
+ "Creates and operates UTM virtual machines on this Mac. Tools that change or enter a VM work only on VMs this server created (or ones its operator allowed); every other VM is visible in list_vms but read-only. " +
29
+ "A VM being started does not mean its guest is ready: call wait_for_guest before guest_exec or file transfer. " +
30
+ "delete_vm and snapshot_restore cannot be undone, so confirm with the user before using them on anything they care about. Call get_policy to see which host directories you may use." +
31
+ feedbackGuidance,
32
+ },
33
+ );
34
+
35
+ registerUtmFeedback(server, VERSION);
36
+
37
+ /** Register a tool whose handler returns a plain object. Every call is written to the audit log. */
38
+ function tool(name, config, handler) {
39
+ server.registerTool(name, config, async (args) => {
40
+ try {
41
+ const result = await handler(args);
42
+ audit(name, args, { ok: true });
43
+ if (result?.content) return result;
44
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
45
+ } catch (error) {
46
+ audit(name, args, { ok: false, error: error.message });
47
+ return { isError: true, content: [{ type: "text", text: error.message }] };
48
+ }
49
+ });
50
+ }
51
+
52
+ const readOnly = { readOnlyHint: true, openWorldHint: false };
53
+ const change = { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
54
+ const destructive = { readOnlyHint: false, destructiveHint: true, openWorldHint: false };
55
+
56
+ async function managedVm(ref) {
57
+ const found = await utm.resolveVm(ref);
58
+ requireManaged(found);
59
+ return found;
60
+ }
61
+
62
+ async function stoppedVm(ref, action) {
63
+ const found = await managedVm(ref);
64
+ if (found.status !== "stopped") throw new Error(`"${found.name}" is ${found.status}. Stop it before you ${action}.`);
65
+ return found;
66
+ }
67
+
68
+ async function newVmName(name) {
69
+ if (await utm.vmExists(name)) throw new Error(`A virtual machine named "${name}" already exists.`);
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------------------------
73
+ // Looking
74
+
75
+ tool("get_policy", {
76
+ description: "What this server is allowed to touch: which VMs it may change, which host directories you may name for images, shared folders and file transfer, and where its audit log is. Read-only.",
77
+ inputSchema: {},
78
+ annotations: readOnly,
79
+ }, async () => ({ server_version: VERSION, utm_version: await osascript(scripts.UTM_VERSION), ...describePolicy() }));
80
+
81
+ tool("list_vms", {
82
+ description: "List every VM registered in UTM with its UUID, name, status and backend. `managed` says whether this server may change it.",
83
+ inputSchema: {},
84
+ annotations: readOnly,
85
+ }, async () => ({ vms: (await utm.listVms()).map((item) => ({ ...item, managed: isManaged(item) })) }));
86
+
87
+ tool("get_vm", {
88
+ description: "One VM in detail: status, memory, CPUs, drives, network, shared folder, snapshots, and the guest's IP address if its guest agent is answering. Works on any VM.",
89
+ inputSchema: { vm },
90
+ annotations: readOnly,
91
+ }, async (args) => {
92
+ const found = await utm.resolveVm(args.vm);
93
+ const detail = await utm.describeVm(found.id);
94
+ const addresses = found.status === "started" ? await utm.guestAddresses(found.id) : null;
95
+ let snapshotList = [];
96
+ try {
97
+ snapshotList = await utm.snapshots(found.id);
98
+ } catch {
99
+ // Not every backend has snapshots.
100
+ }
101
+ return { ...found, managed: isManaged(found), ...detail, guest_agent: addresses !== null, guest_addresses: addresses ?? [], snapshots: snapshotList };
102
+ });
103
+
104
+ // ---------------------------------------------------------------------------------------------
105
+ // Creating
106
+
107
+ tool("create_linux_vm", {
108
+ description:
109
+ "Create a Linux VM from a distribution's cloud image and start it. cloud-init creates a passwordless-sudo user, installs the QEMU guest agent and authorises your SSH key, with no installer. " +
110
+ "The image is copied; the original is not modified. Returns as soon as the VM is started: call wait_for_guest next (first boot takes about a minute). " +
111
+ "Use an arm64 image on Apple silicon, for example Debian's debian-13-genericcloud-arm64.qcow2. Debian's `genericcloud` kernel cannot mount shared folders; use the `generic` image if you need one.",
112
+ inputSchema: {
113
+ name: newName.describe("Name for the new VM. Also becomes the guest's hostname."),
114
+ image: z.string().describe("Absolute host path of the cloud image (.qcow2 or .img), inside an allowed host directory."),
115
+ memory_mib: z.number().int().min(512).max(65536).default(2048),
116
+ cpus: z.number().int().min(1).max(32).default(2),
117
+ disk_gib: z.number().int().min(4).max(2048).default(16).describe("Size to grow the system disk to."),
118
+ user: z.string().regex(/^[a-z_][a-z0-9_-]{0,30}$/).default("agent").describe("Login to create in the guest."),
119
+ ssh_public_key: z.string().regex(/^(ssh|ecdsa)-[A-Za-z0-9-]+ [A-Za-z0-9+/=]+( [^\n]*)?$/).optional().describe("A public key line to authorise for that user."),
120
+ start: z.boolean().default(true),
121
+ },
122
+ annotations: change,
123
+ }, async (args) => {
124
+ const image = hostPath(args.image);
125
+ await newVmName(args.name);
126
+ const seed = await buildLinuxSeed({ name: args.name, user: args.user, sshPublicKey: args.ssh_public_key });
127
+ let id;
128
+ try {
129
+ id = await osascript(scripts.CREATE_LINUX, [args.name, image, seed.iso, args.memory_mib, args.cpus, args.disk_gib * 1024, NOTES], { timeoutMs: 600_000 });
130
+ } finally {
131
+ seed.cleanup();
132
+ }
133
+ if (args.start) await utmctlOk(["start", id, "--hide"]);
134
+ return { id, name: args.name, user: args.user, status: args.start ? "started" : "stopped", next: "Call wait_for_guest; the first boot installs the guest agent and takes about a minute." };
135
+ });
136
+
137
+ tool("create_windows_vm", {
138
+ description:
139
+ "Create a Windows 11 (ARM64) VM from an installer ISO and start an unattended installation: an answer file partitions the disk, installs Windows, creates a local administrator, and installs UTM's guest tools so the guest agent answers. " +
140
+ "Returns once the installer is booting. Installation takes about 20 minutes, reboots several times and needs no input. Poll wait_for_guest (it is ready when the guest agent answers) and use capture_screen to see where it is. " +
141
+ "When it is done, stop the VM and call detach_media: the answer disc holds the account password in plain text.",
142
+ inputSchema: {
143
+ name: newName.describe("Name for the new VM."),
144
+ iso: z.string().describe("Absolute host path of a Windows 11 ARM64 installer ISO, inside an allowed host directory."),
145
+ memory_mib: z.number().int().min(4096).max(65536).default(4096),
146
+ cpus: z.number().int().min(2).max(32).default(4),
147
+ disk_gib: z.number().int().min(40).max(2048).default(64),
148
+ username: z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,19}$/).default("agent").describe("Local administrator account to create."),
149
+ password: z.string().min(1).max(64).optional().describe("Password for that account. One is generated and returned if you leave this out."),
150
+ edition: z.string().default("Windows 11 Pro").describe("Image name inside the ISO to install."),
151
+ product_key: z.string().regex(/^([A-Z0-9]{5}-){4}[A-Z0-9]{5}$/).optional().describe("Defaults to Microsoft's public generic key for Windows 11 Pro, which installs without activating."),
152
+ },
153
+ annotations: change,
154
+ }, async (args) => {
155
+ const iso = hostPath(args.iso);
156
+ await newVmName(args.name);
157
+ const password = args.password ?? randomBytes(9).toString("base64url");
158
+ const computerName = args.name.replace(/[^A-Za-z0-9-]/g, "-").slice(0, 15);
159
+ const support = await buildWindowsSupport(args.name, {
160
+ computerName,
161
+ username: args.username,
162
+ password,
163
+ edition: args.edition,
164
+ productKey: args.product_key ?? GENERIC_WINDOWS_PRO_KEY,
165
+ });
166
+ const id = await osascript(scripts.CREATE_WINDOWS, [args.name, iso, support, args.memory_mib, args.cpus, args.disk_gib * 1024, NOTES]);
167
+ await utmctlOk(["start", id, "--hide"]);
168
+ await utm.pressKeyThroughBoot(id, 20);
169
+ return {
170
+ id,
171
+ name: args.name,
172
+ username: args.username,
173
+ password,
174
+ status: "installing",
175
+ next: "Poll wait_for_guest until ready (about 20 minutes). Use capture_screen to watch. If the screen shows a firmware shell or 'Press any key to boot from CD', stop the VM and start it again with boot_from_cd. Afterwards shut the guest down (guest_exec shutdown /s /t 0, then stop_vm) and call detach_media.",
176
+ };
177
+ });
178
+
179
+ tool("clone_vm", {
180
+ description:
181
+ "Copy a stopped VM under a new name, and give the copy its own MAC address so both can be on the network. Takes about a second. " +
182
+ "The copy is otherwise identical: same hostname, machine identity, SSH host keys and snapshots. A Linux guest set up by cloud-init needs its cloud-init state reset before the copy gets a network address; see the utm skill.",
183
+ inputSchema: { vm, name: newName.describe("Name for the copy.") },
184
+ annotations: change,
185
+ }, async (args) => {
186
+ const source = await stoppedVm(args.vm, "clone it");
187
+ await newVmName(args.name);
188
+ await utmctlOk(["clone", source.id, "--name", args.name], { timeoutMs: 600_000 });
189
+ const copy = await utm.resolveVm(args.name);
190
+ const mac = utm.randomMac();
191
+ await osascript(scripts.SET_MAC, [copy.id, mac]);
192
+ return { id: copy.id, name: copy.name, mac, status: "stopped", cloned_from: source.name };
193
+ });
194
+
195
+ // ---------------------------------------------------------------------------------------------
196
+ // Running
197
+
198
+ tool("start_vm", {
199
+ description: "Start a VM, or resume a suspended one. Returns when UTM reports it started, which is before the guest has booted: call wait_for_guest next.",
200
+ inputSchema: {
201
+ vm,
202
+ disposable: z.boolean().default(false).describe("Run without saving anything to disk; every change is gone when the VM stops."),
203
+ boot_from_cd: z.boolean().default(false).describe("Tap a key for the first 20 seconds to get past an installer disc's 'Press any key to boot from CD or DVD' prompt."),
204
+ },
205
+ annotations: change,
206
+ }, async (args) => {
207
+ const found = await managedVm(args.vm);
208
+ await utmctlOk(["start", found.id, "--hide", ...(args.disposable ? ["--disposable"] : [])]);
209
+ if (args.boot_from_cd) await utm.pressKeyThroughBoot(found.id, 20);
210
+ return { id: found.id, name: found.name, status: await utm.status(found.id) };
211
+ });
212
+
213
+ tool("stop_vm", {
214
+ description: "Stop a VM. `request` asks the guest OS to shut down cleanly and waits up to two minutes (Windows guests often ignore it; shut those down with guest_exec and `shutdown /s /t 0`, then call this to wait); `force` powers it off at once, like pulling the plug; `kill` ends the VM process and is for a VM that does not respond to force.",
215
+ inputSchema: { vm, mode: z.enum(["request", "force", "kill"]).default("request") },
216
+ annotations: change,
217
+ }, async (args) => {
218
+ const found = await managedVm(args.vm);
219
+ if (found.status === "stopped") return { id: found.id, name: found.name, status: "stopped" };
220
+ // A guest that is already shutting down from the inside needs no second request.
221
+ if (found.status === "started" || args.mode !== "request") await utmctlOk(["stop", found.id, `--${args.mode}`]);
222
+ const stopped = await utm.waitForStatus(found.id, "stopped", args.mode === "request" ? 120_000 : 20_000);
223
+ return {
224
+ id: found.id,
225
+ name: found.name,
226
+ status: await utm.status(found.id),
227
+ ...(stopped ? {} : { note: args.mode === "request" ? "The guest has not shut down yet; Windows guests often ignore the request. Shut it down from inside with guest_exec ([\"shutdown\", \"/s\", \"/t\", \"0\"] on Windows, [\"systemctl\", \"poweroff\"] on Linux) and call stop_vm again to wait, or use mode force." : "Still stopping." }),
228
+ };
229
+ });
230
+
231
+ tool("suspend_vm", {
232
+ description: "Pause a running VM in memory. start_vm resumes it. Not available for a VM with an NVMe disk, which includes Windows VMs made here.",
233
+ inputSchema: { vm },
234
+ annotations: change,
235
+ }, async (args) => {
236
+ const found = await managedVm(args.vm);
237
+ await utmctlOk(["suspend", found.id]);
238
+ await utm.waitForStatus(found.id, "paused", 20_000);
239
+ return { id: found.id, name: found.name, status: await utm.status(found.id) };
240
+ });
241
+
242
+ tool("delete_vm", {
243
+ description: "Delete a VM and all of its data, including its disks and snapshots. There is no undo. The VM must be stopped. Confirm with the user first unless you created this VM for the current task.",
244
+ inputSchema: { vm },
245
+ annotations: destructive,
246
+ }, async (args) => {
247
+ const found = await stoppedVm(args.vm, "delete it");
248
+ await utmctlOk(["delete", found.id]);
249
+ removeMedia(found.name);
250
+ return { deleted: found.name, id: found.id };
251
+ });
252
+
253
+ // ---------------------------------------------------------------------------------------------
254
+ // Configuring
255
+
256
+ tool("configure_vm", {
257
+ description: "Change a stopped VM's memory, CPU count or system disk size. A disk can be grown; the guest then has to grow its own partition (cloud-init Linux images do that on the next boot).",
258
+ inputSchema: {
259
+ vm,
260
+ memory_mib: z.number().int().min(512).max(65536).optional(),
261
+ cpus: z.number().int().min(1).max(32).optional(),
262
+ disk_gib: z.number().int().min(4).max(2048).optional().describe("New size of the first fixed disk."),
263
+ },
264
+ annotations: change,
265
+ }, async (args) => {
266
+ const found = await stoppedVm(args.vm, "change its configuration");
267
+ await osascript(scripts.CONFIGURE, [found.id, args.memory_mib ?? "", args.cpus ?? "", args.disk_gib ? args.disk_gib * 1024 : "", "0"], { timeoutMs: 600_000 });
268
+ return { id: found.id, name: found.name, ...(await utm.describeVm(found.id)) };
269
+ });
270
+
271
+ tool("detach_media", {
272
+ description: "Remove every removable drive (installer ISO, guest tools, answer disc) from a stopped VM and delete the install media this server generated for it. Do this once an installation has finished.",
273
+ inputSchema: { vm },
274
+ annotations: change,
275
+ }, async (args) => {
276
+ const found = await stoppedVm(args.vm, "detach its media");
277
+ await osascript(scripts.CONFIGURE, [found.id, "", "", "", "1"]);
278
+ removeMedia(found.name);
279
+ return { id: found.id, name: found.name, drives: (await utm.describeVm(found.id)).drives };
280
+ });
281
+
282
+ tool("set_shared_folder", {
283
+ description:
284
+ "Share one host directory with a stopped VM. Linux guests use mode VirtFS and mount it with `mount -t 9p -o trans=virtio,version=9p2000.L share <dir>`; Windows guests use WebDAV and see a network drive once the guest tools are installed. " +
285
+ "The folder is the host's real directory: snapshots do not cover it, and a rollback does not undo what the guest wrote there. Prefer guest_push_file and guest_pull_file unless the guest needs a live view.",
286
+ inputSchema: {
287
+ vm,
288
+ directory: z.string().describe("Absolute host path of the directory to share, inside an allowed host directory."),
289
+ mode: z.enum(["VirtFS", "WebDAV"]).default("VirtFS"),
290
+ },
291
+ annotations: change,
292
+ }, async (args) => {
293
+ const found = await stoppedVm(args.vm, "change its shared folder");
294
+ const directory = hostPath(args.directory);
295
+ if (!statSync(directory).isDirectory()) throw new Error(`${directory} is not a directory.`);
296
+ await osascript(scripts.SET_SHARE, [found.id, args.mode, directory]);
297
+ return { id: found.id, name: found.name, shared_folder: directory, mode: args.mode };
298
+ });
299
+
300
+ // ---------------------------------------------------------------------------------------------
301
+ // Inside the guest
302
+
303
+ tool("wait_for_guest", {
304
+ description: "Wait until the guest's agent answers, which is what makes guest_exec, file transfer and the IP address available. Returns `ready` with the guest's IP, or `ready: false` if the time ran out; call it again to keep waiting.",
305
+ inputSchema: { vm, timeout_seconds: z.number().int().min(1).max(600).default(120) },
306
+ annotations: readOnly,
307
+ }, async (args) => {
308
+ const found = await managedVm(args.vm);
309
+ return { id: found.id, name: found.name, ...(await utm.waitForGuest(found.id, args.timeout_seconds * 1000)) };
310
+ });
311
+
312
+ tool("guest_exec", {
313
+ description:
314
+ "Run a program inside the guest and return its exit code, stdout and stderr. The command is a program and its arguments, not a shell line: for pipes, redirects or `&&`, run a shell, e.g. [\"sh\", \"-c\", \"…\"] on Linux or [\"powershell\", \"-NoProfile\", \"-Command\", \"…\"] on Windows. " +
315
+ "Runs with the guest agent's privileges: root on Linux, SYSTEM on Windows.",
316
+ inputSchema: {
317
+ vm,
318
+ command: z.array(z.string()).min(1).describe("Program followed by its arguments."),
319
+ env: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), z.string()).optional().describe("Environment variables to set."),
320
+ stdin: z.string().optional().describe("Text to send to the program's standard input."),
321
+ timeout_seconds: z.number().int().min(1).max(3600).default(120),
322
+ },
323
+ annotations: change,
324
+ }, async (args) => {
325
+ const found = await managedVm(args.vm);
326
+ const argv = ["exec", found.id, "--hide"];
327
+ if (args.stdin !== undefined) argv.push("--input");
328
+ for (const [key, value] of Object.entries(args.env ?? {})) argv.push("--env", `${key}=${value}`);
329
+ argv.push("--cmd", ...args.command);
330
+ const result = await utmctl(argv, { input: args.stdin, timeoutMs: args.timeout_seconds * 1000 });
331
+ if (/guest agent is not running/i.test(result.stderr)) throw new Error("The guest agent is not answering. Call wait_for_guest first.");
332
+ return {
333
+ exit_code: result.timedOut ? null : result.code,
334
+ stdout: result.stdout,
335
+ stderr: result.stderr,
336
+ ...(result.timedOut ? { timed_out: true, note: "Stopped waiting; the program may still be running in the guest." } : {}),
337
+ ...(result.truncated ? { truncated: true } : {}),
338
+ };
339
+ });
340
+
341
+ tool("guest_push_file", {
342
+ description: `Copy one file from the host into the guest. The host file must be inside an allowed host directory (the exchange directory ${FILES_DIR} always is). Binary safe. For a directory, archive it first.`,
343
+ inputSchema: {
344
+ vm,
345
+ host_path: z.string().describe("Absolute path of the file on the host."),
346
+ guest_path: z.string().min(1).describe("Destination path in the guest, e.g. /tmp/in.tar or C:\\Users\\Public\\in.zip."),
347
+ },
348
+ annotations: change,
349
+ }, async (args) => {
350
+ const found = await managedVm(args.vm);
351
+ const source = hostPath(args.host_path);
352
+ if (!statSync(source).isFile()) throw new Error(`${source} is not a file.`);
353
+ await utmctlOk(["file", "push", found.id, args.guest_path, "--hide"], { stdinFile: source, timeoutMs: 1_800_000 });
354
+ return { pushed: source, guest_path: args.guest_path, bytes: statSync(source).size };
355
+ });
356
+
357
+ tool("guest_pull_file", {
358
+ description: `Copy one file from the guest to the host. The destination must be inside an allowed host directory (the exchange directory ${FILES_DIR} always is). Binary safe. Replaces an existing file.`,
359
+ inputSchema: {
360
+ vm,
361
+ guest_path: z.string().min(1).describe("Path of the file in the guest."),
362
+ host_path: z.string().describe("Absolute destination path on the host."),
363
+ },
364
+ annotations: change,
365
+ }, async (args) => {
366
+ const found = await managedVm(args.vm);
367
+ const destination = hostPath(args.host_path, { mustExist: false });
368
+ await utmctlOk(["file", "pull", found.id, args.guest_path, "--hide"], { stdoutFile: destination, timeoutMs: 1_800_000 });
369
+ return { pulled: args.guest_path, host_path: destination, bytes: statSync(destination).size };
370
+ });
371
+
372
+ // ---------------------------------------------------------------------------------------------
373
+ // Snapshots
374
+
375
+ tool("snapshot_list", {
376
+ description: "List a VM's snapshots, newest first. `includes_running_state` means restoring it returns the VM to that running moment rather than to a powered-off disk.",
377
+ inputSchema: { vm },
378
+ annotations: readOnly,
379
+ }, async (args) => {
380
+ const found = await utm.resolveVm(args.vm);
381
+ return { id: found.id, name: found.name, snapshots: await utm.snapshots(found.id) };
382
+ });
383
+
384
+ tool("snapshot_create", {
385
+ description: "Save the VM's current state as a snapshot. Taken while the VM is running it includes the running state and takes a second or two; taken while stopped it holds the disks only. A VM with an NVMe disk, which includes Windows VMs made here, can only be snapshotted while stopped. Shared folders and removable drives are not included.",
386
+ inputSchema: { vm, name: z.string().min(1).max(80).describe("A name already in use gets a number appended; the name actually used is returned.") },
387
+ annotations: change,
388
+ }, async (args) => {
389
+ const found = await managedVm(args.vm);
390
+ const created = (await utmctlOk(["snapshot", "create", found.id, "--name", args.name], { timeoutMs: 600_000 })).trim();
391
+ const all = await utm.snapshots(found.id);
392
+ return { id: found.id, name: found.name, snapshot: all.find((item) => item.name === created) ?? { name: created } };
393
+ });
394
+
395
+ tool("snapshot_restore", {
396
+ description: "Replace the VM's current state with a snapshot. Everything that happened in the VM since that snapshot is lost, and there is no undo; take a new snapshot first if the current state might matter. Does not affect shared folders.",
397
+ inputSchema: { vm, snapshot: z.string().min(1).describe("The snapshot's name or id.") },
398
+ annotations: destructive,
399
+ }, async (args) => {
400
+ const found = await managedVm(args.vm);
401
+ await utmctlOk(["snapshot", "restore", found.id, "--snapshot", args.snapshot], { timeoutMs: 600_000 });
402
+ return { id: found.id, name: found.name, restored: args.snapshot, status: await utm.status(found.id) };
403
+ });
404
+
405
+ tool("snapshot_delete", {
406
+ description: "Delete a snapshot and its data. There is no undo. The VM's current state is not affected.",
407
+ inputSchema: { vm, snapshot: z.string().min(1).describe("The snapshot's name or id.") },
408
+ annotations: destructive,
409
+ }, async (args) => {
410
+ const found = await managedVm(args.vm);
411
+ await utmctlOk(["snapshot", "delete", found.id, "--snapshot", args.snapshot], { timeoutMs: 600_000 });
412
+ return { id: found.id, name: found.name, deleted: args.snapshot };
413
+ });
414
+
415
+ // ---------------------------------------------------------------------------------------------
416
+ // The display, for what a command cannot reach: an installer, a login screen, a boot menu.
417
+
418
+ tool("capture_screen", {
419
+ description: "Take a picture of a running VM's display and return it. The VM needs a display device: Windows VMs made here have one, Linux VMs made here are headless and do not. Use this to see where an installer or boot is, not as the normal way to read a guest.",
420
+ inputSchema: { vm },
421
+ annotations: readOnly,
422
+ }, async (args) => {
423
+ const found = await managedVm(args.vm);
424
+ const dir = mkdtempSync(join(tmpdir(), "utm-mcp-screen-"));
425
+ try {
426
+ const file = join(dir, "screen.png");
427
+ await osascript(scripts.CAPTURE, [found.id, file]);
428
+ return { content: [{ type: "image", data: readFileSync(file).toString("base64"), mimeType: "image/png" }] };
429
+ } finally {
430
+ rmSync(dir, { recursive: true, force: true });
431
+ }
432
+ });
433
+
434
+ tool("send_keys", {
435
+ description: `Type into a running VM's display. Give \`text\` to type characters, or \`keys\` to press named keys and combinations in order, e.g. ["tab", "enter"], ["alt+f4"], ["ctrl+alt+delete"]. Known keys: ${utm.KEY_NAMES.join(", ")}. A last resort for screens no command can reach.`,
436
+ inputSchema: {
437
+ vm,
438
+ text: z.string().max(500).optional(),
439
+ keys: z.array(z.string()).max(50).optional(),
440
+ },
441
+ annotations: change,
442
+ }, async (args) => {
443
+ if (args.text === undefined && !args.keys?.length) throw new Error("Give text or keys.");
444
+ const found = await managedVm(args.vm);
445
+ if (args.text !== undefined) await osascript(scripts.KEYSTROKE, [found.id, args.text]);
446
+ for (const combo of args.keys ?? []) await utm.sendScanCodes(found.id, utm.scanCodesFor(combo));
447
+ return { sent: { text: args.text, keys: args.keys } };
448
+ });
449
+
450
+ tool("click", {
451
+ description: "Click at a position on a running VM's display, in the pixel coordinates of the image capture_screen returns. A last resort for screens no command or key can reach.",
452
+ inputSchema: { vm, x: z.number().int().min(0), y: z.number().int().min(0), button: z.enum(["left", "right"]).default("left") },
453
+ annotations: change,
454
+ }, async (args) => {
455
+ const found = await managedVm(args.vm);
456
+ await osascript(scripts.CLICK, [found.id, args.x, args.y, args.button]);
457
+ return { clicked: { x: args.x, y: args.y, button: args.button } };
458
+ });
459
+
460
+ await server.connect(new StdioServerTransport());
package/src/utm.mjs ADDED
@@ -0,0 +1,162 @@
1
+ // Operations on UTM, built from the fixed commands in exec.mjs and applescript.mjs.
2
+ import * as scripts from "./applescript.mjs";
3
+ import { osascript, utmctl, utmctlOk } from "./exec.mjs";
4
+
5
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
6
+
7
+ function parseRow(line) {
8
+ const [id, status, backend, managed, ...name] = line.split("\t");
9
+ return { id, name: name.join("\t"), status, backend, managed: managed === "1" };
10
+ }
11
+
12
+ export async function listVms() {
13
+ const out = await osascript(scripts.LIST);
14
+ return out.split("\n").filter(Boolean).map(parseRow);
15
+ }
16
+
17
+ /** Find one VM by UUID or exact name. */
18
+ export async function resolveVm(ref) {
19
+ try {
20
+ return parseRow(await osascript(scripts.RESOLVE, [ref]));
21
+ } catch {
22
+ throw new Error(`No virtual machine with the name or UUID "${ref}". Use list_vms to see what exists.`);
23
+ }
24
+ }
25
+
26
+ export async function vmExists(name) {
27
+ return (await listVms()).some((vm) => vm.name === name);
28
+ }
29
+
30
+ export async function describeVm(id) {
31
+ const out = await osascript(scripts.DESCRIBE, [id]);
32
+ const info = { drives: [], networks: [], shared_folders: [] };
33
+ for (const line of out.split("\n")) {
34
+ const at = line.indexOf("=");
35
+ const key = line.slice(0, at);
36
+ const value = line.slice(at + 1);
37
+ if (key === "drive") {
38
+ const [driveId, removable, bus, hostSizeMib, source] = value.split("\t");
39
+ info.drives.push({ id: driveId, removable: removable === "true", interface: bus, host_size_mib: Number(hostSizeMib), source: source || null });
40
+ } else if (key === "network") {
41
+ const [mode, mac] = value.split("\t");
42
+ info.networks.push({ mode, mac });
43
+ } else if (key === "shared_folder") info.shared_folders.push(value);
44
+ else if (key === "memory_mib" || key === "cpus" || key === "displays") info[key] = Number(value);
45
+ else if (key) info[key] = value;
46
+ }
47
+ return info;
48
+ }
49
+
50
+ export async function status(id) {
51
+ return (await utmctlOk(["status", id])).trim();
52
+ }
53
+
54
+ export async function waitForStatus(id, wanted, timeoutMs) {
55
+ const deadline = Date.now() + timeoutMs;
56
+ for (;;) {
57
+ const now = await status(id);
58
+ if (now === wanted) return true;
59
+ if (Date.now() >= deadline) return false;
60
+ await sleep(1500);
61
+ }
62
+ }
63
+
64
+ /** The guest's addresses, or null when the guest agent does not answer. */
65
+ export async function guestAddresses(id) {
66
+ const result = await utmctl(["ip-address", id, "--hide"], { timeoutMs: 20_000 });
67
+ if (result.code !== 0 || result.timedOut) return null;
68
+ return result.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
69
+ }
70
+
71
+ /**
72
+ * Wait for the guest agent, which is what "ready" means: a started VM may still be booting.
73
+ * Gives the network a little longer once the agent answers, since the agent can be up first.
74
+ */
75
+ export async function waitForGuest(id, timeoutMs) {
76
+ const deadline = Date.now() + timeoutMs;
77
+ let agentSince = 0;
78
+ for (;;) {
79
+ const now = await status(id);
80
+ if (now !== "started") return { ready: false, status: now, reason: `The VM is ${now}, not started.` };
81
+ const addresses = await guestAddresses(id);
82
+ if (addresses) {
83
+ if (addresses.length > 0) return { ready: true, ip: addresses[0], addresses };
84
+ agentSince ||= Date.now();
85
+ if (Date.now() - agentSince > 30_000 || Date.now() >= deadline) {
86
+ return { ready: true, ip: null, addresses: [], note: "The guest agent answers but the guest has no IP address. guest_exec and file transfer still work; use them to inspect its network." };
87
+ }
88
+ } else if (Date.now() >= deadline) {
89
+ return { ready: false, status: now, reason: "The guest agent has not answered yet. The guest may still be booting or installing, or has no guest agent." };
90
+ }
91
+ await sleep(3000);
92
+ }
93
+ }
94
+
95
+ export async function snapshots(id) {
96
+ const out = await utmctlOk(["snapshot", "list", id, "--json"]);
97
+ return JSON.parse(out || "[]").map((item) => ({
98
+ id: item.id,
99
+ name: item.name,
100
+ created: item.created,
101
+ size_bytes: item.size,
102
+ includes_running_state: item.includesRunningState,
103
+ data_missing: item.dataMissing,
104
+ }));
105
+ }
106
+
107
+ /** A locally administered address in the range QEMU uses. */
108
+ export function randomMac() {
109
+ const byte = () => Math.floor(Math.random() * 256).toString(16).padStart(2, "0").toUpperCase();
110
+ return `52:54:00:${byte()}:${byte()}:${byte()}`;
111
+ }
112
+
113
+ // PC AT set 1 make codes. A key is released by sending its code with the high bit set.
114
+ const KEYS = {
115
+ esc: [0x01], enter: [0x1c], tab: [0x0f], space: [0x39], backspace: [0x0e],
116
+ up: [0xe0, 0x48], down: [0xe0, 0x50], left: [0xe0, 0x4b], right: [0xe0, 0x4d],
117
+ delete: [0xe0, 0x53], home: [0xe0, 0x47], end: [0xe0, 0x4f], pageup: [0xe0, 0x49], pagedown: [0xe0, 0x51],
118
+ f1: [0x3b], f2: [0x3c], f3: [0x3d], f4: [0x3e], f5: [0x3f], f6: [0x40], f7: [0x41], f8: [0x42], f9: [0x43], f10: [0x44], f11: [0x57], f12: [0x58],
119
+ ctrl: [0x1d], shift: [0x2a], alt: [0x38], win: [0xe0, 0x5b],
120
+ };
121
+ "1234567890".split("").forEach((digit, index) => { KEYS[digit] = [0x02 + index]; });
122
+ "qwertyuiop".split("").forEach((letter, index) => { KEYS[letter] = [0x10 + index]; });
123
+ "asdfghjkl".split("").forEach((letter, index) => { KEYS[letter] = [0x1e + index]; });
124
+ "zxcvbnm".split("").forEach((letter, index) => { KEYS[letter] = [0x2c + index]; });
125
+
126
+ export const KEY_NAMES = Object.keys(KEYS);
127
+
128
+ const press = (codes) => codes;
129
+ const release = (codes) => codes.map((code) => (code === 0xe0 ? code : code | 0x80));
130
+
131
+ /** "enter", "alt+f4", "ctrl+alt+delete": hold everything before the last key, tap the last one. */
132
+ export function scanCodesFor(combo) {
133
+ const names = combo.toLowerCase().split("+").map((part) => part.trim());
134
+ const unknown = names.find((name) => !KEYS[name]);
135
+ if (unknown) throw new Error(`Unknown key "${unknown}". Known keys: ${KEY_NAMES.join(", ")}.`);
136
+ const held = names.slice(0, -1).map((name) => KEYS[name]);
137
+ const key = KEYS[names.at(-1)];
138
+ return [...held.flatMap(press), ...press(key), ...release(key), ...held.reverse().flatMap(release)];
139
+ }
140
+
141
+ export async function sendScanCodes(id, codes) {
142
+ await osascript(scripts.SCAN_CODES, [id, ...codes]);
143
+ }
144
+
145
+ /**
146
+ * Windows and other installer discs show "Press any key to boot from CD or DVD" for a few seconds
147
+ * and otherwise fall through to an empty disk. Tap a key through that window.
148
+ *
149
+ * The key is an arrow, never space or enter: the taps can outlast the prompt, and Windows Setup's
150
+ * first window has Cancel focused, where space or enter cancels the installation.
151
+ */
152
+ export async function pressKeyThroughBoot(id, seconds) {
153
+ const deadline = Date.now() + seconds * 1000;
154
+ while (Date.now() < deadline) {
155
+ try {
156
+ await sendScanCodes(id, scanCodesFor("left"));
157
+ } catch {
158
+ // The display may not be up for the first moment after start.
159
+ }
160
+ await sleep(700);
161
+ }
162
+ }