hcloud-mcp 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,117 @@
1
+ import { z } from "zod";
2
+ import { hcloudRequest } from "./hcloud-api.js";
3
+ import { ADDITIVE, ADDITIVE_IDEMPOTENT, DESTRUCTIVE_IDEMPOTENT, READ_ONLY, json, listAll, withToolError } from "./tool-helpers.js";
4
+ const labelsSchema = z.record(z.string(), z.string());
5
+ // Every resource whose spec has POST /{collection}/{id}/actions/change_protection.
6
+ // Certificates have no change_protection action. DNS zones and RRSets are covered by
7
+ // change_zone_protection / change_rrset_protection in dns-tools.ts.
8
+ const PROTECTION_RESOURCES = {
9
+ server: "servers",
10
+ volume: "volumes",
11
+ floating_ip: "floating_ips",
12
+ primary_ip: "primary_ips",
13
+ load_balancer: "load_balancers",
14
+ network: "networks",
15
+ image: "images",
16
+ };
17
+ export function registerImageTools(server) {
18
+ server.registerTool("create_snapshot", {
19
+ description: "Create an image from a server's disk. type snapshot (default) is independent of the server and survives its deletion; billed per GB-month. type backup needs backups enabled and is deleted with the server. Shut the server down first for a consistent disk. Returns the image (status creating) and an Action; the server is locked until it finishes",
20
+ inputSchema: {
21
+ id: z.number().describe("Server ID"),
22
+ description: z.string().optional().describe("Image description (auto-generated if omitted)"),
23
+ type: z.enum(["snapshot", "backup"]).optional().describe("Default snapshot"),
24
+ labels: labelsSchema.optional(),
25
+ },
26
+ annotations: ADDITIVE,
27
+ }, async ({ id, description, type, labels }) => withToolError(async () => json(await hcloudRequest("POST", `/servers/${id}/actions/create_image`, {
28
+ body: { type: type ?? "snapshot", description, labels },
29
+ }))));
30
+ server.registerTool("list_snapshots", {
31
+ description: "List images with filters (list_images has none): by default only snapshot and backup images. Filter by label_selector, bound_to (server IDs, backups only), status, architecture, name. All pages",
32
+ inputSchema: {
33
+ type: z.array(z.enum(["snapshot", "backup", "system", "app"])).optional()
34
+ .describe("Image types; default [\"snapshot\", \"backup\"]"),
35
+ bound_to: z.array(z.string()).optional().describe("Server IDs the backup images are bound to"),
36
+ label_selector: z.string().optional().describe("e.g. env=prod"),
37
+ status: z.array(z.enum(["available", "creating", "unavailable"])).optional(),
38
+ architecture: z.enum(["x86", "arm"]).optional(),
39
+ name: z.string().optional().describe("Exact name (system/app images have names; snapshots usually not)"),
40
+ include_deprecated: z.boolean().optional(),
41
+ sort: z.array(z.string()).optional().describe("e.g. [\"created:desc\"]; fields id, name, created"),
42
+ },
43
+ annotations: READ_ONLY,
44
+ }, async ({ type, ...filters }) => withToolError(async () => {
45
+ const images = await listAll((p) => hcloudRequest("GET", "/images", {
46
+ query: { type: type ?? ["snapshot", "backup"], ...filters, ...p },
47
+ }), "images");
48
+ return json(images);
49
+ }));
50
+ server.registerTool("get_image", {
51
+ description: "Get an image by ID (type, status, image_size/disk_size in GB, created_from, bound_to, protection, labels)",
52
+ inputSchema: { id: z.number().describe("Image ID") },
53
+ annotations: READ_ONLY,
54
+ }, async ({ id }) => withToolError(async () => json(await hcloudRequest("GET", `/images/${id}`))));
55
+ server.registerTool("update_image", {
56
+ description: "Update a snapshot or backup image: description, labels (REPLACES the whole label set), or type \"snapshot\" to convert a backup into a snapshot (it then survives server deletion and disabling backups). System/app images cannot be updated",
57
+ inputSchema: {
58
+ id: z.number().describe("Image ID"),
59
+ description: z.string().optional(),
60
+ type: z.literal("snapshot").optional().describe("Convert a backup image to a snapshot"),
61
+ labels: labelsSchema.optional().describe("Replaces all existing labels"),
62
+ },
63
+ annotations: ADDITIVE_IDEMPOTENT,
64
+ }, async ({ id, description, type, labels }) => withToolError(async () => {
65
+ if (description === undefined && type === undefined && labels === undefined) {
66
+ throw new Error("Pass at least one of description, type, labels");
67
+ }
68
+ return json(await hcloudRequest("PUT", `/images/${id}`, { body: { description, type, labels } }));
69
+ }));
70
+ server.registerTool("delete_image", {
71
+ description: "Delete a snapshot or backup image (system/app images cannot be deleted). Fails if delete protection is on. Irreversible; confirm with the user first",
72
+ inputSchema: { id: z.number().describe("Image ID") },
73
+ annotations: DESTRUCTIVE_IDEMPOTENT,
74
+ }, async ({ id }) => withToolError(async () => {
75
+ await hcloudRequest("DELETE", `/images/${id}`);
76
+ return json({ deleted: true, id });
77
+ }));
78
+ server.registerTool("enable_server_backups", {
79
+ description: "Enable automatic daily backups for a server: +20% of the server price, 7 rolling backup slots (list them with list_snapshots type [\"backup\"] and bound_to). Returns an Action",
80
+ inputSchema: { id: z.number().describe("Server ID") },
81
+ annotations: ADDITIVE_IDEMPOTENT,
82
+ }, async ({ id }) => withToolError(async () => json(await hcloudRequest("POST", `/servers/${id}/actions/enable_backup`))));
83
+ server.registerTool("disable_server_backups", {
84
+ description: "Disable automatic backups for a server. IMMEDIATELY DELETES ALL EXISTING BACKUPS of the server; convert any you need to snapshots first (update_image type snapshot). Confirm with the user first. Returns an Action",
85
+ inputSchema: { id: z.number().describe("Server ID") },
86
+ annotations: DESTRUCTIVE_IDEMPOTENT,
87
+ }, async ({ id }) => withToolError(async () => json(await hcloudRequest("POST", `/servers/${id}/actions/disable_backup`))));
88
+ server.registerTool("change_protection", {
89
+ description: "Enable/disable protection on a server, volume, floating_ip, primary_ip, load_balancer, network or image (snapshot/backup). Protected resources cannot be deleted (servers: nor rebuilt). `delete` applies to all; `rebuild` only to servers, and the API currently requires a server's delete and rebuild to be equal, so passing just one for a server sets both. For DNS use change_zone_protection / change_rrset_protection; certificates have no protection. Returns an Action",
90
+ inputSchema: {
91
+ resource: z.enum(["server", "volume", "floating_ip", "primary_ip", "load_balancer", "network", "image"]),
92
+ id: z.number().describe("Resource ID"),
93
+ delete: z.boolean().optional().describe("Prevent deletion"),
94
+ rebuild: z.boolean().optional().describe("Servers only: prevent rebuild"),
95
+ },
96
+ annotations: DESTRUCTIVE_IDEMPOTENT,
97
+ }, async ({ resource, id, delete: del, rebuild }) => withToolError(async () => {
98
+ let body;
99
+ if (resource === "server") {
100
+ if (del === undefined && rebuild === undefined)
101
+ throw new Error("Pass delete and/or rebuild");
102
+ if (del !== undefined && rebuild !== undefined && del !== rebuild) {
103
+ throw new Error("For servers the API currently requires delete and rebuild to have the same value");
104
+ }
105
+ const value = (del ?? rebuild);
106
+ body = { delete: value, rebuild: value };
107
+ }
108
+ else {
109
+ if (rebuild !== undefined)
110
+ throw new Error(`rebuild protection only exists for servers, not ${resource}`);
111
+ if (del === undefined)
112
+ throw new Error("Pass delete (true or false)");
113
+ body = { delete: del };
114
+ }
115
+ return json(await hcloudRequest("POST", `/${PROTECTION_RESOURCES[resource]}/${id}/actions/change_protection`, { body }));
116
+ }));
117
+ }
package/dist/index.js CHANGED
@@ -4,22 +4,48 @@ import { fileURLToPath } from "url";
4
4
  import { config as loadEnv } from "dotenv";
