@solomonneas/proxmox-mcp 0.2.0 → 0.5.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.
@@ -16,6 +16,13 @@ function isTruthy(value) {
16
16
  if (!value) return false;
17
17
  return ["true", "1", "yes"].includes(value.toLowerCase());
18
18
  }
19
+ function hostnameFromUrl(url) {
20
+ try {
21
+ return new URL(url).hostname;
22
+ } catch {
23
+ return url;
24
+ }
25
+ }
19
26
  function resolveConfig(env) {
20
27
  const url = env.PROXMOX_URL;
21
28
  const tokenId = env.PROXMOX_TOKEN_ID;
@@ -23,16 +30,29 @@ function resolveConfig(env) {
23
30
  if (!url) throw new ConfigError("PROXMOX_URL is required");
24
31
  if (!tokenId) throw new ConfigError("PROXMOX_TOKEN_ID is required");
25
32
  if (!tokenSecret) throw new ConfigError("PROXMOX_TOKEN_SECRET is required");
33
+ const trimmedUrl = url.replace(/\/+$/, "");
34
+ const sshHost = env.PROXMOX_SSH_HOST ?? hostnameFromUrl(trimmedUrl);
35
+ const sshPort = env.PROXMOX_SSH_PORT ? parseInt(env.PROXMOX_SSH_PORT, 10) : 22;
36
+ const sshUser = env.PROXMOX_SSH_USER ?? "root";
37
+ const sshKey = env.PROXMOX_SSH_KEY ?? "~/.ssh/id_ed25519";
26
38
  return {
27
- url: url.replace(/\/+$/, ""),
39
+ url: trimmedUrl,
28
40
  tokenId,
29
41
  tokenSecret,
30
- tlsInsecure: isTruthy(env.PROXMOX_TLS_INSECURE)
42
+ tlsInsecure: isTruthy(env.PROXMOX_TLS_INSECURE),
43
+ ssh: {
44
+ host: sshHost,
45
+ port: sshPort,
46
+ user: sshUser,
47
+ keyPath: sshKey,
48
+ vmUser: env.PROXMOX_VM_SSH_USER ?? sshUser,
49
+ vmKeyPath: env.PROXMOX_VM_SSH_KEY ?? sshKey
50
+ }
31
51
  };
32
52
  }
33
53
 
34
54
  // src/proxmox-client.ts
35
- import { Agent as UndiciAgent } from "undici";
55
+ import { request as httpsRequest } from "https";
36
56
  var ProxmoxClientError = class extends Error {
37
57
  constructor(status, message) {
38
58
  super(`Proxmox ${status}: ${message}`);
@@ -48,29 +68,27 @@ var ProxmoxUnreachableError = class extends Error {
48
68
  }
49
69
  };
50
70
  var ProxmoxClient = class {
51
- constructor(cfg2, opts = {}) {
52
- this.cfg = cfg2;
53
- this.authHeader = `PVEAPIToken=${cfg2.tokenId}=${cfg2.tokenSecret}`;
71
+ constructor(cfg, opts = {}) {
72
+ this.cfg = cfg;
73
+ this.authHeader = `PVEAPIToken=${cfg.tokenId}=${cfg.tokenSecret}`;
54
74
  this.retryDelayMs = opts.retryDelayMs ?? 1e3;
55
- if (cfg2.tlsInsecure && cfg2.url.startsWith("https://")) {
56
- this.dispatcher = new UndiciAgent({ connect: { rejectUnauthorized: false } });
57
- }
75
+ this.usesInsecureTls = cfg.tlsInsecure && cfg.url.startsWith("https://");
58
76
  }
59
77
  cfg;
60
78
  authHeader;
61
79
  retryDelayMs;
62
- // Node's global fetch (undici) ignores node:https.Agent. To actually skip
63
- // cert verification for self-signed PVE hosts we pass an undici Agent via
64
- // the `dispatcher` init option.
65
- dispatcher;
66
- async get(path) {
67
- return this.request("GET", path);
68
- }
69
- async post(path, body) {
70
- return this.request("POST", path, body);
71
- }
72
- async request(method, path, body) {
73
- const url = this.cfg.url + "/api2/json" + path;
80
+ usesInsecureTls;
81
+ async get(path2) {
82
+ return this.request("GET", path2);
83
+ }
84
+ async post(path2, body) {
85
+ return this.request("POST", path2, body);
86
+ }
87
+ async delete(path2) {
88
+ return this.request("DELETE", path2);
89
+ }
90
+ async request(method, path2, body) {
91
+ const url = this.cfg.url + "/api2/json" + path2;
74
92
  const headers = { authorization: this.authHeader };
75
93
  let bodyStr;
76
94
  if (body !== void 0) {
@@ -90,16 +108,14 @@ var ProxmoxClient = class {
90
108
  let lastErr;
91
109
  for (let attempt = 0; attempt < 2; attempt++) {
92
110
  try {
93
- const init = { method, headers, body: bodyStr };
94
- if (this.dispatcher) init.dispatcher = this.dispatcher;
95
- const res = await fetch(url, init);
111
+ const res = await this.fetchUrl(url, method, headers, bodyStr);
96
112
  if (res.status >= 200 && res.status < 300) {
97
113
  const text = await res.text();
98
114
  if (!text) return void 0;
99
115
  const parsed = JSON.parse(text);
100
116
  return parsed && typeof parsed === "object" && "data" in parsed ? parsed.data : parsed;
101
117
  }
102
- if (res.status >= 500) {
118
+ if ([502, 503, 504].includes(res.status)) {
103
119
  lastErr = new ProxmoxUnreachableError(`HTTP ${res.status}`);
104
120
  if (attempt === 0) await sleep(this.retryDelayMs);
105
121
  continue;
@@ -119,10 +135,190 @@ var ProxmoxClient = class {
119
135
  }
120
136
  throw lastErr ?? new ProxmoxUnreachableError("unknown");
121
137
  }
138
+ async fetchUrl(url, method, headers, body) {
139
+ if (!this.usesInsecureTls) {
140
+ return fetch(url, { method, headers, body });
141
+ }
142
+ return nodeRequest(url, method, headers, body, false);
143
+ }
122
144
  };
123
145
  function sleep(ms) {
124
146
  return new Promise((r) => setTimeout(r, ms));
125
147
  }
148
+ function nodeRequest(url, method, headers, body, rejectUnauthorized) {
149
+ return new Promise((resolve, reject) => {
150
+ const parsed = new URL(url);
151
+ const requestHeaders = { ...headers };
152
+ if (body !== void 0 && requestHeaders["content-length"] === void 0) {
153
+ requestHeaders["content-length"] = String(Buffer.byteLength(body, "utf8"));
154
+ }
155
+ const req = httpsRequest(
156
+ parsed,
157
+ { method, headers: requestHeaders, rejectUnauthorized },
158
+ (res) => {
159
+ const chunks = [];
160
+ res.on("data", (chunk) => chunks.push(chunk));
161
+ res.on("end", () => {
162
+ const text = Buffer.concat(chunks).toString("utf8");
163
+ resolve({
164
+ status: res.statusCode ?? 0,
165
+ text: async () => text
166
+ });
167
+ });
168
+ }
169
+ );
170
+ req.on("error", reject);
171
+ if (body !== void 0) req.write(body);
172
+ req.end();
173
+ });
174
+ }
175
+
176
+ // src/ssh-executor.ts
177
+ import { Client } from "ssh2";
178
+ import { readFile } from "fs/promises";
179
+ import { homedir } from "os";
180
+ var DEFAULT_MAX_OUTPUT_BYTES = 1024 * 1024;
181
+ var SshExecError = class extends Error {
182
+ constructor(phase, message) {
183
+ super(`ssh ${phase}: ${message}`);
184
+ this.phase = phase;
185
+ this.name = "SshExecError";
186
+ }
187
+ phase;
188
+ };
189
+ function expandHome(p) {
190
+ if (p.startsWith("~/")) return homedir() + p.slice(1);
191
+ if (p === "~") return homedir();
192
+ return p;
193
+ }
194
+ async function loadKey(keyPath) {
195
+ try {
196
+ return await readFile(expandHome(keyPath));
197
+ } catch (e) {
198
+ const err = e;
199
+ if (err.code === "ENOENT") {
200
+ throw new SshExecError("connect", `key file not found: ${keyPath}`);
201
+ }
202
+ throw new SshExecError("connect", `cannot read key file ${keyPath}: ${err.message}`);
203
+ }
204
+ }
205
+ function base64(s) {
206
+ return Buffer.from(s, "utf8").toString("base64");
207
+ }
208
+ function buildLxcCommand(vmid, command) {
209
+ const b64 = base64(command);
210
+ return `sudo pct exec ${vmid} -- sh -c "$(echo ${b64} | base64 -d)"`;
211
+ }
212
+ function buildDirectCommand(command) {
213
+ const b64 = base64(command);
214
+ return `sh -c "$(echo ${b64} | base64 -d)"`;
215
+ }
216
+ function resolveMaxOutputBytes() {
217
+ const raw = process.env.PROXMOX_SSH_MAX_OUTPUT_BYTES;
218
+ if (!raw) return DEFAULT_MAX_OUTPUT_BYTES;
219
+ const parsed = Number.parseInt(raw, 10);
220
+ if (!Number.isFinite(parsed) || parsed < 1024) return DEFAULT_MAX_OUTPUT_BYTES;
221
+ return parsed;
222
+ }
223
+ async function runOverSsh(cfg, remoteCommand, timeoutMs, stdin) {
224
+ const key = await loadKey(cfg.keyPath);
225
+ const maxOutputBytes = resolveMaxOutputBytes();
226
+ return new Promise((resolve, reject) => {
227
+ const conn = new Client();
228
+ let stdout = "";
229
+ let stderr = "";
230
+ let stdoutBytes = 0;
231
+ let stderrBytes = 0;
232
+ let settled = false;
233
+ const timer = setTimeout(() => {
234
+ if (settled) return;
235
+ settled = true;
236
+ try {
237
+ conn.end();
238
+ } catch {
239
+ }
240
+ try {
241
+ conn.destroy();
242
+ } catch {
243
+ }
244
+ reject(new SshExecError("timeout", `command exceeded ${timeoutMs}ms`));
245
+ }, timeoutMs);
246
+ const finish = (result) => {
247
+ if (settled) return;
248
+ settled = true;
249
+ clearTimeout(timer);
250
+ try {
251
+ conn.end();
252
+ } catch {
253
+ }
254
+ resolve(result);
255
+ };
256
+ const fail = (phase, message) => {
257
+ if (settled) return;
258
+ settled = true;
259
+ clearTimeout(timer);
260
+ try {
261
+ conn.end();
262
+ } catch {
263
+ }
264
+ try {
265
+ conn.destroy();
266
+ } catch {
267
+ }
268
+ reject(new SshExecError(phase, message));
269
+ };
270
+ const appendOutput = (streamName, chunk) => {
271
+ if (settled) return;
272
+ if (streamName === "stdout") {
273
+ stdoutBytes += chunk.length;
274
+ if (stdoutBytes > maxOutputBytes) {
275
+ fail("exec", `stdout exceeded ${maxOutputBytes} bytes`);
276
+ return;
277
+ }
278
+ stdout += chunk.toString("utf8");
279
+ return;
280
+ }
281
+ stderrBytes += chunk.length;
282
+ if (stderrBytes > maxOutputBytes) {
283
+ fail("exec", `stderr exceeded ${maxOutputBytes} bytes`);
284
+ return;
285
+ }
286
+ stderr += chunk.toString("utf8");
287
+ };
288
+ conn.on("error", (err) => fail("connect", err.message));
289
+ conn.on("ready", () => {
290
+ conn.exec(remoteCommand, (err, stream) => {
291
+ if (err) return fail("exec", err.message);
292
+ stream.on("data", (chunk) => {
293
+ appendOutput("stdout", chunk);
294
+ });
295
+ stream.stderr.on("data", (chunk) => {
296
+ appendOutput("stderr", chunk);
297
+ });
298
+ stream.on("close", (code) => {
299
+ finish({ stdout, stderr, exitCode: code ?? -1 });
300
+ });
301
+ if (stdin !== void 0) {
302
+ stream.write(stdin);
303
+ stream.end();
304
+ }
305
+ });
306
+ });
307
+ conn.connect({
308
+ host: cfg.host,
309
+ port: cfg.port,
310
+ username: cfg.user,
311
+ privateKey: key,
312
+ readyTimeout: timeoutMs
313
+ });
314
+ });
315
+ }
316
+ async function execInLxc(hostCfg, vmid, command, timeoutMs, stdin) {
317
+ return runOverSsh(hostCfg, buildLxcCommand(vmid, command), timeoutMs, stdin);
318
+ }
319
+ async function execViaDirectSsh(targetCfg, command, timeoutMs, stdin) {
320
+ return runOverSsh(targetCfg, buildDirectCommand(command), timeoutMs, stdin);
321
+ }
126
322
 
127
323
  // src/security.ts
128
324
  var SECRETS = /* @__PURE__ */ new Set();
@@ -162,11 +358,34 @@ function redact(value) {
162
358
  import { Type } from "@sinclair/typebox";
163
359
 
164
360
  // src/tools/_util.ts
361
+ import { Value } from "@sinclair/typebox/value";
165
362
  function jsonToolResult(payload) {
166
363
  return {
167
364
  content: [{ type: "text", text: JSON.stringify(payload, null, 2) }]
168
365
  };
169
366
  }
367
+ var ToolInputError = class extends Error {
368
+ constructor(message) {
369
+ super(message);
370
+ this.name = "ToolInputError";
371
+ }
372
+ };
373
+ function validateToolArgs(schema, raw, toolName) {
374
+ if (Value.Check(schema, raw)) return raw;
375
+ const first = [...Value.Errors(schema, raw)][0];
376
+ const where = first?.path ? ` at ${first.path}` : "";
377
+ const message = first?.message ?? "input does not match schema";
378
+ throw new ToolInputError(`${toolName} invalid input${where}: ${message}`);
379
+ }
380
+ var SAFE_SEGMENT_RE = /^[\w.-]+$/;
381
+ function assertSafePathSegment(value, label) {
382
+ if (!SAFE_SEGMENT_RE.test(value)) {
383
+ throw new ToolInputError(
384
+ `invalid ${label} "${value}": expected only letters, digits, '_', '.', or '-'`
385
+ );
386
+ }
387
+ return value;
388
+ }
170
389
  async function resolveResource(client, vmid) {
171
390
  const resources = await client.get(
172
391
  "/cluster/resources"
@@ -194,14 +413,14 @@ function parseTaskUpid(upid) {
194
413
 
195
414
  // src/tools/proxmox_status.ts
196
415
  var Schema = Type.Object({}, { additionalProperties: false });
197
- function createProxmoxStatusTool(getClient2) {
416
+ function createProxmoxStatusTool(getClient) {
198
417
  return {
199
418
  name: "proxmox_status",
200
419
  label: "proxmox: status",
201
420
  description: "Get PVE version + per-node status (online state, CPU, memory, uptime) via GET /version + GET /cluster/resources?type=node.",
202
421
  parameters: Schema,
203
422
  execute: async () => {
204
- const client = getClient2();
423
+ const client = getClient();
205
424
  const [version, nodes] = await Promise.all([
206
425
  client.get("/version"),
207
426
  client.get("/cluster/resources?type=node")
@@ -214,14 +433,14 @@ function createProxmoxStatusTool(getClient2) {
214
433
  // src/tools/proxmox_list_containers.ts
215
434
  import { Type as Type2 } from "@sinclair/typebox";
216
435
  var Schema2 = Type2.Object({}, { additionalProperties: false });
217
- function createProxmoxListContainersTool(getClient2) {
436
+ function createProxmoxListContainersTool(getClient) {
218
437
  return {
219
438
  name: "proxmox_list_containers",
220
439
  label: "proxmox: list containers",
221
440
  description: "List every LXC container across the cluster (vmid, name, node, status, CPU/mem) via GET /cluster/resources?type=vm filtered client-side to type=lxc.",
222
441
  parameters: Schema2,
223
442
  execute: async () => {
224
- const client = getClient2();
443
+ const client = getClient();
225
444
  const all = await client.get("/cluster/resources?type=vm");
226
445
  const containers = all.filter((r) => r.type === "lxc");
227
446
  return jsonToolResult({ count: containers.length, containers });
@@ -232,14 +451,14 @@ function createProxmoxListContainersTool(getClient2) {
232
451
  // src/tools/proxmox_list_vms.ts
233
452
  import { Type as Type3 } from "@sinclair/typebox";
234
453
  var Schema3 = Type3.Object({}, { additionalProperties: false });
235
- function createProxmoxListVmsTool(getClient2) {
454
+ function createProxmoxListVmsTool(getClient) {
236
455
  return {
237
456
  name: "proxmox_list_vms",
238
457
  label: "proxmox: list VMs",
239
458
  description: "List every QEMU VM across the cluster (vmid, name, node, status, CPU/mem) via GET /cluster/resources?type=vm filtered client-side to type=qemu.",
240
459
  parameters: Schema3,
241
460
  execute: async () => {
242
- const client = getClient2();
461
+ const client = getClient();
243
462
  const all = await client.get("/cluster/resources?type=vm");
244
463
  const vms = all.filter((r) => r.type === "qemu");
245
464
  return jsonToolResult({ count: vms.length, vms });
@@ -249,21 +468,22 @@ function createProxmoxListVmsTool(getClient2) {
249
468
 
250
469
  // src/tools/proxmox_get_resource.ts
251
470
  import { Type as Type4 } from "@sinclair/typebox";
471
+ var NAME = "proxmox_get_resource";
252
472
  var Schema4 = Type4.Object(
253
473
  {
254
474
  vmid: Type4.Integer({ minimum: 1, description: "Container or VM ID." })
255
475
  },
256
476
  { additionalProperties: false }
257
477
  );
258
- function createProxmoxGetResourceTool(getClient2) {
478
+ function createProxmoxGetResourceTool(getClient) {
259
479
  return {
260
- name: "proxmox_get_resource",
480
+ name: NAME,
261
481
  label: "proxmox: get resource",
262
482
  description: "Get full current status for one LXC or VM by vmid (resolves node+type from cluster resources, then GET /nodes/{node}/{type}/{vmid}/status/current).",
263
483
  parameters: Schema4,
264
484
  execute: async (_id, raw) => {
265
- const args = raw;
266
- const client = getClient2();
485
+ const args = validateToolArgs(Schema4, raw, NAME);
486
+ const client = getClient();
267
487
  const { node, type } = await resolveResource(client, args.vmid);
268
488
  const status = await client.get(
269
489
  `/nodes/${node}/${type}/${args.vmid}/status/current`
@@ -273,29 +493,286 @@ function createProxmoxGetResourceTool(getClient2) {
273
493
  };
274
494
  }
275
495
 
276
- // src/tools/proxmox_recent_tasks.ts
496
+ // src/tools/proxmox_get_vm_config.ts
277
497
  import { Type as Type5 } from "@sinclair/typebox";
278
498
  var Schema5 = Type5.Object(
279
499
  {
280
- limit: Type5.Optional(
281
- Type5.Integer({ minimum: 1, maximum: 500, description: "Max tasks to return (default 25)." })
500
+ vmid: Type5.Integer({ minimum: 1, description: "QEMU VM ID." })
501
+ },
502
+ { additionalProperties: false }
503
+ );
504
+ var NAME2 = "proxmox_get_vm_config";
505
+ function createProxmoxGetVmConfigTool(getClient) {
506
+ return {
507
+ name: NAME2,
508
+ label: "proxmox: get VM config",
509
+ description: "Get QEMU VM config by vmid (GET /nodes/{node}/qemu/{vmid}/config). Fails if the vmid is not a QEMU VM.",
510
+ parameters: Schema5,
511
+ execute: async (_id, raw) => {
512
+ const args = validateToolArgs(Schema5, raw, NAME2);
513
+ const client = getClient();
514
+ const { node, type } = await resolveResource(client, args.vmid);
515
+ if (type !== "qemu") throw new Error(`vmid ${args.vmid} is ${type}, not qemu`);
516
+ const config = await client.get(`/nodes/${node}/qemu/${args.vmid}/config`);
517
+ return jsonToolResult({ vmid: args.vmid, node, type, config });
518
+ }
519
+ };
520
+ }
521
+
522
+ // src/tools/proxmox_get_container_config.ts
523
+ import { Type as Type6 } from "@sinclair/typebox";
524
+ var Schema6 = Type6.Object(
525
+ {
526
+ vmid: Type6.Integer({ minimum: 1, description: "LXC container ID." })
527
+ },
528
+ { additionalProperties: false }
529
+ );
530
+ var NAME3 = "proxmox_get_container_config";
531
+ function createProxmoxGetContainerConfigTool(getClient) {
532
+ return {
533
+ name: NAME3,
534
+ label: "proxmox: get container config",
535
+ description: "Get LXC container config by vmid (GET /nodes/{node}/lxc/{vmid}/config). Fails if the vmid is not an LXC container.",
536
+ parameters: Schema6,
537
+ execute: async (_id, raw) => {
538
+ const args = validateToolArgs(Schema6, raw, NAME3);
539
+ const client = getClient();
540
+ const { node, type } = await resolveResource(client, args.vmid);
541
+ if (type !== "lxc") throw new Error(`vmid ${args.vmid} is ${type}, not lxc`);
542
+ const config = await client.get(`/nodes/${node}/lxc/${args.vmid}/config`);
543
+ return jsonToolResult({ vmid: args.vmid, node, type, config });
544
+ }
545
+ };
546
+ }
547
+
548
+ // src/tools/proxmox_validate_qemu_smoke_source.ts
549
+ import { Type as Type7 } from "@sinclair/typebox";
550
+ var Schema7 = Type7.Object(
551
+ {
552
+ vmid: Type7.Integer({ minimum: 1, description: "QEMU VM ID to validate as a smoke clone source." }),
553
+ max_disk_gb: Type7.Optional(
554
+ Type7.Integer({ minimum: 1, description: "Maximum acceptable source disk size in GiB (default 64)." })
555
+ ),
556
+ allow_running: Type7.Optional(
557
+ Type7.Boolean({ description: "Allow running sources instead of requiring stopped/template state (default false)." })
558
+ )
559
+ },
560
+ { additionalProperties: false }
561
+ );
562
+ var NAME4 = "proxmox_validate_qemu_smoke_source";
563
+ var GIB = 1024 ** 3;
564
+ var UNSAFE_PREFIXES = ["hostpci", "usb"];
565
+ function truthyProxmoxValue(value) {
566
+ if (value === 1 || value === true) return true;
567
+ if (typeof value !== "string") return false;
568
+ return value === "1" || value.startsWith("enabled=1") || value.split(",").includes("enabled=1");
569
+ }
570
+ function configKeysWithPrefixes(config, prefixes) {
571
+ return Object.keys(config).filter((key) => prefixes.some((prefix) => key.startsWith(prefix)));
572
+ }
573
+ function diskSizeGiB(resource) {
574
+ return typeof resource.maxdisk === "number" ? resource.maxdisk / GIB : void 0;
575
+ }
576
+ function createProxmoxValidateQemuSmokeSourceTool(getClient) {
577
+ return {
578
+ name: NAME4,
579
+ label: "proxmox: validate QEMU smoke source",
580
+ description: "Validate that a QEMU VM is a safe live-smoke clone source. Checks passthrough devices, guest agent, running state, and disk size before cloning.",
581
+ parameters: Schema7,
582
+ execute: async (_id, raw) => {
583
+ const args = validateToolArgs(
584
+ Schema7,
585
+ raw,
586
+ NAME4
587
+ );
588
+ const client = getClient();
589
+ const { node, type } = await resolveResource(client, args.vmid);
590
+ if (type !== "qemu") throw new Error(`vmid ${args.vmid} is ${type}, not qemu`);
591
+ const resources = await client.get("/cluster/resources");
592
+ const resource = resources.find((entry) => entry.vmid === args.vmid && entry.type === "qemu");
593
+ if (!resource) throw new Error(`vmid ${args.vmid} not found in cluster resources as qemu`);
594
+ const config = await client.get(`/nodes/${node}/qemu/${args.vmid}/config`);
595
+ const blockers = [];
596
+ const warnings = [];
597
+ const unsafeKeys = configKeysWithPrefixes(config, UNSAFE_PREFIXES);
598
+ if (unsafeKeys.length > 0) {
599
+ blockers.push(`unsafe passthrough/device config present: ${unsafeKeys.join(", ")}`);
600
+ }
601
+ if (typeof config.args === "string" && config.args.length > 0) {
602
+ blockers.push("raw qemu args present");
603
+ }
604
+ if (!truthyProxmoxValue(config.agent)) {
605
+ blockers.push("QEMU guest agent is not enabled in VM config");
606
+ }
607
+ const maxDiskGb = args.max_disk_gb ?? 64;
608
+ const sizeGiB = diskSizeGiB(resource);
609
+ if (typeof sizeGiB === "number" && sizeGiB > maxDiskGb) {
610
+ blockers.push(`source disk is ${sizeGiB.toFixed(1)} GiB, over ${maxDiskGb} GiB limit`);
611
+ }
612
+ const isTemplate = resource.template === 1 || truthyProxmoxValue(config.template);
613
+ if (!isTemplate && resource.status === "running" && args.allow_running !== true) {
614
+ blockers.push("source VM is running; stop it first or pass allow_running:true");
615
+ }
616
+ if (!isTemplate && resource.status !== "stopped" && resource.status !== "running") {
617
+ warnings.push(`source VM status is ${resource.status ?? "unknown"}`);
618
+ }
619
+ return jsonToolResult({
620
+ vmid: args.vmid,
621
+ node,
622
+ ok: blockers.length === 0,
623
+ blockers,
624
+ warnings,
625
+ resource: {
626
+ name: resource.name,
627
+ status: resource.status,
628
+ template: resource.template === 1,
629
+ pool: resource.pool,
630
+ tags: resource.tags,
631
+ disk_gb: typeof sizeGiB === "number" ? Number(sizeGiB.toFixed(1)) : void 0
632
+ },
633
+ config_summary: {
634
+ agent: config.agent,
635
+ unsafe_keys: unsafeKeys,
636
+ has_raw_args: typeof config.args === "string" && config.args.length > 0
637
+ }
638
+ });
639
+ }
640
+ };
641
+ }
642
+
643
+ // src/tools/proxmox_audit_permissions.ts
644
+ import { Type as Type8 } from "@sinclair/typebox";
645
+ var Schema8 = Type8.Object(
646
+ {
647
+ userid: Type8.Optional(
648
+ Type8.String({
649
+ minLength: 1,
650
+ description: "Optional user or full API token ID to audit. Defaults to current API identity."
651
+ })
652
+ ),
653
+ paths: Type8.Optional(
654
+ Type8.Array(Type8.String({ minLength: 1 }), {
655
+ minItems: 1,
656
+ description: "Permission paths to inspect. Defaults to common smoke-test paths."
657
+ })
658
+ ),
659
+ pool: Type8.Optional(Type8.String({ minLength: 1, description: "Pool path shortcut (default mcp-smoke)." })),
660
+ template_storage: Type8.Optional(Type8.String({ minLength: 1, description: "Template storage shortcut (default local)." })),
661
+ root_storage: Type8.Optional(Type8.String({ minLength: 1, description: "Root disk storage shortcut (default local-lvm)." })),
662
+ source_vmid: Type8.Optional(Type8.Integer({ minimum: 1, description: "Optional source VMID path to inspect." })),
663
+ target_vmid: Type8.Optional(Type8.Integer({ minimum: 1, description: "Optional target VMID path to inspect." })),
664
+ required_privileges: Type8.Optional(
665
+ Type8.Array(Type8.String({ minLength: 1 }), {
666
+ minItems: 1,
667
+ description: "Privileges to summarize on every returned path."
668
+ })
669
+ )
670
+ },
671
+ { additionalProperties: false }
672
+ );
673
+ var NAME5 = "proxmox_audit_permissions";
674
+ var DEFAULT_REQUIRED = [
675
+ "Datastore.AllocateSpace",
676
+ "Datastore.Audit",
677
+ "Pool.Allocate",
678
+ "Pool.Audit",
679
+ "SDN.Use",
680
+ "Sys.Audit",
681
+ "VM.Allocate",
682
+ "VM.Audit",
683
+ "VM.Backup",
684
+ "VM.Clone",
685
+ "VM.Config.Disk",
686
+ "VM.Config.Memory",
687
+ "VM.Config.Network",
688
+ "VM.Config.Options",
689
+ "VM.GuestAgent.Audit",
690
+ "VM.PowerMgmt",
691
+ "VM.Snapshot",
692
+ "VM.Snapshot.Rollback"
693
+ ];
694
+ function defaultPaths(args) {
695
+ const pool = assertSafePathSegment(args.pool ?? "mcp-smoke", "pool");
696
+ const templateStorage = assertSafePathSegment(args.template_storage ?? "local", "template_storage");
697
+ const rootStorage = assertSafePathSegment(args.root_storage ?? "local-lvm", "root_storage");
698
+ const paths = [
699
+ "/",
700
+ `/pool/${pool}`,
701
+ `/storage/${templateStorage}`,
702
+ `/storage/${rootStorage}`,
703
+ "/sdn"
704
+ ];
705
+ if (args.source_vmid !== void 0) paths.push(`/vms/${args.source_vmid}`);
706
+ if (args.target_vmid !== void 0) paths.push(`/vms/${args.target_vmid}`);
707
+ return [...new Set(paths)];
708
+ }
709
+ function withQuery(path2, params) {
710
+ const search = new URLSearchParams();
711
+ for (const [key, value] of Object.entries(params)) {
712
+ if (value !== void 0) search.append(key, value);
713
+ }
714
+ const qs = search.toString();
715
+ return qs ? `${path2}?${qs}` : path2;
716
+ }
717
+ function createProxmoxAuditPermissionsTool(getClient) {
718
+ return {
719
+ name: NAME5,
720
+ label: "proxmox: audit permissions",
721
+ description: "Read effective Proxmox permissions for the current token or a specified user/token across smoke-relevant paths (GET /access/permissions).",
722
+ parameters: Schema8,
723
+ execute: async (_id, raw) => {
724
+ const args = validateToolArgs(Schema8, raw, NAME5);
725
+ const paths = args.paths ?? defaultPaths(args);
726
+ const required = args.required_privileges ?? DEFAULT_REQUIRED;
727
+ const client = getClient();
728
+ const results = [];
729
+ for (const path2 of paths) {
730
+ const permissions = await client.get(
731
+ withQuery("/access/permissions", { path: path2, userid: args.userid })
732
+ );
733
+ const privileges = permissions[path2] ?? permissions[Object.keys(permissions)[0] ?? ""] ?? {};
734
+ const missing = required.filter((priv) => privileges[priv] !== 1);
735
+ results.push({
736
+ path: path2,
737
+ privilege_count: Object.keys(privileges).length,
738
+ missing_required: missing,
739
+ has_all_required: missing.length === 0,
740
+ privileges
741
+ });
742
+ }
743
+ return jsonToolResult({
744
+ userid: args.userid ?? "current",
745
+ required_privileges: required,
746
+ paths: results
747
+ });
748
+ }
749
+ };
750
+ }
751
+
752
+ // src/tools/proxmox_recent_tasks.ts
753
+ import { Type as Type9 } from "@sinclair/typebox";
754
+ var NAME6 = "proxmox_recent_tasks";
755
+ var Schema9 = Type9.Object(
756
+ {
757
+ limit: Type9.Optional(
758
+ Type9.Integer({ minimum: 1, maximum: 500, description: "Max tasks to return (default 25)." })
282
759
  ),
283
- vmid: Type5.Optional(
284
- Type5.Integer({ minimum: 1, description: "Filter tasks by vmid (post-filter)." })
760
+ vmid: Type9.Optional(
761
+ Type9.Integer({ minimum: 1, description: "Filter tasks by vmid (post-filter)." })
285
762
  )
286
763
  },
287
764
  { additionalProperties: false }
288
765
  );
289
- function createProxmoxRecentTasksTool(getClient2) {
766
+ function createProxmoxRecentTasksTool(getClient) {
290
767
  return {
291
- name: "proxmox_recent_tasks",
768
+ name: NAME6,
292
769
  label: "proxmox: recent tasks",
293
770
  description: "List recent cluster tasks (UPID, type, status, node, user, timing) via GET /cluster/tasks. Optionally filter by vmid (post-filter client-side).",
294
- parameters: Schema5,
771
+ parameters: Schema9,
295
772
  execute: async (_id, raw) => {
296
- const args = raw;
773
+ const args = validateToolArgs(Schema9, raw, NAME6);
297
774
  const limit = args.limit ?? 25;
298
- const client = getClient2();
775
+ const client = getClient();
299
776
  const tasks = await client.get("/cluster/tasks");
300
777
  let filtered = tasks;
301
778
  if (args.vmid !== void 0) {
@@ -313,27 +790,28 @@ function createProxmoxRecentTasksTool(getClient2) {
313
790
  }
314
791
 
315
792
  // src/tools/proxmox_list_backups.ts
316
- import { Type as Type6 } from "@sinclair/typebox";
317
- var Schema6 = Type6.Object(
793
+ import { Type as Type10 } from "@sinclair/typebox";
794
+ var NAME7 = "proxmox_list_backups";
795
+ var Schema10 = Type10.Object(
318
796
  {
319
- node: Type6.Optional(
320
- Type6.String({ minLength: 1, description: "Node to query (defaults to first node)." })
797
+ node: Type10.Optional(
798
+ Type10.String({ minLength: 1, description: "Node to query (defaults to first node)." })
321
799
  ),
322
- vmid: Type6.Optional(
323
- Type6.Integer({ minimum: 1, description: "Filter backups to a single vmid (post-filter)." })
800
+ vmid: Type10.Optional(
801
+ Type10.Integer({ minimum: 1, description: "Filter backups to a single vmid (post-filter)." })
324
802
  )
325
803
  },
326
804
  { additionalProperties: false }
327
805
  );
328
- function createProxmoxListBackupsTool(getClient2) {
806
+ function createProxmoxListBackupsTool(getClient) {
329
807
  return {
330
- name: "proxmox_list_backups",
808
+ name: NAME7,
331
809
  label: "proxmox: list backups",
332
810
  description: "List backup volumes on a node. Walks each backup-capable storage via GET /nodes/{node}/storage/{storage}/content?content=backup. Optionally filter by vmid.",
333
- parameters: Schema6,
811
+ parameters: Schema10,
334
812
  execute: async (_id, raw) => {
335
- const args = raw;
336
- const client = getClient2();
813
+ const args = validateToolArgs(Schema10, raw, NAME7);
814
+ const client = getClient();
337
815
  let node = args.node;
338
816
  if (!node) {
339
817
  const nodes = await client.get("/cluster/resources?type=node");
@@ -355,28 +833,29 @@ function createProxmoxListBackupsTool(getClient2) {
355
833
  }
356
834
 
357
835
  // src/tools/proxmox_resource_usage.ts
358
- import { Type as Type7 } from "@sinclair/typebox";
359
- var Schema7 = Type7.Object(
836
+ import { Type as Type11 } from "@sinclair/typebox";
837
+ var NAME8 = "proxmox_resource_usage";
838
+ var Schema11 = Type11.Object(
360
839
  {
361
- vmid: Type7.Integer({ minimum: 1, description: "Container or VM ID." }),
362
- timeframe: Type7.Optional(
363
- Type7.Union([Type7.Literal("hour"), Type7.Literal("day"), Type7.Literal("week")], {
840
+ vmid: Type11.Integer({ minimum: 1, description: "Container or VM ID." }),
841
+ timeframe: Type11.Optional(
842
+ Type11.Union([Type11.Literal("hour"), Type11.Literal("day"), Type11.Literal("week")], {
364
843
  description: "RRD timeframe window (default hour)."
365
844
  })
366
845
  )
367
846
  },
368
847
  { additionalProperties: false }
369
848
  );
370
- function createProxmoxResourceUsageTool(getClient2) {
849
+ function createProxmoxResourceUsageTool(getClient) {
371
850
  return {
372
- name: "proxmox_resource_usage",
851
+ name: NAME8,
373
852
  label: "proxmox: resource usage",
374
853
  description: "Get historical CPU/memory/disk/network samples for one LXC or VM via GET /nodes/{node}/{type}/{vmid}/rrddata?timeframe=<hour|day|week>.",
375
- parameters: Schema7,
854
+ parameters: Schema11,
376
855
  execute: async (_id, raw) => {
377
- const args = raw;
856
+ const args = validateToolArgs(Schema11, raw, NAME8);
378
857
  const timeframe = args.timeframe ?? "hour";
379
- const client = getClient2();
858
+ const client = getClient();
380
859
  const { node, type } = await resolveResource(client, args.vmid);
381
860
  const samples = await client.get(
382
861
  `/nodes/${node}/${type}/${args.vmid}/rrddata?timeframe=${timeframe}`
@@ -387,7 +866,7 @@ function createProxmoxResourceUsageTool(getClient2) {
387
866
  }
388
867
 
389
868
  // src/tools/proxmox_start_resource.ts
390
- import { Type as Type8 } from "@sinclair/typebox";
869
+ import { Type as Type12 } from "@sinclair/typebox";
391
870
 
392
871
  // src/gates.ts
393
872
  var WriteGateError = class extends Error {
@@ -401,28 +880,43 @@ function assertConfirmedWrite(args, toolName) {
401
880
  throw new WriteGateError(`${toolName} is a write operation. Pass {"confirm": true} to proceed.`);
402
881
  }
403
882
  }
883
+ function assertDestructive(args, toolName) {
884
+ if (args.confirm !== true || args.destructive !== true) {
885
+ throw new WriteGateError(
886
+ `${toolName} is a destructive operation. Pass {"confirm": true, "destructive": true} to proceed.`
887
+ );
888
+ }
889
+ }
890
+ function assertEnvFlag(envKey, toolName, env = process.env) {
891
+ const value = env[envKey];
892
+ if (!value || !["true", "1", "yes"].includes(value.toLowerCase())) {
893
+ throw new WriteGateError(
894
+ `${toolName} requires env flag ${envKey}=1 to be set. This is a destructive operation gate independent of the confirm/destructive args.`
895
+ );
896
+ }
897
+ }
404
898
 
405
899
  // src/tools/proxmox_start_resource.ts
406
- var Schema8 = Type8.Object(
900
+ var Schema12 = Type12.Object(
407
901
  {
408
- vmid: Type8.Integer({ minimum: 1, description: "Container or VM ID." }),
409
- confirm: Type8.Boolean({
902
+ vmid: Type12.Integer({ minimum: 1, description: "Container or VM ID." }),
903
+ confirm: Type12.Boolean({
410
904
  description: "Must be true to write. Tier-2 safe-write gate."
411
905
  })
412
906
  },
413
907
  { additionalProperties: false }
414
908
  );
415
- var NAME = "proxmox_start_resource";
416
- function createProxmoxStartResourceTool(getClient2) {
909
+ var NAME9 = "proxmox_start_resource";
910
+ function createProxmoxStartResourceTool(getClient) {
417
911
  return {
418
- name: NAME,
912
+ name: NAME9,
419
913
  label: "proxmox: start resource",
420
914
  description: "Start a stopped LXC container or QEMU VM by vmid. Tier-2 write; requires confirm:true.",
421
- parameters: Schema8,
915
+ parameters: Schema12,
422
916
  execute: async (_id, raw) => {
423
- assertConfirmedWrite(raw, NAME);
424
- const args = raw;
425
- const client = getClient2();
917
+ assertConfirmedWrite(raw, NAME9);
918
+ const args = validateToolArgs(Schema12, raw, NAME9);
919
+ const client = getClient();
426
920
  const { node, type } = await resolveResource(client, args.vmid);
427
921
  const upid = await client.post(
428
922
  `/nodes/${node}/${type}/${args.vmid}/status/start`,
@@ -434,15 +928,15 @@ function createProxmoxStartResourceTool(getClient2) {
434
928
  }
435
929
 
436
930
  // src/tools/proxmox_stop_resource.ts
437
- import { Type as Type9 } from "@sinclair/typebox";
438
- var Schema9 = Type9.Object(
931
+ import { Type as Type13 } from "@sinclair/typebox";
932
+ var Schema13 = Type13.Object(
439
933
  {
440
- vmid: Type9.Integer({ minimum: 1, description: "Container or VM ID." }),
441
- confirm: Type9.Boolean({
934
+ vmid: Type13.Integer({ minimum: 1, description: "Container or VM ID." }),
935
+ confirm: Type13.Boolean({
442
936
  description: "Must be true to write. Tier-2 safe-write gate."
443
937
  }),
444
- timeoutSeconds: Type9.Optional(
445
- Type9.Integer({
938
+ timeoutSeconds: Type13.Optional(
939
+ Type13.Integer({
446
940
  minimum: 1,
447
941
  description: "Optional shutdown timeout in seconds (passed through to PVE as `timeout`)."
448
942
  })
@@ -450,17 +944,17 @@ var Schema9 = Type9.Object(
450
944
  },
451
945
  { additionalProperties: false }
452
946
  );
453
- var NAME2 = "proxmox_stop_resource";
454
- function createProxmoxStopResourceTool(getClient2) {
947
+ var NAME10 = "proxmox_stop_resource";
948
+ function createProxmoxStopResourceTool(getClient) {
455
949
  return {
456
- name: NAME2,
950
+ name: NAME10,
457
951
  label: "proxmox: stop resource",
458
952
  description: "Gracefully shutdown an LXC container or QEMU VM by vmid (POST status/shutdown). Tier-2 write; requires confirm:true.",
459
- parameters: Schema9,
953
+ parameters: Schema13,
460
954
  execute: async (_id, raw) => {
461
- assertConfirmedWrite(raw, NAME2);
462
- const args = raw;
463
- const client = getClient2();
955
+ assertConfirmedWrite(raw, NAME10);
956
+ const args = validateToolArgs(Schema13, raw, NAME10);
957
+ const client = getClient();
464
958
  const { node, type } = await resolveResource(client, args.vmid);
465
959
  const body = {};
466
960
  if (typeof args.timeoutSeconds === "number") {
@@ -476,27 +970,27 @@ function createProxmoxStopResourceTool(getClient2) {
476
970
  }
477
971
 
478
972
  // src/tools/proxmox_reboot_resource.ts
479
- import { Type as Type10 } from "@sinclair/typebox";
480
- var Schema10 = Type10.Object(
973
+ import { Type as Type14 } from "@sinclair/typebox";
974
+ var Schema14 = Type14.Object(
481
975
  {
482
- vmid: Type10.Integer({ minimum: 1, description: "Container or VM ID." }),
483
- confirm: Type10.Boolean({
976
+ vmid: Type14.Integer({ minimum: 1, description: "Container or VM ID." }),
977
+ confirm: Type14.Boolean({
484
978
  description: "Must be true to write. Tier-2 safe-write gate."
485
979
  })
486
980
  },
487
981
  { additionalProperties: false }
488
982
  );
489
- var NAME3 = "proxmox_reboot_resource";
490
- function createProxmoxRebootResourceTool(getClient2) {
983
+ var NAME11 = "proxmox_reboot_resource";
984
+ function createProxmoxRebootResourceTool(getClient) {
491
985
  return {
492
- name: NAME3,
986
+ name: NAME11,
493
987
  label: "proxmox: reboot resource",
494
988
  description: "Reboot an LXC container or QEMU VM by vmid (POST status/reboot). Tier-2 write; requires confirm:true.",
495
- parameters: Schema10,
989
+ parameters: Schema14,
496
990
  execute: async (_id, raw) => {
497
- assertConfirmedWrite(raw, NAME3);
498
- const args = raw;
499
- const client = getClient2();
991
+ assertConfirmedWrite(raw, NAME11);
992
+ const args = validateToolArgs(Schema14, raw, NAME11);
993
+ const client = getClient();
500
994
  const { node, type } = await resolveResource(client, args.vmid);
501
995
  const upid = await client.post(
502
996
  `/nodes/${node}/${type}/${args.vmid}/status/reboot`,
@@ -508,34 +1002,38 @@ function createProxmoxRebootResourceTool(getClient2) {
508
1002
  }
509
1003
 
510
1004
  // src/tools/proxmox_snapshot_resource.ts
511
- import { Type as Type11 } from "@sinclair/typebox";
512
- var Schema11 = Type11.Object(
1005
+ import { Type as Type15 } from "@sinclair/typebox";
1006
+ var Schema15 = Type15.Object(
513
1007
  {
514
- vmid: Type11.Integer({ minimum: 1, description: "Container or VM ID." }),
515
- snapname: Type11.String({
1008
+ vmid: Type15.Integer({ minimum: 1, description: "Container or VM ID." }),
1009
+ snapname: Type15.String({
516
1010
  minLength: 1,
517
1011
  description: "Snapshot name (PVE convention: lowercase, no spaces)."
518
1012
  }),
519
- description: Type11.Optional(
520
- Type11.String({ description: "Optional human description for the snapshot." })
1013
+ description: Type15.Optional(
1014
+ Type15.String({ description: "Optional human description for the snapshot." })
521
1015
  ),
522
- confirm: Type11.Boolean({
1016
+ confirm: Type15.Boolean({
523
1017
  description: "Must be true to write. Tier-2 safe-write gate."
524
1018
  })
525
1019
  },
526
1020
  { additionalProperties: false }
527
1021
  );
528
- var NAME4 = "proxmox_snapshot_resource";
529
- function createProxmoxSnapshotResourceTool(getClient2) {
1022
+ var NAME12 = "proxmox_snapshot_resource";
1023
+ function createProxmoxSnapshotResourceTool(getClient) {
530
1024
  return {
531
- name: NAME4,
1025
+ name: NAME12,
532
1026
  label: "proxmox: snapshot resource",
533
1027
  description: "Create a snapshot of an LXC container or QEMU VM by vmid (POST /snapshot with {snapname, description?}). Tier-2 write; requires confirm:true.",
534
- parameters: Schema11,
1028
+ parameters: Schema15,
535
1029
  execute: async (_id, raw) => {
536
- assertConfirmedWrite(raw, NAME4);
537
- const args = raw;
538
- const client = getClient2();
1030
+ assertConfirmedWrite(raw, NAME12);
1031
+ const args = validateToolArgs(
1032
+ Schema15,
1033
+ raw,
1034
+ NAME12
1035
+ );
1036
+ const client = getClient();
539
1037
  const { node, type } = await resolveResource(client, args.vmid);
540
1038
  const body = { snapname: args.snapname };
541
1039
  if (typeof args.description === "string" && args.description.length > 0) {
@@ -556,39 +1054,75 @@ function createProxmoxSnapshotResourceTool(getClient2) {
556
1054
  };
557
1055
  }
558
1056
 
1057
+ // src/tools/proxmox_rollback_snapshot.ts
1058
+ import { Type as Type16 } from "@sinclair/typebox";
1059
+ var Schema16 = Type16.Object(
1060
+ {
1061
+ vmid: Type16.Integer({ minimum: 1, description: "Container or VM ID." }),
1062
+ snapname: Type16.String({ minLength: 1, description: "Snapshot name to roll back to." }),
1063
+ start: Type16.Optional(
1064
+ Type16.Boolean({ description: "Start the resource after rollback completes (default false)." })
1065
+ ),
1066
+ confirm: Type16.Boolean({ description: "Must be true. Tier-3 destructive gate." }),
1067
+ destructive: Type16.Boolean({ description: "Must be true. Tier-3 destructive gate." })
1068
+ },
1069
+ { additionalProperties: false }
1070
+ );
1071
+ var NAME13 = "proxmox_rollback_snapshot";
1072
+ function createProxmoxRollbackSnapshotTool(getClient) {
1073
+ return {
1074
+ name: NAME13,
1075
+ label: "proxmox: rollback snapshot",
1076
+ description: "Roll back an LXC container or QEMU VM to a named snapshot. Tier-3 destructive because it reverts guest state; requires confirm:true, destructive:true, and env PROXMOX_ENABLE_DESTRUCTIVE=1.",
1077
+ parameters: Schema16,
1078
+ execute: async (_id, raw) => {
1079
+ assertEnvFlag("PROXMOX_ENABLE_DESTRUCTIVE", NAME13);
1080
+ assertDestructive(raw, NAME13);
1081
+ const args = validateToolArgs(Schema16, raw, NAME13);
1082
+ const client = getClient();
1083
+ const { node, type } = await resolveResource(client, args.vmid);
1084
+ const upid = await client.post(
1085
+ `/nodes/${node}/${type}/${args.vmid}/snapshot/${encodeURIComponent(args.snapname)}/rollback`,
1086
+ { start: args.start ? 1 : 0 }
1087
+ );
1088
+ return jsonToolResult({ vmid: args.vmid, node, type, snapname: args.snapname, start: args.start === true, upid });
1089
+ }
1090
+ };
1091
+ }
1092
+
559
1093
  // src/tools/proxmox_run_backup.ts
560
- import { Type as Type12 } from "@sinclair/typebox";
561
- var Schema12 = Type12.Object(
1094
+ import { Type as Type17 } from "@sinclair/typebox";
1095
+ var Schema17 = Type17.Object(
562
1096
  {
563
- vmid: Type12.Integer({ minimum: 1, description: "Container or VM ID to back up." }),
564
- storage: Type12.String({
1097
+ vmid: Type17.Integer({ minimum: 1, description: "Container or VM ID to back up." }),
1098
+ storage: Type17.String({
565
1099
  minLength: 1,
566
1100
  description: "PVE storage ID where the vzdump archive should be written."
567
1101
  }),
568
- mode: Type12.Optional(
569
- Type12.Union(
570
- [Type12.Literal("snapshot"), Type12.Literal("suspend"), Type12.Literal("stop")],
1102
+ mode: Type17.Optional(
1103
+ Type17.Union(
1104
+ [Type17.Literal("snapshot"), Type17.Literal("suspend"), Type17.Literal("stop")],
571
1105
  { description: "Backup mode. Defaults to 'snapshot'." }
572
1106
  )
573
1107
  ),
574
- confirm: Type12.Boolean({
1108
+ confirm: Type17.Boolean({
575
1109
  description: "Must be true to write. Tier-2 safe-write gate."
576
1110
  })
577
1111
  },
578
1112
  { additionalProperties: false }
579
1113
  );
580
- var NAME5 = "proxmox_run_backup";
581
- function createProxmoxRunBackupTool(getClient2) {
1114
+ var NAME14 = "proxmox_run_backup";
1115
+ function createProxmoxRunBackupTool(getClient) {
582
1116
  return {
583
- name: NAME5,
1117
+ name: NAME14,
584
1118
  label: "proxmox: run backup",
585
1119
  description: "Trigger a vzdump backup of a single vmid to a target storage (POST /nodes/{node}/vzdump with {vmid, storage, mode, compress:'zstd'}). Tier-2 write; requires confirm:true.",
586
- parameters: Schema12,
1120
+ parameters: Schema17,
587
1121
  execute: async (_id, raw) => {
588
- assertConfirmedWrite(raw, NAME5);
589
- const args = raw;
1122
+ assertConfirmedWrite(raw, NAME14);
1123
+ const args = validateToolArgs(Schema17, raw, NAME14);
590
1124
  const mode = args.mode ?? "snapshot";
591
- const client = getClient2();
1125
+ const client = getClient();
592
1126
  const { node } = await resolveResource(client, args.vmid);
593
1127
  const upid = await client.post(`/nodes/${node}/vzdump`, {
594
1128
  vmid: args.vmid,
@@ -608,26 +1142,27 @@ function createProxmoxRunBackupTool(getClient2) {
608
1142
  }
609
1143
 
610
1144
  // src/tools/proxmox_get_task_status.ts
611
- import { Type as Type13 } from "@sinclair/typebox";
612
- var Schema13 = Type13.Object(
1145
+ import { Type as Type18 } from "@sinclair/typebox";
1146
+ var NAME15 = "proxmox_get_task_status";
1147
+ var Schema18 = Type18.Object(
613
1148
  {
614
- upid: Type13.String({
1149
+ upid: Type18.String({
615
1150
  minLength: 1,
616
1151
  description: "Task UPID returned by a prior write tool (e.g. start, stop, snapshot, backup)."
617
1152
  })
618
1153
  },
619
1154
  { additionalProperties: false }
620
1155
  );
621
- function createProxmoxGetTaskStatusTool(getClient2) {
1156
+ function createProxmoxGetTaskStatusTool(getClient) {
622
1157
  return {
623
- name: "proxmox_get_task_status",
1158
+ name: NAME15,
624
1159
  label: "proxmox: get task status",
625
1160
  description: "Get the current status of a Proxmox task by UPID (running/stopped, exit status) via GET /nodes/{node}/tasks/{upid}/status. Node is parsed from the UPID.",
626
- parameters: Schema13,
1161
+ parameters: Schema18,
627
1162
  execute: async (_id, raw) => {
628
- const args = raw;
1163
+ const args = validateToolArgs(Schema18, raw, NAME15);
629
1164
  const { node } = parseTaskUpid(args.upid);
630
- const client = getClient2();
1165
+ const client = getClient();
631
1166
  const status = await client.get(
632
1167
  `/nodes/${node}/tasks/${encodeURIComponent(args.upid)}/status`
633
1168
  );
@@ -637,18 +1172,19 @@ function createProxmoxGetTaskStatusTool(getClient2) {
637
1172
  }
638
1173
 
639
1174
  // src/tools/proxmox_get_task_log.ts
640
- import { Type as Type14 } from "@sinclair/typebox";
641
- var Schema14 = Type14.Object(
1175
+ import { Type as Type19 } from "@sinclair/typebox";
1176
+ var NAME16 = "proxmox_get_task_log";
1177
+ var Schema19 = Type19.Object(
642
1178
  {
643
- upid: Type14.String({
1179
+ upid: Type19.String({
644
1180
  minLength: 1,
645
1181
  description: "Task UPID returned by a prior write tool."
646
1182
  }),
647
- start: Type14.Optional(
648
- Type14.Integer({ minimum: 0, description: "Line offset to start from (default 0)." })
1183
+ start: Type19.Optional(
1184
+ Type19.Integer({ minimum: 0, description: "Line offset to start from (default 0)." })
649
1185
  ),
650
- limit: Type14.Optional(
651
- Type14.Integer({
1186
+ limit: Type19.Optional(
1187
+ Type19.Integer({
652
1188
  minimum: 1,
653
1189
  maximum: 500,
654
1190
  description: "Max lines to return (default 50, max 500)."
@@ -657,18 +1193,18 @@ var Schema14 = Type14.Object(
657
1193
  },
658
1194
  { additionalProperties: false }
659
1195
  );
660
- function createProxmoxGetTaskLogTool(getClient2) {
1196
+ function createProxmoxGetTaskLogTool(getClient) {
661
1197
  return {
662
- name: "proxmox_get_task_log",
1198
+ name: NAME16,
663
1199
  label: "proxmox: get task log",
664
1200
  description: "Tail a Proxmox task log by UPID via GET /nodes/{node}/tasks/{upid}/log?start=N&limit=M. Node is parsed from the UPID. Returns { lines, total }.",
665
- parameters: Schema14,
1201
+ parameters: Schema19,
666
1202
  execute: async (_id, raw) => {
667
- const args = raw;
1203
+ const args = validateToolArgs(Schema19, raw, NAME16);
668
1204
  const { node } = parseTaskUpid(args.upid);
669
1205
  const start = args.start ?? 0;
670
1206
  const limit = args.limit ?? 50;
671
- const client = getClient2();
1207
+ const client = getClient();
672
1208
  const lines = await client.get(
673
1209
  `/nodes/${node}/tasks/${encodeURIComponent(args.upid)}/log?start=${start}&limit=${limit}`
674
1210
  );
@@ -677,44 +1213,1520 @@ function createProxmoxGetTaskLogTool(getClient2) {
677
1213
  };
678
1214
  }
679
1215
 
680
- // mcp-server.ts
681
- var cfg = resolveConfig(process.env);
682
- registerSecret(cfg.tokenId);
683
- registerSecret(cfg.tokenSecret);
684
- registerSecret(`PVEAPIToken=${cfg.tokenId}=${cfg.tokenSecret}`);
685
- var getClient = () => new ProxmoxClient(cfg);
686
- var tools = [
687
- createProxmoxStatusTool(getClient),
688
- createProxmoxListContainersTool(getClient),
689
- createProxmoxListVmsTool(getClient),
690
- createProxmoxGetResourceTool(getClient),
691
- createProxmoxRecentTasksTool(getClient),
692
- createProxmoxListBackupsTool(getClient),
693
- createProxmoxResourceUsageTool(getClient),
694
- createProxmoxStartResourceTool(getClient),
695
- createProxmoxStopResourceTool(getClient),
696
- createProxmoxRebootResourceTool(getClient),
697
- createProxmoxSnapshotResourceTool(getClient),
698
- createProxmoxRunBackupTool(getClient),
699
- createProxmoxGetTaskStatusTool(getClient),
700
- createProxmoxGetTaskLogTool(getClient)
701
- ];
702
- var toolMap = new Map(tools.map((t) => [t.name, t]));
703
- var server = new Server({ name: "proxmox-mcp", version: "0.2.0" }, { capabilities: { tools: {} } });
704
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
705
- tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.parameters }))
706
- }));
707
- server.setRequestHandler(CallToolRequestSchema, async (req) => {
708
- const t = toolMap.get(req.params.name);
709
- if (!t) {
710
- return { content: [{ type: "text", text: JSON.stringify({ error: `unknown tool: ${req.params.name}` }) }], isError: true };
711
- }
712
- try {
713
- return await t.execute(req.params.name, req.params.arguments ?? {});
714
- } catch (e) {
715
- const msg = redact(e.message);
716
- return { content: [{ type: "text", text: JSON.stringify({ error: msg }) }], isError: true };
717
- }
718
- });
719
- var transport = new StdioServerTransport();
720
- await server.connect(transport);
1216
+ // src/tools/proxmox_list_templates.ts
1217
+ import { Type as Type20 } from "@sinclair/typebox";
1218
+ var NAME17 = "proxmox_list_templates";
1219
+ var Schema20 = Type20.Object(
1220
+ {
1221
+ node: Type20.Optional(
1222
+ Type20.String({ minLength: 1, description: "Node to query (defaults to first node)." })
1223
+ ),
1224
+ storage: Type20.Optional(
1225
+ Type20.String({ minLength: 1, description: "Storage to query (defaults to 'local')." })
1226
+ ),
1227
+ kind: Type20.Optional(
1228
+ Type20.Union(
1229
+ [Type20.Literal("vztmpl"), Type20.Literal("iso"), Type20.Literal("both")],
1230
+ { description: "Template kind: 'vztmpl' (CT templates), 'iso' (VM ISOs), or 'both'. Defaults to 'both'." }
1231
+ )
1232
+ )
1233
+ },
1234
+ { additionalProperties: false }
1235
+ );
1236
+ function createProxmoxListTemplatesTool(getClient) {
1237
+ return {
1238
+ name: NAME17,
1239
+ label: "proxmox: list templates",
1240
+ description: "List available LXC container templates (vztmpl) and/or VM ISOs on a node/storage (GET /nodes/{node}/storage/{storage}/content?content=vztmpl|iso). Defaults to both kinds on storage 'local'.",
1241
+ parameters: Schema20,
1242
+ execute: async (_id, raw) => {
1243
+ const args = validateToolArgs(Schema20, raw, NAME17);
1244
+ const client = getClient();
1245
+ let node = args.node;
1246
+ if (!node) {
1247
+ const nodes = await client.get("/cluster/resources?type=node");
1248
+ if (nodes.length === 0) throw new Error("no nodes found in cluster resources");
1249
+ node = nodes[0].node;
1250
+ }
1251
+ const storage = args.storage ?? "local";
1252
+ const kind = args.kind ?? "both";
1253
+ assertSafePathSegment(node, "node");
1254
+ assertSafePathSegment(storage, "storage");
1255
+ const nodeSeg = encodeURIComponent(node);
1256
+ const storageSeg = encodeURIComponent(storage);
1257
+ const out = {
1258
+ node,
1259
+ storage
1260
+ };
1261
+ if (kind === "vztmpl" || kind === "both") {
1262
+ out.container_templates = await client.get(
1263
+ `/nodes/${nodeSeg}/storage/${storageSeg}/content?content=vztmpl`
1264
+ );
1265
+ }
1266
+ if (kind === "iso" || kind === "both") {
1267
+ out.vm_isos = await client.get(
1268
+ `/nodes/${nodeSeg}/storage/${storageSeg}/content?content=iso`
1269
+ );
1270
+ }
1271
+ return jsonToolResult(out);
1272
+ }
1273
+ };
1274
+ }
1275
+
1276
+ // src/tools/proxmox_list_storage.ts
1277
+ import { Type as Type21 } from "@sinclair/typebox";
1278
+ var Schema21 = Type21.Object(
1279
+ {
1280
+ node: Type21.Optional(
1281
+ Type21.String({ minLength: 1, description: "Node to query. Defaults to all nodes." })
1282
+ )
1283
+ },
1284
+ { additionalProperties: false }
1285
+ );
1286
+ var NAME18 = "proxmox_list_storage";
1287
+ function createProxmoxListStorageTool(getClient) {
1288
+ return {
1289
+ name: NAME18,
1290
+ label: "proxmox: list storage",
1291
+ description: "List Proxmox storage status on one node or all nodes via GET /nodes/{node}/storage.",
1292
+ parameters: Schema21,
1293
+ execute: async (_id, raw = {}) => {
1294
+ const args = validateToolArgs(Schema21, raw, NAME18);
1295
+ const client = getClient();
1296
+ let nodes;
1297
+ if (args.node) {
1298
+ nodes = [args.node];
1299
+ } else {
1300
+ const resources = await client.get("/cluster/resources?type=node");
1301
+ nodes = resources.map((n) => n.node);
1302
+ if (nodes.length === 0) throw new Error("no nodes found in cluster resources");
1303
+ }
1304
+ const results = [];
1305
+ for (const node of nodes) {
1306
+ const storage = await client.get(`/nodes/${node}/storage`);
1307
+ results.push({ node, storage });
1308
+ }
1309
+ return jsonToolResult({ count: results.reduce((sum, n) => sum + n.storage.length, 0), nodes: results });
1310
+ }
1311
+ };
1312
+ }
1313
+
1314
+ // src/tools/proxmox_list_snapshots.ts
1315
+ import { Type as Type22 } from "@sinclair/typebox";
1316
+ var Schema22 = Type22.Object(
1317
+ {
1318
+ vmid: Type22.Integer({ minimum: 1, description: "Container or VM ID." })
1319
+ },
1320
+ { additionalProperties: false }
1321
+ );
1322
+ var NAME19 = "proxmox_list_snapshots";
1323
+ function createProxmoxListSnapshotsTool(getClient) {
1324
+ return {
1325
+ name: NAME19,
1326
+ label: "proxmox: list snapshots",
1327
+ description: "List snapshots for one LXC container or QEMU VM via GET /nodes/{node}/{type}/{vmid}/snapshot.",
1328
+ parameters: Schema22,
1329
+ execute: async (_id, raw) => {
1330
+ const args = validateToolArgs(Schema22, raw, NAME19);
1331
+ const client = getClient();
1332
+ const { node, type } = await resolveResource(client, args.vmid);
1333
+ const snapshots = await client.get(`/nodes/${node}/${type}/${args.vmid}/snapshot`);
1334
+ return jsonToolResult({ vmid: args.vmid, node, type, count: snapshots.length, snapshots });
1335
+ }
1336
+ };
1337
+ }
1338
+
1339
+ // src/tools/proxmox_guest_network.ts
1340
+ import { Type as Type23 } from "@sinclair/typebox";
1341
+ var Schema23 = Type23.Object(
1342
+ {
1343
+ vmid: Type23.Integer({ minimum: 1, description: "Container or VM ID." })
1344
+ },
1345
+ { additionalProperties: false }
1346
+ );
1347
+ var NAME20 = "proxmox_guest_network";
1348
+ function usableIpv4(ip) {
1349
+ return !ip.startsWith("127.") && !ip.startsWith("169.254.") && ip !== "0.0.0.0";
1350
+ }
1351
+ function createProxmoxGuestNetworkTool(getClient) {
1352
+ return {
1353
+ name: NAME20,
1354
+ label: "proxmox: guest network",
1355
+ description: "Return guest network interfaces and usable IPv4 addresses for a QEMU VM via guest agent or an LXC container via its interfaces endpoint.",
1356
+ parameters: Schema23,
1357
+ execute: async (_id, raw) => {
1358
+ const args = validateToolArgs(Schema23, raw, NAME20);
1359
+ const client = getClient();
1360
+ const { node, type } = await resolveResource(client, args.vmid);
1361
+ if (type === "qemu") {
1362
+ const data = await client.get(
1363
+ `/nodes/${node}/qemu/${args.vmid}/agent/network-get-interfaces`
1364
+ );
1365
+ const interfaces2 = data.result ?? [];
1366
+ const ipv42 = interfaces2.flatMap(
1367
+ (iface) => (iface["ip-addresses"] ?? []).filter((ip) => ip["ip-address-type"] === "ipv4" && ip["ip-address"] && usableIpv4(ip["ip-address"])).map((ip) => ({ interface: iface.name, address: ip["ip-address"], prefix: ip.prefix }))
1368
+ );
1369
+ return jsonToolResult({ vmid: args.vmid, node, type, ipv4: ipv42, interfaces: interfaces2 });
1370
+ }
1371
+ const interfaces = await client.get(`/nodes/${node}/lxc/${args.vmid}/interfaces`);
1372
+ const ipv4 = interfaces.filter((iface) => iface.inet && usableIpv4(iface.inet.split("/")[0])).map((iface) => {
1373
+ const [address, prefix] = iface.inet.split("/");
1374
+ return { interface: iface.name, address, prefix: prefix ? Number(prefix) : void 0 };
1375
+ });
1376
+ return jsonToolResult({ vmid: args.vmid, node, type, ipv4, interfaces });
1377
+ }
1378
+ };
1379
+ }
1380
+
1381
+ // src/tools/proxmox_wait_task.ts
1382
+ import { Type as Type24 } from "@sinclair/typebox";
1383
+ var Schema24 = Type24.Object(
1384
+ {
1385
+ upid: Type24.String({ minLength: 1, description: "Task UPID to wait for." }),
1386
+ timeoutSeconds: Type24.Optional(
1387
+ Type24.Integer({ minimum: 1, maximum: 3600, description: "Max wait time in seconds. Default 60." })
1388
+ ),
1389
+ intervalMs: Type24.Optional(
1390
+ Type24.Integer({ minimum: 100, maximum: 1e4, description: "Polling interval in milliseconds. Default 1000." })
1391
+ )
1392
+ },
1393
+ { additionalProperties: false }
1394
+ );
1395
+ var NAME21 = "proxmox_wait_task";
1396
+ function createProxmoxWaitTaskTool(getClient) {
1397
+ return {
1398
+ name: NAME21,
1399
+ label: "proxmox: wait task",
1400
+ description: "Poll a Proxmox task by UPID until it stops or the timeout expires. Returns done:false on timeout with the last status.",
1401
+ parameters: Schema24,
1402
+ execute: async (_id, raw) => {
1403
+ const args = validateToolArgs(Schema24, raw, NAME21);
1404
+ const { node } = parseTaskUpid(args.upid);
1405
+ const timeoutMs = (args.timeoutSeconds ?? 60) * 1e3;
1406
+ const intervalMs = args.intervalMs ?? 1e3;
1407
+ const deadline = Date.now() + timeoutMs;
1408
+ const client = getClient();
1409
+ let polls = 0;
1410
+ let lastStatus = null;
1411
+ while (Date.now() <= deadline) {
1412
+ polls += 1;
1413
+ lastStatus = await client.get(
1414
+ `/nodes/${node}/tasks/${encodeURIComponent(args.upid)}/status`
1415
+ );
1416
+ if (lastStatus.status === "stopped" || lastStatus.exitstatus) {
1417
+ return jsonToolResult({ upid: args.upid, node, done: true, polls, status: lastStatus });
1418
+ }
1419
+ await sleep2(Math.min(intervalMs, Math.max(0, deadline - Date.now())));
1420
+ }
1421
+ return jsonToolResult({ upid: args.upid, node, done: false, polls, status: lastStatus });
1422
+ }
1423
+ };
1424
+ }
1425
+ function sleep2(ms) {
1426
+ return new Promise((resolve) => setTimeout(resolve, ms));
1427
+ }
1428
+
1429
+ // src/tools/proxmox_next_vmid.ts
1430
+ import { Type as Type25 } from "@sinclair/typebox";
1431
+ var Schema25 = Type25.Object({}, { additionalProperties: false });
1432
+ var NAME22 = "proxmox_next_vmid";
1433
+ function createProxmoxNextVmidTool(getClient) {
1434
+ return {
1435
+ name: NAME22,
1436
+ label: "proxmox: next vmid",
1437
+ description: "Return the next available Proxmox VMID via GET /cluster/nextid.",
1438
+ parameters: Schema25,
1439
+ execute: async (_id, raw = {}) => {
1440
+ validateToolArgs(Schema25, raw, NAME22);
1441
+ const nextid = await getClient().get("/cluster/nextid");
1442
+ return jsonToolResult({ vmid: Number(nextid) });
1443
+ }
1444
+ };
1445
+ }
1446
+
1447
+ // src/tools/proxmox_list_pool_resources.ts
1448
+ import { Type as Type26 } from "@sinclair/typebox";
1449
+ var Schema26 = Type26.Object(
1450
+ {
1451
+ pool: Type26.Optional(
1452
+ Type26.String({ minLength: 1, description: "Pool ID to inspect (default mcp-smoke)." })
1453
+ )
1454
+ },
1455
+ { additionalProperties: false }
1456
+ );
1457
+ var NAME23 = "proxmox_list_pool_resources";
1458
+ function createProxmoxListPoolResourcesTool(getClient) {
1459
+ return {
1460
+ name: NAME23,
1461
+ label: "proxmox: list pool resources",
1462
+ description: "List resources assigned to a Proxmox pool (GET /pools/{pool}). Defaults to the mcp-smoke pool for smoke-test audits.",
1463
+ parameters: Schema26,
1464
+ execute: async (_id = "id", raw = {}) => {
1465
+ const args = validateToolArgs(Schema26, raw, NAME23);
1466
+ const pool = args.pool ?? "mcp-smoke";
1467
+ const detail = await getClient().get(`/pools/${encodeURIComponent(pool)}`);
1468
+ const members = Array.isArray(detail.members) ? detail.members : [];
1469
+ return jsonToolResult({
1470
+ pool,
1471
+ comment: detail.comment,
1472
+ count: members.length,
1473
+ resources: members
1474
+ });
1475
+ }
1476
+ };
1477
+ }
1478
+
1479
+ // src/tools/proxmox_create_container.ts
1480
+ import { Type as Type27 } from "@sinclair/typebox";
1481
+ var Schema27 = Type27.Object(
1482
+ {
1483
+ vmid: Type27.Integer({ minimum: 1, description: "VMID for the new container." }),
1484
+ hostname: Type27.String({ minLength: 1, description: "Container hostname." }),
1485
+ ostemplate: Type27.String({
1486
+ minLength: 1,
1487
+ description: "OS template volid (e.g. 'local:vztmpl/ubuntu-24.04-standard_*.tar.zst')."
1488
+ }),
1489
+ node: Type27.Optional(
1490
+ Type27.String({ minLength: 1, description: "Node to create on (defaults to first node)." })
1491
+ ),
1492
+ storage: Type27.Optional(
1493
+ Type27.String({ minLength: 1, description: "Root storage (default 'local-lvm')." })
1494
+ ),
1495
+ memory: Type27.Optional(
1496
+ Type27.Integer({ minimum: 16, description: "Memory in MiB (default 512)." })
1497
+ ),
1498
+ cores: Type27.Optional(
1499
+ Type27.Integer({ minimum: 1, description: "CPU cores (default 1)." })
1500
+ ),
1501
+ rootfs_size: Type27.Optional(
1502
+ Type27.String({ minLength: 1, description: "Root filesystem size in GB (default '8')." })
1503
+ ),
1504
+ net: Type27.Optional(
1505
+ Type27.String({
1506
+ minLength: 1,
1507
+ description: "Network config for net0 (default 'name=eth0,bridge=vmbr0,ip=dhcp')."
1508
+ })
1509
+ ),
1510
+ start: Type27.Optional(
1511
+ Type27.Boolean({ description: "Start after create (default false)." })
1512
+ ),
1513
+ pool: Type27.Optional(
1514
+ Type27.String({ minLength: 1, description: "Optional resource pool ID to place the container into." })
1515
+ ),
1516
+ onboot: Type27.Optional(
1517
+ Type27.Boolean({ description: "Start container on host boot (default false)." })
1518
+ ),
1519
+ unprivileged: Type27.Optional(
1520
+ Type27.Boolean({ description: "Create an unprivileged container (default true)." })
1521
+ ),
1522
+ protection: Type27.Optional(
1523
+ Type27.Boolean({ description: "Enable Proxmox protection flag (default false)." })
1524
+ ),
1525
+ features: Type27.Optional(
1526
+ Type27.String({ minLength: 1, description: "Optional LXC features string, e.g. 'nesting=1'." })
1527
+ ),
1528
+ description: Type27.Optional(
1529
+ Type27.String({ description: "Optional container description." })
1530
+ ),
1531
+ tags: Type27.Optional(
1532
+ Type27.String({ minLength: 1, description: "Optional semicolon-delimited Proxmox tags." })
1533
+ ),
1534
+ password: Type27.Optional(
1535
+ Type27.String({ description: "Root password (optional)." })
1536
+ ),
1537
+ ssh_public_keys: Type27.Optional(
1538
+ Type27.String({ description: "SSH public keys (optional)." })
1539
+ ),
1540
+ confirm: Type27.Boolean({
1541
+ description: "Must be true to write. Tier-2 safe-write gate."
1542
+ })
1543
+ },
1544
+ { additionalProperties: false }
1545
+ );
1546
+ var NAME24 = "proxmox_create_container";
1547
+ function createProxmoxCreateContainerTool(getClient) {
1548
+ return {
1549
+ name: NAME24,
1550
+ label: "proxmox: create container",
1551
+ description: "Create a new LXC container on a node (POST /nodes/{node}/lxc) with sensible defaults (storage local-lvm, 512MiB, 1 core, 8GB rootfs, DHCP net). Tier-2 write; requires confirm:true.",
1552
+ parameters: Schema27,
1553
+ execute: async (_id, raw) => {
1554
+ assertConfirmedWrite(raw, NAME24);
1555
+ const args = validateToolArgs(Schema27, raw, NAME24);
1556
+ if (typeof args.password === "string" && args.password.length > 0) {
1557
+ registerSecret(args.password);
1558
+ }
1559
+ const client = getClient();
1560
+ let node = args.node;
1561
+ if (!node) {
1562
+ const nodes = await client.get("/cluster/resources?type=node");
1563
+ if (nodes.length === 0) throw new Error("no nodes found in cluster resources");
1564
+ node = nodes[0].node;
1565
+ }
1566
+ const storage = args.storage ?? "local-lvm";
1567
+ const rootfsSize = args.rootfs_size ?? "8";
1568
+ const body = {
1569
+ vmid: args.vmid,
1570
+ hostname: args.hostname,
1571
+ ostemplate: args.ostemplate,
1572
+ storage,
1573
+ memory: args.memory ?? 512,
1574
+ cores: args.cores ?? 1,
1575
+ rootfs: `${storage}:${rootfsSize}`,
1576
+ net0: args.net ?? "name=eth0,bridge=vmbr0,ip=dhcp",
1577
+ start: args.start ? 1 : 0,
1578
+ onboot: args.onboot ? 1 : 0,
1579
+ unprivileged: args.unprivileged === false ? 0 : 1,
1580
+ protection: args.protection ? 1 : 0
1581
+ };
1582
+ for (const key of ["pool", "features"]) {
1583
+ const value = args[key];
1584
+ if (typeof value === "string" && value.length > 0) body[key] = value;
1585
+ }
1586
+ if (typeof args.password === "string" && args.password.length > 0) {
1587
+ body.password = args.password;
1588
+ }
1589
+ if (typeof args.ssh_public_keys === "string" && args.ssh_public_keys.length > 0) {
1590
+ body["ssh-public-keys"] = args.ssh_public_keys;
1591
+ }
1592
+ if (typeof args.description === "string" && args.description.length > 0) {
1593
+ body.description = args.description;
1594
+ }
1595
+ if (typeof args.tags === "string" && args.tags.length > 0) {
1596
+ body.tags = args.tags;
1597
+ }
1598
+ const upid = await client.post(`/nodes/${node}/lxc`, body);
1599
+ return jsonToolResult({
1600
+ vmid: args.vmid,
1601
+ node,
1602
+ hostname: args.hostname,
1603
+ upid
1604
+ });
1605
+ }
1606
+ };
1607
+ }
1608
+
1609
+ // src/tools/proxmox_create_vm.ts
1610
+ import { Type as Type28 } from "@sinclair/typebox";
1611
+ var Schema28 = Type28.Object(
1612
+ {
1613
+ vmid: Type28.Integer({ minimum: 1, description: "VMID for the new VM." }),
1614
+ name: Type28.String({ minLength: 1, description: "VM display name." }),
1615
+ node: Type28.Optional(
1616
+ Type28.String({ minLength: 1, description: "Node to create on (defaults to first node)." })
1617
+ ),
1618
+ memory: Type28.Optional(
1619
+ Type28.Integer({ minimum: 16, description: "Memory in MiB (default 2048)." })
1620
+ ),
1621
+ cores: Type28.Optional(
1622
+ Type28.Integer({ minimum: 1, description: "CPU cores (default 2)." })
1623
+ ),
1624
+ iso: Type28.Optional(
1625
+ Type28.String({
1626
+ minLength: 1,
1627
+ description: "ISO volid for install media (e.g. 'local:iso/ubuntu-24.04.iso'). If set, attaches as ide2 cdrom."
1628
+ })
1629
+ ),
1630
+ disk_size: Type28.Optional(
1631
+ Type28.String({ minLength: 1, description: "Primary disk size in GB on scsi0 (default '32')." })
1632
+ ),
1633
+ storage: Type28.Optional(
1634
+ Type28.String({ minLength: 1, description: "Disk storage (default 'local-lvm')." })
1635
+ ),
1636
+ net: Type28.Optional(
1637
+ Type28.String({
1638
+ minLength: 1,
1639
+ description: "Network config for net0 (default 'model=virtio,bridge=vmbr0')."
1640
+ })
1641
+ ),
1642
+ start: Type28.Optional(
1643
+ Type28.Boolean({ description: "Start after create (default false)." })
1644
+ ),
1645
+ pool: Type28.Optional(
1646
+ Type28.String({ minLength: 1, description: "Optional resource pool ID to place the VM into." })
1647
+ ),
1648
+ onboot: Type28.Optional(
1649
+ Type28.Boolean({ description: "Start VM on host boot (default false)." })
1650
+ ),
1651
+ protection: Type28.Optional(
1652
+ Type28.Boolean({ description: "Enable Proxmox protection flag (default false)." })
1653
+ ),
1654
+ agent: Type28.Optional(
1655
+ Type28.Boolean({ description: "Enable QEMU guest agent in VM config (default false)." })
1656
+ ),
1657
+ scsihw: Type28.Optional(
1658
+ Type28.String({ minLength: 1, description: "Optional SCSI controller, e.g. 'virtio-scsi-pci'." })
1659
+ ),
1660
+ boot: Type28.Optional(
1661
+ Type28.String({ minLength: 1, description: "Optional boot order string." })
1662
+ ),
1663
+ bios: Type28.Optional(
1664
+ Type28.Union([Type28.Literal("seabios"), Type28.Literal("ovmf")], { description: "Optional VM BIOS type." })
1665
+ ),
1666
+ machine: Type28.Optional(
1667
+ Type28.String({ minLength: 1, description: "Optional machine type." })
1668
+ ),
1669
+ cpu: Type28.Optional(
1670
+ Type28.String({ minLength: 1, description: "Optional CPU type." })
1671
+ ),
1672
+ sockets: Type28.Optional(
1673
+ Type28.Integer({ minimum: 1, description: "Optional socket count." })
1674
+ ),
1675
+ description: Type28.Optional(
1676
+ Type28.String({ description: "Optional VM description." })
1677
+ ),
1678
+ tags: Type28.Optional(
1679
+ Type28.String({ minLength: 1, description: "Optional semicolon-delimited Proxmox tags." })
1680
+ ),
1681
+ ciuser: Type28.Optional(
1682
+ Type28.String({ minLength: 1, description: "Optional cloud-init username." })
1683
+ ),
1684
+ cipassword: Type28.Optional(
1685
+ Type28.String({ description: "Optional cloud-init password." })
1686
+ ),
1687
+ sshkeys: Type28.Optional(
1688
+ Type28.String({ description: "Optional cloud-init SSH public keys." })
1689
+ ),
1690
+ ipconfig0: Type28.Optional(
1691
+ Type28.String({ minLength: 1, description: "Optional cloud-init ipconfig0, e.g. 'ip=dhcp'." })
1692
+ ),
1693
+ nameserver: Type28.Optional(
1694
+ Type28.String({ minLength: 1, description: "Optional cloud-init DNS server list." })
1695
+ ),
1696
+ searchdomain: Type28.Optional(
1697
+ Type28.String({ minLength: 1, description: "Optional cloud-init DNS search domain." })
1698
+ ),
1699
+ confirm: Type28.Boolean({
1700
+ description: "Must be true to write. Tier-2 safe-write gate."
1701
+ })
1702
+ },
1703
+ { additionalProperties: false }
1704
+ );
1705
+ var NAME25 = "proxmox_create_vm";
1706
+ function createProxmoxCreateVmTool(getClient) {
1707
+ return {
1708
+ name: NAME25,
1709
+ label: "proxmox: create vm",
1710
+ description: "Create a new QEMU VM on a node (POST /nodes/{node}/qemu) with sensible defaults (2GiB, 2 cores, 32GB disk on local-lvm, virtio net). Optionally attaches an ISO as ide2 cdrom. Tier-2 write; requires confirm:true.",
1711
+ parameters: Schema28,
1712
+ execute: async (_id, raw) => {
1713
+ assertConfirmedWrite(raw, NAME25);
1714
+ const args = validateToolArgs(Schema28, raw, NAME25);
1715
+ if (typeof args.cipassword === "string" && args.cipassword.length > 0) {
1716
+ registerSecret(args.cipassword);
1717
+ }
1718
+ const client = getClient();
1719
+ let node = args.node;
1720
+ if (!node) {
1721
+ const nodes = await client.get("/cluster/resources?type=node");
1722
+ if (nodes.length === 0) throw new Error("no nodes found in cluster resources");
1723
+ node = nodes[0].node;
1724
+ }
1725
+ const storage = args.storage ?? "local-lvm";
1726
+ const diskSize = args.disk_size ?? "32";
1727
+ const body = {
1728
+ vmid: args.vmid,
1729
+ name: args.name,
1730
+ memory: args.memory ?? 2048,
1731
+ cores: args.cores ?? 2,
1732
+ scsi0: `${storage}:${diskSize}`,
1733
+ net0: args.net ?? "model=virtio,bridge=vmbr0",
1734
+ start: args.start ? 1 : 0,
1735
+ onboot: args.onboot ? 1 : 0,
1736
+ protection: args.protection ? 1 : 0,
1737
+ agent: args.agent ? 1 : 0
1738
+ };
1739
+ if (typeof args.iso === "string" && args.iso.length > 0) {
1740
+ body.ide2 = `${args.iso},media=cdrom`;
1741
+ }
1742
+ for (const key of ["pool", "scsihw", "boot", "bios", "machine", "cpu", "description", "tags", "ciuser", "cipassword", "sshkeys", "ipconfig0", "nameserver", "searchdomain"]) {
1743
+ const value = args[key];
1744
+ if (typeof value === "string" && value.length > 0) body[key] = value;
1745
+ }
1746
+ if (typeof args.sockets === "number") body.sockets = args.sockets;
1747
+ const upid = await client.post(`/nodes/${node}/qemu`, body);
1748
+ return jsonToolResult({
1749
+ vmid: args.vmid,
1750
+ node,
1751
+ name: args.name,
1752
+ upid
1753
+ });
1754
+ }
1755
+ };
1756
+ }
1757
+
1758
+ // src/tools/proxmox_clone_resource.ts
1759
+ import { Type as Type29 } from "@sinclair/typebox";
1760
+ var Schema29 = Type29.Object(
1761
+ {
1762
+ source_vmid: Type29.Integer({ minimum: 1, description: "Source CT/VM ID to clone from." }),
1763
+ new_vmid: Type29.Integer({ minimum: 1, description: "VMID for the cloned resource." }),
1764
+ name: Type29.String({ minLength: 1, description: "Name/hostname for the new clone." }),
1765
+ full: Type29.Optional(
1766
+ Type29.Boolean({ description: "Full clone (default true). Set false for a linked clone." })
1767
+ ),
1768
+ storage: Type29.Optional(
1769
+ Type29.String({ minLength: 1, description: "Target storage (default: same as source)." })
1770
+ ),
1771
+ target_node: Type29.Optional(
1772
+ Type29.String({ minLength: 1, description: "Optional target node for the clone." })
1773
+ ),
1774
+ pool: Type29.Optional(
1775
+ Type29.String({ minLength: 1, description: "Optional resource pool ID for the clone." })
1776
+ ),
1777
+ snapname: Type29.Optional(
1778
+ Type29.String({ minLength: 1, description: "Clone from a named snapshot (optional)." })
1779
+ ),
1780
+ description: Type29.Optional(
1781
+ Type29.String({ description: "Optional description for the clone." })
1782
+ ),
1783
+ confirm: Type29.Boolean({
1784
+ description: "Must be true to write. Tier-2 safe-write gate."
1785
+ })
1786
+ },
1787
+ { additionalProperties: false }
1788
+ );
1789
+ var NAME26 = "proxmox_clone_resource";
1790
+ function createProxmoxCloneResourceTool(getClient) {
1791
+ return {
1792
+ name: NAME26,
1793
+ label: "proxmox: clone resource",
1794
+ description: "Clone an existing LXC or QEMU resource by source_vmid to a new_vmid (POST /nodes/{node}/{type}/{source_vmid}/clone). Resolves source node/type from cluster resources. Tier-2 write; requires confirm:true.",
1795
+ parameters: Schema29,
1796
+ execute: async (_id, raw) => {
1797
+ assertConfirmedWrite(raw, NAME26);
1798
+ const args = validateToolArgs(Schema29, raw, NAME26);
1799
+ const client = getClient();
1800
+ const { node, type } = await resolveResource(client, args.source_vmid);
1801
+ const body = {
1802
+ newid: args.new_vmid,
1803
+ name: args.name,
1804
+ full: args.full !== false ? 1 : 0
1805
+ };
1806
+ if (typeof args.storage === "string" && args.storage.length > 0) {
1807
+ body.storage = args.storage;
1808
+ }
1809
+ if (typeof args.target_node === "string" && args.target_node.length > 0) {
1810
+ body.target = args.target_node;
1811
+ }
1812
+ if (typeof args.pool === "string" && args.pool.length > 0) {
1813
+ body.pool = args.pool;
1814
+ }
1815
+ if (typeof args.snapname === "string" && args.snapname.length > 0) {
1816
+ body.snapname = args.snapname;
1817
+ }
1818
+ if (typeof args.description === "string" && args.description.length > 0) {
1819
+ body.description = args.description;
1820
+ }
1821
+ const upid = await client.post(
1822
+ `/nodes/${node}/${type}/${args.source_vmid}/clone`,
1823
+ body
1824
+ );
1825
+ return jsonToolResult({
1826
+ source_vmid: args.source_vmid,
1827
+ new_vmid: args.new_vmid,
1828
+ node,
1829
+ type,
1830
+ name: args.name,
1831
+ upid
1832
+ });
1833
+ }
1834
+ };
1835
+ }
1836
+
1837
+ // src/tools/proxmox_destroy_resource.ts
1838
+ import { Type as Type30 } from "@sinclair/typebox";
1839
+ var Schema30 = Type30.Object(
1840
+ {
1841
+ vmid: Type30.Integer({ minimum: 1, description: "Container or VM ID to destroy." }),
1842
+ purge: Type30.Optional(
1843
+ Type30.Boolean({
1844
+ description: "Remove from PVE backup/replication config too (default true)."
1845
+ })
1846
+ ),
1847
+ force: Type30.Optional(
1848
+ Type30.Boolean({
1849
+ description: "Allow destroying a running VM (default false)."
1850
+ })
1851
+ ),
1852
+ confirm: Type30.Boolean({
1853
+ description: "Must be true. Tier-3 destructive gate."
1854
+ }),
1855
+ destructive: Type30.Boolean({
1856
+ description: "Must be true. Tier-3 destructive gate."
1857
+ })
1858
+ },
1859
+ { additionalProperties: false }
1860
+ );
1861
+ var NAME27 = "proxmox_destroy_resource";
1862
+ function createProxmoxDestroyResourceTool(getClient) {
1863
+ return {
1864
+ name: NAME27,
1865
+ label: "proxmox: destroy resource",
1866
+ description: "Permanently delete an LXC container or QEMU VM by vmid (DELETE /nodes/{node}/{type}/{vmid}). Tier-3 destructive; requires confirm:true, destructive:true, and env PROXMOX_ENABLE_DESTRUCTIVE=1.",
1867
+ parameters: Schema30,
1868
+ execute: async (_id, raw) => {
1869
+ assertEnvFlag("PROXMOX_ENABLE_DESTRUCTIVE", NAME27);
1870
+ assertDestructive(raw, NAME27);
1871
+ const args = validateToolArgs(Schema30, raw, NAME27);
1872
+ const purge = args.purge !== false;
1873
+ const force = args.force === true;
1874
+ const client = getClient();
1875
+ const { node, type } = await resolveResource(client, args.vmid);
1876
+ const params = new URLSearchParams();
1877
+ if (purge) {
1878
+ params.append("purge", "1");
1879
+ params.append("destroy-unreferenced-disks", "1");
1880
+ }
1881
+ if (force && type === "lxc") params.append("force", "1");
1882
+ const qs = params.toString();
1883
+ const path2 = qs.length > 0 ? `/nodes/${node}/${type}/${args.vmid}?${qs}` : `/nodes/${node}/${type}/${args.vmid}`;
1884
+ const upid = await client.delete(path2);
1885
+ return jsonToolResult({ vmid: args.vmid, node, type, upid });
1886
+ }
1887
+ };
1888
+ }
1889
+
1890
+ // src/tools/proxmox_cleanup_smoke_resources.ts
1891
+ import { Type as Type31 } from "@sinclair/typebox";
1892
+ var Schema31 = Type31.Object(
1893
+ {
1894
+ pool: Type31.Optional(
1895
+ Type31.String({ minLength: 1, description: "Pool ID to clean up (default mcp-smoke)." })
1896
+ ),
1897
+ name_prefix: Type31.Optional(
1898
+ Type31.String({
1899
+ minLength: 1,
1900
+ description: "Only delete guest names starting with this prefix (default mcp-smoke-)."
1901
+ })
1902
+ ),
1903
+ force: Type31.Optional(
1904
+ Type31.Boolean({
1905
+ description: "Allow deleting running smoke guests. Also passes force=1 for LXC cleanup (default false)."
1906
+ })
1907
+ ),
1908
+ dry_run: Type31.Optional(
1909
+ Type31.Boolean({ description: "Preview matching targets without deleting them (default true)." })
1910
+ ),
1911
+ wait: Type31.Optional(
1912
+ Type31.Boolean({ description: "Wait for delete tasks to finish when dry_run:false (default true)." })
1913
+ ),
1914
+ confirm: Type31.Optional(
1915
+ Type31.Boolean({ description: "Must be true when dry_run:false. Tier-3 destructive gate." })
1916
+ ),
1917
+ destructive: Type31.Optional(
1918
+ Type31.Boolean({ description: "Must be true when dry_run:false. Tier-3 destructive gate." })
1919
+ ),
1920
+ timeoutSeconds: Type31.Optional(
1921
+ Type31.Integer({ minimum: 1, maximum: 3600, description: "Max seconds to wait per delete task (default 180)." })
1922
+ ),
1923
+ intervalMs: Type31.Optional(
1924
+ Type31.Integer({ minimum: 100, maximum: 1e4, description: "Task polling interval in milliseconds (default 1000)." })
1925
+ )
1926
+ },
1927
+ { additionalProperties: false }
1928
+ );
1929
+ var NAME28 = "proxmox_cleanup_smoke_resources";
1930
+ function normalizeType(type) {
1931
+ if (type === "qemu") return "qemu";
1932
+ if (type === "lxc" || type === "openvz") return "lxc";
1933
+ return null;
1934
+ }
1935
+ function targetFromMember(member, namePrefix) {
1936
+ const type = normalizeType(member.type);
1937
+ const name = member.name ?? "";
1938
+ if (!type || typeof member.vmid !== "number" || !member.node || !name.startsWith(namePrefix)) return null;
1939
+ return {
1940
+ vmid: member.vmid,
1941
+ node: member.node,
1942
+ type,
1943
+ name,
1944
+ status: member.status
1945
+ };
1946
+ }
1947
+ async function waitForTask(client, upid, timeoutSeconds, intervalMs) {
1948
+ const { node } = parseTaskUpid(upid);
1949
+ const deadline = Date.now() + timeoutSeconds * 1e3;
1950
+ let polls = 0;
1951
+ let status = null;
1952
+ while (Date.now() <= deadline) {
1953
+ polls += 1;
1954
+ status = await client.get(`/nodes/${node}/tasks/${encodeURIComponent(upid)}/status`);
1955
+ if (status.status === "stopped" || status.exitstatus) {
1956
+ return { upid, node, done: true, polls, status };
1957
+ }
1958
+ await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, Math.max(0, deadline - Date.now()))));
1959
+ }
1960
+ return { upid, node, done: false, polls, status };
1961
+ }
1962
+ function createProxmoxCleanupSmokeResourcesTool(getClient) {
1963
+ return {
1964
+ name: NAME28,
1965
+ label: "proxmox: cleanup smoke resources",
1966
+ description: "Preview or destroy smoke-test LXC/QEMU resources from a pool when their names match the smoke prefix. Defaults to dry_run:true. Actual deletion requires dry_run:false, confirm:true, destructive:true, and PROXMOX_ENABLE_DESTRUCTIVE=1.",
1967
+ parameters: Schema31,
1968
+ execute: async (_id, raw) => {
1969
+ const args = validateToolArgs(Schema31, raw, NAME28);
1970
+ const pool = args.pool ?? "mcp-smoke";
1971
+ const namePrefix = args.name_prefix ?? "mcp-smoke-";
1972
+ const force = args.force === true;
1973
+ const dryRun = args.dry_run !== false;
1974
+ const wait = args.wait !== false;
1975
+ const client = getClient();
1976
+ const detail = await client.get(`/pools/${encodeURIComponent(pool)}`);
1977
+ const members = Array.isArray(detail.members) ? detail.members : [];
1978
+ const targets = members.map((member) => targetFromMember(member, namePrefix)).filter((target) => target !== null);
1979
+ const running = targets.filter((target) => target.status === "running");
1980
+ const deleteTargets = force ? targets : targets.filter((target) => target.status !== "running");
1981
+ const skippedRunning = force ? [] : running;
1982
+ if (dryRun) {
1983
+ return jsonToolResult({
1984
+ pool,
1985
+ name_prefix: namePrefix,
1986
+ dry_run: true,
1987
+ matched: targets.length,
1988
+ targets,
1989
+ skipped_running: skippedRunning,
1990
+ skipped: members.length - targets.length + skippedRunning.length
1991
+ });
1992
+ }
1993
+ assertEnvFlag("PROXMOX_ENABLE_DESTRUCTIVE", NAME28);
1994
+ assertDestructive(raw, NAME28);
1995
+ const destroyed = [];
1996
+ for (const target of deleteTargets) {
1997
+ const params = new URLSearchParams();
1998
+ params.append("purge", "1");
1999
+ params.append("destroy-unreferenced-disks", "1");
2000
+ if (force && target.type === "lxc") params.append("force", "1");
2001
+ const upid = await client.delete(
2002
+ `/nodes/${target.node}/${target.type}/${target.vmid}?${params.toString()}`
2003
+ );
2004
+ const entry = { ...target, upid };
2005
+ if (wait) {
2006
+ entry.wait = await waitForTask(client, upid, args.timeoutSeconds ?? 180, args.intervalMs ?? 1e3);
2007
+ }
2008
+ destroyed.push(entry);
2009
+ }
2010
+ return jsonToolResult({
2011
+ pool,
2012
+ name_prefix: namePrefix,
2013
+ dry_run: false,
2014
+ matched: targets.length,
2015
+ destroyed,
2016
+ skipped_running: skippedRunning,
2017
+ skipped: members.length - targets.length + skippedRunning.length
2018
+ });
2019
+ }
2020
+ };
2021
+ }
2022
+
2023
+ // src/tools/proxmox_delete_snapshot.ts
2024
+ import { Type as Type32 } from "@sinclair/typebox";
2025
+ var Schema32 = Type32.Object(
2026
+ {
2027
+ vmid: Type32.Integer({ minimum: 1, description: "Container or VM ID." }),
2028
+ snapname: Type32.String({
2029
+ minLength: 1,
2030
+ description: "Snapshot name to delete."
2031
+ }),
2032
+ confirm: Type32.Boolean({
2033
+ description: "Must be true. Tier-3 destructive gate."
2034
+ }),
2035
+ destructive: Type32.Boolean({
2036
+ description: "Must be true. Tier-3 destructive gate."
2037
+ })
2038
+ },
2039
+ { additionalProperties: false }
2040
+ );
2041
+ var NAME29 = "proxmox_delete_snapshot";
2042
+ function createProxmoxDeleteSnapshotTool(getClient) {
2043
+ return {
2044
+ name: NAME29,
2045
+ label: "proxmox: delete snapshot",
2046
+ description: "Delete a named snapshot from an LXC container or QEMU VM (DELETE /nodes/{node}/{type}/{vmid}/snapshot/{snapname}). Tier-3 destructive; requires confirm:true, destructive:true, and env PROXMOX_ENABLE_DESTRUCTIVE=1.",
2047
+ parameters: Schema32,
2048
+ execute: async (_id, raw) => {
2049
+ assertEnvFlag("PROXMOX_ENABLE_DESTRUCTIVE", NAME29);
2050
+ assertDestructive(raw, NAME29);
2051
+ const args = validateToolArgs(
2052
+ Schema32,
2053
+ raw,
2054
+ NAME29
2055
+ );
2056
+ const client = getClient();
2057
+ const { node, type } = await resolveResource(client, args.vmid);
2058
+ const upid = await client.delete(
2059
+ `/nodes/${node}/${type}/${args.vmid}/snapshot/${encodeURIComponent(args.snapname)}`
2060
+ );
2061
+ return jsonToolResult({ vmid: args.vmid, node, type, snapname: args.snapname, upid });
2062
+ }
2063
+ };
2064
+ }
2065
+
2066
+ // src/tools/proxmox_force_stop_resource.ts
2067
+ import { Type as Type33 } from "@sinclair/typebox";
2068
+ var Schema33 = Type33.Object(
2069
+ {
2070
+ vmid: Type33.Integer({ minimum: 1, description: "Container or VM ID to hard-stop." }),
2071
+ confirm: Type33.Boolean({
2072
+ description: "Must be true. Tier-3 destructive gate."
2073
+ }),
2074
+ destructive: Type33.Boolean({
2075
+ description: "Must be true. Tier-3 destructive gate."
2076
+ })
2077
+ },
2078
+ { additionalProperties: false }
2079
+ );
2080
+ var NAME30 = "proxmox_force_stop_resource";
2081
+ function createProxmoxForceStopResourceTool(getClient) {
2082
+ return {
2083
+ name: NAME30,
2084
+ label: "proxmox: force stop resource",
2085
+ description: "Hard-kill an LXC container or QEMU VM (POST /nodes/{node}/{type}/{vmid}/status/stop). Unlike reboot/shutdown this is a non-graceful stop. Tier-3 destructive; requires confirm:true, destructive:true, and env PROXMOX_ENABLE_DESTRUCTIVE=1.",
2086
+ parameters: Schema33,
2087
+ execute: async (_id, raw) => {
2088
+ assertEnvFlag("PROXMOX_ENABLE_DESTRUCTIVE", NAME30);
2089
+ assertDestructive(raw, NAME30);
2090
+ const args = validateToolArgs(Schema33, raw, NAME30);
2091
+ const client = getClient();
2092
+ const { node, type } = await resolveResource(client, args.vmid);
2093
+ const upid = await client.post(
2094
+ `/nodes/${node}/${type}/${args.vmid}/status/stop`,
2095
+ {}
2096
+ );
2097
+ return jsonToolResult({ vmid: args.vmid, node, type, upid });
2098
+ }
2099
+ };
2100
+ }
2101
+
2102
+ // src/tools/proxmox_exec.ts
2103
+ import { Type as Type34 } from "@sinclair/typebox";
2104
+
2105
+ // src/tools/ssh-target.ts
2106
+ function nonEmptyEnv(key) {
2107
+ const value = process.env[key];
2108
+ return value && value.length > 0 ? value : null;
2109
+ }
2110
+ function usableIpv42(ip) {
2111
+ if (ip.startsWith("127.")) return false;
2112
+ if (ip.startsWith("169.254.")) return false;
2113
+ if (ip === "0.0.0.0") return false;
2114
+ return true;
2115
+ }
2116
+ async function resolveQemuSshHost(client, node, vmid) {
2117
+ const envHost = nonEmptyEnv(`PROXMOX_VM_${vmid}_SSH_HOST`);
2118
+ if (envHost) return envHost;
2119
+ try {
2120
+ const data = await client.get(
2121
+ `/nodes/${node}/qemu/${vmid}/agent/network-get-interfaces`
2122
+ );
2123
+ const ifaces = data?.result ?? [];
2124
+ for (const iface of ifaces) {
2125
+ if (iface.name === "lo") continue;
2126
+ const ips = iface["ip-addresses"] ?? [];
2127
+ for (const entry of ips) {
2128
+ const ip = entry["ip-address"];
2129
+ if (!ip) continue;
2130
+ if (entry["ip-address-type"] !== "ipv4") continue;
2131
+ if (!usableIpv42(ip)) continue;
2132
+ return ip;
2133
+ }
2134
+ }
2135
+ } catch {
2136
+ }
2137
+ return null;
2138
+ }
2139
+ function qemuSshTarget(vmid, host, defaults) {
2140
+ return {
2141
+ host,
2142
+ port: 22,
2143
+ user: nonEmptyEnv(`PROXMOX_VM_${vmid}_SSH_USER`) ?? defaults.vmUser,
2144
+ keyPath: nonEmptyEnv(`PROXMOX_VM_${vmid}_SSH_KEY`) ?? defaults.vmKeyPath
2145
+ };
2146
+ }
2147
+ function missingQemuSshHostMessage(vmid) {
2148
+ return `vmid ${vmid} is QEMU and has no PROXMOX_VM_${vmid}_SSH_HOST set and guest agent did not return a usable IP. Install qemu-guest-agent in the VM and enable it with 'qm set ${vmid} --agent 1', or pin the IP via env.`;
2149
+ }
2150
+
2151
+ // src/tools/proxmox_exec.ts
2152
+ var Schema34 = Type34.Object(
2153
+ {
2154
+ vmid: Type34.Integer({ minimum: 1, description: "Container or VM id." }),
2155
+ command: Type34.String({ minLength: 1, description: "Shell command to run inside the resource." }),
2156
+ timeout: Type34.Optional(
2157
+ Type34.Integer({ minimum: 1, maximum: 3600, description: "Timeout in seconds (default 30)." })
2158
+ ),
2159
+ confirm: Type34.Boolean({ description: "Must be true to execute. Tier-2 safe-write gate." })
2160
+ },
2161
+ { additionalProperties: false }
2162
+ );
2163
+ var NAME31 = "proxmox_exec";
2164
+ function createProxmoxExecTool(getClient, getSsh, vmDefaults) {
2165
+ return {
2166
+ name: NAME31,
2167
+ label: "proxmox: exec in container or VM",
2168
+ description: "Run a shell command inside an LXC container (via SSH+pct exec) or QEMU VM (via direct SSH, IP from guest agent or env override). Returns stdout/stderr/exit_code. Tier-2 write; requires confirm:true.",
2169
+ parameters: Schema34,
2170
+ execute: async (_id, raw) => {
2171
+ assertConfirmedWrite(raw, NAME31);
2172
+ const args = validateToolArgs(Schema34, raw, NAME31);
2173
+ const timeoutMs = (args.timeout ?? 30) * 1e3;
2174
+ const client = getClient();
2175
+ const { node, type } = await resolveResource(client, args.vmid);
2176
+ const ssh = getSsh();
2177
+ if (type === "lxc") {
2178
+ const result2 = await ssh.execInLxc(args.vmid, args.command, timeoutMs);
2179
+ return jsonToolResult({
2180
+ vmid: args.vmid,
2181
+ type,
2182
+ stdout: result2.stdout,
2183
+ stderr: result2.stderr,
2184
+ exit_code: result2.exitCode
2185
+ });
2186
+ }
2187
+ const host = await resolveQemuSshHost(client, node, args.vmid);
2188
+ if (!host) {
2189
+ throw new Error(missingQemuSshHostMessage(args.vmid));
2190
+ }
2191
+ const target = qemuSshTarget(args.vmid, host, vmDefaults);
2192
+ const result = await ssh.execViaDirectSsh(target, args.command, timeoutMs);
2193
+ return jsonToolResult({
2194
+ vmid: args.vmid,
2195
+ type,
2196
+ stdout: result.stdout,
2197
+ stderr: result.stderr,
2198
+ exit_code: result.exitCode
2199
+ });
2200
+ }
2201
+ };
2202
+ }
2203
+
2204
+ // src/tools/proxmox_read_file.ts
2205
+ import { Type as Type35 } from "@sinclair/typebox";
2206
+ var Schema35 = Type35.Object(
2207
+ {
2208
+ vmid: Type35.Integer({ minimum: 1, description: "Container or VM id." }),
2209
+ path: Type35.String({ minLength: 1, description: "Absolute file path inside the resource." }),
2210
+ confirm: Type35.Boolean({ description: "Must be true to read files from inside a guest." })
2211
+ },
2212
+ { additionalProperties: false }
2213
+ );
2214
+ var NAME32 = "proxmox_read_file";
2215
+ function shellSingleQuote(s) {
2216
+ return `'${s.replace(/'/g, `'\\''`)}'`;
2217
+ }
2218
+ function assertAbsoluteGuestPath(path2, toolName) {
2219
+ if (!path2.startsWith("/")) throw new Error(`${toolName} path must be absolute`);
2220
+ if (path2.includes("\0")) throw new Error(`${toolName} path cannot contain NUL bytes`);
2221
+ }
2222
+ function createProxmoxReadFileTool(getClient, getSsh, vmDefaults) {
2223
+ return {
2224
+ name: NAME32,
2225
+ label: "proxmox: read file from container or VM",
2226
+ description: "Read a file from inside an LXC container or QEMU VM. Gated guest read; requires confirm:true.",
2227
+ parameters: Schema35,
2228
+ execute: async (_id, raw) => {
2229
+ assertConfirmedWrite(raw, NAME32);
2230
+ const args = validateToolArgs(Schema35, raw, NAME32);
2231
+ assertAbsoluteGuestPath(args.path, NAME32);
2232
+ const client = getClient();
2233
+ const { node, type } = await resolveResource(client, args.vmid);
2234
+ const command = `cat -- ${shellSingleQuote(args.path)}`;
2235
+ const ssh = getSsh();
2236
+ const timeoutMs = 3e4;
2237
+ let result;
2238
+ if (type === "lxc") {
2239
+ result = await ssh.execInLxc(args.vmid, command, timeoutMs);
2240
+ } else {
2241
+ const host = await resolveQemuSshHost(client, node, args.vmid);
2242
+ if (!host) {
2243
+ throw new Error(missingQemuSshHostMessage(args.vmid));
2244
+ }
2245
+ result = await ssh.execViaDirectSsh(qemuSshTarget(args.vmid, host, vmDefaults), command, timeoutMs);
2246
+ }
2247
+ if (result.exitCode !== 0) {
2248
+ throw new Error(result.stderr.trim() || `read_file failed with exit code ${result.exitCode}`);
2249
+ }
2250
+ return jsonToolResult({ vmid: args.vmid, path: args.path, content: result.stdout });
2251
+ }
2252
+ };
2253
+ }
2254
+
2255
+ // src/tools/proxmox_write_file.ts
2256
+ import { Type as Type36 } from "@sinclair/typebox";
2257
+ import path from "path";
2258
+ var Schema36 = Type36.Object(
2259
+ {
2260
+ vmid: Type36.Integer({ minimum: 1, description: "Container or VM id." }),
2261
+ path: Type36.String({ minLength: 1, description: "Absolute destination path inside the resource." }),
2262
+ content: Type36.String({ description: "Text content to write." }),
2263
+ confirm: Type36.Boolean({ description: "Must be true to write. Tier-2 safe-write gate." })
2264
+ },
2265
+ { additionalProperties: false }
2266
+ );
2267
+ var NAME33 = "proxmox_write_file";
2268
+ function shellSingleQuote2(s) {
2269
+ return `'${s.replace(/'/g, `'\\''`)}'`;
2270
+ }
2271
+ function assertAbsoluteGuestPath2(path2, toolName) {
2272
+ if (!path2.startsWith("/")) throw new Error(`${toolName} path must be absolute`);
2273
+ if (path2.includes("\0")) throw new Error(`${toolName} path cannot contain NUL bytes`);
2274
+ }
2275
+ function createProxmoxWriteFileTool(getClient, getSsh, vmDefaults) {
2276
+ return {
2277
+ name: NAME33,
2278
+ label: "proxmox: write file to container or VM",
2279
+ description: "Write a text file to a path inside an LXC container or QEMU VM. Creates parent directories. Tier-2 write; requires confirm:true.",
2280
+ parameters: Schema36,
2281
+ execute: async (_id, raw) => {
2282
+ assertConfirmedWrite(raw, NAME33);
2283
+ const args = validateToolArgs(Schema36, raw, NAME33);
2284
+ assertAbsoluteGuestPath2(args.path, NAME33);
2285
+ const client = getClient();
2286
+ const { node, type } = await resolveResource(client, args.vmid);
2287
+ const ssh = getSsh();
2288
+ const timeoutMs = 3e4;
2289
+ const parent = path.posix.dirname(args.path);
2290
+ const mkdirCmd = `mkdir -p -- ${shellSingleQuote2(parent)}`;
2291
+ const writeCmd = `cat > ${shellSingleQuote2(args.path)}`;
2292
+ const runOne = async (command, stdin) => {
2293
+ if (type === "lxc") {
2294
+ return ssh.execInLxc(args.vmid, command, timeoutMs, stdin);
2295
+ }
2296
+ const host = await resolveQemuSshHost(client, node, args.vmid);
2297
+ if (!host) {
2298
+ throw new Error(missingQemuSshHostMessage(args.vmid));
2299
+ }
2300
+ return ssh.execViaDirectSsh(qemuSshTarget(args.vmid, host, vmDefaults), command, timeoutMs, stdin);
2301
+ };
2302
+ const mkdirResult = await runOne(mkdirCmd);
2303
+ if (mkdirResult.exitCode !== 0) {
2304
+ throw new Error(mkdirResult.stderr.trim() || `mkdir failed with exit code ${mkdirResult.exitCode}`);
2305
+ }
2306
+ const writeResult = await runOne(writeCmd, args.content);
2307
+ if (writeResult.exitCode !== 0) {
2308
+ throw new Error(writeResult.stderr.trim() || `write failed with exit code ${writeResult.exitCode}`);
2309
+ }
2310
+ return jsonToolResult({
2311
+ vmid: args.vmid,
2312
+ path: args.path,
2313
+ bytes_written: Buffer.byteLength(args.content, "utf8")
2314
+ });
2315
+ }
2316
+ };
2317
+ }
2318
+
2319
+ // src/tools/proxmox_stat_path.ts
2320
+ import { Type as Type37 } from "@sinclair/typebox";
2321
+
2322
+ // src/tools/guest-command.ts
2323
+ function shellSingleQuote3(s) {
2324
+ return `'${s.replace(/'/g, `'\\''`)}'`;
2325
+ }
2326
+ function assertAbsoluteGuestPath3(path2, toolName) {
2327
+ if (!path2.startsWith("/")) throw new Error(`${toolName} path must be absolute`);
2328
+ if (path2.includes("\0")) throw new Error(`${toolName} path cannot contain NUL bytes`);
2329
+ }
2330
+ async function runGuestCommand(client, ssh, vmDefaults, vmid, command, timeoutMs, stdin) {
2331
+ const { node, type } = await resolveResource(client, vmid);
2332
+ if (type === "lxc") {
2333
+ return { node, type, result: await ssh.execInLxc(vmid, command, timeoutMs, stdin) };
2334
+ }
2335
+ const host = await resolveQemuSshHost(client, node, vmid);
2336
+ if (!host) throw new Error(missingQemuSshHostMessage(vmid));
2337
+ const target = qemuSshTarget(vmid, host, vmDefaults);
2338
+ return { node, type, result: await ssh.execViaDirectSsh(target, command, timeoutMs, stdin) };
2339
+ }
2340
+
2341
+ // src/tools/proxmox_stat_path.ts
2342
+ var Schema37 = Type37.Object(
2343
+ {
2344
+ vmid: Type37.Integer({ minimum: 1, description: "Container or VM id." }),
2345
+ path: Type37.String({ minLength: 1, description: "Absolute path inside the guest." }),
2346
+ confirm: Type37.Boolean({ description: "Must be true to inspect guest filesystem metadata." })
2347
+ },
2348
+ { additionalProperties: false }
2349
+ );
2350
+ var NAME34 = "proxmox_stat_path";
2351
+ function parseStatOutput(stdout) {
2352
+ const fields = stdout.split("\0");
2353
+ if (fields.at(-1) === "") fields.pop();
2354
+ if (fields.length !== 7) {
2355
+ throw new Error(`${NAME34} unexpected stat output: expected 7 NUL-delimited fields, got ${fields.length}`);
2356
+ }
2357
+ const [file_type, size, owner, group, mode, mtime, name] = fields;
2358
+ return {
2359
+ file_type,
2360
+ size: Number(size),
2361
+ owner,
2362
+ group,
2363
+ mode,
2364
+ mtime: Number(mtime),
2365
+ name
2366
+ };
2367
+ }
2368
+ function createProxmoxStatPathTool(getClient, getSsh, vmDefaults) {
2369
+ return {
2370
+ name: NAME34,
2371
+ label: "proxmox: stat guest path",
2372
+ description: "Return structured metadata for a path inside an LXC container or QEMU VM. Gated guest read; requires confirm:true.",
2373
+ parameters: Schema37,
2374
+ execute: async (_id, raw) => {
2375
+ assertConfirmedWrite(raw, NAME34);
2376
+ const args = validateToolArgs(Schema37, raw, NAME34);
2377
+ assertAbsoluteGuestPath3(args.path, NAME34);
2378
+ const command = `stat -Lc '%F\\0%s\\0%U\\0%G\\0%a\\0%Y\\0%n\\0' -- ${shellSingleQuote3(args.path)}`;
2379
+ const { node, type, result } = await runGuestCommand(
2380
+ getClient(),
2381
+ getSsh(),
2382
+ vmDefaults,
2383
+ args.vmid,
2384
+ command,
2385
+ 3e4
2386
+ );
2387
+ if (result.exitCode !== 0) throw new Error(result.stderr.trim() || `stat failed with exit code ${result.exitCode}`);
2388
+ const stat = parseStatOutput(result.stdout);
2389
+ return jsonToolResult({
2390
+ vmid: args.vmid,
2391
+ node,
2392
+ type,
2393
+ path: args.path,
2394
+ ...stat
2395
+ });
2396
+ }
2397
+ };
2398
+ }
2399
+
2400
+ // src/tools/proxmox_list_directory.ts
2401
+ import { Type as Type38 } from "@sinclair/typebox";
2402
+ var Schema38 = Type38.Object(
2403
+ {
2404
+ vmid: Type38.Integer({ minimum: 1, description: "Container or VM id." }),
2405
+ path: Type38.String({ minLength: 1, description: "Absolute directory path inside the guest." }),
2406
+ confirm: Type38.Boolean({ description: "Must be true to inspect guest directory contents." })
2407
+ },
2408
+ { additionalProperties: false }
2409
+ );
2410
+ var NAME35 = "proxmox_list_directory";
2411
+ function parseFindEntries(stdout) {
2412
+ if (stdout === "") return [];
2413
+ const fields = stdout.split("\0");
2414
+ if (fields.at(-1) === "") fields.pop();
2415
+ if (fields.length % 4 !== 0) {
2416
+ throw new Error(`${NAME35} unexpected find output: incomplete NUL-delimited record`);
2417
+ }
2418
+ const entries = [];
2419
+ for (let i = 0; i < fields.length; i += 4) {
2420
+ entries.push({
2421
+ name: fields[i],
2422
+ kind: fields[i + 1],
2423
+ size: Number(fields[i + 2]),
2424
+ mtime: Number(fields[i + 3])
2425
+ });
2426
+ }
2427
+ entries.sort((a, b) => a.name.localeCompare(b.name));
2428
+ return entries;
2429
+ }
2430
+ function createProxmoxListDirectoryTool(getClient, getSsh, vmDefaults) {
2431
+ return {
2432
+ name: NAME35,
2433
+ label: "proxmox: list guest directory",
2434
+ description: "List one directory inside an LXC container or QEMU VM. Gated guest read; requires confirm:true.",
2435
+ parameters: Schema38,
2436
+ execute: async (_id, raw) => {
2437
+ assertConfirmedWrite(raw, NAME35);
2438
+ const args = validateToolArgs(Schema38, raw, NAME35);
2439
+ assertAbsoluteGuestPath3(args.path, NAME35);
2440
+ const command = `find ${shellSingleQuote3(args.path)} -mindepth 1 -maxdepth 1 -printf '%f\\0%y\\0%s\\0%T@\\0'`;
2441
+ const { node, type, result } = await runGuestCommand(
2442
+ getClient(),
2443
+ getSsh(),
2444
+ vmDefaults,
2445
+ args.vmid,
2446
+ command,
2447
+ 3e4
2448
+ );
2449
+ if (result.exitCode !== 0) {
2450
+ throw new Error(result.stderr.trim() || `list_directory failed with exit code ${result.exitCode}`);
2451
+ }
2452
+ const entries = parseFindEntries(result.stdout);
2453
+ return jsonToolResult({ vmid: args.vmid, node, type, path: args.path, count: entries.length, entries });
2454
+ }
2455
+ };
2456
+ }
2457
+
2458
+ // src/tools/proxmox_service_status.ts
2459
+ import { Type as Type39 } from "@sinclair/typebox";
2460
+ var Schema39 = Type39.Object(
2461
+ {
2462
+ vmid: Type39.Integer({ minimum: 1, description: "Container or VM id." }),
2463
+ service: Type39.String({ minLength: 1, description: "systemd service name inside the guest." }),
2464
+ confirm: Type39.Boolean({ description: "Must be true to inspect guest service state." })
2465
+ },
2466
+ { additionalProperties: false }
2467
+ );
2468
+ var NAME36 = "proxmox_service_status";
2469
+ function parseSystemctlShow(stdout) {
2470
+ const out = {};
2471
+ for (const line of stdout.trimEnd().split("\n")) {
2472
+ const idx = line.indexOf("=");
2473
+ if (idx <= 0) continue;
2474
+ out[line.slice(0, idx)] = line.slice(idx + 1);
2475
+ }
2476
+ return out;
2477
+ }
2478
+ function createProxmoxServiceStatusTool(getClient, getSsh, vmDefaults) {
2479
+ return {
2480
+ name: NAME36,
2481
+ label: "proxmox: guest service status",
2482
+ description: "Return systemd service status from inside an LXC container or QEMU VM. Gated guest read; requires confirm:true.",
2483
+ parameters: Schema39,
2484
+ execute: async (_id, raw) => {
2485
+ assertConfirmedWrite(raw, NAME36);
2486
+ const args = validateToolArgs(Schema39, raw, NAME36);
2487
+ if (args.service.includes("\0")) throw new Error(`${NAME36} service cannot contain NUL bytes`);
2488
+ const command = `systemctl show --no-pager --property=Id,LoadState,ActiveState,SubState,UnitFileState,Description -- ${shellSingleQuote3(args.service)}`;
2489
+ const { node, type, result } = await runGuestCommand(
2490
+ getClient(),
2491
+ getSsh(),
2492
+ vmDefaults,
2493
+ args.vmid,
2494
+ command,
2495
+ 3e4
2496
+ );
2497
+ if (result.exitCode !== 0) {
2498
+ throw new Error(result.stderr.trim() || `service_status failed with exit code ${result.exitCode}`);
2499
+ }
2500
+ const status = parseSystemctlShow(result.stdout);
2501
+ return jsonToolResult({ vmid: args.vmid, node, type, service: args.service, status });
2502
+ }
2503
+ };
2504
+ }
2505
+
2506
+ // src/tools/service-action.ts
2507
+ import { Type as Type40 } from "@sinclair/typebox";
2508
+ function parseSystemctlShow2(stdout) {
2509
+ const out = {};
2510
+ for (const line of stdout.trimEnd().split("\n")) {
2511
+ const idx = line.indexOf("=");
2512
+ if (idx <= 0) continue;
2513
+ out[line.slice(0, idx)] = line.slice(idx + 1);
2514
+ }
2515
+ return out;
2516
+ }
2517
+ function schemaFor(action) {
2518
+ return Type40.Object(
2519
+ {
2520
+ vmid: Type40.Integer({ minimum: 1, description: "Container or VM id." }),
2521
+ service: Type40.String({ minLength: 1, description: `systemd service name to ${action} inside the guest.` }),
2522
+ confirm: Type40.Boolean({ description: `Must be true to ${action} a guest service.` })
2523
+ },
2524
+ { additionalProperties: false }
2525
+ );
2526
+ }
2527
+ function createServiceActionTool(action, getClient, getSsh, vmDefaults) {
2528
+ const name = `proxmox_service_${action}`;
2529
+ const schema = schemaFor(action);
2530
+ return {
2531
+ name,
2532
+ label: `proxmox: guest service ${action}`,
2533
+ description: `${action[0].toUpperCase()}${action.slice(1)} a systemd service inside an LXC container or QEMU VM. Tier-2 write; requires confirm:true.`,
2534
+ parameters: schema,
2535
+ execute: async (_id, raw) => {
2536
+ assertConfirmedWrite(raw, name);
2537
+ const args = validateToolArgs(schema, raw, name);
2538
+ if (args.service.includes("\0")) throw new Error(`${name} service cannot contain NUL bytes`);
2539
+ const quoted = shellSingleQuote3(args.service);
2540
+ const command = `systemctl ${action} -- ${quoted} && systemctl show --no-pager --property=Id,LoadState,ActiveState,SubState,UnitFileState,Description -- ${quoted}`;
2541
+ const { node, type, result } = await runGuestCommand(
2542
+ getClient(),
2543
+ getSsh(),
2544
+ vmDefaults,
2545
+ args.vmid,
2546
+ command,
2547
+ 6e4
2548
+ );
2549
+ if (result.exitCode !== 0) {
2550
+ throw new Error(result.stderr.trim() || `service_${action} failed with exit code ${result.exitCode}`);
2551
+ }
2552
+ return jsonToolResult({
2553
+ vmid: args.vmid,
2554
+ node,
2555
+ type,
2556
+ service: args.service,
2557
+ action,
2558
+ status: parseSystemctlShow2(result.stdout)
2559
+ });
2560
+ }
2561
+ };
2562
+ }
2563
+
2564
+ // src/tools/proxmox_service_start.ts
2565
+ function createProxmoxServiceStartTool(getClient, getSsh, vmDefaults) {
2566
+ return createServiceActionTool("start", getClient, getSsh, vmDefaults);
2567
+ }
2568
+
2569
+ // src/tools/proxmox_service_stop.ts
2570
+ function createProxmoxServiceStopTool(getClient, getSsh, vmDefaults) {
2571
+ return createServiceActionTool("stop", getClient, getSsh, vmDefaults);
2572
+ }
2573
+
2574
+ // src/tools/proxmox_service_restart.ts
2575
+ function createProxmoxServiceRestartTool(getClient, getSsh, vmDefaults) {
2576
+ return createServiceActionTool("restart", getClient, getSsh, vmDefaults);
2577
+ }
2578
+
2579
+ // src/errors.ts
2580
+ function classifyToolError(error) {
2581
+ const err = error instanceof Error ? error : new Error(String(error));
2582
+ if (err instanceof ToolInputError) {
2583
+ return { error: err.message, code: "TOOL_INPUT_INVALID", name: err.name };
2584
+ }
2585
+ if (err instanceof WriteGateError) {
2586
+ const code = err.message.includes("requires env flag") ? "DESTRUCTIVE_ENV_REQUIRED" : err.message.includes("destructive operation") ? "DESTRUCTIVE_CONFIRMATION_REQUIRED" : "WRITE_CONFIRMATION_REQUIRED";
2587
+ return { error: err.message, code, name: err.name };
2588
+ }
2589
+ if (err instanceof ProxmoxClientError) {
2590
+ return { error: err.message, code: `PROXMOX_HTTP_${err.status}`, name: err.name, status: err.status };
2591
+ }
2592
+ if (err instanceof ProxmoxUnreachableError) {
2593
+ return { error: err.message, code: "PROXMOX_UNREACHABLE", name: err.name };
2594
+ }
2595
+ if (err instanceof SshExecError) {
2596
+ return { error: err.message, code: `SSH_${err.phase.toUpperCase()}_FAILED`, name: err.name };
2597
+ }
2598
+ if (/vmid \d+ not found in cluster resources/.test(err.message)) {
2599
+ return { error: err.message, code: "VMID_NOT_FOUND", name: err.name };
2600
+ }
2601
+ if (/invalid UPID format/.test(err.message)) {
2602
+ return { error: err.message, code: "TASK_UPID_INVALID", name: err.name };
2603
+ }
2604
+ if (/task did not finish OK/i.test(err.message) || /task failed/i.test(err.message)) {
2605
+ return { error: err.message, code: "TASK_FAILED", name: err.name };
2606
+ }
2607
+ return { error: err.message, code: "TOOL_ERROR", name: err.name };
2608
+ }
2609
+
2610
+ // mcp-server.ts
2611
+ import { realpathSync } from "fs";
2612
+ import { pathToFileURL } from "url";
2613
+ async function startServer() {
2614
+ const cfg = resolveConfig(process.env);
2615
+ registerSecret(cfg.tokenId);
2616
+ registerSecret(cfg.tokenSecret);
2617
+ registerSecret(`PVEAPIToken=${cfg.tokenId}=${cfg.tokenSecret}`);
2618
+ const getClient = () => new ProxmoxClient(cfg);
2619
+ const hostCfg = {
2620
+ host: cfg.ssh.host,
2621
+ port: cfg.ssh.port,
2622
+ user: cfg.ssh.user,
2623
+ keyPath: cfg.ssh.keyPath
2624
+ };
2625
+ const getSsh = () => ({
2626
+ execInLxc: (vmid, command, timeoutMs, stdin) => execInLxc(hostCfg, vmid, command, timeoutMs, stdin),
2627
+ execViaDirectSsh: (target, command, timeoutMs, stdin) => execViaDirectSsh(target, command, timeoutMs, stdin)
2628
+ });
2629
+ const vmDefaults = { vmUser: cfg.ssh.vmUser, vmKeyPath: cfg.ssh.vmKeyPath };
2630
+ const tools = [
2631
+ createProxmoxStatusTool(getClient),
2632
+ createProxmoxListContainersTool(getClient),
2633
+ createProxmoxListVmsTool(getClient),
2634
+ createProxmoxGetResourceTool(getClient),
2635
+ createProxmoxGetVmConfigTool(getClient),
2636
+ createProxmoxGetContainerConfigTool(getClient),
2637
+ createProxmoxValidateQemuSmokeSourceTool(getClient),
2638
+ createProxmoxAuditPermissionsTool(getClient),
2639
+ createProxmoxRecentTasksTool(getClient),
2640
+ createProxmoxListBackupsTool(getClient),
2641
+ createProxmoxResourceUsageTool(getClient),
2642
+ createProxmoxStartResourceTool(getClient),
2643
+ createProxmoxStopResourceTool(getClient),
2644
+ createProxmoxRebootResourceTool(getClient),
2645
+ createProxmoxSnapshotResourceTool(getClient),
2646
+ createProxmoxRollbackSnapshotTool(getClient),
2647
+ createProxmoxRunBackupTool(getClient),
2648
+ createProxmoxGetTaskStatusTool(getClient),
2649
+ createProxmoxGetTaskLogTool(getClient),
2650
+ createProxmoxListTemplatesTool(getClient),
2651
+ createProxmoxListStorageTool(getClient),
2652
+ createProxmoxListSnapshotsTool(getClient),
2653
+ createProxmoxGuestNetworkTool(getClient),
2654
+ createProxmoxWaitTaskTool(getClient),
2655
+ createProxmoxNextVmidTool(getClient),
2656
+ createProxmoxListPoolResourcesTool(getClient),
2657
+ createProxmoxCreateContainerTool(getClient),
2658
+ createProxmoxCreateVmTool(getClient),
2659
+ createProxmoxCloneResourceTool(getClient),
2660
+ createProxmoxDestroyResourceTool(getClient),
2661
+ createProxmoxCleanupSmokeResourcesTool(getClient),
2662
+ createProxmoxDeleteSnapshotTool(getClient),
2663
+ createProxmoxForceStopResourceTool(getClient),
2664
+ createProxmoxExecTool(getClient, getSsh, vmDefaults),
2665
+ createProxmoxReadFileTool(getClient, getSsh, vmDefaults),
2666
+ createProxmoxWriteFileTool(getClient, getSsh, vmDefaults),
2667
+ createProxmoxStatPathTool(getClient, getSsh, vmDefaults),
2668
+ createProxmoxListDirectoryTool(getClient, getSsh, vmDefaults),
2669
+ createProxmoxServiceStatusTool(getClient, getSsh, vmDefaults),
2670
+ createProxmoxServiceStartTool(getClient, getSsh, vmDefaults),
2671
+ createProxmoxServiceStopTool(getClient, getSsh, vmDefaults),
2672
+ createProxmoxServiceRestartTool(getClient, getSsh, vmDefaults)
2673
+ ];
2674
+ const toolMap = new Map(tools.map((t) => [t.name, t]));
2675
+ const server = new Server({ name: "proxmox-mcp", version: "0.5.0" }, { capabilities: { tools: {} } });
2676
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
2677
+ tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.parameters }))
2678
+ }));
2679
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
2680
+ const t = toolMap.get(req.params.name);
2681
+ if (!t) {
2682
+ return {
2683
+ content: [{
2684
+ type: "text",
2685
+ text: JSON.stringify({
2686
+ error: `unknown tool: ${req.params.name}`,
2687
+ code: "UNKNOWN_TOOL",
2688
+ name: "UnknownToolError"
2689
+ })
2690
+ }],
2691
+ isError: true
2692
+ };
2693
+ }
2694
+ try {
2695
+ return await t.execute(req.params.name, req.params.arguments ?? {});
2696
+ } catch (e) {
2697
+ const payload = redact(classifyToolError(e));
2698
+ return { content: [{ type: "text", text: JSON.stringify(payload) }], isError: true };
2699
+ }
2700
+ });
2701
+ const transport = new StdioServerTransport();
2702
+ const __send = transport.send.bind(transport);
2703
+ transport.send = (message) => {
2704
+ const tools2 = message?.result?.tools;
2705
+ if (Array.isArray(tools2)) {
2706
+ for (const t of tools2) {
2707
+ if (t?.inputSchema) delete t.inputSchema.$schema;
2708
+ if (t?.outputSchema) delete t.outputSchema.$schema;
2709
+ }
2710
+ }
2711
+ return __send(message);
2712
+ };
2713
+ await server.connect(transport);
2714
+ }
2715
+ var isEntrypoint = (() => {
2716
+ const arg = process.argv[1];
2717
+ if (typeof arg !== "string") return false;
2718
+ try {
2719
+ return import.meta.url === pathToFileURL(realpathSync(arg)).href;
2720
+ } catch {
2721
+ return false;
2722
+ }
2723
+ })();
2724
+ if (isEntrypoint) {
2725
+ startServer().catch((error) => {
2726
+ console.error(`proxmox-mcp fatal: ${error instanceof Error ? error.message : String(error)}`);
2727
+ process.exit(1);
2728
+ });
2729
+ }
2730
+ export {
2731
+ startServer
2732
+ };