hcloud-mcp 0.3.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.
@@ -1,6 +1,5 @@
1
- // Minimal typed client for Hetzner Cloud API endpoints that hetzner-sdk-ts does not
2
- // cover (e.g. DNS zones / RRSets). Uses the same token as the SDK.
3
- import { OpenAPI } from "hetzner-sdk-ts";
1
+ // Minimal fetch client for the Hetzner Cloud API (and the Hetzner API for Storage Boxes).
2
+ // Reads the project token from HCLOUD_TOKEN (index.ts loads .env / exits if unset).
4
3
  // Cloud API (servers, networks, DNS, ...) and the Hetzner API (Storage Boxes) accept the same project token.
5
4
  export const CLOUD_API = "https://api.hetzner.cloud/v1";
6
5
  export const HETZNER_API = "https://api.hetzner.com/v1";
@@ -9,14 +8,16 @@ export class HcloudApiError extends Error {
9
8
  code;
10
9
  details;
11
10
  constructor(status, code, message, details) {
12
- super(`${code} (${status}): ${message}${details ? ` ${JSON.stringify(details)}` : ""}`);
11
+ // The API sends `details: {}` on most errors; only append details that carry something.
12
+ const hasDetails = details != null && (typeof details !== "object" || Object.keys(details).length > 0);
13
+ super(`${code} (${status}): ${message}${hasDetails ? ` ${JSON.stringify(details)}` : ""}`);
13
14
  this.status = status;
14
15
  this.code = code;
15
16
  this.details = details;
16
17
  }
17
18
  }