5
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
- import { OpenAPI } from "hetzner-sdk-ts";
8
7
  import { registerTools } from "./register-tools.js";
8
+ import { registerDnsTools } from "./dns-tools.js";
9
+ import { registerExtraTools } from "./extra-tools.js";
10
+ import { registerStorageBoxTools } from "./storage-box-tools.js";
11
+ import { registerCertificateTools } from "./certificate-tools.js";
12
+ import { registerImageTools } from "./image-tools.js";
13
+ import { registerServerOpsTools } from "./server-ops-tools.js";
14
+ import { registerActionGapTools } from "./action-gap-tools.js";
9
15
  import { SERVER_INSTRUCTIONS } from "./instructions.js";
10
16
  // Load .env from project root (parent of dist) so IDE-spawned server finds token when env isn't set
11
17
  if (!process.env.HCLOUD_TOKEN) {
12
18
  const __dirname = dirname(fileURLToPath(import.meta.url));
13
19
  loadEnv({ path: join(__dirname, "..", ".env") });
14
20
  }
15
- const token = process.env.HCLOUD_TOKEN;
16
- if (!token) {
21
+ if (!process.env.HCLOUD_TOKEN) {
17
22
  console.error("Error: HCLOUD_TOKEN environment variable is required");
18
23
  process.exit(1);
19
24
  }
20
- OpenAPI.TOKEN = token;
21
- const server = new McpServer({ name: "hetzner-cloud", version: "0.2.0" }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
22
- registerTools(server);
25
+ const server = new McpServer({ name: "hetzner-cloud", version: "0.4.0" }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
26
+ // Tool groups. HCLOUD_TOOLSETS (comma-separated) limits which load, for clients with
27
+ // tool-count limits; default is all. "core" is always loaded.
28
+ const TOOLSETS = {
29
+ core: [registerTools, registerExtraTools, registerActionGapTools],
30
+ dns: [registerDnsTools],
31
+ images: [registerImageTools],
32
+ ops: [registerServerOpsTools],
33
+ certificates: [registerCertificateTools],
34
+ storage_boxes: [registerStorageBoxTools],
35
+ };
36
+ const requested = (process.env.HCLOUD_TOOLSETS ?? "")
37
+ .split(",").map((t) => t.trim().toLowerCase()).filter(Boolean);
38
+ const unknown = requested.filter((t) => t !== "all" && !(t in TOOLSETS));
39
+ if (unknown.length) {
40
+ console.error(`Error: unknown HCLOUD_TOOLSETS ${unknown.join(", ")}. Valid: all, ${Object.keys(TOOLSETS).join(", ")}`);
41
+ process.exit(1);
42
+ }
43
+ const enabled = requested.length === 0 || requested.includes("all")
44
+ ? Object.keys(TOOLSETS)
45
+ : ["core", ...requested.filter((t) => t !== "core")];
46
+ for (const name of enabled)
47
+ for (const register of TOOLSETS[name])
48
+ register(server);
23
49
  async function main() {
24
50
  const transport = new StdioServerTransport();
25
51
  await server.connect(transport);
@@ -9,5 +9,14 @@ export const SERVER_INSTRUCTIONS = `Hetzner Cloud API tools. Notes:
9
9
  - Firewall CIDRs must not have host bits set. Use 10.0.1.0/24, not 10.0.1.42/24. For a single host use /32 or /128.
10
10
  - For private networks use subnet type "cloud". Type "server" is deprecated.
11
11
  - List tools return all pages. In large projects, prefer get_* by ID when you already know it.
12
- - Destructive tools (delete_*, reset_server, change_server_type, power_off_server) act immediately with no undo. Confirm with the user before using them on resources you did not create in this session.
12
+ - Destructive tools (delete_*, rebuild_server, import_zonefile, reset_server, change_server_type, power_off_server) act immediately with no undo. Confirm with the user before using them on resources you did not create in this session.
13
+ - Reverse DNS: change_dns_ptr always needs dns_ptr. Pass a hostname to set it, or null to reset it.
14
+ - DNS: zones are referenced by ID or name (example.com). RRSet names are relative to the zone ("@" is the apex) and lowercase. TXT values must be quoted ("\"v=spf1 -all\""). Use add_rrset_records to append (it creates the RRSet if missing). set_rrset_records replaces all records and import_zonefile replaces the whole zone, so export_zonefile first as a backup. change_rrset_ttl needs ttl, or null for the zone default. A new zone only answers once the registrar delegates the domain to its authoritative_nameservers.
15
+ - Protected resources fail with "protected" (423). Use change_protection with delete:false, but only after the user confirms. For servers, delete and rebuild protection must have the same value.
16
+ - Secrets: root_password (from rebuild_server, enable_rescue and reset_root_password), console wss_url and passwords, and Storage Box passwords go to the user and nowhere else. Never put them in files, labels or later tool calls. A request_console URL expires after 60 seconds.
17
+ - Before risky changes (rebuild, change_type), offer create_snapshot. Power the server off first for a consistent disk. disable_server_backups deletes all existing backups immediately.
18
+ - Labels in update_* tools replace the whole set. Read the current labels and merge them first.
19
+ - Metrics: call get_*_metrics with last_minutes and include_values=false first. CPU is per vCPU (100 = one full core).
20
+ - Managed certificates only work for domains in a primary Hetzner DNS zone that is delegated to Hetzner. Certificates are attached to load balancers through http.certificates on update_load_balancer_service.
21
+ - Storage Boxes live on api.hetzner.com and use the same token. Poll their actions with get_storage_box_action. rollback_storage_box_snapshot discards everything newer than the snapshot.
13
22
  - Pricing: get_pricing returns prices per location and server type, in EUR, with and without VAT.`;