hcloud-mcp 0.2.0 → 0.3.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.
@@ -1,5 +1,6 @@
1
1
  import { ServersService, LoadBalancersService, NetworksService, VolumesService, FirewallsService, FirewallActionsService, FloatingIPsService, SshKeysService, ImagesService, LocationsService, ServerTypesService, PlacementGroupsService, PrimaryIPsService, ServerActionsService, VolumeActionsService, FloatingIpActionsService, LoadBalancerActionsService, NetworkActionsService, PricingService, ActionsService, LoadBalancerTypesService, PrimaryIpActionsService, } from "hetzner-sdk-ts";
2
2
  import { z } from "zod";
3
+ import { listAll, withToolError } from "./tool-helpers.js";
3
4
  // Firewall rule: direction, protocol required; source_ips for 'in', destination_ips for 'out'; port for tcp/udp
4
5
  const firewallRuleSchema = z.object({
5
6
  direction: z.enum(["in", "out"]),
@@ -14,34 +15,6 @@ const firewallApplyToSchema = z.object({
14
15
  server: z.object({ id: z.number() }).optional(),
15
16
  label_selector: z.object({ selector: z.string() }).optional(),
16
17
  });
17
- const formatError = (error) => {
18
- if (error instanceof Error) {
19
- return error.message;
20
- }
21
- return String(error);
22
- };
23
- async function withToolError(run) {
24
- try {
25
- return await run();
26
- }
27
- catch (error) {
28
- return { content: [{ type: "text", text: `Error: ${formatError(error)}` }], isError: true };
29
- }
30
- }
31
- // Hetzner list endpoints are paginated (default 25, max 50 per page). Follow
32
- // meta.pagination.next_page so list tools return every item, not just page 1.
33
- // (Link headers are deprecated by Hetzner; meta.pagination is the supported mechanism.)
34
- async function listAll(fetchPage, key) {
35
- const items = [];
36
- let page = 1;
37
- while (page != null) {
38
- const response = await fetchPage({ page, perPage: 50 });
39
- items.push(...(response?.[key] ?? []));
40
- const next = response?.meta?.pagination?.next_page ?? null;
41
- page = next != null && next > page ? next : null; // guard against non-advancing pagination
42
- }
43
- return items;
44
- }
45
18
  export function registerTools(server) {
46
19
  // --- Servers ---
47
20
  server.tool("list_servers", "List all servers", {}, async (_args, _extra) => withToolError(async () => {
@@ -321,6 +294,7 @@ export function registerTools(server) {
321
294
  certificates: z.array(z.number()).optional(),
322
295
  redirect_http: z.boolean().optional(),
323
296
  sticky_sessions: z.boolean().optional(),
297
+ timeout_idle: z.number().int().min(30).max(300).optional().describe("Idle timeout in seconds (30-300, default 50)"),
324
298
  })
325
299
  .optional(),
326
300
  }, async (args, _extra) => withToolError(async () => {
@@ -0,0 +1,91 @@
1
+ import { z } from "zod";
2
+ import { hcloudRequest } from "./hcloud-api.js";
3
+ import { json, withToolError } from "./tool-helpers.js";
4
+ // Hetzner keeps metrics for 30 days.
5
+ const MAX_LAST_MINUTES = 30 * 24 * 60;
6
+ /** Resolve start/end: explicit ISO-8601 pair, or now − last_minutes → now (default 60). */
7
+ export function resolveRange({ start, end, last_minutes }, now = new Date()) {
8
+ if ((start === undefined) !== (end === undefined)) {
9
+ throw new Error("Pass both start and end, or neither (then last_minutes applies)");
10
+ }
11
+ if (start !== undefined && end !== undefined) {
12
+ if (last_minutes !== undefined)
13
+ throw new Error("Pass either start/end or last_minutes, not both");
14
+ const s = new Date(start);
15
+ const e = new Date(end);
16
+ if (Number.isNaN(s.getTime()))
17
+ throw new Error(`Invalid start timestamp: ${start}`);
18
+ if (Number.isNaN(e.getTime()))
19
+ throw new Error(`Invalid end timestamp: ${end}`);
20
+ if (s >= e)
21
+ throw new Error("start must be before end");
22
+ return { start: s.toISOString(), end: e.toISOString() };
23
+ }
24
+ const minutes = last_minutes ?? 60;
25
+ return { start: new Date(now.getTime() - minutes * 60_000).toISOString(), end: now.toISOString() };
26
+ }
27
+ /** Per-series count/min/avg/max/last so the agent doesn't have to scan every sample. */
28
+ export function summarize(metrics) {
29
+ const out = {};
30
+ for (const [name, series] of Object.entries(metrics?.time_series ?? {})) {
31
+ const nums = (series?.values ?? []).map(([, v]) => Number(v)).filter((n) => Number.isFinite(n));
32
+ const round = (n) => Math.round(n * 1000) / 1000;
33
+ out[name] = nums.length
34
+ ? {
35
+ points: nums.length,
36
+ min: round(Math.min(...nums)),
37
+ avg: round(nums.reduce((a, b) => a + b, 0) / nums.length),
38
+ max: round(Math.max(...nums)),
39
+ last: round(nums[nums.length - 1]),
40
+ }
41
+ : { points: 0, min: null, avg: null, max: null, last: null };
42
+ }
43
+ return out;
44
+ }
45
+ const timeParams = {
46
+ start: z.string().optional().describe("Period start, ISO-8601/RFC3339 (e.g. 2026-11-11T10:00:00Z). Give with end, or omit both and use last_minutes"),
47
+ end: z.string().optional().describe("Period end, ISO-8601/RFC3339. Give with start"),
48
+ last_minutes: z.number().int().min(1).max(MAX_LAST_MINUTES).optional()
49
+ .describe("Convenience: period = now minus N minutes until now. Used only when start/end are omitted; default 60. Max 43200 (30-day retention)"),
50
+ step: z.number().positive().optional()
51
+ .describe("Resolution in seconds. Omit to let the API pick (~200 samples); the API caps at 500 samples and adjusts step to fit"),
52
+ include_values: z.boolean().optional()
53
+ .describe("Include the raw time series ([unix_ts, \"value\"] pairs) after the summary. Default true; set false for just the min/avg/max/last summary (much smaller output)"),
54
+ };
55
+ async function getMetrics(path, type, args) {
56
+ const range = resolveRange(args);
57
+ const res = await hcloudRequest("GET", path, {
58
+ // The spec says multiple types are comma-separated (type=cpu,disk).
59
+ query: { type: type.join(","), start: range.start, end: range.end, step: args.step !== undefined ? String(args.step) : undefined },
60
+ });
61
+ const m = res.metrics;
62
+ const summary = summarize(m);
63
+ return json({
64
+ summary,
65
+ start: m?.start,
66
+ end: m?.end,
67
+ step: m?.step,
68
+ ...(args.include_values === false ? {} : { time_series: m?.time_series }),
69
+ });
70
+ }
71
+ export function registerServerOpsTools(server) {
72
+ server.tool("enable_rescue", "Enable the Hetzner Rescue System (minimal Linux for repair/reinstall) on a server. Does NOT reboot: rescue only takes effect at the next boot, so follow with reset_server (or reboot) once the Action succeeds. Rescue is disabled automatically when the server first boots into it, or if it is not used within 60 minutes. Returns an Action and root_password for the rescue system (valid once the Action succeeds; treat as a secret). Pass ssh_keys to log in by key instead", {
73
+ id: z.number().describe("Server ID"),
74
+ type: z.enum(["linux64"]).optional().describe("Rescue system type; only linux64 exists (default)"),
75
+ ssh_keys: z.array(z.number()).optional().describe("SSH key IDs to inject into the rescue system"),
76
+ }, async ({ id, type, ssh_keys }) => withToolError(async () => json(await hcloudRequest("POST", `/servers/${id}/actions/enable_rescue`, { body: { type, ssh_keys } }))));
77
+ server.tool("disable_rescue", "Disable the Hetzner Rescue System so the server boots from its own disk next time. Does NOT reboot the server. Usually not needed: rescue disables itself after the first boot into it or after 60 minutes unused. Returns an Action", { id: z.number().describe("Server ID") }, async ({ id }) => withToolError(async () => json(await hcloudRequest("POST", `/servers/${id}/actions/disable_rescue`))));
78
+ server.tool("reset_root_password", "Generate and set a new root password on a server. Only works on Linux servers that are running (status 'running') AND have the qemu guest agent running; stock images may not ship it, in which case the API accepts the request but the Action ends in error. Returns an Action plus root_password, which is only in effect once the Action succeeds (poll get_action; treat it as a secret). Fallback if it fails: enable_rescue + reset_server, then change the password from the rescue system", { id: z.number().describe("Server ID") }, async ({ id }) => withToolError(async () => json(await hcloudRequest("POST", `/servers/${id}/actions/reset_password`))));
79
+ server.tool("request_console", "Request VNC-over-websocket console credentials (keyboard, monitor, mouse) for a server. Returns wss_url (contains a token) and a VNC password, plus an Action. The URL must be used to connect within 1 minute; request a new one after that. An already-open connection is not cut off by that timeout. Treat both values as secrets", { id: z.number().describe("Server ID") }, async ({ id }) => withToolError(async () => json(await hcloudRequest("POST", `/servers/${id}/actions/request_console`))));
80
+ server.tool("get_server_metrics", "Get server metrics (last 30 days only). Output starts with a per-series summary {points,min,avg,max,last}, then the raw time_series unless include_values=false. Series: cpu → cpu (percent, per vCPU: 100 = one full vCPU, so divide by vCPU count for overall usage); disk → disk.0.iops.read/write (iop/s), disk.0.bandwidth.read/write (bytes/s); network → network.0.pps.in/out (packets/s), network.0.bandwidth.in/out (bytes/s) on the public interface. Time range: pass start+end (ISO-8601), or omit both and use last_minutes (default 60)", {
81
+ id: z.number().describe("Server ID"),
82
+ type: z.array(z.enum(["cpu", "disk", "network"])).min(1).describe("Metric types, e.g. [\"cpu\"] or [\"cpu\",\"network\"]"),
83
+ ...timeParams,
84
+ }, async ({ id, type, ...rest }) => withToolError(() => getMetrics(`/servers/${id}/metrics`, type, rest)));
85
+ server.tool("get_load_balancer_metrics", "Get load balancer metrics (last 30 days only). Output starts with a per-series summary {points,min,avg,max,last}, then the raw time_series unless include_values=false. Series: open_connections (number), connections_per_second, requests_per_second, bandwidth → bandwidth.in/bandwidth.out (bytes/s). Time range: pass start+end (ISO-8601), or omit both and use last_minutes (default 60)", {
86
+ id: z.number().describe("Load balancer ID"),
87
+ type: z.array(z.enum(["open_connections", "connections_per_second", "requests_per_second", "bandwidth"])).min(1)
88
+ .describe("Metric types, e.g. [\"requests_per_second\",\"bandwidth\"]"),
89
+ ...timeParams,
90
+ }, async ({ id, type, ...rest }) => withToolError(() => getMetrics(`/load_balancers/${id}/metrics`, type, rest)));
91
+ }
@@ -0,0 +1,131 @@
1
+ import { z } from "zod";
2
+ import { HETZNER_API, hcloudRequest } from "./hcloud-api.js";
3
+ import { json, listAll, withToolError } from "./tool-helpers.js";
4
+ // Every Storage Box request must go to api.hetzner.com, never api.hetzner.cloud.
5
+ const sb = (method, path, opts = {}) => hcloudRequest(method, path, { ...opts, baseUrl: HETZNER_API });
6
+ const boxPath = (id) => `/storage_boxes/${id}`;
7
+ const subPath = (id, sub) => `${boxPath(id)}/subaccounts/${sub}`;
8
+ const snapPath = (id, snap) => `${boxPath(id)}/snapshots/${snap}`;
9
+ const boxId = z.number().int().positive().describe("Storage Box ID");
10
+ const subaccountId = z.number().int().positive().describe("Subaccount ID");
11
+ const snapshotId = z.number().int().positive().describe("Snapshot ID");
12
+ const labels = z.record(z.string());
13
+ const labelSelector = z.string().optional().describe("Label selector, e.g. env=prod");
14
+ const sort = z
15
+ .array(z.string())
16
+ .optional()
17
+ .describe('Sort fields with optional direction, e.g. ["name:asc", "created:desc"]');
18
+ const password = z
19
+ .string()
20
+ .min(12)
21
+ .max(128)
22
+ .describe("Password policy: 12-128 chars from a-z A-Z ÄÖÜäöüß 0-9 ^°!§$%/()=?+#-.,;:~*@{}_& with at least one upper case letter, " +
23
+ "lower case letter, digit and special character; must not appear in known data breaches. " +
24
+ "Generate a strong random one; never echo it back to the user unless they asked for it");
25
+ const homeDirectory = z
26
+ .string()
27
+ .describe('Home directory relative to the main account root, e.g. "backups/app1". Created if missing');
28
+ const boxAccess = {
29
+ reachable_externally: z.boolean().optional().describe("Allow access from outside the Hetzner network"),
30
+ samba_enabled: z.boolean().optional().describe("Enable Samba/SMB"),
31
+ ssh_enabled: z.boolean().optional().describe("Enable SSH/SFTP/SCP (port 23)"),
32
+ webdav_enabled: z.boolean().optional().describe("Enable WebDAV"),
33
+ zfs_enabled: z.boolean().optional().describe("Show the .zfs snapshot folder"),
34
+ };
35
+ const subAccess = {
36
+ reachable_externally: boxAccess.reachable_externally,
37
+ samba_enabled: boxAccess.samba_enabled,
38
+ ssh_enabled: boxAccess.ssh_enabled,
39
+ webdav_enabled: boxAccess.webdav_enabled,
40
+ readonly: z.boolean().optional().describe("Read-only subaccount"),
41
+ };
42
+ const actionStatus = z.array(z.enum(["running", "success", "error"])).optional().describe("Filter by status");
43
+ const POLL = "Returns an Action; poll get_storage_box_action until status is success";
44
+ const CONFIRM = "Irreversible; confirm with the user first";
45
+ export function registerStorageBoxTools(server) {
46
+ // --- Storage Box Types ---
47
+ server.tool("list_storage_box_types", "List Storage Box Types (bx11, bx21, ...) with size, snapshot/subaccount limits and per-location hourly/monthly prices and setup fees", { name: z.string().optional() }, async (args) => withToolError(async () => json(await listAll((p) => sb("GET", "/storage_box_types", { query: { ...args, page: p.page, per_page: p.perPage } }), "storage_box_types"))));
48
+ server.tool("get_storage_box_type", "Get a Storage Box Type by ID", { id: z.number().int().positive() }, async ({ id }) => withToolError(async () => json((await sb("GET", `/storage_box_types/${id}`)).storage_box_type)));
49
+ // --- Storage Boxes ---
50
+ server.tool("list_storage_boxes", "List Storage Boxes (all pages). Optional filters by exact name and label selector", { name: z.string().optional(), label_selector: labelSelector, sort }, async (args) => withToolError(async () => json(await listAll((p) => sb("GET", "/storage_boxes", { query: { ...args, page: p.page, per_page: p.perPage } }), "storage_boxes"))));
51
+ server.tool("get_storage_box", "Get a Storage Box: status (initializing/active/locked), type, location, username, server FQDN, access settings, snapshot plan, protection, disk usage stats. username/server/system are null while initializing", { id: boxId }, async ({ id }) => withToolError(async () => json((await sb("GET", boxPath(id))).storage_box)));
52
+ server.tool("create_storage_box", `Create a Storage Box (billed hourly, capped at the monthly price; see list_storage_box_types for prices). ${POLL}; provisioning can take several minutes and username/server stay null until status is active`, {
53
+ name: z.string().describe("Storage Box name"),
54
+ location: z.string().describe("Location ID or name, e.g. fsn1, hel1 (see list_storage_box_types prices for availability)"),
55
+ storage_box_type: z.string().describe("Storage Box Type ID or name, e.g. bx11"),
56
+ password,
57
+ labels: labels.optional(),
58
+ ssh_keys: z.array(z.string()).optional().describe("SSH public keys in OpenSSH format to install"),
59
+ access_settings: z.object(boxAccess).optional().describe("Initial access settings"),
60
+ }, async (args) => withToolError(async () => {
61
+ const res = await sb("POST", "/storage_boxes", { body: args });
62
+ return json({ storage_box: res.storage_box, action: res.action });
63
+ }));
64
+ server.tool("update_storage_box", "Update a Storage Box's name and/or labels (labels replace the whole set)", { id: boxId, name: z.string().optional(), labels: labels.optional() }, async ({ id, ...body }) => withToolError(async () => json((await sb("PUT", boxPath(id), { body })).storage_box)));
65
+ server.tool("delete_storage_box", `Delete a Storage Box and ALL its data, subaccounts and snapshots. ${CONFIRM}. Fails if delete protection is enabled. ${POLL}`, { id: boxId }, async ({ id }) => withToolError(async () => json(await sb("DELETE", boxPath(id)))));
66
+ server.tool("list_storage_box_folders", "List folders in a Storage Box directory (not files). Box must be active", { id: boxId, path: z.string().optional().describe('Relative path to list (default: root)') }, async ({ id, path }) => withToolError(async () => json((await sb("GET", `${boxPath(id)}/folders`, { query: { path } })).folders)));
67
+ // --- Actions ---
68
+ server.tool("get_storage_box_action", "Get a Storage Box Action by ID (create/delete/reset_password/snapshot/subaccount actions). This is the documented endpoint for Storage Box Actions (get_action currently also resolves them)", { id: z.number().int().positive().describe("Action ID") }, async ({ id }) => withToolError(async () => json((await sb("GET", `/storage_boxes/actions/${id}`)).action)));
69
+ server.tool("list_storage_box_actions", "List Actions (all pages). With storage_box_id: actions for that box. Without: actions across all Storage Boxes (optionally filtered by id)", {
70
+ storage_box_id: boxId.optional(),
71
+ id: z.array(z.number().int().positive()).optional().describe("Filter by action IDs (Storage-Box-wide listing)"),
72
+ status: actionStatus,
73
+ sort,
74
+ }, async ({ storage_box_id, ...query }) => withToolError(async () => {
75
+ const path = storage_box_id ? `${boxPath(storage_box_id)}/actions` : "/storage_boxes/actions";
76
+ if (storage_box_id && query.id)
77
+ throw new Error("id filter is only supported without storage_box_id");
78
+ return json(await listAll((p) => sb("GET", path, { query: { ...query, page: p.page, per_page: p.perPage } }), "actions"));
79
+ }));
80
+ server.tool("change_storage_box_protection", `Enable/disable delete protection for a Storage Box. ${POLL}`, { id: boxId, delete: z.boolean().describe("Prevent deletion") }, async ({ id, ...body }) => withToolError(async () => json(await sb("POST", `${boxPath(id)}/actions/change_protection`, { body }))));
81
+ server.tool("change_storage_box_type", `Upgrade/downgrade a Storage Box to another type (changes billing). Cannot downgrade below current usage. ${POLL}`, { id: boxId, storage_box_type: z.string().describe("Target Storage Box Type ID or name, e.g. bx21") }, async ({ id, ...body }) => withToolError(async () => json(await sb("POST", `${boxPath(id)}/actions/change_type`, { body }))));
82
+ server.tool("reset_storage_box_password", `Set a new password for the Storage Box main account (existing clients using the old password lose access). ${POLL}`, { id: boxId, password }, async ({ id, ...body }) => withToolError(async () => json(await sb("POST", `${boxPath(id)}/actions/reset_password`, { body }))));
83
+ server.tool("update_storage_box_access_settings", `Update the main account's access settings (partial: omitted fields are unchanged). ${POLL}`, { id: boxId, ...boxAccess }, async ({ id, ...body }) => withToolError(async () => {
84
+ if (Object.keys(body).length === 0)
85
+ throw new Error("Provide at least one access setting");
86
+ return json(await sb("POST", `${boxPath(id)}/actions/update_access_settings`, { body }));
87
+ }));
88
+ server.tool("enable_storage_box_snapshot_plan", `Enable (or replace) the automatic snapshot plan. Runs at hour:minute UTC, optionally only on day_of_week (1=Mon..7=Sun) and/or day_of_month; null/omitted = every day. Oldest automatic snapshots beyond max_snapshots are deleted. ${POLL}`, {
89
+ id: boxId,
90
+ max_snapshots: z.number().int().min(1).describe("Snapshots to keep (<= the type's automatic_snapshot_limit)"),
91
+ hour: z.number().int().min(0).max(23).describe("Hour (UTC)"),
92
+ minute: z.number().int().min(0).max(59).describe("Minute (UTC)"),
93
+ day_of_week: z.number().int().min(1).max(7).nullable().optional().describe("1=Monday..7=Sunday; null = every day"),
94
+ day_of_month: z.number().int().min(1).max(31).nullable().optional().describe("Day of month; null = every day"),
95
+ }, async ({ id, ...body }) => withToolError(async () => json(await sb("POST", `${boxPath(id)}/actions/enable_snapshot_plan`, { body }))));
96
+ server.tool("disable_storage_box_snapshot_plan", `Disable the automatic snapshot plan. Existing automatic snapshots are kept (delete them manually). ${POLL}`, { id: boxId }, async ({ id }) => withToolError(async () => json(await sb("POST", `${boxPath(id)}/actions/disable_snapshot_plan`))));
97
+ server.tool("rollback_storage_box_snapshot", `Roll a Storage Box back to a snapshot. Deletes all newer snapshots and ALL data written since the snapshot. ${CONFIRM}. ${POLL}`, { id: boxId, snapshot: z.string().describe("Snapshot ID or name") }, async ({ id, ...body }) => withToolError(async () => json(await sb("POST", `${boxPath(id)}/actions/rollback_snapshot`, { body }))));
98
+ // --- Subaccounts ---
99
+ server.tool("list_storage_box_subaccounts", "List subaccounts of a Storage Box (username, home_directory, access settings, server FQDN)", { id: boxId, name: z.string().optional(), username: z.string().optional(), label_selector: labelSelector, sort }, async ({ id, ...query }) => withToolError(async () => json((await sb("GET", `${boxPath(id)}/subaccounts`, { query })).subaccounts)));
100
+ server.tool("get_storage_box_subaccount", "Get a Storage Box subaccount", { id: boxId, subaccount_id: subaccountId }, async ({ id, subaccount_id }) => withToolError(async () => json((await sb("GET", subPath(id, subaccount_id))).subaccount)));
101
+ server.tool("create_storage_box_subaccount", `Create a subaccount: a separate login restricted to home_directory inside the box (shares the box's quota). Username is assigned by Hetzner (<box-username>-subN). Returns {subaccount: {id, storage_box}, action}; ${POLL}, then get_storage_box_subaccount for details`, {
102
+ id: boxId,
103
+ home_directory: homeDirectory,
104
+ password,
105
+ name: z.string().optional().describe("Defaults to the generated username"),
106
+ description: z.string().optional(),
107
+ labels: labels.optional(),
108
+ access_settings: z.object(subAccess).optional(),
109
+ }, async ({ id, ...body }) => withToolError(async () => json(await sb("POST", `${boxPath(id)}/subaccounts`, { body }))));
110
+ server.tool("update_storage_box_subaccount", "Update a subaccount's name, description and/or labels (labels replace the whole set). Use change_storage_box_subaccount_home_directory / update_storage_box_subaccount_access_settings for those", {
111
+ id: boxId,
112
+ subaccount_id: subaccountId,
113
+ name: z.string().optional(),
114
+ description: z.string().optional(),
115
+ labels: labels.optional(),
116
+ }, async ({ id, subaccount_id, ...body }) => withToolError(async () => json((await sb("PUT", subPath(id, subaccount_id), { body })).subaccount)));
117
+ server.tool("delete_storage_box_subaccount", `Delete a subaccount (its login stops working; files in its home directory remain in the main account). ${CONFIRM}. ${POLL}`, { id: boxId, subaccount_id: subaccountId }, async ({ id, subaccount_id }) => withToolError(async () => json(await sb("DELETE", subPath(id, subaccount_id)))));
118
+ server.tool("change_storage_box_subaccount_home_directory", `Change a subaccount's home directory (created if missing). ${POLL}`, { id: boxId, subaccount_id: subaccountId, home_directory: homeDirectory }, async ({ id, subaccount_id, ...body }) => withToolError(async () => json(await sb("POST", `${subPath(id, subaccount_id)}/actions/change_home_directory`, { body }))));
119
+ server.tool("reset_storage_box_subaccount_password", `Set a new password for a subaccount. ${POLL}`, { id: boxId, subaccount_id: subaccountId, password }, async ({ id, subaccount_id, ...body }) => withToolError(async () => json(await sb("POST", `${subPath(id, subaccount_id)}/actions/reset_subaccount_password`, { body }))));
120
+ server.tool("update_storage_box_subaccount_access_settings", `Update a subaccount's access settings incl. readonly (partial: omitted fields are unchanged). ${POLL}`, { id: boxId, subaccount_id: subaccountId, ...subAccess }, async ({ id, subaccount_id, ...body }) => withToolError(async () => {
121
+ if (Object.keys(body).length === 0)
122
+ throw new Error("Provide at least one access setting");
123
+ return json(await sb("POST", `${subPath(id, subaccount_id)}/actions/update_access_settings`, { body }));
124
+ }));
125
+ // --- Snapshots ---
126
+ server.tool("list_storage_box_snapshots", "List snapshots of a Storage Box (manual and automatic; is_automatic filters)", { id: boxId, name: z.string().optional(), label_selector: labelSelector, is_automatic: z.boolean().optional(), sort }, async ({ id, ...query }) => withToolError(async () => json((await sb("GET", `${boxPath(id)}/snapshots`, { query })).snapshots)));
127
+ server.tool("get_storage_box_snapshot", "Get a Storage Box snapshot (name, description, size stats, is_automatic)", { id: boxId, snapshot_id: snapshotId }, async ({ id, snapshot_id }) => withToolError(async () => json((await sb("GET", snapPath(id, snapshot_id))).snapshot)));
128
+ server.tool("create_storage_box_snapshot", `Create a manual snapshot (limited by the type's snapshot_limit). Returns {snapshot: {id, storage_box}, action}; ${POLL}, then get_storage_box_snapshot for details`, { id: boxId, description: z.string().optional(), labels: labels.optional() }, async ({ id, ...body }) => withToolError(async () => json(await sb("POST", `${boxPath(id)}/snapshots`, { body }))));
129
+ server.tool("update_storage_box_snapshot", "Update a snapshot's description and/or labels (labels replace the whole set)", { id: boxId, snapshot_id: snapshotId, description: z.string().optional(), labels: labels.optional() }, async ({ id, snapshot_id, ...body }) => withToolError(async () => json((await sb("PUT", snapPath(id, snapshot_id), { body })).snapshot)));
130
+ server.tool("delete_storage_box_snapshot", `Delete a snapshot. ${CONFIRM}. ${POLL}`, { id: boxId, snapshot_id: snapshotId }, async ({ id, snapshot_id }) => withToolError(async () => json(await sb("DELETE", snapPath(id, snapshot_id)))));
131
+ }
@@ -0,0 +1,48 @@
1
+ // Shared helpers for tool modules.
2
+ // hetzner-sdk-ts throws ApiError with the Hetzner error JSON in `body` and a vague
3
+ // message ("Forbidden", "Generic Error: ..."). Surface the API's code/message instead,
4
+ // matching HcloudApiError's format: "<code> (<status>): <message> <details>".
5
+ export const formatError = (error) => {
6
+ const e = error;
7
+ if (e && e.name === "ApiError" && e.body != null) {
8
+ let body = e.body;
9
+ if (typeof body === "string") {
10
+ try {
11
+ body = JSON.parse(body);
12
+ }
13
+ catch { /* keep string */ }
14
+ }
15
+ const apiErr = body?.error;
16
+ if (apiErr?.code) {
17
+ const details = apiErr.details && Object.keys(apiErr.details).length ? ` ${JSON.stringify(apiErr.details)}` : "";
18
+ return `${apiErr.code} (${e.status}): ${apiErr.message ?? ""}${details}`;
19
+ }
20
+ }
21
+ if (error instanceof Error) {
22
+ return error.message;
23
+ }
24
+ return String(error);
25
+ };
26
+ export async function withToolError(run) {
27
+ try {
28
+ return await run();
29
+ }
30
+ catch (error) {
31
+ return { content: [{ type: "text", text: `Error: ${formatError(error)}` }], isError: true };
32
+ }
33
+ }
34
+ // Hetzner list endpoints are paginated (default 25, max 50 per page). Follow
35
+ // meta.pagination.next_page so list tools return every item, not just page 1.
36
+ // (Link headers are deprecated by Hetzner; meta.pagination is the supported mechanism.)
37
+ export async function listAll(fetchPage, key) {
38
+ const items = [];
39
+ let page = 1;
40
+ while (page != null) {
41
+ const response = await fetchPage({ page, perPage: 50 });
42
+ items.push(...(response?.[key] ?? []));
43
+ const next = response?.meta?.pagination?.next_page ?? null;
44
+ page = next != null && next > page ? next : null; // guard against non-advancing pagination
45
+ }
46
+ return items;
47
+ }
48
+ export const json = (value) => ({ content: [{ type: "text", text: JSON.stringify(value, null, 2) }] });
package/package.json CHANGED
@@ -1,20 +1,31 @@
1
1
  {
2
2
  "name": "hcloud-mcp",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Standalone MCP server for Hetzner Cloud API — use with Cursor, Claude Desktop, CLI, or any MCP client",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
+ "files": [
8
+ "dist",
9
+ "skills",
10
+ "run.js"
11
+ ],
7
12
  "bin": {
8
13
  "hcloud-mcp": "dist/index.js"
9
14
  },
10
15
  "scripts": {
11
- "build": "tsc",
16
+ "build": "rm -rf dist && tsc",
12
17
  "prepublishOnly": "npm run build",
13
18
  "start": "node dist/index.js",
14
19
  "dev": "tsc --watch",
15
20
  "test:api": "node scripts/test-list-api.mjs",
16
21
  "test:mcp": "node scripts/test-mcp-list.mjs",
17
22
  "test:live": "node scripts/test-live-lifecycle.mjs",
23
+ "test:live:dns": "node scripts/test-live-dns.mjs",
24
+ "test:live:images": "node scripts/test-live-images.mjs",
25
+ "test:live:ops": "node scripts/test-live-server-ops.mjs",
26
+ "test:live:actions": "node scripts/test-live-action-gaps.mjs",
27
+ "test:live:certs": "node scripts/test-live-certificates.mjs",
28
+ "test:live:storage": "node scripts/test-live-storage-box.mjs",
18
29
  "audit:api": "cross-env DRY_RUN=1 node scripts/audit-api-shapes.mjs"
19
30
  },
20
31
  "keywords": [
@@ -24,7 +35,10 @@
24
35
  "model-context-protocol"
25
36
  ],
26
37
  "license": "MIT",
27
- "repository": "github:Xodus-CO/hcloud-mcp",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/Xodus-CO/hcloud-mcp.git"
41
+ },
28
42
  "homepage": "https://github.com/Xodus-CO/hcloud-mcp#readme",
29
43
  "bugs": "https://github.com/Xodus-CO/hcloud-mcp/issues",
30
44
  "dependencies": {
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: hetzner-cloud
3
- description: Use when provisioning, changing, or tearing down Hetzner Cloud resources through the hcloud-mcp tools (servers, networks, firewalls, load balancers, volumes, floating or primary IPs), or when a Hetzner call fails with must_be_unassigned, locked, invalid_input, or a 410.
3
+ description: Use when provisioning, changing, recovering, or tearing down Hetzner resources through the hcloud-mcp tools (servers, networks, firewalls, load balancers, volumes, IPs, DNS, certificates, snapshots, Storage Boxes), or when a Hetzner call fails with must_be_unassigned, locked, invalid_input, or a 410.
4
4
  ---
5
5
 
6
6
  # Hetzner Cloud via hcloud-mcp
@@ -37,6 +37,50 @@ Deleting an assigned IP fails with `must_be_unassigned`.
37
37
 
38
38
  **Filtering by label:** no list tool takes a `label_selector`. Call the list tool for each resource type, including firewalls and primary IPs, then filter on `labels` yourself. List tools return every page.
39
39
 
40
+ ## DNS
41
+ - **Zone and RRSet references:** refer to a zone by name (`example.com`) or by ID. RRSet `name` is relative to the zone: `@` is the apex, `www` is www.example.com. Use lowercase.
42
+ - **Record values** use zone-file syntax:
43
+ - TXT values must be quoted, e.g. `"\"v=spf1 -all\""`.
44
+ - MX values look like `"10 mail.example.com."`.
45
+ - A record pointing at a server: use the IP from `get_server`, at `public_net.ipv4.ip`.
46
+ - **Picking the right tool:**
47
+
48
+ | Task | Tool |
49
+ |---|---|
50
+ | Add a record | `add_rrset_records` (creates the RRSet if it's missing) |
51
+ | Replace all records | `set_rrset_records` |
52
+ | Drop one record | `remove_rrset_records` (removing the last record deletes the RRSet) |
53
+ | Change a record's comment | `update_rrset_records` |
54
+
55
+ - **Back up before bulk changes:** `export_zonefile`, then `import_zonefile`. Import replaces every RRSet in the zone. Never import a partial file.
56
+ - **A new zone answers nothing yet.** Tell the user to point the domain's nameservers at the registrar to `get_zone.authoritative_nameservers.assigned`.
57
+ - **Errors:** `protected` means `change_rrset_protection` or `change_zone_protection` is on; ask the user before turning it off. `incorrect_zone_mode` means you tried a record edit on a secondary zone.
58
+
59
+ ## Recovery, snapshots, protection
60
+ - **Before a risky change** (`rebuild_server`, `change_server_type`): power the server off → `create_snapshot` (wait for it to finish) → make the change. Find and clean up snapshots later with `list_snapshots`, since they bill per GB-month.
61
+ - **Locked out of a server:** first try `reset_root_password`, which needs the qemu guest agent; stock images have it. If that fails: `enable_rescue` → wait for the Action → `reset_server` → fix things from the rescue system. Rescue switches itself off after one boot. `request_console` gives a browser VNC URL that must be used within 60 seconds.
62
+ - **Secrets:** passwords and console URLs go to the user only. Never write them to files, labels, or later tool arguments.
63
+ - **Protection:** use `change_protection(resource, id, delete)`. On servers it also sets rebuild protection, because the API requires both to match. Only remove protection after the user confirms.
64
+ - **Backups:** `disable_server_backups` deletes every existing backup. To keep one, run `update_image type:"snapshot"` on it first.
65
+
66
+ ## Metrics
67
+ Call `get_server_metrics` or `get_load_balancer_metrics` with `last_minutes` and `include_values:false` to get the summary first. Pull the raw series only if something looks off. CPU is per vCPU: 200 means two full cores.
68
+
69
+ ## Certificates and load balancer HTTPS
70
+ - **Managed (Let's Encrypt):** the domain must be in a primary Hetzner DNS zone that is delegated to Hetzner. Steps: `create_zone` → user delegates it at the registrar → `create_certificate type:managed` → poll `get_action`. Hetzner renews it automatically.
71
+ - **Uploaded:** certificates never renew. To rotate, create the new cert, point the LB service at it via `update_load_balancer_service http.certificates`, then delete the old one. Check `used_by` before deleting any certificate.
72
+
73
+ ## Storage Boxes
74
+ - **Where they live:** `api.hetzner.com`, using the same token. Poll their actions with `get_storage_box_action`, and wait for the box's `status: active`.
75
+ - **Passwords:** 12–128 characters, with upper case, lower case, a digit and a special character. Generate a random one rather than inventing a memorable one. A password reset locks out existing clients.
76
+ - **Irreversible actions:** `rollback_storage_box_snapshot` discards newer snapshots and all data written since. `delete_storage_box` removes everything. Confirm first, and suggest `change_storage_box_protection`.
77
+
78
+ ## Labels and network changes
79
+ - **Labels:** every `update_*` replaces the whole label set. Read the current labels and merge.
80
+ - **Alias IPs:** `change_server_alias_ips` replaces the whole list. Send the existing IPs plus the new one.
81
+ - **Placement groups:** `add_server_to_placement_group` needs the server powered off. Removing works while it runs.
82
+ - **Network ranges:** `change_network_ip_range` can only widen the range (e.g. /16 → /15), and needs every member detached first.
83
+
40
84
  ## Common mistakes
41
85
  | Symptom | Cause and fix |
42
86
  |---|---|
@@ -47,4 +91,4 @@ Deleting an assigned IP fails with `must_be_unassigned`.
47
91
  | `protected` | Delete protection is on. Ask the user before you change it |
48
92
 
49
93
  ## Safety
50
- Deletes, `reset_server`, `power_off_server`, and `change_server_type` can't be undone. Before you run any of them, list exactly what will be affected and get the user's confirmation.
94
+ Deletes, `rebuild_server` (wipes the disk), `import_zonefile`, `rollback_storage_box_snapshot`, `disable_server_backups`, `reset_server`, `power_off_server`, and `change_server_type` can't be undone. Before you run any of them, list exactly what will be affected and get the user's confirmation.
@@ -1,45 +0,0 @@
1
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
- import { ListToolsRequestSchema, CallToolRequestSchema, ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
3
- import { z } from "zod";
4
- import { zodToJsonSchema } from "zod-to-json-schema";
5
- export class McpServer {
6
- server;
7
- tools = new Map();
8
- constructor(info) {
9
- this.server = new Server(info, {
10
- capabilities: {
11
- tools: {},
12
- },
13
- });
14
- this.server.setRequestHandler(ListToolsRequestSchema, async () => {
15
- return {
16
- tools: Array.from(this.tools.entries()).map(([name, tool]) => ({
17
- name,
18
- description: tool.description,
19
- inputSchema: zodToJsonSchema(tool.parameters),
20
- })),
21
- };
22
- });
23
- this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
24
- const tool = this.tools.get(request.params.name);
25
- if (!tool) {
26
- throw new McpError(ErrorCode.MethodNotFound, `Tool not found: ${request.params.name}`);
27
- }
28
- const args = tool.parameters.safeParse(request.params.arguments);
29
- if (!args.success) {
30
- throw new McpError(ErrorCode.InvalidParams, `Invalid arguments: ${args.error.message}`);
31
- }
32
- return await tool.handler(args.data);
33
- });
34
- }
35
- tool(name, description, parameters, handler) {
36
- this.tools.set(name, {
37
- description,
38
- parameters: z.object(parameters),
39
- handler,
40
- });
41
- }
42
- async connect(transport) {
43
- return this.server.connect(transport);
44
- }
45
- }
@@ -1,160 +0,0 @@
1
- /**
2
- * Audit script: verify request body shapes for create_* tools match the Hetzner API.
3
- * Builds minimal valid payloads and calls the SDK.
4
- * With DRY_RUN=1: uses invalid token so requests fail with 401 (no resources created).
5
- * With real token: makes real API calls and may create resources.
6
- * Run from project root: node scripts/audit-api-shapes.mjs
7
- */
8
- import "dotenv/config";
9
- import {
10
- ServersService,
11
- LoadBalancersService,
12
- NetworksService,
13
- VolumesService,
14
- FloatingIPsService,
15
- SshKeysService,
16
- PlacementGroupsService,
17
- OpenAPI,
18
- } from "hetzner-sdk-ts";
19
-
20
- let token = process.env.HCLOUD_TOKEN;
21
- if (!token) {
22
- console.error("Error: HCLOUD_TOKEN environment variable is required");
23
- process.exit(1);
24
- }
25
- if (process.env.DRY_RUN === "1") {
26
- token = "invalid";
27
- console.log(
28
- "DRY_RUN=1: using invalid token (no resources will be created)\n",
29
- );
30
- }
31
- OpenAPI.TOKEN = token;
32
-
33
- function ok(name, err) {
34
- const msg = err?.message || String(err);
35
- if (msg.includes("Unauthorized") || msg.includes("401")) {
36
- console.log(
37
- `${name}: OK (request shape accepted, auth failed as expected or token invalid)`,
38
- );
39
- return true;
40
- }
41
- if (msg.includes("invalid") || msg.includes("400")) {
42
- console.error(`${name}: FAIL - API rejected payload:`, msg);
43
- return false;
44
- }
45
- console.error(`${name}: FAIL -`, msg);
46
- return false;
47
- }
48
-
49
- async function run() {
50
- let failed = 0;
51
-
52
- console.log("Auditing create_* request body shapes...\n");
53
-
54
- // create_server
55
- try {
56
- await ServersService.postServers({
57
- requestBody: {
58
- name: "audit-test-server",
59
- server_type: "cx11",
60
- image: "ubuntu-24.04",
61
- location: "fsn1",
62
- },
63
- });
64
- console.log("create_server: OK (request sent)");
65
- } catch (e) {
66
- if (!ok("create_server", e)) failed++;
67
- }
68
-
69
- // create_load_balancer
70
- try {
71
- await LoadBalancersService.postLoadBalancers({
72
- requestBody: {
73
- name: "audit-test-lb",
74
- load_balancer_type: "lb11",
75
- location: "fsn1",
76
- },
77
- });
78
- console.log("create_load_balancer: OK (request sent)");
79
- } catch (e) {
80
- if (!ok("create_load_balancer", e)) failed++;
81
- }
82
-
83
- // create_network
84
- try {
85
- await NetworksService.postNetworks({
86
- requestBody: {
87
- name: "audit-test-network",
88
- ip_range: "10.0.0.0/16",
89
- },
90
- });
91
- console.log("create_network: OK (request sent)");
92
- } catch (e) {
93
- if (!ok("create_network", e)) failed++;
94
- }
95
-
96
- // create_volume
97
- try {
98
- await VolumesService.postVolumes({
99
- requestBody: {
100
- name: "audit-test-volume",
101
- size: 10,
102
- location: "fsn1",
103
- },
104
- });
105
- console.log("create_volume: OK (request sent)");
106
- } catch (e) {
107
- if (!ok("create_volume", e)) failed++;
108
- }
109
-
110
- // create_floating_ip
111
- try {
112
- await FloatingIPsService.postFloatingIps({
113
- requestBody: {
114
- type: "ipv4",
115
- home_location: "fsn1",
116
- },
117
- });
118
- console.log("create_floating_ip: OK (request sent)");
119
- } catch (e) {
120
- if (!ok("create_floating_ip", e)) failed++;
121
- }
122
-
123
- // create_ssh_key
124
- try {
125
- await SshKeysService.postSshKeys({
126
- requestBody: {
127
- name: "audit-test-key",
128
- public_key:
129
- "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI audit-test-invalid-key",
130
- },
131
- });
132
- console.log("create_ssh_key: OK (request sent)");
133
- } catch (e) {
134
- if (!ok("create_ssh_key", e)) failed++;
135
- }
136
-
137
- // create_placement_group
138
- try {
139
- await PlacementGroupsService.postPlacementGroups({
140
- requestBody: {
141
- name: "audit-test-pg",
142
- type: "spread",
143
- },
144
- });
145
- console.log("create_placement_group: OK (request sent)");
146
- } catch (e) {
147
- if (!ok("create_placement_group", e)) failed++;
148
- }
149
-
150
- console.log("");
151
- if (failed > 0) {
152
- console.error(
153
- `${failed} audit(s) failed. Check payload shapes against SDK/API.`,
154
- );
155
- process.exit(1);
156
- }
157
- console.log("All create_* payload shapes accepted by API.");
158
- }
159
-
160
- run();