18
19
  function token() {
19
- const t = (typeof OpenAPI.TOKEN === "string" ? OpenAPI.TOKEN : undefined) ?? process.env.HCLOUD_TOKEN;
20
+ const t = process.env.HCLOUD_TOKEN;
20
21
  if (!t)
21
22
  throw new Error("HCLOUD_TOKEN is not set");
22
23
  return t;
@@ -41,7 +42,16 @@ export async function hcloudRequest(method, path, options = {}) {
41
42
  if (res.status === 204)
42
43
  return {};
43
44
  const text = await res.text();
44
- const data = text ? JSON.parse(text) : {};
45
+ let data = {};
46
+ try {
47
+ data = text ? JSON.parse(text) : {};
48
+ }
49
+ catch (e) {
50
+ // Non-JSON body (e.g. an HTML 502 from a proxy): report the HTTP status instead.
51
+ if (!res.ok)
52
+ throw new HcloudApiError(res.status, "http_error", res.statusText);
53
+ throw e;
54
+ }
45
55
  if (!res.ok) {
46
56
  const err = data?.error ?? {};
47
57
  throw new HcloudApiError(res.status, err.code ?? "http_error", err.message ?? res.statusText, err.details);
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { hcloudRequest } from "./hcloud-api.js";
3
- import { json, listAll, withToolError } from "./tool-helpers.js";
3
+ import { ADDITIVE, ADDITIVE_IDEMPOTENT, DESTRUCTIVE_IDEMPOTENT, READ_ONLY, json, listAll, withToolError } from "./tool-helpers.js";
4
4
  const labelsSchema = z.record(z.string(), z.string());
5
5
  // Every resource whose spec has POST /{collection}/{id}/actions/change_protection.
6
6
  // Certificates have no change_protection action. DNS zones and RRSets are covered by
@@ -15,53 +15,85 @@ const PROTECTION_RESOURCES = {
15
15
  image: "images",
16
16
  };
17
17
  export function registerImageTools(server) {
18
- server.tool("create_snapshot", "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", {
19
- id: z.number().describe("Server ID"),
20
- description: z.string().optional().describe("Image description (auto-generated if omitted)"),
21
- type: z.enum(["snapshot", "backup"]).optional().describe("Default snapshot"),
22
- labels: labelsSchema.optional(),
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,
23
27
  }, async ({ id, description, type, labels }) => withToolError(async () => json(await hcloudRequest("POST", `/servers/${id}/actions/create_image`, {
24
28
  body: { type: type ?? "snapshot", description, labels },
25
29
  }))));
26
- server.tool("list_snapshots", "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", {
27
- type: z.array(z.enum(["snapshot", "backup", "system", "app"])).optional()
28
- .describe("Image types; default [\"snapshot\", \"backup\"]"),
29
- bound_to: z.array(z.string()).optional().describe("Server IDs the backup images are bound to"),
30
- label_selector: z.string().optional().describe("e.g. env=prod"),
31
- status: z.array(z.enum(["available", "creating", "unavailable"])).optional(),
32
- architecture: z.enum(["x86", "arm"]).optional(),
33
- name: z.string().optional().describe("Exact name (system/app images have names; snapshots usually not)"),
34
- include_deprecated: z.boolean().optional(),
35
- sort: z.array(z.string()).optional().describe("e.g. [\"created:desc\"]; fields id, name, created"),
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,
36
44
  }, async ({ type, ...filters }) => withToolError(async () => {
37
45
  const images = await listAll((p) => hcloudRequest("GET", "/images", {
38
- query: { type: type ?? ["snapshot", "backup"], ...filters, page: p.page, per_page: p.perPage },
46
+ query: { type: type ?? ["snapshot", "backup"], ...filters, ...p },
39
47
  }), "images");
40
48
  return json(images);
41
49
  }));
42
- server.tool("get_image", "Get an image by ID (type, status, image_size/disk_size in GB, created_from, bound_to, protection, labels)", { id: z.number().describe("Image ID") }, async ({ id }) => withToolError(async () => json(await hcloudRequest("GET", `/images/${id}`))));
43
- server.tool("update_image", "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", {
44
- id: z.number().describe("Image ID"),
45
- description: z.string().optional(),
46
- type: z.literal("snapshot").optional().describe("Convert a backup image to a snapshot"),
47
- labels: labelsSchema.optional().describe("Replaces all existing labels"),
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,
48
64
  }, async ({ id, description, type, labels }) => withToolError(async () => {
49
65
  if (description === undefined && type === undefined && labels === undefined) {
50
66
  throw new Error("Pass at least one of description, type, labels");
51
67
  }
52
68
  return json(await hcloudRequest("PUT", `/images/${id}`, { body: { description, type, labels } }));
53
69
  }));
54
- server.tool("delete_image", "Delete a snapshot or backup image (system/app images cannot be deleted). Fails if delete protection is on. Irreversible; confirm with the user first", { id: z.number().describe("Image ID") }, async ({ id }) => withToolError(async () => {
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 () => {
55
75
  await hcloudRequest("DELETE", `/images/${id}`);
56
76
  return json({ deleted: true, id });
57
77
  }));
58
- server.tool("enable_server_backups", "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", { id: z.number().describe("Server ID") }, async ({ id }) => withToolError(async () => json(await hcloudRequest("POST", `/servers/${id}/actions/enable_backup`))));
59
- server.tool("disable_server_backups", "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", { id: z.number().describe("Server ID") }, async ({ id }) => withToolError(async () => json(await hcloudRequest("POST", `/servers/${id}/actions/disable_backup`))));
60
- server.tool("change_protection", "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", {
61
- resource: z.enum(["server", "volume", "floating_ip", "primary_ip", "load_balancer", "network", "image"]),
62
- id: z.number().describe("Resource ID"),
63
- delete: z.boolean().optional().describe("Prevent deletion"),
64
- rebuild: z.boolean().optional().describe("Servers only: prevent rebuild"),
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,
65
97
  }, async ({ resource, id, delete: del, rebuild }) => withToolError(async () => {
66
98
  let body;
67
99
  if (resource === "server") {
package/dist/index.js CHANGED
@@ -4,7 +4,6 @@ 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";
9
8
  import { registerDnsTools } from "./dns-tools.js";
10
9
  import { registerExtraTools } from "./extra-tools.js";
@@ -19,13 +18,11 @@ if (!process.env.HCLOUD_TOKEN) {
19
18
  const __dirname = dirname(fileURLToPath(import.meta.url));
20
19
  loadEnv({ path: join(__dirname, "..", ".env") });
21
20
  }
22
- const token = process.env.HCLOUD_TOKEN;
23
- if (!token) {
21
+ if (!process.env.HCLOUD_TOKEN) {
24
22
  console.error("Error: HCLOUD_TOKEN environment variable is required");
25
23
  process.exit(1);
26
24
  }
27
- OpenAPI.TOKEN = token;
28
- const server = new McpServer({ name: "hetzner-cloud", version: "0.3.0" }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
25
+ const server = new McpServer({ name: "hetzner-cloud", version: "0.4.0" }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
29
26
  // Tool groups. HCLOUD_TOOLSETS (comma-separated) limits which load, for clients with
30
27
  // tool-count limits; default is all. "core" is always loaded.
31
28
  const TOOLSETS = {