@solomonneas/proxmox-mcp 0.3.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,32 +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);
80
+ usesInsecureTls;
81
+ async get(path2) {
82
+ return this.request("GET", path2);
68
83
  }
69
- async post(path, body) {
70
- return this.request("POST", path, body);
84
+ async post(path2, body) {
85
+ return this.request("POST", path2, body);
71
86
  }
72
- async delete(path) {
73
- return this.request("DELETE", path);
87
+ async delete(path2) {
88
+ return this.request("DELETE", path2);
74
89
  }
75
- async request(method, path, body) {
76
- const url = this.cfg.url + "/api2/json" + path;
90
+ async request(method, path2, body) {
91
+ const url = this.cfg.url + "/api2/json" + path2;
77
92
  const headers = { authorization: this.authHeader };
78
93
  let bodyStr;
79
94
  if (body !== void 0) {
@@ -93,16 +108,14 @@ var ProxmoxClient = class {
93
108
  let lastErr;
94
109
  for (let attempt = 0; attempt < 2; attempt++) {
95
110
  try {
96
- const init = { method, headers, body: bodyStr };
97
- if (this.dispatcher) init.dispatcher = this.dispatcher;
98
- const res = await fetch(url, init);
111
+ const res = await this.fetchUrl(url, method, headers, bodyStr);
99
112
  if (res.status >= 200 && res.status < 300) {
100
113
  const text = await res.text();
101
114
  if (!text) return void 0;
102
115
  const parsed = JSON.parse(text);
103
116
  return parsed && typeof parsed === "object" && "data" in parsed ? parsed.data : parsed;
104
117
  }
105
- if (res.status >= 500) {
118
+ if ([502, 503, 504].includes(res.status)) {
106
119
  lastErr = new ProxmoxUnreachableError(`HTTP ${res.status}`);
107
120
  if (attempt === 0) await sleep(this.retryDelayMs);
108
121
  continue;
@@ -122,10 +135,190 @@ var ProxmoxClient = class {
122
135
  }
123
136
  throw lastErr ?? new ProxmoxUnreachableError("unknown");
124
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
+ }
125
144
  };
126
145
  function sleep(ms) {
127
146
  return new Promise((r) => setTimeout(r, ms));
128
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
+ }
129
322
 
130
323
  // src/security.ts
131
324
  var SECRETS = /* @__PURE__ */ new Set();
@@ -165,11 +358,34 @@ function redact(value) {
165
358
  import { Type } from "@sinclair/typebox";
166
359
 
167
360
  // src/tools/_util.ts
361
+ import { Value } from "@sinclair/typebox/value";
168
362
  function jsonToolResult(payload) {
169
363
  return {
170
364
  content: [{ type: "text", text: JSON.stringify(payload, null, 2) }]
171
365
  };
172
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
+ }
173
389
  async function resolveResource(client, vmid) {
174
390
  const resources = await client.get(
175
391
  "/cluster/resources"
@@ -197,14 +413,14 @@ function parseTaskUpid(upid) {
197
413
 
198
414
  // src/tools/proxmox_status.ts
199
415
  var Schema = Type.Object({}, { additionalProperties: false });
200
- function createProxmoxStatusTool(getClient2) {
416
+ function createProxmoxStatusTool(getClient) {
201
417
  return {
202
418
  name: "proxmox_status",
203
419
  label: "proxmox: status",
204
420
  description: "Get PVE version + per-node status (online state, CPU, memory, uptime) via GET /version + GET /cluster/resources?type=node.",
205
421
  parameters: Schema,
206
422
  execute: async () => {
207
- const client = getClient2();
423
+ const client = getClient();
208
424
  const [version, nodes] = await Promise.all([
209
425
  client.get("/version"),
210
426
  client.get("/cluster/resources?type=node")
@@ -217,14 +433,14 @@ function createProxmoxStatusTool(getClient2) {
217
433
  // src/tools/proxmox_list_containers.ts
218
434
  import { Type as Type2 } from "@sinclair/typebox";
219
435
  var Schema2 = Type2.Object({}, { additionalProperties: false });
220
- function createProxmoxListContainersTool(getClient2) {
436
+ function createProxmoxListContainersTool(getClient) {
221
437
  return {
222
438
  name: "proxmox_list_containers",
223
439
  label: "proxmox: list containers",
224
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.",
225
441
  parameters: Schema2,
226
442
  execute: async () => {
227
- const client = getClient2();
443
+ const client = getClient();
228
444
  const all = await client.get("/cluster/resources?type=vm");
229
445
  const containers = all.filter((r) => r.type === "lxc");
230
446
  return jsonToolResult({ count: containers.length, containers });
@@ -235,14 +451,14 @@ function createProxmoxListContainersTool(getClient2) {
235
451
  // src/tools/proxmox_list_vms.ts
236
452
  import { Type as Type3 } from "@sinclair/typebox";
237
453
  var Schema3 = Type3.Object({}, { additionalProperties: false });
238
- function createProxmoxListVmsTool(getClient2) {
454
+ function createProxmoxListVmsTool(getClient) {
239
455
  return {
240
456
  name: "proxmox_list_vms",
241
457
  label: "proxmox: list VMs",
242
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.",
243
459
  parameters: Schema3,
244
460
  execute: async () => {
245
- const client = getClient2();
461
+ const client = getClient();
246
462
  const all = await client.get("/cluster/resources?type=vm");
247
463
  const vms = all.filter((r) => r.type === "qemu");
248
464
  return jsonToolResult({ count: vms.length, vms });
@@ -252,21 +468,22 @@ function createProxmoxListVmsTool(getClient2) {
252
468
 
253
469
  // src/tools/proxmox_get_resource.ts
254
470
  import { Type as Type4 } from "@sinclair/typebox";
471
+ var NAME = "proxmox_get_resource";
255
472
  var Schema4 = Type4.Object(
256
473
  {
257
474
  vmid: Type4.Integer({ minimum: 1, description: "Container or VM ID." })
258
475
  },
259
476
  { additionalProperties: false }
260
477
  );
261
- function createProxmoxGetResourceTool(getClient2) {
478
+ function createProxmoxGetResourceTool(getClient) {
262
479
  return {
263
- name: "proxmox_get_resource",
480
+ name: NAME,
264
481
  label: "proxmox: get resource",
265
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).",
266
483
  parameters: Schema4,
267
484
  execute: async (_id, raw) => {
268
- const args = raw;
269
- const client = getClient2();
485
+ const args = validateToolArgs(Schema4, raw, NAME);
486
+ const client = getClient();
270
487
  const { node, type } = await resolveResource(client, args.vmid);
271
488
  const status = await client.get(
272
489
  `/nodes/${node}/${type}/${args.vmid}/status/current`
@@ -276,29 +493,286 @@ function createProxmoxGetResourceTool(getClient2) {
276
493
  };
277
494
  }
278
495
 
279
- // src/tools/proxmox_recent_tasks.ts
496
+ // src/tools/proxmox_get_vm_config.ts
280
497
  import { Type as Type5 } from "@sinclair/typebox";
281
498
  var Schema5 = Type5.Object(
282
499
  {
283
- limit: Type5.Optional(
284
- 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)." })
285
759
  ),
286
- vmid: Type5.Optional(
287
- 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)." })
288
762
  )
289
763
  },
290
764
  { additionalProperties: false }
291
765
  );
292
- function createProxmoxRecentTasksTool(getClient2) {
766
+ function createProxmoxRecentTasksTool(getClient) {
293
767
  return {
294
- name: "proxmox_recent_tasks",
768
+ name: NAME6,
295
769
  label: "proxmox: recent tasks",
296
770
  description: "List recent cluster tasks (UPID, type, status, node, user, timing) via GET /cluster/tasks. Optionally filter by vmid (post-filter client-side).",
297
- parameters: Schema5,
771
+ parameters: Schema9,
298
772
  execute: async (_id, raw) => {
299
- const args = raw;
773
+ const args = validateToolArgs(Schema9, raw, NAME6);
300
774
  const limit = args.limit ?? 25;
301
- const client = getClient2();
775
+ const client = getClient();
302
776
  const tasks = await client.get("/cluster/tasks");
303
777
  let filtered = tasks;
304
778
  if (args.vmid !== void 0) {
@@ -316,27 +790,28 @@ function createProxmoxRecentTasksTool(getClient2) {
316
790
  }
317
791
 
318
792
  // src/tools/proxmox_list_backups.ts
319
- import { Type as Type6 } from "@sinclair/typebox";
320
- var Schema6 = Type6.Object(
793
+ import { Type as Type10 } from "@sinclair/typebox";
794
+ var NAME7 = "proxmox_list_backups";
795
+ var Schema10 = Type10.Object(
321
796
  {
322
- node: Type6.Optional(
323
- 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)." })
324
799
  ),
325
- vmid: Type6.Optional(
326
- 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)." })
327
802
  )
328
803
  },
329
804
  { additionalProperties: false }
330
805
  );
331
- function createProxmoxListBackupsTool(getClient2) {
806
+ function createProxmoxListBackupsTool(getClient) {
332
807
  return {
333
- name: "proxmox_list_backups",
808
+ name: NAME7,
334
809
  label: "proxmox: list backups",
335
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.",
336
- parameters: Schema6,
811
+ parameters: Schema10,
337
812
  execute: async (_id, raw) => {
338
- const args = raw;
339
- const client = getClient2();
813
+ const args = validateToolArgs(Schema10, raw, NAME7);
814
+ const client = getClient();
340
815
  let node = args.node;
341
816
  if (!node) {
342
817
  const nodes = await client.get("/cluster/resources?type=node");
@@ -358,28 +833,29 @@ function createProxmoxListBackupsTool(getClient2) {
358
833
  }
359
834
 
360
835
  // src/tools/proxmox_resource_usage.ts
361
- import { Type as Type7 } from "@sinclair/typebox";
362
- var Schema7 = Type7.Object(
836
+ import { Type as Type11 } from "@sinclair/typebox";
837
+ var NAME8 = "proxmox_resource_usage";
838
+ var Schema11 = Type11.Object(
363
839
  {
364
- vmid: Type7.Integer({ minimum: 1, description: "Container or VM ID." }),
365
- timeframe: Type7.Optional(
366
- 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")], {
367
843
  description: "RRD timeframe window (default hour)."
368
844
  })
369
845
  )
370
846
  },
371
847
  { additionalProperties: false }
372
848
  );
373
- function createProxmoxResourceUsageTool(getClient2) {
849
+ function createProxmoxResourceUsageTool(getClient) {
374
850
  return {
375
- name: "proxmox_resource_usage",
851
+ name: NAME8,
376
852
  label: "proxmox: resource usage",
377
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>.",
378
- parameters: Schema7,
854
+ parameters: Schema11,
379
855
  execute: async (_id, raw) => {
380
- const args = raw;
856
+ const args = validateToolArgs(Schema11, raw, NAME8);
381
857
  const timeframe = args.timeframe ?? "hour";
382
- const client = getClient2();
858
+ const client = getClient();
383
859
  const { node, type } = await resolveResource(client, args.vmid);
384
860
  const samples = await client.get(
385
861
  `/nodes/${node}/${type}/${args.vmid}/rrddata?timeframe=${timeframe}`
@@ -390,7 +866,7 @@ function createProxmoxResourceUsageTool(getClient2) {
390
866
  }
391
867
 
392
868
  // src/tools/proxmox_start_resource.ts
393
- import { Type as Type8 } from "@sinclair/typebox";
869
+ import { Type as Type12 } from "@sinclair/typebox";
394
870
 
395
871
  // src/gates.ts
396
872
  var WriteGateError = class extends Error {
@@ -421,26 +897,26 @@ function assertEnvFlag(envKey, toolName, env = process.env) {
421
897
  }
422
898
 
423
899
  // src/tools/proxmox_start_resource.ts
424
- var Schema8 = Type8.Object(
900
+ var Schema12 = Type12.Object(
425
901
  {
426
- vmid: Type8.Integer({ minimum: 1, description: "Container or VM ID." }),
427
- confirm: Type8.Boolean({
902
+ vmid: Type12.Integer({ minimum: 1, description: "Container or VM ID." }),
903
+ confirm: Type12.Boolean({
428
904
  description: "Must be true to write. Tier-2 safe-write gate."
429
905
  })
430
906
  },
431
907
  { additionalProperties: false }
432
908
  );
433
- var NAME = "proxmox_start_resource";
434
- function createProxmoxStartResourceTool(getClient2) {
909
+ var NAME9 = "proxmox_start_resource";
910
+ function createProxmoxStartResourceTool(getClient) {
435
911
  return {
436
- name: NAME,
912
+ name: NAME9,
437
913
  label: "proxmox: start resource",
438
914
  description: "Start a stopped LXC container or QEMU VM by vmid. Tier-2 write; requires confirm:true.",
439
- parameters: Schema8,
915
+ parameters: Schema12,
440
916
  execute: async (_id, raw) => {
441
- assertConfirmedWrite(raw, NAME);
442
- const args = raw;
443
- const client = getClient2();
917
+ assertConfirmedWrite(raw, NAME9);
918
+ const args = validateToolArgs(Schema12, raw, NAME9);
919
+ const client = getClient();
444
920
  const { node, type } = await resolveResource(client, args.vmid);
445
921
  const upid = await client.post(
446
922
  `/nodes/${node}/${type}/${args.vmid}/status/start`,
@@ -452,15 +928,15 @@ function createProxmoxStartResourceTool(getClient2) {
452
928
  }
453
929
 
454
930
  // src/tools/proxmox_stop_resource.ts
455
- import { Type as Type9 } from "@sinclair/typebox";
456
- var Schema9 = Type9.Object(
931
+ import { Type as Type13 } from "@sinclair/typebox";
932
+ var Schema13 = Type13.Object(
457
933
  {
458
- vmid: Type9.Integer({ minimum: 1, description: "Container or VM ID." }),
459
- confirm: Type9.Boolean({
934
+ vmid: Type13.Integer({ minimum: 1, description: "Container or VM ID." }),
935
+ confirm: Type13.Boolean({
460
936
  description: "Must be true to write. Tier-2 safe-write gate."
461
937
  }),
462
- timeoutSeconds: Type9.Optional(
463
- Type9.Integer({
938
+ timeoutSeconds: Type13.Optional(
939
+ Type13.Integer({
464
940
  minimum: 1,
465
941
  description: "Optional shutdown timeout in seconds (passed through to PVE as `timeout`)."
466
942
  })
@@ -468,17 +944,17 @@ var Schema9 = Type9.Object(
468
944
  },
469
945
  { additionalProperties: false }
470
946
  );
471
- var NAME2 = "proxmox_stop_resource";
472
- function createProxmoxStopResourceTool(getClient2) {
947
+ var NAME10 = "proxmox_stop_resource";
948
+ function createProxmoxStopResourceTool(getClient) {
473
949
  return {
474
- name: NAME2,
950
+ name: NAME10,
475
951
  label: "proxmox: stop resource",
476
952
  description: "Gracefully shutdown an LXC container or QEMU VM by vmid (POST status/shutdown). Tier-2 write; requires confirm:true.",
477
- parameters: Schema9,
953
+ parameters: Schema13,
478
954
  execute: async (_id, raw) => {
479
- assertConfirmedWrite(raw, NAME2);
480
- const args = raw;
481
- const client = getClient2();
955
+ assertConfirmedWrite(raw, NAME10);
956
+ const args = validateToolArgs(Schema13, raw, NAME10);
957
+ const client = getClient();
482
958
  const { node, type } = await resolveResource(client, args.vmid);
483
959
  const body = {};
484
960
  if (typeof args.timeoutSeconds === "number") {
@@ -494,27 +970,27 @@ function createProxmoxStopResourceTool(getClient2) {
494
970
  }
495
971
 
496
972
  // src/tools/proxmox_reboot_resource.ts
497
- import { Type as Type10 } from "@sinclair/typebox";
498
- var Schema10 = Type10.Object(
973
+ import { Type as Type14 } from "@sinclair/typebox";
974
+ var Schema14 = Type14.Object(
499
975
  {
500
- vmid: Type10.Integer({ minimum: 1, description: "Container or VM ID." }),
501
- confirm: Type10.Boolean({
976
+ vmid: Type14.Integer({ minimum: 1, description: "Container or VM ID." }),
977
+ confirm: Type14.Boolean({
502
978
  description: "Must be true to write. Tier-2 safe-write gate."
503
979
  })
504
980
  },
505
981
  { additionalProperties: false }
506
982
  );
507
- var NAME3 = "proxmox_reboot_resource";
508
- function createProxmoxRebootResourceTool(getClient2) {
983
+ var NAME11 = "proxmox_reboot_resource";
984
+ function createProxmoxRebootResourceTool(getClient) {
509
985
  return {
510
- name: NAME3,
986
+ name: NAME11,
511
987
  label: "proxmox: reboot resource",
512
988
  description: "Reboot an LXC container or QEMU VM by vmid (POST status/reboot). Tier-2 write; requires confirm:true.",
513
- parameters: Schema10,
989
+ parameters: Schema14,
514
990
  execute: async (_id, raw) => {
515
- assertConfirmedWrite(raw, NAME3);
516
- const args = raw;
517
- const client = getClient2();
991
+ assertConfirmedWrite(raw, NAME11);
992
+ const args = validateToolArgs(Schema14, raw, NAME11);
993
+ const client = getClient();
518
994
  const { node, type } = await resolveResource(client, args.vmid);
519
995
  const upid = await client.post(
520
996
  `/nodes/${node}/${type}/${args.vmid}/status/reboot`,
@@ -526,34 +1002,38 @@ function createProxmoxRebootResourceTool(getClient2) {
526
1002
  }
527
1003
 
528
1004
  // src/tools/proxmox_snapshot_resource.ts
529
- import { Type as Type11 } from "@sinclair/typebox";
530
- var Schema11 = Type11.Object(
1005
+ import { Type as Type15 } from "@sinclair/typebox";
1006
+ var Schema15 = Type15.Object(
531
1007
  {
532
- vmid: Type11.Integer({ minimum: 1, description: "Container or VM ID." }),
533
- snapname: Type11.String({
1008
+ vmid: Type15.Integer({ minimum: 1, description: "Container or VM ID." }),
1009
+ snapname: Type15.String({
534
1010
  minLength: 1,
535
1011
  description: "Snapshot name (PVE convention: lowercase, no spaces)."
536
1012
  }),
537
- description: Type11.Optional(
538
- Type11.String({ description: "Optional human description for the snapshot." })
1013
+ description: Type15.Optional(
1014
+ Type15.String({ description: "Optional human description for the snapshot." })
539
1015
  ),
540
- confirm: Type11.Boolean({
1016
+ confirm: Type15.Boolean({
541
1017
  description: "Must be true to write. Tier-2 safe-write gate."
542
1018
  })
543
1019
  },
544
1020
  { additionalProperties: false }
545
1021
  );
546
- var NAME4 = "proxmox_snapshot_resource";
547
- function createProxmoxSnapshotResourceTool(getClient2) {
1022
+ var NAME12 = "proxmox_snapshot_resource";
1023
+ function createProxmoxSnapshotResourceTool(getClient) {
548
1024
  return {
549
- name: NAME4,
1025
+ name: NAME12,
550
1026
  label: "proxmox: snapshot resource",
551
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.",
552
- parameters: Schema11,
1028
+ parameters: Schema15,
553
1029
  execute: async (_id, raw) => {
554
- assertConfirmedWrite(raw, NAME4);
555
- const args = raw;
556
- const client = getClient2();
1030
+ assertConfirmedWrite(raw, NAME12);
1031
+ const args = validateToolArgs(
1032
+ Schema15,
1033
+ raw,
1034
+ NAME12
1035
+ );
1036
+ const client = getClient();
557
1037
  const { node, type } = await resolveResource(client, args.vmid);
558
1038
  const body = { snapname: args.snapname };
559
1039
  if (typeof args.description === "string" && args.description.length > 0) {
@@ -574,39 +1054,75 @@ function createProxmoxSnapshotResourceTool(getClient2) {
574
1054
  };
575
1055
  }
576
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
+
577
1093
  // src/tools/proxmox_run_backup.ts
578
- import { Type as Type12 } from "@sinclair/typebox";
579
- var Schema12 = Type12.Object(
1094
+ import { Type as Type17 } from "@sinclair/typebox";
1095
+ var Schema17 = Type17.Object(
580
1096
  {
581
- vmid: Type12.Integer({ minimum: 1, description: "Container or VM ID to back up." }),
582
- storage: Type12.String({
1097
+ vmid: Type17.Integer({ minimum: 1, description: "Container or VM ID to back up." }),
1098
+ storage: Type17.String({
583
1099
  minLength: 1,
584
1100
  description: "PVE storage ID where the vzdump archive should be written."
585
1101
  }),
586
- mode: Type12.Optional(
587
- Type12.Union(
588
- [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")],
589
1105
  { description: "Backup mode. Defaults to 'snapshot'." }
590
1106
  )
591
1107
  ),
592
- confirm: Type12.Boolean({
1108
+ confirm: Type17.Boolean({
593
1109
  description: "Must be true to write. Tier-2 safe-write gate."
594
1110
  })
595
1111
  },
596
1112
  { additionalProperties: false }
597
1113
  );
598
- var NAME5 = "proxmox_run_backup";
599
- function createProxmoxRunBackupTool(getClient2) {
1114
+ var NAME14 = "proxmox_run_backup";
1115
+ function createProxmoxRunBackupTool(getClient) {
600
1116
  return {
601
- name: NAME5,
1117
+ name: NAME14,
602
1118
  label: "proxmox: run backup",
603
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.",
604
- parameters: Schema12,
1120
+ parameters: Schema17,
605
1121
  execute: async (_id, raw) => {
606
- assertConfirmedWrite(raw, NAME5);
607
- const args = raw;
1122
+ assertConfirmedWrite(raw, NAME14);
1123
+ const args = validateToolArgs(Schema17, raw, NAME14);
608
1124
  const mode = args.mode ?? "snapshot";
609
- const client = getClient2();
1125
+ const client = getClient();
610
1126
  const { node } = await resolveResource(client, args.vmid);
611
1127
  const upid = await client.post(`/nodes/${node}/vzdump`, {
612
1128
  vmid: args.vmid,
@@ -626,26 +1142,27 @@ function createProxmoxRunBackupTool(getClient2) {
626
1142
  }
627
1143
 
628
1144
  // src/tools/proxmox_get_task_status.ts
629
- import { Type as Type13 } from "@sinclair/typebox";
630
- var Schema13 = Type13.Object(
1145
+ import { Type as Type18 } from "@sinclair/typebox";
1146
+ var NAME15 = "proxmox_get_task_status";
1147
+ var Schema18 = Type18.Object(
631
1148
  {
632
- upid: Type13.String({
1149
+ upid: Type18.String({
633
1150
  minLength: 1,
634
1151
  description: "Task UPID returned by a prior write tool (e.g. start, stop, snapshot, backup)."
635
1152
  })
636
1153
  },
637
1154
  { additionalProperties: false }
638
1155
  );
639
- function createProxmoxGetTaskStatusTool(getClient2) {
1156
+ function createProxmoxGetTaskStatusTool(getClient) {
640
1157
  return {
641
- name: "proxmox_get_task_status",
1158
+ name: NAME15,
642
1159
  label: "proxmox: get task status",
643
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.",
644
- parameters: Schema13,
1161
+ parameters: Schema18,
645
1162
  execute: async (_id, raw) => {
646
- const args = raw;
1163
+ const args = validateToolArgs(Schema18, raw, NAME15);
647
1164
  const { node } = parseTaskUpid(args.upid);
648
- const client = getClient2();
1165
+ const client = getClient();
649
1166
  const status = await client.get(
650
1167
  `/nodes/${node}/tasks/${encodeURIComponent(args.upid)}/status`
651
1168
  );
@@ -655,18 +1172,19 @@ function createProxmoxGetTaskStatusTool(getClient2) {
655
1172
  }
656
1173
 
657
1174
  // src/tools/proxmox_get_task_log.ts
658
- import { Type as Type14 } from "@sinclair/typebox";
659
- var Schema14 = Type14.Object(
1175
+ import { Type as Type19 } from "@sinclair/typebox";
1176
+ var NAME16 = "proxmox_get_task_log";
1177
+ var Schema19 = Type19.Object(
660
1178
  {
661
- upid: Type14.String({
1179
+ upid: Type19.String({
662
1180
  minLength: 1,
663
1181
  description: "Task UPID returned by a prior write tool."
664
1182
  }),
665
- start: Type14.Optional(
666
- 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)." })
667
1185
  ),
668
- limit: Type14.Optional(
669
- Type14.Integer({
1186
+ limit: Type19.Optional(
1187
+ Type19.Integer({
670
1188
  minimum: 1,
671
1189
  maximum: 500,
672
1190
  description: "Max lines to return (default 50, max 500)."
@@ -675,18 +1193,18 @@ var Schema14 = Type14.Object(
675
1193
  },
676
1194
  { additionalProperties: false }
677
1195
  );
678
- function createProxmoxGetTaskLogTool(getClient2) {
1196
+ function createProxmoxGetTaskLogTool(getClient) {
679
1197
  return {
680
- name: "proxmox_get_task_log",
1198
+ name: NAME16,
681
1199
  label: "proxmox: get task log",
682
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 }.",
683
- parameters: Schema14,
1201
+ parameters: Schema19,
684
1202
  execute: async (_id, raw) => {
685
- const args = raw;
1203
+ const args = validateToolArgs(Schema19, raw, NAME16);
686
1204
  const { node } = parseTaskUpid(args.upid);
687
1205
  const start = args.start ?? 0;
688
1206
  const limit = args.limit ?? 50;
689
- const client = getClient2();
1207
+ const client = getClient();
690
1208
  const lines = await client.get(
691
1209
  `/nodes/${node}/tasks/${encodeURIComponent(args.upid)}/log?start=${start}&limit=${limit}`
692
1210
  );
@@ -696,33 +1214,34 @@ function createProxmoxGetTaskLogTool(getClient2) {
696
1214
  }
697
1215
 
698
1216
  // src/tools/proxmox_list_templates.ts
699
- import { Type as Type15 } from "@sinclair/typebox";
700
- var Schema15 = Type15.Object(
1217
+ import { Type as Type20 } from "@sinclair/typebox";
1218
+ var NAME17 = "proxmox_list_templates";
1219
+ var Schema20 = Type20.Object(
701
1220
  {
702
- node: Type15.Optional(
703
- Type15.String({ minLength: 1, description: "Node to query (defaults to first node)." })
1221
+ node: Type20.Optional(
1222
+ Type20.String({ minLength: 1, description: "Node to query (defaults to first node)." })
704
1223
  ),
705
- storage: Type15.Optional(
706
- Type15.String({ minLength: 1, description: "Storage to query (defaults to 'local')." })
1224
+ storage: Type20.Optional(
1225
+ Type20.String({ minLength: 1, description: "Storage to query (defaults to 'local')." })
707
1226
  ),
708
- kind: Type15.Optional(
709
- Type15.Union(
710
- [Type15.Literal("vztmpl"), Type15.Literal("iso"), Type15.Literal("both")],
1227
+ kind: Type20.Optional(
1228
+ Type20.Union(
1229
+ [Type20.Literal("vztmpl"), Type20.Literal("iso"), Type20.Literal("both")],
711
1230
  { description: "Template kind: 'vztmpl' (CT templates), 'iso' (VM ISOs), or 'both'. Defaults to 'both'." }
712
1231
  )
713
1232
  )
714
1233
  },
715
1234
  { additionalProperties: false }
716
1235
  );
717
- function createProxmoxListTemplatesTool(getClient2) {
1236
+ function createProxmoxListTemplatesTool(getClient) {
718
1237
  return {
719
- name: "proxmox_list_templates",
1238
+ name: NAME17,
720
1239
  label: "proxmox: list templates",
721
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'.",
722
- parameters: Schema15,
1241
+ parameters: Schema20,
723
1242
  execute: async (_id, raw) => {
724
- const args = raw;
725
- const client = getClient2();
1243
+ const args = validateToolArgs(Schema20, raw, NAME17);
1244
+ const client = getClient();
726
1245
  let node = args.node;
727
1246
  if (!node) {
728
1247
  const nodes = await client.get("/cluster/resources?type=node");
@@ -731,18 +1250,22 @@ function createProxmoxListTemplatesTool(getClient2) {
731
1250
  }
732
1251
  const storage = args.storage ?? "local";
733
1252
  const kind = args.kind ?? "both";
1253
+ assertSafePathSegment(node, "node");
1254
+ assertSafePathSegment(storage, "storage");
1255
+ const nodeSeg = encodeURIComponent(node);
1256
+ const storageSeg = encodeURIComponent(storage);
734
1257
  const out = {
735
1258
  node,
736
1259
  storage
737
1260
  };
738
1261
  if (kind === "vztmpl" || kind === "both") {
739
1262
  out.container_templates = await client.get(
740
- `/nodes/${node}/storage/${storage}/content?content=vztmpl`
1263
+ `/nodes/${nodeSeg}/storage/${storageSeg}/content?content=vztmpl`
741
1264
  );
742
1265
  }
743
1266
  if (kind === "iso" || kind === "both") {
744
1267
  out.vm_isos = await client.get(
745
- `/nodes/${node}/storage/${storage}/content?content=iso`
1268
+ `/nodes/${nodeSeg}/storage/${storageSeg}/content?content=iso`
746
1269
  );
747
1270
  }
748
1271
  return jsonToolResult(out);
@@ -750,63 +1273,290 @@ function createProxmoxListTemplatesTool(getClient2) {
750
1273
  };
751
1274
  }
752
1275
 
753
- // src/tools/proxmox_create_container.ts
754
- import { Type as Type16 } from "@sinclair/typebox";
755
- var Schema16 = Type16.Object(
1276
+ // src/tools/proxmox_list_storage.ts
1277
+ import { Type as Type21 } from "@sinclair/typebox";
1278
+ var Schema21 = Type21.Object(
756
1279
  {
757
- vmid: Type16.Integer({ minimum: 1, description: "VMID for the new container." }),
758
- hostname: Type16.String({ minLength: 1, description: "Container hostname." }),
759
- ostemplate: Type16.String({
760
- minLength: 1,
761
- description: "OS template volid (e.g. 'local:vztmpl/ubuntu-24.04-standard_*.tar.zst')."
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')."
762
1488
  }),
763
- node: Type16.Optional(
764
- Type16.String({ minLength: 1, description: "Node to create on (defaults to first node)." })
1489
+ node: Type27.Optional(
1490
+ Type27.String({ minLength: 1, description: "Node to create on (defaults to first node)." })
765
1491
  ),
766
- storage: Type16.Optional(
767
- Type16.String({ minLength: 1, description: "Root storage (default 'local-lvm')." })
1492
+ storage: Type27.Optional(
1493
+ Type27.String({ minLength: 1, description: "Root storage (default 'local-lvm')." })
768
1494
  ),
769
- memory: Type16.Optional(
770
- Type16.Integer({ minimum: 16, description: "Memory in MiB (default 512)." })
1495
+ memory: Type27.Optional(
1496
+ Type27.Integer({ minimum: 16, description: "Memory in MiB (default 512)." })
771
1497
  ),
772
- cores: Type16.Optional(
773
- Type16.Integer({ minimum: 1, description: "CPU cores (default 1)." })
1498
+ cores: Type27.Optional(
1499
+ Type27.Integer({ minimum: 1, description: "CPU cores (default 1)." })
774
1500
  ),
775
- rootfs_size: Type16.Optional(
776
- Type16.String({ minLength: 1, description: "Root filesystem size in GB (default '8')." })
1501
+ rootfs_size: Type27.Optional(
1502
+ Type27.String({ minLength: 1, description: "Root filesystem size in GB (default '8')." })
777
1503
  ),
778
- net: Type16.Optional(
779
- Type16.String({
1504
+ net: Type27.Optional(
1505
+ Type27.String({
780
1506
  minLength: 1,
781
1507
  description: "Network config for net0 (default 'name=eth0,bridge=vmbr0,ip=dhcp')."
782
1508
  })
783
1509
  ),
784
- start: Type16.Optional(
785
- Type16.Boolean({ description: "Start after create (default false)." })
1510
+ start: Type27.Optional(
1511
+ Type27.Boolean({ description: "Start after create (default false)." })
786
1512
  ),
787
- password: Type16.Optional(
788
- Type16.String({ description: "Root password (optional)." })
1513
+ pool: Type27.Optional(
1514
+ Type27.String({ minLength: 1, description: "Optional resource pool ID to place the container into." })
789
1515
  ),
790
- ssh_public_keys: Type16.Optional(
791
- Type16.String({ description: "SSH public keys (optional)." })
1516
+ onboot: Type27.Optional(
1517
+ Type27.Boolean({ description: "Start container on host boot (default false)." })
792
1518
  ),
793
- confirm: Type16.Boolean({
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({
794
1541
  description: "Must be true to write. Tier-2 safe-write gate."
795
1542
  })
796
1543
  },
797
1544
  { additionalProperties: false }
798
1545
  );
799
- var NAME6 = "proxmox_create_container";
800
- function createProxmoxCreateContainerTool(getClient2) {
1546
+ var NAME24 = "proxmox_create_container";
1547
+ function createProxmoxCreateContainerTool(getClient) {
801
1548
  return {
802
- name: NAME6,
1549
+ name: NAME24,
803
1550
  label: "proxmox: create container",
804
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.",
805
- parameters: Schema16,
1552
+ parameters: Schema27,
806
1553
  execute: async (_id, raw) => {
807
- assertConfirmedWrite(raw, NAME6);
808
- const args = raw;
809
- const client = getClient2();
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();
810
1560
  let node = args.node;
811
1561
  if (!node) {
812
1562
  const nodes = await client.get("/cluster/resources?type=node");
@@ -824,14 +1574,27 @@ function createProxmoxCreateContainerTool(getClient2) {
824
1574
  cores: args.cores ?? 1,
825
1575
  rootfs: `${storage}:${rootfsSize}`,
826
1576
  net0: args.net ?? "name=eth0,bridge=vmbr0,ip=dhcp",
827
- start: args.start ? 1 : 0
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
828
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
+ }
829
1586
  if (typeof args.password === "string" && args.password.length > 0) {
830
1587
  body.password = args.password;
831
1588
  }
832
1589
  if (typeof args.ssh_public_keys === "string" && args.ssh_public_keys.length > 0) {
833
1590
  body["ssh-public-keys"] = args.ssh_public_keys;
834
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
+ }
835
1598
  const upid = await client.post(`/nodes/${node}/lxc`, body);
836
1599
  return jsonToolResult({
837
1600
  vmid: args.vmid,
@@ -844,58 +1607,115 @@ function createProxmoxCreateContainerTool(getClient2) {
844
1607
  }
845
1608
 
846
1609
  // src/tools/proxmox_create_vm.ts
847
- import { Type as Type17 } from "@sinclair/typebox";
848
- var Schema17 = Type17.Object(
1610
+ import { Type as Type28 } from "@sinclair/typebox";
1611
+ var Schema28 = Type28.Object(
849
1612
  {
850
- vmid: Type17.Integer({ minimum: 1, description: "VMID for the new VM." }),
851
- name: Type17.String({ minLength: 1, description: "VM display name." }),
852
- node: Type17.Optional(
853
- Type17.String({ minLength: 1, description: "Node to create on (defaults to first node)." })
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)." })
854
1617
  ),
855
- memory: Type17.Optional(
856
- Type17.Integer({ minimum: 16, description: "Memory in MiB (default 2048)." })
1618
+ memory: Type28.Optional(
1619
+ Type28.Integer({ minimum: 16, description: "Memory in MiB (default 2048)." })
857
1620
  ),
858
- cores: Type17.Optional(
859
- Type17.Integer({ minimum: 1, description: "CPU cores (default 2)." })
1621
+ cores: Type28.Optional(
1622
+ Type28.Integer({ minimum: 1, description: "CPU cores (default 2)." })
860
1623
  ),
861
- iso: Type17.Optional(
862
- Type17.String({
1624
+ iso: Type28.Optional(
1625
+ Type28.String({
863
1626
  minLength: 1,
864
1627
  description: "ISO volid for install media (e.g. 'local:iso/ubuntu-24.04.iso'). If set, attaches as ide2 cdrom."
865
1628
  })
866
1629
  ),
867
- disk_size: Type17.Optional(
868
- Type17.String({ minLength: 1, description: "Primary disk size in GB on scsi0 (default '32')." })
1630
+ disk_size: Type28.Optional(
1631
+ Type28.String({ minLength: 1, description: "Primary disk size in GB on scsi0 (default '32')." })
869
1632
  ),
870
- storage: Type17.Optional(
871
- Type17.String({ minLength: 1, description: "Disk storage (default 'local-lvm')." })
1633
+ storage: Type28.Optional(
1634
+ Type28.String({ minLength: 1, description: "Disk storage (default 'local-lvm')." })
872
1635
  ),
873
- net: Type17.Optional(
874
- Type17.String({
1636
+ net: Type28.Optional(
1637
+ Type28.String({
875
1638
  minLength: 1,
876
1639
  description: "Network config for net0 (default 'model=virtio,bridge=vmbr0')."
877
1640
  })
878
1641
  ),
879
- start: Type17.Optional(
880
- Type17.Boolean({ description: "Start after create (default false)." })
1642
+ start: Type28.Optional(
1643
+ Type28.Boolean({ description: "Start after create (default false)." })
881
1644
  ),
882
- confirm: Type17.Boolean({
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({
883
1700
  description: "Must be true to write. Tier-2 safe-write gate."
884
1701
  })
885
1702
  },
886
1703
  { additionalProperties: false }
887
1704
  );
888
- var NAME7 = "proxmox_create_vm";
889
- function createProxmoxCreateVmTool(getClient2) {
1705
+ var NAME25 = "proxmox_create_vm";
1706
+ function createProxmoxCreateVmTool(getClient) {
890
1707
  return {
891
- name: NAME7,
1708
+ name: NAME25,
892
1709
  label: "proxmox: create vm",
893
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.",
894
- parameters: Schema17,
1711
+ parameters: Schema28,
895
1712
  execute: async (_id, raw) => {
896
- assertConfirmedWrite(raw, NAME7);
897
- const args = raw;
898
- const client = getClient2();
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();
899
1719
  let node = args.node;
900
1720
  if (!node) {
901
1721
  const nodes = await client.get("/cluster/resources?type=node");
@@ -911,11 +1731,19 @@ function createProxmoxCreateVmTool(getClient2) {
911
1731
  cores: args.cores ?? 2,
912
1732
  scsi0: `${storage}:${diskSize}`,
913
1733
  net0: args.net ?? "model=virtio,bridge=vmbr0",
914
- start: args.start ? 1 : 0
1734
+ start: args.start ? 1 : 0,
1735
+ onboot: args.onboot ? 1 : 0,
1736
+ protection: args.protection ? 1 : 0,
1737
+ agent: args.agent ? 1 : 0
915
1738
  };
916
1739
  if (typeof args.iso === "string" && args.iso.length > 0) {
917
1740
  body.ide2 = `${args.iso},media=cdrom`;
918
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;
919
1747
  const upid = await client.post(`/nodes/${node}/qemu`, body);
920
1748
  return jsonToolResult({
921
1749
  vmid: args.vmid,
@@ -928,38 +1756,47 @@ function createProxmoxCreateVmTool(getClient2) {
928
1756
  }
929
1757
 
930
1758
  // src/tools/proxmox_clone_resource.ts
931
- import { Type as Type18 } from "@sinclair/typebox";
932
- var Schema18 = Type18.Object(
1759
+ import { Type as Type29 } from "@sinclair/typebox";
1760
+ var Schema29 = Type29.Object(
933
1761
  {
934
- source_vmid: Type18.Integer({ minimum: 1, description: "Source CT/VM ID to clone from." }),
935
- new_vmid: Type18.Integer({ minimum: 1, description: "VMID for the cloned resource." }),
936
- name: Type18.String({ minLength: 1, description: "Name/hostname for the new clone." }),
937
- full: Type18.Optional(
938
- Type18.Boolean({ description: "Full clone (default true). Set false for a linked clone." })
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." })
939
1776
  ),
940
- storage: Type18.Optional(
941
- Type18.String({ minLength: 1, description: "Target storage (default: same as source)." })
1777
+ snapname: Type29.Optional(
1778
+ Type29.String({ minLength: 1, description: "Clone from a named snapshot (optional)." })
942
1779
  ),
943
- snapname: Type18.Optional(
944
- Type18.String({ minLength: 1, description: "Clone from a named snapshot (optional)." })
1780
+ description: Type29.Optional(
1781
+ Type29.String({ description: "Optional description for the clone." })
945
1782
  ),
946
- confirm: Type18.Boolean({
1783
+ confirm: Type29.Boolean({
947
1784
  description: "Must be true to write. Tier-2 safe-write gate."
948
1785
  })
949
1786
  },
950
1787
  { additionalProperties: false }
951
1788
  );
952
- var NAME8 = "proxmox_clone_resource";
953
- function createProxmoxCloneResourceTool(getClient2) {
1789
+ var NAME26 = "proxmox_clone_resource";
1790
+ function createProxmoxCloneResourceTool(getClient) {
954
1791
  return {
955
- name: NAME8,
1792
+ name: NAME26,
956
1793
  label: "proxmox: clone resource",
957
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.",
958
- parameters: Schema18,
1795
+ parameters: Schema29,
959
1796
  execute: async (_id, raw) => {
960
- assertConfirmedWrite(raw, NAME8);
961
- const args = raw;
962
- const client = getClient2();
1797
+ assertConfirmedWrite(raw, NAME26);
1798
+ const args = validateToolArgs(Schema29, raw, NAME26);
1799
+ const client = getClient();
963
1800
  const { node, type } = await resolveResource(client, args.source_vmid);
964
1801
  const body = {
965
1802
  newid: args.new_vmid,
@@ -969,9 +1806,18 @@ function createProxmoxCloneResourceTool(getClient2) {
969
1806
  if (typeof args.storage === "string" && args.storage.length > 0) {
970
1807
  body.storage = args.storage;
971
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
+ }
972
1815
  if (typeof args.snapname === "string" && args.snapname.length > 0) {
973
1816
  body.snapname = args.snapname;
974
1817
  }
1818
+ if (typeof args.description === "string" && args.description.length > 0) {
1819
+ body.description = args.description;
1820
+ }
975
1821
  const upid = await client.post(
976
1822
  `/nodes/${node}/${type}/${args.source_vmid}/clone`,
977
1823
  body
@@ -989,43 +1835,43 @@ function createProxmoxCloneResourceTool(getClient2) {
989
1835
  }
990
1836
 
991
1837
  // src/tools/proxmox_destroy_resource.ts
992
- import { Type as Type19 } from "@sinclair/typebox";
993
- var Schema19 = Type19.Object(
1838
+ import { Type as Type30 } from "@sinclair/typebox";
1839
+ var Schema30 = Type30.Object(
994
1840
  {
995
- vmid: Type19.Integer({ minimum: 1, description: "Container or VM ID to destroy." }),
996
- purge: Type19.Optional(
997
- Type19.Boolean({
1841
+ vmid: Type30.Integer({ minimum: 1, description: "Container or VM ID to destroy." }),
1842
+ purge: Type30.Optional(
1843
+ Type30.Boolean({
998
1844
  description: "Remove from PVE backup/replication config too (default true)."
999
1845
  })
1000
1846
  ),
1001
- force: Type19.Optional(
1002
- Type19.Boolean({
1847
+ force: Type30.Optional(
1848
+ Type30.Boolean({
1003
1849
  description: "Allow destroying a running VM (default false)."
1004
1850
  })
1005
1851
  ),
1006
- confirm: Type19.Boolean({
1852
+ confirm: Type30.Boolean({
1007
1853
  description: "Must be true. Tier-3 destructive gate."
1008
1854
  }),
1009
- destructive: Type19.Boolean({
1855
+ destructive: Type30.Boolean({
1010
1856
  description: "Must be true. Tier-3 destructive gate."
1011
1857
  })
1012
1858
  },
1013
1859
  { additionalProperties: false }
1014
1860
  );
1015
- var NAME9 = "proxmox_destroy_resource";
1016
- function createProxmoxDestroyResourceTool(getClient2) {
1861
+ var NAME27 = "proxmox_destroy_resource";
1862
+ function createProxmoxDestroyResourceTool(getClient) {
1017
1863
  return {
1018
- name: NAME9,
1864
+ name: NAME27,
1019
1865
  label: "proxmox: destroy resource",
1020
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.",
1021
- parameters: Schema19,
1867
+ parameters: Schema30,
1022
1868
  execute: async (_id, raw) => {
1023
- assertEnvFlag("PROXMOX_ENABLE_DESTRUCTIVE", NAME9);
1024
- assertDestructive(raw, NAME9);
1025
- const args = raw;
1869
+ assertEnvFlag("PROXMOX_ENABLE_DESTRUCTIVE", NAME27);
1870
+ assertDestructive(raw, NAME27);
1871
+ const args = validateToolArgs(Schema30, raw, NAME27);
1026
1872
  const purge = args.purge !== false;
1027
1873
  const force = args.force === true;
1028
- const client = getClient2();
1874
+ const client = getClient();
1029
1875
  const { node, type } = await resolveResource(client, args.vmid);
1030
1876
  const params = new URLSearchParams();
1031
1877
  if (purge) {
@@ -1034,43 +1880,180 @@ function createProxmoxDestroyResourceTool(getClient2) {
1034
1880
  }
1035
1881
  if (force && type === "lxc") params.append("force", "1");
1036
1882
  const qs = params.toString();
1037
- const path = qs.length > 0 ? `/nodes/${node}/${type}/${args.vmid}?${qs}` : `/nodes/${node}/${type}/${args.vmid}`;
1038
- const upid = await client.delete(path);
1883
+ const path2 = qs.length > 0 ? `/nodes/${node}/${type}/${args.vmid}?${qs}` : `/nodes/${node}/${type}/${args.vmid}`;
1884
+ const upid = await client.delete(path2);
1039
1885
  return jsonToolResult({ vmid: args.vmid, node, type, upid });
1040
1886
  }
1041
1887
  };
1042
1888
  }
1043
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
+
1044
2023
  // src/tools/proxmox_delete_snapshot.ts
1045
- import { Type as Type20 } from "@sinclair/typebox";
1046
- var Schema20 = Type20.Object(
2024
+ import { Type as Type32 } from "@sinclair/typebox";
2025
+ var Schema32 = Type32.Object(
1047
2026
  {
1048
- vmid: Type20.Integer({ minimum: 1, description: "Container or VM ID." }),
1049
- snapname: Type20.String({
2027
+ vmid: Type32.Integer({ minimum: 1, description: "Container or VM ID." }),
2028
+ snapname: Type32.String({
1050
2029
  minLength: 1,
1051
2030
  description: "Snapshot name to delete."
1052
2031
  }),
1053
- confirm: Type20.Boolean({
2032
+ confirm: Type32.Boolean({
1054
2033
  description: "Must be true. Tier-3 destructive gate."
1055
2034
  }),
1056
- destructive: Type20.Boolean({
2035
+ destructive: Type32.Boolean({
1057
2036
  description: "Must be true. Tier-3 destructive gate."
1058
2037
  })
1059
2038
  },
1060
2039
  { additionalProperties: false }
1061
2040
  );
1062
- var NAME10 = "proxmox_delete_snapshot";
1063
- function createProxmoxDeleteSnapshotTool(getClient2) {
2041
+ var NAME29 = "proxmox_delete_snapshot";
2042
+ function createProxmoxDeleteSnapshotTool(getClient) {
1064
2043
  return {
1065
- name: NAME10,
2044
+ name: NAME29,
1066
2045
  label: "proxmox: delete snapshot",
1067
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.",
1068
- parameters: Schema20,
2047
+ parameters: Schema32,
1069
2048
  execute: async (_id, raw) => {
1070
- assertEnvFlag("PROXMOX_ENABLE_DESTRUCTIVE", NAME10);
1071
- assertDestructive(raw, NAME10);
1072
- const args = raw;
1073
- const client = getClient2();
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();
1074
2057
  const { node, type } = await resolveResource(client, args.vmid);
1075
2058
  const upid = await client.delete(
1076
2059
  `/nodes/${node}/${type}/${args.vmid}/snapshot/${encodeURIComponent(args.snapname)}`
@@ -1081,31 +2064,31 @@ function createProxmoxDeleteSnapshotTool(getClient2) {
1081
2064
  }
1082
2065
 
1083
2066
  // src/tools/proxmox_force_stop_resource.ts
1084
- import { Type as Type21 } from "@sinclair/typebox";
1085
- var Schema21 = Type21.Object(
2067
+ import { Type as Type33 } from "@sinclair/typebox";
2068
+ var Schema33 = Type33.Object(
1086
2069
  {
1087
- vmid: Type21.Integer({ minimum: 1, description: "Container or VM ID to hard-stop." }),
1088
- confirm: Type21.Boolean({
2070
+ vmid: Type33.Integer({ minimum: 1, description: "Container or VM ID to hard-stop." }),
2071
+ confirm: Type33.Boolean({
1089
2072
  description: "Must be true. Tier-3 destructive gate."
1090
2073
  }),
1091
- destructive: Type21.Boolean({
2074
+ destructive: Type33.Boolean({
1092
2075
  description: "Must be true. Tier-3 destructive gate."
1093
2076
  })
1094
2077
  },
1095
2078
  { additionalProperties: false }
1096
2079
  );
1097
- var NAME11 = "proxmox_force_stop_resource";
1098
- function createProxmoxForceStopResourceTool(getClient2) {
2080
+ var NAME30 = "proxmox_force_stop_resource";
2081
+ function createProxmoxForceStopResourceTool(getClient) {
1099
2082
  return {
1100
- name: NAME11,
2083
+ name: NAME30,
1101
2084
  label: "proxmox: force stop resource",
1102
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.",
1103
- parameters: Schema21,
2086
+ parameters: Schema33,
1104
2087
  execute: async (_id, raw) => {
1105
- assertEnvFlag("PROXMOX_ENABLE_DESTRUCTIVE", NAME11);
1106
- assertDestructive(raw, NAME11);
1107
- const args = raw;
1108
- const client = getClient2();
2088
+ assertEnvFlag("PROXMOX_ENABLE_DESTRUCTIVE", NAME30);
2089
+ assertDestructive(raw, NAME30);
2090
+ const args = validateToolArgs(Schema33, raw, NAME30);
2091
+ const client = getClient();
1109
2092
  const { node, type } = await resolveResource(client, args.vmid);
1110
2093
  const upid = await client.post(
1111
2094
  `/nodes/${node}/${type}/${args.vmid}/status/stop`,
@@ -1116,51 +2099,634 @@ function createProxmoxForceStopResourceTool(getClient2) {
1116
2099
  };
1117
2100
  }
1118
2101
 
1119
- // mcp-server.ts
1120
- var cfg = resolveConfig(process.env);
1121
- registerSecret(cfg.tokenId);
1122
- registerSecret(cfg.tokenSecret);
1123
- registerSecret(`PVEAPIToken=${cfg.tokenId}=${cfg.tokenSecret}`);
1124
- var getClient = () => new ProxmoxClient(cfg);
1125
- var tools = [
1126
- createProxmoxStatusTool(getClient),
1127
- createProxmoxListContainersTool(getClient),
1128
- createProxmoxListVmsTool(getClient),
1129
- createProxmoxGetResourceTool(getClient),
1130
- createProxmoxRecentTasksTool(getClient),
1131
- createProxmoxListBackupsTool(getClient),
1132
- createProxmoxResourceUsageTool(getClient),
1133
- createProxmoxStartResourceTool(getClient),
1134
- createProxmoxStopResourceTool(getClient),
1135
- createProxmoxRebootResourceTool(getClient),
1136
- createProxmoxSnapshotResourceTool(getClient),
1137
- createProxmoxRunBackupTool(getClient),
1138
- createProxmoxGetTaskStatusTool(getClient),
1139
- createProxmoxGetTaskLogTool(getClient),
1140
- createProxmoxListTemplatesTool(getClient),
1141
- createProxmoxCreateContainerTool(getClient),
1142
- createProxmoxCreateVmTool(getClient),
1143
- createProxmoxCloneResourceTool(getClient),
1144
- createProxmoxDestroyResourceTool(getClient),
1145
- createProxmoxDeleteSnapshotTool(getClient),
1146
- createProxmoxForceStopResourceTool(getClient)
1147
- ];
1148
- var toolMap = new Map(tools.map((t) => [t.name, t]));
1149
- var server = new Server({ name: "proxmox-mcp", version: "0.3.0" }, { capabilities: { tools: {} } });
1150
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
1151
- tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.parameters }))
1152
- }));
1153
- server.setRequestHandler(CallToolRequestSchema, async (req) => {
1154
- const t = toolMap.get(req.params.name);
1155
- if (!t) {
1156
- return { content: [{ type: "text", text: JSON.stringify({ error: `unknown tool: ${req.params.name}` }) }], isError: true };
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 {
1157
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;
1158
2718
  try {
1159
- return await t.execute(req.params.name, req.params.arguments ?? {});
1160
- } catch (e) {
1161
- const msg = redact(e.message);
1162
- return { content: [{ type: "text", text: JSON.stringify({ error: msg }) }], isError: true };
2719
+ return import.meta.url === pathToFileURL(realpathSync(arg)).href;
2720
+ } catch {
2721
+ return false;
1163
2722
  }
1164
- });
1165
- var transport = new StdioServerTransport();
1166
- await server.connect(transport);
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
+ };