hcloud-mcp 0.1.1 → 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.
- package/README.md +83 -10
- package/dist/action-gap-tools.js +66 -0
- package/dist/certificate-tools.js +65 -0
- package/dist/dns-tools.js +86 -0
- package/dist/extra-tools.js +33 -0
- package/dist/hcloud-api.js +52 -0
- package/dist/image-tools.js +85 -0
- package/dist/index.js +32 -2
- package/dist/instructions.js +22 -0
- package/dist/register-tools.js +59 -72
- package/dist/server-ops-tools.js +91 -0
- package/dist/storage-box-tools.js +131 -0
- package/dist/tool-helpers.js +48 -0
- package/package.json +18 -3
- package/skills/hetzner-cloud/SKILL.md +94 -0
- package/dist/mcp-server.js +0 -45
- package/scripts/audit-api-shapes.mjs +0 -160
- package/scripts/test-list-api.mjs +0 -47
- package/scripts/test-mcp-list.mjs +0 -62
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Sent to MCP clients in the initialize response; most clients put it in the model's context.
|
|
2
|
+
// Keep it short and about how to use the tools, not a list of them.
|
|
3
|
+
export const SERVER_INSTRUCTIONS = `Hetzner Cloud API tools. Notes:
|
|
4
|
+
|
|
5
|
+
- Placement is by location (fsn1, nbg1, hel1, ash, hil, sin), not datacenter. Datacenters were removed from the API in 2026.
|
|
6
|
+
- Before create_server, call list_server_types. Each type has locations[] with available, recommended and deprecation. Pick a location where the type is available and not deprecated. Call list_images and skip any image whose deprecation is set.
|
|
7
|
+
- Most create, delete and action tools return an Action. They run asynchronously. Poll get_action until status is "success" or "error" before you start a step that depends on the result.
|
|
8
|
+
- Detach first, then delete. Floating IPs and Primary IPs must be unassigned before deletion (error must_be_unassigned). Assigning or unassigning a Primary IP requires the server to be powered off. Detach volumes and remove LB targets before you delete their servers.
|
|
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
|
+
- For private networks use subnet type "cloud". Type "server" is deprecated.
|
|
11
|
+
- List tools return all pages. In large projects, prefer get_* by ID when you already know it.
|
|
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.
|
|
22
|
+
- Pricing: get_pricing returns prices per location and server type, in EUR, with and without VAT.`;
|
package/dist/register-tools.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import { ServersService, LoadBalancersService, NetworksService, VolumesService, FirewallsService, FirewallActionsService, FloatingIPsService, SshKeysService, ImagesService, LocationsService, ServerTypesService, PlacementGroupsService, PrimaryIPsService, ServerActionsService, VolumeActionsService, FloatingIpActionsService, LoadBalancerActionsService, NetworkActionsService, PricingService, ActionsService, LoadBalancerTypesService,
|
|
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"]),
|
|
6
7
|
protocol: z.enum(["tcp", "udp", "icmp", "esp", "gre"]),
|
|
7
|
-
source_ips: z.array(z.string()).optional(),
|
|
8
|
-
destination_ips: z.array(z.string()).optional(),
|
|
8
|
+
source_ips: z.array(z.string()).optional().describe("CIDRs for direction=in; host bits must be zero (10.0.1.0/24, not 10.0.1.42/24; single host 192.0.2.2/32)"),
|
|
9
|
+
destination_ips: z.array(z.string()).optional().describe("CIDRs for direction=out; host bits must be zero"),
|
|
9
10
|
port: z.string().optional(),
|
|
10
11
|
description: z.string().nullable().optional(),
|
|
11
12
|
});
|
|
@@ -14,25 +15,11 @@ 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
18
|
export function registerTools(server) {
|
|
32
19
|
// --- Servers ---
|
|
33
20
|
server.tool("list_servers", "List all servers", {}, async (_args, _extra) => withToolError(async () => {
|
|
34
|
-
const
|
|
35
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
21
|
+
const items = await listAll((p) => ServersService.getServers(p), "servers");
|
|
22
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
36
23
|
}));
|
|
37
24
|
server.tool("get_server", "Get a single server by ID", { id: z.number() }, async ({ id }, _extra) => withToolError(async () => {
|
|
38
25
|
const response = await ServersService.getServers1({ id });
|
|
@@ -42,8 +29,7 @@ export function registerTools(server) {
|
|
|
42
29
|
name: z.string(),
|
|
43
30
|
server_type: z.string(),
|
|
44
31
|
image: z.string(),
|
|
45
|
-
location: z.string().optional().describe("
|
|
46
|
-
datacenter: z.string().optional().describe("ID or name (omit if location set)"),
|
|
32
|
+
location: z.string().optional().describe("Location name or ID, e.g. fsn1, nbg1, hel1, ash, hil, sin. Check list_server_types locations[].available first"),
|
|
47
33
|
start_after_create: z.boolean().optional(),
|
|
48
34
|
ssh_keys: z.array(z.union([z.string(), z.number()])).optional().describe("List of SSH key names or IDs"),
|
|
49
35
|
firewalls: z.array(z.object({ firewall: z.number() })).optional(),
|
|
@@ -66,7 +52,6 @@ export function registerTools(server) {
|
|
|
66
52
|
server_type: args.server_type,
|
|
67
53
|
image: args.image,
|
|
68
54
|
location: args.location,
|
|
69
|
-
datacenter: args.datacenter,
|
|
70
55
|
start_after_create: args.start_after_create,
|
|
71
56
|
ssh_keys: args.ssh_keys?.map((k) => (typeof k === "number" ? String(k) : k)),
|
|
72
57
|
firewalls: args.firewalls,
|
|
@@ -164,8 +149,8 @@ export function registerTools(server) {
|
|
|
164
149
|
}));
|
|
165
150
|
// --- Load Balancers ---
|
|
166
151
|
server.tool("list_load_balancers", "List all load balancers", {}, async (_args, _extra) => withToolError(async () => {
|
|
167
|
-
const
|
|
168
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
152
|
+
const items = await listAll((p) => LoadBalancersService.getLoadBalancers(p), "load_balancers");
|
|
153
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
169
154
|
}));
|
|
170
155
|
server.tool("get_load_balancer", "Get a single load balancer by ID", { id: z.number() }, async ({ id }, _extra) => withToolError(async () => {
|
|
171
156
|
const response = await LoadBalancersService.getLoadBalancers1({ id });
|
|
@@ -190,9 +175,10 @@ export function registerTools(server) {
|
|
|
190
175
|
const response = await LoadBalancersService.postLoadBalancers({ requestBody });
|
|
191
176
|
return { content: [{ type: "text", text: JSON.stringify(response, null, 2) }] };
|
|
192
177
|
}));
|
|
193
|
-
server.tool("delete_load_balancer", "Delete a load balancer", { id: z.number() }, async ({ id }, _extra) => withToolError(async () => {
|
|
194
|
-
|
|
195
|
-
|
|
178
|
+
server.tool("delete_load_balancer", "Delete a load balancer. Returns a delete_load_balancer Action; poll get_action until it finishes", { id: z.number() }, async ({ id }, _extra) => withToolError(async () => {
|
|
179
|
+
// Since 2026-10-05 this returns 201 + Action (previously 204 empty).
|
|
180
|
+
const response = await LoadBalancersService.deleteLoadBalancers({ id });
|
|
181
|
+
return { content: [{ type: "text", text: JSON.stringify(response ?? { deleted: true }, null, 2) }] };
|
|
196
182
|
}));
|
|
197
183
|
server.tool("update_load_balancer", "Update a load balancer (name, labels)", {
|
|
198
184
|
id: z.number(),
|
|
@@ -308,6 +294,7 @@ export function registerTools(server) {
|
|
|
308
294
|
certificates: z.array(z.number()).optional(),
|
|
309
295
|
redirect_http: z.boolean().optional(),
|
|
310
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)"),
|
|
311
298
|
})
|
|
312
299
|
.optional(),
|
|
313
300
|
}, async (args, _extra) => withToolError(async () => {
|
|
@@ -320,8 +307,8 @@ export function registerTools(server) {
|
|
|
320
307
|
}));
|
|
321
308
|
// --- Networks ---
|
|
322
309
|
server.tool("list_networks", "List all networks", {}, async (_args, _extra) => withToolError(async () => {
|
|
323
|
-
const
|
|
324
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
310
|
+
const items = await listAll((p) => NetworksService.getNetworks(p), "networks");
|
|
311
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
325
312
|
}));
|
|
326
313
|
server.tool("get_network", "Get a single network by ID", { id: z.number() }, async ({ id }, _extra) => withToolError(async () => {
|
|
327
314
|
const response = await NetworksService.getNetworks1({ id });
|
|
@@ -364,7 +351,8 @@ export function registerTools(server) {
|
|
|
364
351
|
}));
|
|
365
352
|
server.tool("add_network_subnet", "Add a subnet to a network (e.g. for private networking 10.0.0.0/16 in a zone)", {
|
|
366
353
|
id: z.number().describe("Network ID"),
|
|
367
|
-
|
|
354
|
+
// "server" type is deprecated (removal 2027-04-15) and equivalent to "cloud".
|
|
355
|
+
type: z.enum(["cloud", "vswitch"]),
|
|
368
356
|
network_zone: z.string().describe("Network zone, e.g. eu-central"),
|
|
369
357
|
ip_range: z.string().optional().describe("CIDR, e.g. 10.0.0.0/24; omit for auto /24"),
|
|
370
358
|
vswitch_id: z.number().optional().describe("Required if type is vswitch"),
|
|
@@ -387,8 +375,8 @@ export function registerTools(server) {
|
|
|
387
375
|
}));
|
|
388
376
|
// --- Volumes ---
|
|
389
377
|
server.tool("list_volumes", "List all volumes", {}, async (_args, _extra) => withToolError(async () => {
|
|
390
|
-
const
|
|
391
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
378
|
+
const items = await listAll((p) => VolumesService.getVolumes(p), "volumes");
|
|
379
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
392
380
|
}));
|
|
393
381
|
server.tool("get_volume", "Get a single volume by ID", { id: z.number() }, async ({ id }, _extra) => withToolError(async () => {
|
|
394
382
|
const response = await VolumesService.getVolumes1({ id });
|
|
@@ -447,8 +435,8 @@ export function registerTools(server) {
|
|
|
447
435
|
}));
|
|
448
436
|
// --- Firewalls ---
|
|
449
437
|
server.tool("list_firewalls", "List all firewalls", {}, async (_args, _extra) => withToolError(async () => {
|
|
450
|
-
const
|
|
451
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
438
|
+
const items = await listAll((p) => FirewallsService.getFirewalls(p), "firewalls");
|
|
439
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
452
440
|
}));
|
|
453
441
|
server.tool("get_firewall", "Get a single firewall by ID", { id: z.number() }, async ({ id }, _extra) => withToolError(async () => {
|
|
454
442
|
const response = await FirewallsService.getFirewalls1({ id });
|
|
@@ -510,8 +498,8 @@ export function registerTools(server) {
|
|
|
510
498
|
}));
|
|
511
499
|
// --- Floating IPs ---
|
|
512
500
|
server.tool("list_floating_ips", "List all floating IPs", {}, async (_args, _extra) => withToolError(async () => {
|
|
513
|
-
const
|
|
514
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
501
|
+
const items = await listAll((p) => FloatingIPsService.getFloatingIps(p), "floating_ips");
|
|
502
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
515
503
|
}));
|
|
516
504
|
server.tool("create_floating_ip", "Create a floating IP", {
|
|
517
505
|
type: z.enum(["ipv4", "ipv6"]),
|
|
@@ -555,34 +543,36 @@ export function registerTools(server) {
|
|
|
555
543
|
const response = await FloatingIpActionsService.postFloatingIpsActionsUnassign({ id });
|
|
556
544
|
return { content: [{ type: "text", text: JSON.stringify(response, null, 2) }] };
|
|
557
545
|
}));
|
|
558
|
-
server.tool("delete_floating_ip", "Delete a floating IP (
|
|
546
|
+
server.tool("delete_floating_ip", "Delete a floating IP. Must be unassigned first (unassign_floating_ip), else fails with must_be_unassigned", { id: z.number() }, async ({ id }, _extra) => withToolError(async () => {
|
|
559
547
|
await FloatingIPsService.deleteFloatingIps({ id });
|
|
560
548
|
return { content: [{ type: "text", text: "Floating IP deleted successfully" }] };
|
|
561
549
|
}));
|
|
562
550
|
// --- Primary IPs ---
|
|
563
|
-
server.tool("list_primary_ips", "List all Primary IPs (static IPs bound to a
|
|
564
|
-
const
|
|
565
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
551
|
+
server.tool("list_primary_ips", "List all Primary IPs (static IPs bound to a location, assignable to one server)", {}, async (_args, _extra) => withToolError(async () => {
|
|
552
|
+
const items = await listAll((p) => PrimaryIPsService.getPrimaryIps(p), "primary_ips");
|
|
553
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
566
554
|
}));
|
|
567
|
-
server.tool("create_primary_ip", "Create a Primary IP (
|
|
555
|
+
server.tool("create_primary_ip", "Create a Primary IP (location-scoped; server must be off to assign). Provide location OR assignee_id (server).", {
|
|
568
556
|
name: z.string(),
|
|
569
557
|
type: z.enum(["ipv4", "ipv6"]),
|
|
570
|
-
|
|
571
|
-
assignee_id: z.number().optional().describe("Server ID to assign to immediately (omit if
|
|
558
|
+
location: z.string().optional().describe("Location name or ID, e.g. fsn1 (omit if assignee_id set)"),
|
|
559
|
+
assignee_id: z.number().optional().describe("Server ID to assign to immediately (omit if location set)"),
|
|
572
560
|
auto_delete: z.boolean().optional(),
|
|
573
561
|
labels: z.record(z.string()).optional(),
|
|
574
562
|
}, async (args, _extra) => withToolError(async () => {
|
|
575
|
-
const
|
|
563
|
+
const hasLocation = args.location != null && args.location !== "";
|
|
576
564
|
const hasAssignee = args.assignee_id != null;
|
|
577
|
-
if (
|
|
578
|
-
throw new Error("Provide exactly one of
|
|
565
|
+
if (hasLocation === hasAssignee) {
|
|
566
|
+
throw new Error("Provide exactly one of location or assignee_id (mutually exclusive)");
|
|
579
567
|
}
|
|
568
|
+
// hetzner-sdk-ts 1.0.1 still models the removed `datacenter` field; the API
|
|
569
|
+
// (since 2026-07-01) takes `location`. The SDK passes the body through as JSON.
|
|
580
570
|
const requestBody = {
|
|
581
571
|
name: args.name,
|
|
582
572
|
type: args.type,
|
|
583
|
-
|
|
584
|
-
datacenter: args.datacenter,
|
|
573
|
+
location: args.location,
|
|
585
574
|
assignee_id: args.assignee_id,
|
|
575
|
+
...(hasAssignee ? { assignee_type: "server" } : {}),
|
|
586
576
|
auto_delete: args.auto_delete,
|
|
587
577
|
labels: args.labels,
|
|
588
578
|
};
|
|
@@ -604,7 +594,7 @@ export function registerTools(server) {
|
|
|
604
594
|
});
|
|
605
595
|
return { content: [{ type: "text", text: JSON.stringify(response, null, 2) }] };
|
|
606
596
|
}));
|
|
607
|
-
server.tool("delete_primary_ip", "Delete a Primary IP
|
|
597
|
+
server.tool("delete_primary_ip", "Delete a Primary IP. Must be unassigned first (unassign_primary_ip, server powered off), else fails with must_be_unassigned", { id: z.number() }, async ({ id }, _extra) => withToolError(async () => {
|
|
608
598
|
await PrimaryIPsService.deletePrimaryIps({ id });
|
|
609
599
|
return { content: [{ type: "text", text: "Primary IP deleted successfully" }] };
|
|
610
600
|
}));
|
|
@@ -624,17 +614,18 @@ export function registerTools(server) {
|
|
|
624
614
|
}));
|
|
625
615
|
// --- SSH Keys ---
|
|
626
616
|
server.tool("list_ssh_keys", "List all SSH keys", {}, async (_args, _extra) => withToolError(async () => {
|
|
627
|
-
const
|
|
628
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
617
|
+
const items = await listAll((p) => SshKeysService.getSshKeys(p), "ssh_keys");
|
|
618
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
629
619
|
}));
|
|
630
|
-
server.tool("create_ssh_key", "Create a new SSH key", {
|
|
620
|
+
server.tool("create_ssh_key", "Create a new SSH key (public_key is trimmed; the API rejects leading whitespace)", {
|
|
631
621
|
name: z.string(),
|
|
632
622
|
public_key: z.string(),
|
|
633
623
|
labels: z.record(z.string()).optional(),
|
|
634
624
|
}, async (args, _extra) => withToolError(async () => {
|
|
635
625
|
const requestBody = {
|
|
636
626
|
name: args.name,
|
|
637
|
-
|
|
627
|
+
// API rejects leading whitespace since 2026-04-22; pasted keys often carry it.
|
|
628
|
+
public_key: args.public_key.trim(),
|
|
638
629
|
labels: args.labels,
|
|
639
630
|
};
|
|
640
631
|
const response = await SshKeysService.postSshKeys({ requestBody });
|
|
@@ -657,27 +648,23 @@ export function registerTools(server) {
|
|
|
657
648
|
}));
|
|
658
649
|
// --- General Info ---
|
|
659
650
|
server.tool("list_locations", "List all locations", {}, async (_args, _extra) => withToolError(async () => {
|
|
660
|
-
const
|
|
661
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
651
|
+
const items = await listAll((p) => LocationsService.getLocations(p), "locations");
|
|
652
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
662
653
|
}));
|
|
663
|
-
server.tool("list_images", "List all images", {}, async (_args, _extra) => withToolError(async () => {
|
|
664
|
-
const
|
|
665
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
654
|
+
server.tool("list_images", "List all images (check each image's `deprecation` field; deprecated images can stop being usable for new servers)", {}, async (_args, _extra) => withToolError(async () => {
|
|
655
|
+
const items = await listAll((p) => ImagesService.getImages(p), "images");
|
|
656
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
666
657
|
}));
|
|
667
|
-
server.tool("list_server_types", "List all server types", {}, async (_args, _extra) => withToolError(async () => {
|
|
668
|
-
const
|
|
669
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
658
|
+
server.tool("list_server_types", "List all server types. Per-location availability is in locations[]: available, recommended, deprecation (top-level `deprecated` was removed)", {}, async (_args, _extra) => withToolError(async () => {
|
|
659
|
+
const items = await listAll((p) => ServerTypesService.getServerTypes(p), "server_types");
|
|
660
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
670
661
|
}));
|
|
671
|
-
server.tool("list_load_balancer_types", "List all load balancer types (for create_load_balancer load_balancer_type)", {}, async (_args, _extra) => withToolError(async () => {
|
|
672
|
-
const
|
|
673
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
674
|
-
}));
|
|
675
|
-
server.tool("list_datacenters", "List all datacenters (e.g. ash-dc1; where servers can be created)", {}, async (_args, _extra) => withToolError(async () => {
|
|
676
|
-
const response = await DatacentersService.getDatacenters({});
|
|
677
|
-
return { content: [{ type: "text", text: JSON.stringify(response, null, 2) }] };
|
|
662
|
+
server.tool("list_load_balancer_types", "List all load balancer types (for create_load_balancer load_balancer_type; check `deprecation`)", {}, async (_args, _extra) => withToolError(async () => {
|
|
663
|
+
const items = await listAll((p) => LoadBalancerTypesService.getLoadBalancerTypes(p), "load_balancer_types");
|
|
664
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
678
665
|
}));
|
|
679
|
-
server.tool("list_actions", "
|
|
680
|
-
id: z.number().
|
|
666
|
+
server.tool("list_actions", "Get an action by ID with optional status filter. Hetzner no longer supports listing all actions in a project, so id is required. Prefer get_action", {
|
|
667
|
+
id: z.number().describe("Action ID (required by the API since 2025-01-30)"),
|
|
681
668
|
status: z.enum(["running", "success", "error"]).optional(),
|
|
682
669
|
sort: z
|
|
683
670
|
.enum([
|
|
@@ -708,8 +695,8 @@ export function registerTools(server) {
|
|
|
708
695
|
}));
|
|
709
696
|
// --- Placement Groups ---
|
|
710
697
|
server.tool("list_placement_groups", "List all placement groups", {}, async (_args, _extra) => withToolError(async () => {
|
|
711
|
-
const
|
|
712
|
-
return { content: [{ type: "text", text: JSON.stringify(
|
|
698
|
+
const items = await listAll((p) => PlacementGroupsService.getPlacementGroups(p), "placement_groups");
|
|
699
|
+
return { content: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
|
|
713
700
|
}));
|
|
714
701
|
server.tool("create_placement_group", "Create a new placement group", {
|
|
715
702
|
name: z.string(),
|
|
@@ -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) }] });
|