@hoststack.dev/mcp 0.16.1 → 0.18.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/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import { HostStack } from "@hoststack.dev/sdk";
4
4
 
5
5
  // src/version.ts
6
- var MCP_VERSION = true ? "0.16.1" : "0.0.0-dev";
6
+ var MCP_VERSION = true ? "0.18.0" : "0.0.0-dev";
7
7
  var USER_AGENT = `hoststack-mcp/${MCP_VERSION}`;
8
8
 
9
9
  // src/api-client.ts
@@ -229,7 +229,7 @@ definePrompt({
229
229
  const text = `Goal: diagnose the most recent failed deploy on service ${service_id} and propose a fix.
230
230
 
231
231
  Plan (use these tools in order):
232
- 1. \`list_deploys({ service_id: "${service_id}" })\` \u2014 pull recent deploys, newest first. Identify the most recent deploy with status \`failed\` (or \`cancelled\` if the user wants to investigate that too). Capture its publicId, branch, and commitSha.
232
+ 1. \`list_deploys({ service_id: "${service_id}" })\` \u2014 pull recent deploys, newest first. Identify the most recent deploy with status \`failed\` (or \`cancelled\` if the user wants to investigate that too). Capture its publicId, branch, and commitHash.
233
233
  2. \`get_deploy_logs({ service_id: "${service_id}", deploy_id: "<dpl_\u2026>" })\` \u2014 read the full build output. Scan for: stack traces, "ERROR" / "error:" lines, exit codes, missing env vars, OOM-killed signals, network failures pulling dependencies.
234
234
  3. \`get_service({ service_id: "${service_id}" })\` \u2014 confirm the service's runtime, plan, and whether autoDeploy is on. Plan tier matters because OOMs at small tiers point at \`maxMemoryMb\`.
235
235
  4. (Optional) \`list_env_vars({ service_id: "${service_id}" })\` \u2014 only if the build error mentions a missing variable. Don't fetch otherwise; values are masked anyway.
@@ -511,9 +511,9 @@ defineTool({
511
511
  name: "list_alerts",
512
512
  category: "alerts",
513
513
  description: [
514
- "List recent alert-shaped events for the team: deploy failures, git auth losses, service health failures, auto-restarts, ACME cert failures, resource alerts (high CPU), database backup/restore failures, registrant verification lapses.",
514
+ "List recent alert-shaped events for the team: deploy failures, git auth losses, service health failures, uptime failures (a service stopped answering its public URL), new and regressed error issues (an exception the app reported), auto-restarts, ACME cert failures, resource alerts (high CPU), database backup/restore failures, registrant verification lapses.",
515
515
  "",
516
- "When to use: triage 'what's currently broken or recently broke for this team'. Pairs with list_activity_log for the full audit feed; this tool is the alert-shaped subset.",
516
+ "When to use: triage 'what's currently broken or recently broke for this team'. Pairs with list_activity_log for the full audit feed; this tool is the alert-shaped subset. For an `error.issue_new` / `error.issue_regressed` entry, `list_error_issues` and `get_error_issue` carry the stack behind it.",
517
517
  "",
518
518
  'By default events are AGGREGATED by (action, resourceId) so flapping events collapse to one row with a fire count + first/last timestamps \u2014 e.g. "service.auto_restarted on service 31, 8 times in the last hour, last at 14:22". Pass aggregate=false to see every raw row.',
519
519
  "",
@@ -621,7 +621,105 @@ defineTool({
621
621
  });
622
622
 
623
623
  // src/tools/databases.ts
624
+ import { z as z6 } from "zod";
625
+
626
+ // src/tools/machines.ts
624
627
  import { z as z5 } from "zod";
628
+ var machineInput = z5.union([z5.number().int().positive(), z5.string()]).optional().describe(
629
+ `Run this on one of the team's OWN enrolled machines instead of HostStack compute \u2014 the machine's name (e.g. "desktop") or its numeric id. List them with list_machines. Omit for HostStack compute, which is the default and the right answer unless the user asked for their own hardware.`
630
+ );
631
+ async function resolveMachineId(ctx, teamId, machine) {
632
+ const { machines } = await ctx.hoststack.machines.list(teamId);
633
+ if (machines.length === 0) {
634
+ throw new Error(
635
+ "This team has no enrolled machines. Enrol one from the dashboard (Machines \u2192 Add machine) or with `hoststack machines add`, then run the install command it prints on that machine."
636
+ );
637
+ }
638
+ const known = machines.map((m) => `"${m.name}" (id ${m.id})`).join(", ");
639
+ if (typeof machine === "number") {
640
+ const byId = machines.find((m) => m.id === machine);
641
+ if (!byId) throw new Error(`No machine with id ${machine}. This team has: ${known}.`);
642
+ return byId.id;
643
+ }
644
+ const needle = machine.trim().toLowerCase();
645
+ const matches = machines.filter(
646
+ (m) => m.name.toLowerCase() === needle || m.hostname.toLowerCase() === needle
647
+ );
648
+ if (matches.length === 0) {
649
+ throw new Error(`No machine named "${machine}". This team has: ${known}.`);
650
+ }
651
+ if (matches.length > 1) {
652
+ throw new Error(
653
+ `More than one machine is named "${machine}" (ids ${matches.map((m) => m.id).join(", ")}). Pass the numeric id.`
654
+ );
655
+ }
656
+ return matches[0].id;
657
+ }
658
+ function describeMachine(m) {
659
+ if (!m.enrolled) return `${m.name}: registered but never paired`;
660
+ if (m.status !== "active") return `${m.name}: offline`;
661
+ if (m.agentBuild === "from-source") return `${m.name}: online, agent running from source`;
662
+ if (m.agentBuild === "unknown") return `${m.name}: online, agent too old to report its build`;
663
+ return `${m.name}: online`;
664
+ }
665
+ defineTool({
666
+ name: "list_machines",
667
+ category: "machines",
668
+ description: [
669
+ "List the team's OWN enrolled machines \u2014 hardware they supply (a spare desktop, a home server, a VPS they already pay for) that HostStack runs work on. These are NOT HostStack's servers; you cannot enrol, resize or reboot them from here.",
670
+ "",
671
+ "When to use: before creating a service, database or dev box that the user wants on their own hardware (pass the machine name to create_service / create_database / create_standalone_dev_environment), or to explain why something pinned to a machine is down \u2014 a machine that is switched off takes everything on it with it.",
672
+ "",
673
+ "Inputs: none.",
674
+ "",
675
+ "Returns: { items: Machine[] } \u2014 each entry has id (pass this as `machine`), name, status (active|offline|provisioning), enrolled, agentBuild (current|behind|from-source|unknown), agentVersion, lastHeartbeatAt, totalMemoryMb, totalCpuCores, and workloads { devBoxes, services, databases }.",
676
+ "",
677
+ "Notes: a machine is only reachable while its owner has it switched on, and a database pinned to one is reachable ONLY from that same machine \u2014 put the app that queries it there too. Enrolment needs a person at the machine to run an installer, so there is no tool for it: point the user at the dashboard (Machines \u2192 Add machine) or `hoststack machines add`.",
678
+ "",
679
+ 'Example: list_machines() \u2192 { items: [{ id: 12452, name: "desktop", status: "active", workloads: { devBoxes: 8, services: 0, databases: 2 } }] }'
680
+ ].join("\n"),
681
+ input: {},
682
+ handler: async (_args, ctx) => {
683
+ const teamId = await ctx.resolveTeamId();
684
+ const response = await ctx.hoststack.machines.list(teamId);
685
+ const data = shapeList(response, "machines", shape);
686
+ const summary = response.machines.length === 0 ? "This team has no enrolled machines. Everything runs on HostStack compute." : `${response.machines.length} machine${response.machines.length === 1 ? "" : "s"} \u2014 ${response.machines.map(describeMachine).join("; ")}.`;
687
+ return respond({ summary, data });
688
+ }
689
+ });
690
+ defineTool({
691
+ name: "get_machine",
692
+ category: "machines",
693
+ description: [
694
+ "One of the team's own enrolled machines, with what is actually running on it \u2014 rather than the counts list_machines carries.",
695
+ "",
696
+ 'When to use: before advising the user to switch a machine off, move work off it, or remove it \u2014 `running` is the list of things that go away with the machine. Also the fastest answer to "what is on my desktop?".',
697
+ "",
698
+ "Inputs:",
699
+ ' - machine: the machine name (e.g. "desktop") or its numeric id.',
700
+ "",
701
+ 'Returns: { machine: Machine, running: Workload[] } \u2014 each workload has kind ("dev_box" | "service" | "database"), name, status and projectId. The kinds differ in consequence: a dev box waits for its machine to come back, a service is down while it is off, and a database takes down everything reading from it.',
702
+ "",
703
+ 'Example: get_machine({ machine: "desktop" }) \u2192 { machine: { name: "desktop", status: "active" }, running: [{ kind: "database", name: "postgres-58" }] }'
704
+ ].join("\n"),
705
+ input: {
706
+ machine: z5.union([z5.number().int().positive(), z5.string()]).describe('Machine name (e.g. "desktop") or numeric id. List them with list_machines.')
707
+ },
708
+ handler: async (args, ctx) => {
709
+ const teamId = await ctx.resolveTeamId();
710
+ const machineId = await resolveMachineId(ctx, teamId, args.machine);
711
+ const response = await ctx.hoststack.machines.get(teamId, machineId);
712
+ const data = {
713
+ machine: shape(response.machine),
714
+ running: shapeList({ running: response.running }, "running", shape).items
715
+ };
716
+ const running = response.running ?? [];
717
+ const summary = running.length === 0 ? `${describeMachine(response.machine)}. Nothing is running on it.` : `${describeMachine(response.machine)}. Running ${running.length} thing${running.length === 1 ? "" : "s"}: ${running.map((w) => `${w.name} (${w.kind})`).join(", ")}.`;
718
+ return respond({ summary, data });
719
+ }
720
+ });
721
+
722
+ // src/tools/databases.ts
625
723
  var DATABASE_VERSIONS = {
626
724
  postgres: { default: "18", supported: ["18", "17", "16", "15"] },
627
725
  redis: { default: "8", supported: ["8", "7", "6"] },
@@ -658,6 +756,7 @@ defineTool({
658
756
  " - environment_id (optional): bind to a specific environment; defaults to the project Production env.",
659
757
  " - postgis (optional): provision the PostGIS image variant so `CREATE EXTENSION postgis` works. Postgres only.",
660
758
  " - pgvector (optional): provision the pgvector image variant so `CREATE EXTENSION vector` works. Postgres only, mutually exclusive with postgis.",
759
+ " - machine (optional): put it on one of the team's OWN enrolled machines (name or id, see list_machines) instead of HostStack compute. It costs nothing there and is still backed up off-site, but it is reachable ONLY from that same machine \u2014 the service that queries it has to run there too, and linking it to a service anywhere else is refused. No HA and no external access on a machine you own.",
661
760
  "",
662
761
  'Returns: { database: Database } \u2014 note BOTH `id` (numeric \u2014 this is what link_resource_to_service wants) and `publicId` ("db_\u2026" \u2014 what the other database tools want).',
663
762
  "",
@@ -666,16 +765,17 @@ defineTool({
666
765
  'Example: create_database({ project_id: "prj_abc", name: "app-db", engine: "postgres" }) \u2192 { database: { id: 42, publicId: "db_\u2026", status: "creating" } }'
667
766
  ].join("\n"),
668
767
  input: {
669
- project_id: z5.union([z5.number().int().positive(), z5.string()]).describe('Target project \u2014 numeric id or publicId ("prj_\u2026").'),
670
- name: z5.string().min(1).max(100).describe("Database name (1\u2013100 chars)."),
671
- engine: z5.enum(DB_ENGINES).describe("Database engine."),
672
- version: z5.string().max(20).optional().describe(`Engine version. ${VERSION_HELP}. Omit for the engine default.`),
673
- plan: z5.enum(["micro", "starter", "standard", "pro"]).optional().describe('Plan tier (memory/CPU). Default "starter".'),
674
- environment_id: z5.union([z5.number().int().positive(), z5.string()]).optional().describe("Environment to bind to. Defaults to the project Production env."),
675
- postgis: z5.boolean().optional().describe("Postgres only \u2014 enable the PostGIS extension image."),
676
- pgvector: z5.boolean().optional().describe(
768
+ project_id: z6.union([z6.number().int().positive(), z6.string()]).describe('Target project \u2014 numeric id or publicId ("prj_\u2026").'),
769
+ name: z6.string().min(1).max(100).describe("Database name (1\u2013100 chars)."),
770
+ engine: z6.enum(DB_ENGINES).describe("Database engine."),
771
+ version: z6.string().max(20).optional().describe(`Engine version. ${VERSION_HELP}. Omit for the engine default.`),
772
+ plan: z6.enum(["micro", "starter", "standard", "pro"]).optional().describe('Plan tier (memory/CPU). Default "starter".'),
773
+ environment_id: z6.union([z6.number().int().positive(), z6.string()]).optional().describe("Environment to bind to. Defaults to the project Production env."),
774
+ postgis: z6.boolean().optional().describe("Postgres only \u2014 enable the PostGIS extension image."),
775
+ pgvector: z6.boolean().optional().describe(
677
776
  "Postgres only \u2014 enable the pgvector extension image. Exclusive with postgis."
678
- )
777
+ ),
778
+ machine: machineInput
679
779
  },
680
780
  handler: async (args, ctx) => {
681
781
  const teamId = await ctx.resolveTeamId();
@@ -698,6 +798,9 @@ defineTool({
698
798
  }
699
799
  if (args.postgis !== void 0) input.postgis = args.postgis;
700
800
  if (args.pgvector !== void 0) input.pgvector = args.pgvector;
801
+ if (args.machine !== void 0) {
802
+ input.machineId = await resolveMachineId(ctx, teamId, args.machine);
803
+ }
701
804
  const response = await ctx.hoststack.databases.create(teamId, input);
702
805
  const data = { database: shapeDatabase(response.database) };
703
806
  const db = response.database;
@@ -725,7 +828,7 @@ defineTool({
725
828
  'Example: delete_database({ database_id: "db_abc" }) \u2192 { ok: true }'
726
829
  ].join("\n"),
727
830
  input: {
728
- database_id: z5.string().describe("Database publicId (e.g. db_abc) to permanently delete.")
831
+ database_id: z6.string().describe("Database publicId (e.g. db_abc) to permanently delete.")
729
832
  },
730
833
  handler: async (args, ctx) => {
731
834
  const teamId = await ctx.resolveTeamId();
@@ -751,7 +854,7 @@ defineTool({
751
854
  'Example: suspend_database({ database_id: "db_abc" }) \u2192 { ok: true }'
752
855
  ].join("\n"),
753
856
  input: {
754
- database_id: z5.string().describe("Database publicId (e.g. db_abc) to suspend.")
857
+ database_id: z6.string().describe("Database publicId (e.g. db_abc) to suspend.")
755
858
  },
756
859
  handler: async (args, ctx) => {
757
860
  const teamId = await ctx.resolveTeamId();
@@ -777,7 +880,7 @@ defineTool({
777
880
  'Example: resume_database({ database_id: "db_abc" }) \u2192 { ok: true }'
778
881
  ].join("\n"),
779
882
  input: {
780
- database_id: z5.string().describe("Database publicId (e.g. db_abc) to resume.")
883
+ database_id: z6.string().describe("Database publicId (e.g. db_abc) to resume.")
781
884
  },
782
885
  handler: async (args, ctx) => {
783
886
  const teamId = await ctx.resolveTeamId();
@@ -803,7 +906,7 @@ defineTool({
803
906
  'Example: list_databases({ project_id: 12 }) \u2192 { items: [{ publicId: "db_\u2026", type: "postgres", status: "running", \u2026 }] }'
804
907
  ].join("\n"),
805
908
  input: {
806
- project_id: z5.number().int().positive().describe("Numeric project ID (from list_projects).")
909
+ project_id: z6.number().int().positive().describe("Numeric project ID (from list_projects).")
807
910
  },
808
911
  handler: async (args, ctx) => {
809
912
  const teamId = await ctx.resolveTeamId();
@@ -832,10 +935,10 @@ defineTool({
832
935
  'Example: update_database({ database_id: "db_xyz", disk_size_gb: 50 }) \u2192 { database: { diskSizeGb: 50, \u2026 } }'
833
936
  ].join("\n"),
834
937
  input: {
835
- database_id: z5.string().describe("Database publicId (e.g. db_xyz)."),
836
- name: z5.string().min(1).max(100).optional().describe("New database name."),
837
- plan: z5.enum(["free", "micro", "starter", "standard", "pro"]).optional().describe("Plan tier (memory/CPU)."),
838
- disk_size_gb: z5.number().int().min(1).max(1024).optional().describe("New disk size in GB. Must be \u2265 current.")
938
+ database_id: z6.string().describe("Database publicId (e.g. db_xyz)."),
939
+ name: z6.string().min(1).max(100).optional().describe("New database name."),
940
+ plan: z6.enum(["free", "micro", "starter", "standard", "pro"]).optional().describe("Plan tier (memory/CPU)."),
941
+ disk_size_gb: z6.number().int().min(1).max(1024).optional().describe("New disk size in GB. Must be \u2265 current.")
839
942
  },
840
943
  handler: async (args, ctx) => {
841
944
  const teamId = await ctx.resolveTeamId();
@@ -868,7 +971,7 @@ defineTool({
868
971
  'Example: get_database({ database_id: "db_xyz" }) \u2192 { database: { type: "postgres", version: "16", status: "running", \u2026 } }'
869
972
  ].join("\n"),
870
973
  input: {
871
- database_id: z5.string().describe("Database publicId (e.g. db_xyz).")
974
+ database_id: z6.string().describe("Database publicId (e.g. db_xyz).")
872
975
  },
873
976
  handler: async (args, ctx) => {
874
977
  const teamId = await ctx.resolveTeamId();
@@ -906,8 +1009,8 @@ defineTool({
906
1009
  ` - query_database({ database_id: "db_abc", sql: "SELECT id, email FROM users WHERE created_at > now() - interval '1 day' LIMIT 50" })`
907
1010
  ].join("\n"),
908
1011
  input: {
909
- database_id: z5.string().describe("Database publicId (e.g. db_abc)."),
910
- sql: z5.string().min(1).max(16384).describe(
1012
+ database_id: z6.string().describe("Database publicId (e.g. db_abc)."),
1013
+ sql: z6.string().min(1).max(16384).describe(
911
1014
  "A single READ-ONLY SQL statement. No trailing `;`, no embedded `;`, no psql meta-commands."
912
1015
  )
913
1016
  },
@@ -936,7 +1039,7 @@ defineTool({
936
1039
  'Example: upgrade_database_to_ha({ database_id: "db_abc" }) \u2192 { ok: true }'
937
1040
  ].join("\n"),
938
1041
  input: {
939
- database_id: z5.string().describe("Database publicId (e.g. db_abc) to upgrade to HA.")
1042
+ database_id: z6.string().describe("Database publicId (e.g. db_abc) to upgrade to HA.")
940
1043
  },
941
1044
  handler: async (args, ctx) => {
942
1045
  const teamId = await ctx.resolveTeamId();
@@ -965,8 +1068,8 @@ defineTool({
965
1068
  'Example: upgrade_database_version({ database_id: "db_abc", version: "18" }) \u2192 { ok: true }'
966
1069
  ].join("\n"),
967
1070
  input: {
968
- database_id: z5.string().describe("Database publicId (e.g. db_abc) to upgrade."),
969
- version: z5.string().describe('Target engine version, e.g. "18" for postgres or "8" for redis.')
1071
+ database_id: z6.string().describe("Database publicId (e.g. db_abc) to upgrade."),
1072
+ version: z6.string().describe('Target engine version, e.g. "18" for postgres or "8" for redis.')
970
1073
  },
971
1074
  handler: async (args, ctx) => {
972
1075
  const teamId = await ctx.resolveTeamId();
@@ -994,7 +1097,7 @@ defineTool({
994
1097
  'Example: restart_database({ database_id: "db_abc" }) \u2192 { ok: true }'
995
1098
  ].join("\n"),
996
1099
  input: {
997
- database_id: z5.string().describe("Database publicId (e.g. db_abc) to restart.")
1100
+ database_id: z6.string().describe("Database publicId (e.g. db_abc) to restart.")
998
1101
  },
999
1102
  handler: async (args, ctx) => {
1000
1103
  const teamId = await ctx.resolveTeamId();
@@ -1020,7 +1123,7 @@ defineTool({
1020
1123
  'Example: get_database_cluster({ database_id: "db_abc" }) \u2192 { members: [...5 live rows], failovers: [] }'
1021
1124
  ].join("\n"),
1022
1125
  input: {
1023
- database_id: z5.string().describe("Database publicId for the HA cluster.")
1126
+ database_id: z6.string().describe("Database publicId for the HA cluster.")
1024
1127
  },
1025
1128
  handler: async (args, ctx) => {
1026
1129
  const teamId = await ctx.resolveTeamId();
@@ -1032,7 +1135,7 @@ defineTool({
1032
1135
  });
1033
1136
 
1034
1137
  // src/tools/deploys.ts
1035
- import { z as z6 } from "zod";
1138
+ import { z as z7 } from "zod";
1036
1139
  defineTool({
1037
1140
  name: "list_deploys",
1038
1141
  category: "deploys",
@@ -1044,12 +1147,12 @@ defineTool({
1044
1147
  "Inputs:",
1045
1148
  ' - service_id: publicId of the service (e.g. "svc_abc123"). Use list_services to find it.',
1046
1149
  "",
1047
- 'Returns: { items: Deploy[] } \u2014 each deploy includes id, publicId, status (pending|building|deploying|live|failed|cancelled), commitSha, commitMessage, branch, triggeredBy, startedAt, finishedAt, imageBuildMs (docker build / image-pull only; null on skip-build redeploys \u2014 v89), containerBootMs (deploying \u2192 live wall-clock; null on builds that failed before container start \u2014 v89), buildDurationMs (legacy alias of imageBuildMs kept for back-compat), totalDurationMs (full deploy wall-clock = finishedAt \u2212 startedAt). Use imageBuildMs + containerBootMs together to tell "build is slow" apart from "boot is slow".',
1150
+ 'Returns: { items: Deploy[] } \u2014 each deploy includes id, publicId, status (pending|building|deploying|live|failed|cancelled), commitHash (the resolved commit SHA; the key is OMITTED entirely when the deploy recorded none, so a missing key means "no commit", not "wrong key"), commitMessage, branch, triggeredBy, startedAt, finishedAt, imageBuildMs (docker build / image-pull only; null on skip-build redeploys \u2014 v89), containerBootMs (deploying \u2192 live wall-clock; null on builds that failed before container start \u2014 v89), buildDurationMs (legacy alias of imageBuildMs kept for back-compat), totalDurationMs (full deploy wall-clock = finishedAt \u2212 startedAt). Use imageBuildMs + containerBootMs together to tell "build is slow" apart from "boot is slow".',
1048
1151
  "",
1049
1152
  'Example: list_deploys({ service_id: "svc_abc" }) \u2192 { items: [{ publicId: "dpl_\u2026", status: "live", commitMessage: "Fix login", \u2026 }, \u2026] }'
1050
1153
  ].join("\n"),
1051
1154
  input: {
1052
- service_id: z6.string().describe("Service publicId (e.g. svc_abc123).")
1155
+ service_id: z7.string().describe("Service publicId (e.g. svc_abc123).")
1053
1156
  },
1054
1157
  handler: async (args, ctx) => {
1055
1158
  const teamId = await ctx.resolveTeamId();
@@ -1071,13 +1174,13 @@ defineTool({
1071
1174
  " - service_id: publicId of the service.",
1072
1175
  ' - deploy_id: publicId of the deploy (e.g. "dpl_\u2026").',
1073
1176
  "",
1074
- "Returns: { deploy: Deploy } \u2014 full deploy record (status, commitSha, commitMessage, branch, imageBuildMs + containerBootMs (v89 split timings; legacy buildDurationMs preserved as alias), totalDurationMs, finishedAt, etc).",
1177
+ "Returns: { deploy: Deploy } \u2014 full deploy record (status, commitHash (omitted when the deploy recorded no commit), commitMessage, branch, imageBuildMs + containerBootMs (v89 split timings; legacy buildDurationMs preserved as alias), totalDurationMs, finishedAt, etc).",
1075
1178
  "",
1076
1179
  'Example: get_deploy({ service_id: "svc_abc", deploy_id: "dpl_xyz" }) \u2192 { deploy: { status: "live", \u2026 } }'
1077
1180
  ].join("\n"),
1078
1181
  input: {
1079
- service_id: z6.string().describe("Service publicId."),
1080
- deploy_id: z6.string().describe("Deploy publicId.")
1182
+ service_id: z7.string().describe("Service publicId."),
1183
+ deploy_id: z7.string().describe("Deploy publicId.")
1081
1184
  },
1082
1185
  handler: async (args, ctx) => {
1083
1186
  const teamId = await ctx.resolveTeamId();
@@ -1105,9 +1208,9 @@ defineTool({
1105
1208
  'Example: trigger_deploy({ service_id: "svc_abc" }) \u2192 { deploy: { publicId: "dpl_\u2026", status: "pending", \u2026 } }'
1106
1209
  ].join("\n"),
1107
1210
  input: {
1108
- service_id: z6.string().describe("Service publicId."),
1109
- commit_hash: z6.string().max(40).optional().describe("Specific commit to build (default: branch HEAD)."),
1110
- branch: z6.string().max(200).optional().describe("Branch to build (default: service configured branch).")
1211
+ service_id: z7.string().describe("Service publicId."),
1212
+ commit_hash: z7.string().max(40).optional().describe("Specific commit to build (default: branch HEAD)."),
1213
+ branch: z7.string().max(200).optional().describe("Branch to build (default: service configured branch).")
1111
1214
  },
1112
1215
  handler: async (args, ctx) => {
1113
1216
  const teamId = await ctx.resolveTeamId();
@@ -1140,8 +1243,8 @@ defineTool({
1140
1243
  'Example: cancel_deploy({ service_id: "svc_abc", deploy_id: "dpl_xyz" }) \u2192 { ok: true }'
1141
1244
  ].join("\n"),
1142
1245
  input: {
1143
- service_id: z6.string().describe("Service publicId."),
1144
- deploy_id: z6.string().describe("Deploy publicId.")
1246
+ service_id: z7.string().describe("Service publicId."),
1247
+ deploy_id: z7.string().describe("Deploy publicId.")
1145
1248
  },
1146
1249
  handler: async (args, ctx) => {
1147
1250
  const teamId = await ctx.resolveTeamId();
@@ -1169,10 +1272,10 @@ defineTool({
1169
1272
  'Example: get_deploy_logs({ service_id: "svc_abc", deploy_id: "dpl_xyz" }) \u2192 { logs: "Building\u2026\\nStep 1/8\u2026\\n\u2026", lineCount: 42, nextAfterId: 1234 }'
1170
1273
  ].join("\n"),
1171
1274
  input: {
1172
- service_id: z6.string().describe("Service publicId."),
1173
- deploy_id: z6.string().describe("Deploy publicId."),
1174
- after_id: z6.number().int().optional().describe("Pagination cursor from a previous response\u2019s nextAfterId."),
1175
- limit: z6.number().int().min(1).max(5e3).optional().describe("Max log entries to fetch (default 500, hard cap 5000).")
1275
+ service_id: z7.string().describe("Service publicId."),
1276
+ deploy_id: z7.string().describe("Deploy publicId."),
1277
+ after_id: z7.number().int().optional().describe("Pagination cursor from a previous response\u2019s nextAfterId."),
1278
+ limit: z7.number().int().min(1).max(5e3).optional().describe("Max log entries to fetch (default 500, hard cap 5000).")
1176
1279
  },
1177
1280
  handler: async (args, ctx) => {
1178
1281
  const teamId = await ctx.resolveTeamId();
@@ -1212,10 +1315,10 @@ defineTool({
1212
1315
  'Example: diagnose_deploy({ service_id: "svc_abc", deploy_id: "dpl_xyz" }) \u2192 all three sections in one call.'
1213
1316
  ].join("\n"),
1214
1317
  input: {
1215
- service_id: z6.string().describe("Service publicId."),
1216
- deploy_id: z6.string().describe("Deploy publicId."),
1217
- build_log_lines: z6.number().int().min(1).max(2e3).optional().describe("Trailing build log lines. Default 200, max 2000."),
1218
- runtime_log_lines: z6.number().int().min(0).max(1e3).optional().describe(
1318
+ service_id: z7.string().describe("Service publicId."),
1319
+ deploy_id: z7.string().describe("Deploy publicId."),
1320
+ build_log_lines: z7.number().int().min(1).max(2e3).optional().describe("Trailing build log lines. Default 200, max 2000."),
1321
+ runtime_log_lines: z7.number().int().min(0).max(1e3).optional().describe(
1219
1322
  "Trailing runtime log lines since deploy start. Default 100, max 1000. 0 = skip."
1220
1323
  )
1221
1324
  },
@@ -1276,7 +1379,7 @@ defineTool({
1276
1379
  });
1277
1380
 
1278
1381
  // src/tools/dns-records.ts
1279
- import { z as z7 } from "zod";
1382
+ import { z as z8 } from "zod";
1280
1383
  var DNS_RECORD_TYPES = [
1281
1384
  "A",
1282
1385
  "AAAA",
@@ -1291,7 +1394,7 @@ var DNS_RECORD_TYPES = [
1291
1394
  async function resolveZonePublicId(hoststack, teamId, input) {
1292
1395
  if (input.zone_id) {
1293
1396
  const { zones: zones2 } = await hoststack.dns.listZones(teamId);
1294
- const match = zones2.find((z16) => z16.publicId === input.zone_id);
1397
+ const match = zones2.find((z20) => z20.publicId === input.zone_id);
1295
1398
  if (!match) {
1296
1399
  throw new Error(`Zone ${input.zone_id} not found on this team.`);
1297
1400
  }
@@ -1305,7 +1408,7 @@ async function resolveZonePublicId(hoststack, teamId, input) {
1305
1408
  const labels = fqdn.split(".");
1306
1409
  for (let i = 0; i < labels.length - 1; i++) {
1307
1410
  const candidate = labels.slice(i).join(".");
1308
- const match = zones.find((z16) => z16.domainName.toLowerCase() === candidate);
1411
+ const match = zones.find((z20) => z20.domainName.toLowerCase() === candidate);
1309
1412
  if (match && match.status !== "deleting") {
1310
1413
  return { publicId: match.publicId, domainName: match.domainName };
1311
1414
  }
@@ -1350,8 +1453,8 @@ defineTool({
1350
1453
  'Example: list_dns_records({ domain: "micci.dk" }) \u2192 { zone: { domainName: "micci.dk", \u2026 }, items: [{ type: "TXT", name: "@", value: "google-site-verification=\u2026", ttl: 300, \u2026 }] }'
1351
1454
  ].join("\n"),
1352
1455
  input: {
1353
- zone_id: z7.string().optional().describe('Zone publicId (e.g. "dnz_abc").'),
1354
- domain: z7.string().optional().describe("Apex or subdomain \u2014 resolves to the longest-matching hosted zone.")
1456
+ zone_id: z8.string().optional().describe('Zone publicId (e.g. "dnz_abc").'),
1457
+ domain: z8.string().optional().describe("Apex or subdomain \u2014 resolves to the longest-matching hosted zone.")
1355
1458
  },
1356
1459
  handler: async (args, ctx) => {
1357
1460
  const teamId = await ctx.resolveTeamId();
@@ -1384,7 +1487,7 @@ defineTool({
1384
1487
  'Example: get_dns_record({ record_id: "dnr_abc" }) \u2192 { record: { type: "TXT", name: "@", value: "\u2026", status: "active", \u2026 } }'
1385
1488
  ].join("\n"),
1386
1489
  input: {
1387
- record_id: z7.string().describe("Record publicId.")
1490
+ record_id: z8.string().describe("Record publicId.")
1388
1491
  },
1389
1492
  handler: async (args, ctx) => {
1390
1493
  const teamId = await ctx.resolveTeamId();
@@ -1430,13 +1533,13 @@ defineTool({
1430
1533
  'Example: create_dns_record({ domain: "micci.dk", type: "TXT", name: "@", content: "google-site-verification=C0V0scK48g2\u2026", ttl: 300 })'
1431
1534
  ].join("\n"),
1432
1535
  input: {
1433
- zone_id: z7.string().optional().describe("Zone publicId."),
1434
- domain: z7.string().optional().describe("Apex or subdomain to resolve a hosted zone."),
1435
- type: z7.enum(DNS_RECORD_TYPES).describe("DNS record type."),
1436
- name: z7.string().min(1).max(253).describe('"@" for apex, or a bare label. Do NOT include the zone suffix.'),
1437
- content: z7.string().min(1).max(2e3).describe("Record value; TXT values are unquoted."),
1438
- ttl: z7.number().int().min(60).max(86400).optional().describe("TTL in seconds (default 3600)."),
1439
- priority: z7.number().int().min(0).max(65535).optional().describe("Required for MX / SRV.")
1536
+ zone_id: z8.string().optional().describe("Zone publicId."),
1537
+ domain: z8.string().optional().describe("Apex or subdomain to resolve a hosted zone."),
1538
+ type: z8.enum(DNS_RECORD_TYPES).describe("DNS record type."),
1539
+ name: z8.string().min(1).max(253).describe('"@" for apex, or a bare label. Do NOT include the zone suffix.'),
1540
+ content: z8.string().min(1).max(2e3).describe("Record value; TXT values are unquoted."),
1541
+ ttl: z8.number().int().min(60).max(86400).optional().describe("TTL in seconds (default 3600)."),
1542
+ priority: z8.number().int().min(0).max(65535).optional().describe("Required for MX / SRV.")
1440
1543
  },
1441
1544
  handler: async (args, ctx) => {
1442
1545
  if ((args.type === "MX" || args.type === "SRV") && args.priority === void 0) {
@@ -1482,12 +1585,12 @@ defineTool({
1482
1585
  'Example: update_dns_record({ record_id: "dnr_abc", type: "A", name: "api", content: "203.0.113.42", ttl: 300 })'
1483
1586
  ].join("\n"),
1484
1587
  input: {
1485
- record_id: z7.string().describe("Record publicId."),
1486
- type: z7.enum(DNS_RECORD_TYPES).describe("DNS record type."),
1487
- name: z7.string().min(1).max(253).describe('"@" for apex, or a bare label. Do NOT include the zone suffix.'),
1488
- content: z7.string().min(1).max(2e3).describe("Record value; TXT unquoted."),
1489
- ttl: z7.number().int().min(60).max(86400).optional().describe("TTL in seconds (default 3600)."),
1490
- priority: z7.number().int().min(0).max(65535).optional().describe("Required for MX / SRV.")
1588
+ record_id: z8.string().describe("Record publicId."),
1589
+ type: z8.enum(DNS_RECORD_TYPES).describe("DNS record type."),
1590
+ name: z8.string().min(1).max(253).describe('"@" for apex, or a bare label. Do NOT include the zone suffix.'),
1591
+ content: z8.string().min(1).max(2e3).describe("Record value; TXT unquoted."),
1592
+ ttl: z8.number().int().min(60).max(86400).optional().describe("TTL in seconds (default 3600)."),
1593
+ priority: z8.number().int().min(0).max(65535).optional().describe("Required for MX / SRV.")
1491
1594
  },
1492
1595
  handler: async (args, ctx) => {
1493
1596
  if ((args.type === "MX" || args.type === "SRV") && args.priority === void 0) {
@@ -1541,7 +1644,7 @@ defineTool({
1541
1644
  'Example: delete_dns_record({ record_id: "dnr_abc" }) \u2192 { ok: true }'
1542
1645
  ].join("\n"),
1543
1646
  input: {
1544
- record_id: z7.string().describe("Record publicId.")
1647
+ record_id: z8.string().describe("Record publicId.")
1545
1648
  },
1546
1649
  handler: async (args, ctx) => {
1547
1650
  const teamId = await ctx.resolveTeamId();
@@ -1574,7 +1677,7 @@ defineTool({
1574
1677
  'Example: resync_dns_record({ record_id: "dnr_abc" }) \u2192 { record: { status: "active", ... } }'
1575
1678
  ].join("\n"),
1576
1679
  input: {
1577
- record_id: z7.string().describe("Record publicId.")
1680
+ record_id: z8.string().describe("Record publicId.")
1578
1681
  },
1579
1682
  handler: async (args, ctx) => {
1580
1683
  const teamId = await ctx.resolveTeamId();
@@ -1612,7 +1715,7 @@ async function findRecordZone(hoststack, teamId, recordPublicId) {
1612
1715
  }
1613
1716
 
1614
1717
  // src/tools/domains.ts
1615
- import { z as z8 } from "zod";
1718
+ import { z as z9 } from "zod";
1616
1719
  defineTool({
1617
1720
  name: "list_domains",
1618
1721
  category: "domains",
@@ -1652,9 +1755,9 @@ defineTool({
1652
1755
  'Example: add_domain({ hostname: "api.example.com", service_id: "svc_abc" }) \u2192 { domain: { hostname: "api.example.com", dnsTargets: [...], verified: false, \u2026 } }'
1653
1756
  ].join("\n"),
1654
1757
  input: {
1655
- hostname: z8.string().min(3).max(253).describe("Fully-qualified hostname (e.g. api.example.com)."),
1656
- service_id: z8.string().describe("Service publicId to bind to."),
1657
- path_prefix: z8.string().optional().describe('Optional URL prefix for path-based routing (e.g. "/api").')
1758
+ hostname: z9.string().min(3).max(253).describe("Fully-qualified hostname (e.g. api.example.com)."),
1759
+ service_id: z9.string().describe("Service publicId to bind to."),
1760
+ path_prefix: z9.string().optional().describe('Optional URL prefix for path-based routing (e.g. "/api").')
1658
1761
  },
1659
1762
  handler: async (args, ctx) => {
1660
1763
  const teamId = await ctx.resolveTeamId();
@@ -1688,7 +1791,7 @@ defineTool({
1688
1791
  'Example: verify_domain({ domain_id: "dom_xyz" }) \u2192 { ok: true }'
1689
1792
  ].join("\n"),
1690
1793
  input: {
1691
- domain_id: z8.string().describe("Domain publicId.")
1794
+ domain_id: z9.string().describe("Domain publicId.")
1692
1795
  },
1693
1796
  handler: async (args, ctx) => {
1694
1797
  const teamId = await ctx.resolveTeamId();
@@ -1715,7 +1818,7 @@ defineTool({
1715
1818
  'Example: remove_domain({ domain_id: "dom_xyz" }) \u2192 { ok: true }'
1716
1819
  ].join("\n"),
1717
1820
  input: {
1718
- domain_id: z8.string().describe("Domain publicId.")
1821
+ domain_id: z9.string().describe("Domain publicId.")
1719
1822
  },
1720
1823
  handler: async (args, ctx) => {
1721
1824
  const teamId = await ctx.resolveTeamId();
@@ -1725,7 +1828,7 @@ defineTool({
1725
1828
  });
1726
1829
 
1727
1830
  // src/tools/env-vars.ts
1728
- import { z as z9 } from "zod";
1831
+ import { z as z10 } from "zod";
1729
1832
  defineTool({
1730
1833
  name: "list_env_vars",
1731
1834
  category: "env-vars",
@@ -1742,7 +1845,7 @@ defineTool({
1742
1845
  'Example: list_env_vars({ service_id: "svc_abc" }) \u2192 { items: [{ key: "DATABASE_URL", value: "\u2022\u2022\u2022\u2022\u2022\u2022", isSecret: true }, { key: "PORT", value: "3000", isSecret: false }] }'
1743
1846
  ].join("\n"),
1744
1847
  input: {
1745
- service_id: z9.string().describe("Service publicId.")
1848
+ service_id: z10.string().describe("Service publicId.")
1746
1849
  },
1747
1850
  handler: async (args, ctx) => {
1748
1851
  const teamId = await ctx.resolveTeamId();
@@ -1772,11 +1875,11 @@ defineTool({
1772
1875
  'Example: set_env_var({ service_id: "svc_abc", key: "DATABASE_URL", value: "postgres://\u2026", is_secret: true }) \u2192 { envVar: { key: "DATABASE_URL", value: "\u2022\u2022\u2022\u2022\u2022\u2022", \u2026 }, action: "updated" }'
1773
1876
  ].join("\n"),
1774
1877
  input: {
1775
- service_id: z9.string().describe("Service publicId."),
1776
- key: z9.string().min(1).max(128).describe("Env-var key."),
1777
- value: z9.string().describe("New value."),
1778
- is_secret: z9.boolean().optional().describe("Mark as secret (encrypted, masked on read). Default true."),
1779
- target: z9.enum(["build", "runtime", "both"]).optional().describe("Injection target: build, runtime, or both. Default both.")
1878
+ service_id: z10.string().describe("Service publicId."),
1879
+ key: z10.string().min(1).max(128).describe("Env-var key."),
1880
+ value: z10.string().describe("New value."),
1881
+ is_secret: z10.boolean().optional().describe("Mark as secret (encrypted, masked on read). Default true."),
1882
+ target: z10.enum(["build", "runtime", "both"]).optional().describe("Injection target: build, runtime, or both. Default both.")
1780
1883
  },
1781
1884
  handler: async (args, ctx) => {
1782
1885
  const teamId = await ctx.resolveTeamId();
@@ -1828,8 +1931,8 @@ defineTool({
1828
1931
  'Example: delete_env_var({ service_id: "svc_abc", key: "OLD_FLAG" }) \u2192 { ok: true }'
1829
1932
  ].join("\n"),
1830
1933
  input: {
1831
- service_id: z9.string().describe("Service publicId."),
1832
- key: z9.string().min(1).max(128).describe("Env-var key to delete.")
1934
+ service_id: z10.string().describe("Service publicId."),
1935
+ key: z10.string().min(1).max(128).describe("Env-var key to delete.")
1833
1936
  },
1834
1937
  handler: async (args, ctx) => {
1835
1938
  const teamId = await ctx.resolveTeamId();
@@ -1865,13 +1968,13 @@ defineTool({
1865
1968
  'Example: bulk_set_env_vars({ service_id: "svc_abc", env_vars: [{ key: "PORT", value: "3000", is_secret: false }, { key: "DATABASE_URL", value: "\u2026", is_secret: true }] }) \u2192 { ok: true }'
1866
1969
  ].join("\n"),
1867
1970
  input: {
1868
- service_id: z9.string().describe("Service publicId."),
1869
- env_vars: z9.array(
1870
- z9.object({
1871
- key: z9.string().min(1).max(128),
1872
- value: z9.string(),
1873
- is_secret: z9.boolean().optional(),
1874
- target: z9.enum(["build", "runtime", "both"]).optional()
1971
+ service_id: z10.string().describe("Service publicId."),
1972
+ env_vars: z10.array(
1973
+ z10.object({
1974
+ key: z10.string().min(1).max(128),
1975
+ value: z10.string(),
1976
+ is_secret: z10.boolean().optional(),
1977
+ target: z10.enum(["build", "runtime", "both"]).optional()
1875
1978
  })
1876
1979
  ).max(500).describe("Array of env-var rows. Hard cap 500.")
1877
1980
  },
@@ -1897,7 +2000,7 @@ defineTool({
1897
2000
  });
1898
2001
 
1899
2002
  // src/tools/environments.ts
1900
- import { z as z10 } from "zod";
2003
+ import { z as z11 } from "zod";
1901
2004
  defineTool({
1902
2005
  name: "list_environments",
1903
2006
  category: "environments",
@@ -1918,7 +2021,7 @@ defineTool({
1918
2021
  'Example: list_environments({ project_id: "prj_abc" }) \u2192 { items: [{ name: "Production", type: "production", isDefault: true }, { name: "Staging", type: "staging" }] }'
1919
2022
  ].join("\n"),
1920
2023
  input: {
1921
- project_id: z10.string().describe("Project publicId.")
2024
+ project_id: z11.string().describe("Project publicId.")
1922
2025
  },
1923
2026
  handler: async (args, ctx) => {
1924
2027
  const teamId = await ctx.resolveTeamId();
@@ -1952,13 +2055,13 @@ defineTool({
1952
2055
  'Example: create_environment({ project_id: "prj_abc", name: "Staging", type: "staging" }) \u2192 { environment: { id: 7, publicId: "env_\u2026", name: "Staging", type: "staging" } }'
1953
2056
  ].join("\n"),
1954
2057
  input: {
1955
- project_id: z10.string().describe("Project publicId."),
1956
- name: z10.string().min(1).max(64).describe("Environment name (1\u201364 chars)."),
1957
- type: z10.enum(["production", "staging", "development", "preview"]).describe(
2058
+ project_id: z11.string().describe("Project publicId."),
2059
+ name: z11.string().min(1).max(64).describe("Environment name (1\u201364 chars)."),
2060
+ type: z11.enum(["production", "staging", "development", "preview"]).describe(
1958
2061
  // §2.1: "development" here is a project deployment env, NOT a cloud Dev Box.
1959
2062
  'Environment type \u2014 drives the hostname suffix. type="development" creates a PROJECT deployment environment (a -dev hostname suffix), NOT an agentic Dev Box \u2014 for a cloud dev box use create_dev_environment / create_standalone_dev_environment / spin_up_dev_environment.'
1960
2063
  ),
1961
- is_protected: z10.boolean().optional().describe("Require admin role for destructive actions. Default false.")
2064
+ is_protected: z11.boolean().optional().describe("Require admin role for destructive actions. Default false.")
1962
2065
  },
1963
2066
  handler: async (args, ctx) => {
1964
2067
  const teamId = await ctx.resolveTeamId();
@@ -1992,8 +2095,8 @@ defineTool({
1992
2095
  'Example: delete_environment({ project_id: "prj_abc", environment_id: "env_xyz" }) \u2192 { success: true }'
1993
2096
  ].join("\n"),
1994
2097
  input: {
1995
- project_id: z10.string().describe("Project publicId."),
1996
- environment_id: z10.union([z10.string(), z10.number()]).describe("Environment publicId or numeric id.")
2098
+ project_id: z11.string().describe("Project publicId."),
2099
+ environment_id: z11.union([z11.string(), z11.number()]).describe("Environment publicId or numeric id.")
1997
2100
  },
1998
2101
  handler: async (args, ctx) => {
1999
2102
  const teamId = await ctx.resolveTeamId();
@@ -2024,9 +2127,9 @@ defineTool({
2024
2127
  'Example: promote_deploy({ service_id: "svc_staging", deploy_id: "dpl_built", target_environment_id: "env_prod" }) \u2192 { deploy: { id: 99, status: "pending", trigger: "rollback", dockerImageId: "sha256:\u2026" } }'
2025
2128
  ].join("\n"),
2026
2129
  input: {
2027
- service_id: z10.string().describe("Source service publicId."),
2028
- deploy_id: z10.string().describe("Source deploy publicId (must have a built image)."),
2029
- target_environment_id: z10.union([z10.string(), z10.number()]).describe("Target environment publicId or numeric id.")
2130
+ service_id: z11.string().describe("Source service publicId."),
2131
+ deploy_id: z11.string().describe("Source deploy publicId (must have a built image)."),
2132
+ target_environment_id: z11.union([z11.string(), z11.number()]).describe("Target environment publicId or numeric id.")
2030
2133
  },
2031
2134
  handler: async (args, ctx) => {
2032
2135
  const teamId = await ctx.resolveTeamId();
@@ -2048,6 +2151,437 @@ defineTool({
2048
2151
  }
2049
2152
  });
2050
2153
 
2154
+ // src/tools/analytics.ts
2155
+ import { z as z12 } from "zod";
2156
+ async function resolveSiteIds(domains, teamId, api) {
2157
+ if (!domains || domains.length === 0) return void 0;
2158
+ const { sites } = await api.get(`/api/analytics/${teamId}/sites`);
2159
+ const ids = [];
2160
+ const missing = [];
2161
+ for (const domain of domains) {
2162
+ const needle = domain.toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, "");
2163
+ const match = sites.find((s) => s.domain === needle);
2164
+ if (match) ids.push(match.id);
2165
+ else missing.push(domain);
2166
+ }
2167
+ if (missing.length > 0) {
2168
+ throw new Error(
2169
+ `Not tracking ${missing.join(", ")}. Known sites: ${sites.map((s) => s.domain).join(", ") || "none yet"}.`
2170
+ );
2171
+ }
2172
+ return ids.join(",");
2173
+ }
2174
+ defineTool({
2175
+ name: "list_analytics_sites",
2176
+ category: "analytics",
2177
+ description: [
2178
+ "List the websites this team tracks \u2014 domains, their site keys, retention, and which service (if any) serves each one.",
2179
+ "",
2180
+ "When to use: before any other analytics call, to learn which domains exist; or to fetch the script tag a site needs.",
2181
+ "",
2182
+ "The site key is PUBLIC by design \u2014 it ships in a `data-site-key` attribute that anyone can view-source, like a Sentry DSN. It is write-only and scoped to one site. Do not treat it as a secret, and do not confuse it with the team API key.",
2183
+ "",
2184
+ "Returns: { sites: Array }. Each site has id, publicId, name, domain, ingestKey, allowedOrigins, serviceId, serviceName, retentionDays, droppedCount (events refused by the hourly quota and therefore MISSING from every count for that site), and keyGraceEndsAt when a rotation is still in its grace window.",
2185
+ "",
2186
+ 'Each site also carries lastEventAt (null means NOTHING has ever reached ingest for that key) plus lastRefusalReason and refusedRecently, a 7-day tally by reason. An empty chart with lastEventAt set is a site with no traffic; an empty chart with lastEventAt null is a broken setup. Do not report "no visitors" without checking which one you are looking at \u2014 call check_analytics_site for the diagnosis.',
2187
+ "",
2188
+ "Example: list_analytics_sites({}) \u2192 { sites: [{ id: 3, domain: 'micci.dk', ingestKey: 'site_\u2026', retentionDays: 30, serviceName: 'micci-web' }] }."
2189
+ ].join("\n"),
2190
+ input: {},
2191
+ handler: async (_args, ctx) => {
2192
+ const teamId = await ctx.resolveTeamId();
2193
+ const response = await ctx.api.get(`/api/analytics/${teamId}/sites`);
2194
+ const items = Array.isArray(response.sites) ? response.sites.map(shape) : [];
2195
+ const summary = items.length === 0 ? "No analytics sites yet. Create one with create_analytics_site." : `Tracking ${items.length} site${items.length === 1 ? "" : "s"}.`;
2196
+ return respond({ summary, data: { sites: items } });
2197
+ }
2198
+ });
2199
+ defineTool({
2200
+ name: "check_analytics_site",
2201
+ category: "analytics",
2202
+ description: [
2203
+ "Why a site is reporting nothing \u2014 the diagnosis, without having to generate traffic and guess.",
2204
+ "",
2205
+ "When to use: any time a chart is empty, a site was just set up, a key was rotated, or someone asks whether the snippet is installed correctly. Call this BEFORE telling anyone their traffic dropped.",
2206
+ "",
2207
+ "The ingest endpoint answers HTTP 204 to a real site key and to a typo alike \u2014 deliberately, so it cannot be used to enumerate keys \u2014 which means five completely different situations produce the same empty chart: a stale or mistyped key in the deployed snippet, an origin the site does not allow, a blown hourly quota, events blocked in the browser before they leave (CORS, ad blocker, CSP), and simply no visitors yet. This tool tells them apart.",
2208
+ "",
2209
+ "Returns health ('receiving' | 'quiet' | 'refusing' | 'never'), a headline and detail sentence, lastEventAt, lastRefusalAt/Reason/Origin, refusedRecently (a 7-day tally by reason), the site key the snippet must carry, allowed origins, and quota usage this hour.",
2210
+ "",
2211
+ "health='never' means nothing has EVER reached ingest for this key, so the request is not leaving the browser \u2014 check the snippet is in the deployed HTML and tell the user to add `data-debug` to the script tag, which makes the tracker log its resolved endpoint and every accepted 204 to the console.",
2212
+ "",
2213
+ "Example: check_analytics_site({ domain: 'example.com' }) \u2192 { health: 'refusing', headline: 'Reaching us, and being refused.', detail: 'Something on example.com posted 214 event(s) with a site key we do not recognise\u2026', lastEventAt: null, refusedRecently: { unknown_key: 214, bad_origin: 0, bot: 3, over_quota: 0 } }."
2214
+ ].join("\n"),
2215
+ input: {
2216
+ domain: z12.string().max(253).describe("Bare hostname of a site this team tracks.")
2217
+ },
2218
+ handler: async (args, ctx) => {
2219
+ const teamId = await ctx.resolveTeamId();
2220
+ const siteIds = await resolveSiteIds([args.domain], teamId, ctx.api);
2221
+ const status = await ctx.api.get(
2222
+ `/api/analytics/${teamId}/sites/${siteIds}/status`
2223
+ );
2224
+ return respond({ summary: `${args.domain}: ${status.headline}`, data: shape(status) });
2225
+ }
2226
+ });
2227
+ defineTool({
2228
+ name: "get_analytics_summary",
2229
+ category: "analytics",
2230
+ description: [
2231
+ "One row per site: visitors, pageviews, bounce rate, average visit and live visitors, each with the previous period to compare against.",
2232
+ "",
2233
+ 'When to use: "how are my sites doing", a weekly check, or spotting which of several domains moved. This is the cross-site view; use get_analytics_overview for the breakdowns behind one of them.',
2234
+ "",
2235
+ "READ THE VISITOR NUMBER CAREFULLY. Inside a site's raw-event window (35 days by default, so 24h through 30d are raw) `visitors` is a true distinct count over the range. Beyond it the answer comes from a daily rollup and `visitors` is each day's uniques ADDED TOGETHER \u2014 someone who visits daily counts once per day. `visitorsAreSummedDailies` says which you got; quote it when reporting a 90d or 12mo number.",
2236
+ "",
2237
+ "Visitors are never summed ACROSS sites. The same person on two domains is two session ids, and reconciling them would require the cross-domain identity a cookieless tracker exists not to build. Add pageviews if you need a total; do not add visitors.",
2238
+ "",
2239
+ "Inputs: range (24h|7d|30d|90d|12mo, default 7d), domains (optional list; omit for every site).",
2240
+ "",
2241
+ "Example: get_analytics_summary({ range: '30d' }) \u2192 { range: '30d', sites: [{ domain: 'hoststack.dev', current: { visitors: 4210, pageviews: 11890, bounceRate: 47.2 }, previous: {\u2026}, live: 3, visitorsAreSummedDailies: false }] }."
2242
+ ].join("\n"),
2243
+ input: {
2244
+ range: z12.enum(["24h", "7d", "30d", "90d", "12mo"]).optional().describe("Default 7d."),
2245
+ domains: z12.array(z12.string().max(253)).max(50).optional().describe("Bare hostnames. Omit for every site this team tracks.")
2246
+ },
2247
+ handler: async (args, ctx) => {
2248
+ const teamId = await ctx.resolveTeamId();
2249
+ const siteIds = await resolveSiteIds(args.domains, teamId, ctx.api);
2250
+ const response = await ctx.api.get(`/api/analytics/${teamId}/summary`, {
2251
+ range: args.range ?? "7d",
2252
+ ...siteIds ? { siteIds } : {}
2253
+ });
2254
+ const sites = Array.isArray(response.sites) ? response.sites : [];
2255
+ const summed = sites.some((s) => s.visitorsAreSummedDailies);
2256
+ const summary = sites.length === 0 ? "No sites to report on." : `${sites.length} site${sites.length === 1 ? "" : "s"} over ${response.range}.${summed ? " Visitor counts are daily uniques summed, not distinct over the range \u2014 this range is past the raw-event window." : ""}`;
2257
+ return respond({ summary, data: { range: response.range, sites: sites.map(shape) } });
2258
+ }
2259
+ });
2260
+ defineTool({
2261
+ name: "get_analytics_overview",
2262
+ category: "analytics",
2263
+ description: [
2264
+ "The full breakdown for one site (or several): timeseries, top paths, referrers, custom events, browsers, operating systems, languages, screen sizes, campaigns, devices and countries.",
2265
+ "",
2266
+ "When to use: after get_analytics_summary has told you WHICH site moved, and you need to see what drove it \u2014 a referrer that appeared, a campaign that landed, a path that spiked.",
2267
+ "",
2268
+ "Two things change past the raw-event window (35 days by default, so 24h through 30d are raw): `visitors` becomes daily uniques summed rather than a distinct count (`visitorsAreSummedDailies`), and FILTERS ARE IGNORED because the rollup stores per-day aggregates with no events left to filter (`filtersSupported: false`). Check both fields before drawing a conclusion; do not silently present a filtered request that was not filtered.",
2269
+ "",
2270
+ "Inputs: range (24h|7d|30d|90d|12mo, default 7d), domains (optional list; omit for every site), filters (optional map \u2014 country, browser, os, device, language, path, referrer, utmSource, utmMedium, utmCampaign, utmTerm, utmContent).",
2271
+ "",
2272
+ "Example: get_analytics_overview({ domains: ['hoststack.dev'], range: '7d', filters: { country: 'DK' } }) \u2192 { source: 'raw', filtersSupported: true, summary: { current: { visitors: 310, \u2026 } }, topPaths: [{ path: '/pricing', pageviews: 214 }], topReferrers: [{ referrer: 'Direct', visits: 190 }], \u2026 }."
2273
+ ].join("\n"),
2274
+ input: {
2275
+ range: z12.enum(["24h", "7d", "30d", "90d", "12mo"]).optional().describe("Default 7d."),
2276
+ domains: z12.array(z12.string().max(253)).max(50).optional().describe("Bare hostnames. Omit for every site this team tracks."),
2277
+ filters: z12.record(z12.string(), z12.string().max(200)).optional().describe("Dimension filters. Ignored for ranges past the raw-event window.")
2278
+ },
2279
+ handler: async (args, ctx) => {
2280
+ const teamId = await ctx.resolveTeamId();
2281
+ const siteIds = await resolveSiteIds(args.domains, teamId, ctx.api);
2282
+ const response = await ctx.api.get(`/api/analytics/${teamId}/overview`, {
2283
+ range: args.range ?? "7d",
2284
+ ...siteIds ? { siteIds } : {},
2285
+ ...args.filters ?? {}
2286
+ });
2287
+ const { current } = response.summary;
2288
+ const caveats = [];
2289
+ if (response.visitorsAreSummedDailies) {
2290
+ caveats.push(
2291
+ "visitors are daily uniques summed (this range is past the raw-event window)"
2292
+ );
2293
+ }
2294
+ if (args.filters && Object.keys(args.filters).length > 0 && !response.filtersSupported) {
2295
+ caveats.push(
2296
+ "the filters you passed were NOT applied \u2014 they only work on shorter ranges"
2297
+ );
2298
+ }
2299
+ const summary = `${current.pageviews.toLocaleString()} pageviews from ${current.visitors.toLocaleString()} visitors over ${response.range}${caveats.length > 0 ? `. Note: ${caveats.join("; ")}.` : "."}`;
2300
+ return respond({ summary, data: response });
2301
+ }
2302
+ });
2303
+ defineTool({
2304
+ name: "create_analytics_site",
2305
+ category: "analytics",
2306
+ description: [
2307
+ "Start tracking a domain, and return the script tag to paste into its <head>.",
2308
+ "",
2309
+ "When to use: the user wants analytics for a site that is not in list_analytics_sites yet. Works for any domain, whether or not it is hosted on HostStack.",
2310
+ "",
2311
+ "If the domain is already attached to a service on this team, the new site links itself to that service and appears on its Analytics tab. Nothing is counted until the snippet is actually on the page \u2014 creating the site alone produces an empty dashboard, which is expected, not a fault.",
2312
+ "",
2313
+ 'Inputs: domain (required, bare hostname \u2014 "example.com", not a URL), name (optional display name, defaults to the domain).',
2314
+ "",
2315
+ `Example: create_analytics_site({ domain: 'micci.dk' }) \u2192 { site: { id: 3, domain: 'micci.dk', ingestKey: 'site_\u2026' }, snippet: '<script defer src="https://hoststack.dev/t.js" data-site-key="site_\u2026"></script>' }.`
2316
+ ].join("\n"),
2317
+ input: {
2318
+ domain: z12.string().min(1).max(253).describe("Bare hostname, e.g. example.com"),
2319
+ name: z12.string().min(1).max(100).optional().describe("Display name. Defaults to the domain.")
2320
+ },
2321
+ handler: async (args, ctx) => {
2322
+ const teamId = await ctx.resolveTeamId();
2323
+ const site = await ctx.api.post(`/api/analytics/${teamId}/sites`, {
2324
+ domain: args.domain,
2325
+ ...args.name ? { name: args.name } : {}
2326
+ });
2327
+ const snippet = `<script defer src="https://hoststack.dev/t.js" data-site-key="${site.ingestKey}"></script>`;
2328
+ return respond({
2329
+ summary: `Now tracking ${site.domain}. Paste the snippet into its <head> \u2014 nothing is counted until you do.`,
2330
+ data: { site: shape(site), snippet }
2331
+ });
2332
+ }
2333
+ });
2334
+
2335
+ // src/tools/errors.ts
2336
+ import { z as z13 } from "zod";
2337
+ defineTool({
2338
+ name: "list_error_issues",
2339
+ category: "errors",
2340
+ description: [
2341
+ "List error issues for the team \u2014 exceptions the team's own applications reported, grouped by cause rather than listed one per event.",
2342
+ "",
2343
+ 'When to use: "what is throwing in production", triaging after a deploy, or finding the bug behind a user report. Pairs with list_alerts (which tells you an alert fired) and get_service_logs (which shows the raw output around it).',
2344
+ "",
2345
+ 'Grouping: an issue is one distinct problem. Its fingerprint is the exception class, the message with variable parts removed (so "user 41 not found" and "user 9002 not found" are ONE issue), and the topmost stack frame in the team\'s own code \u2014 not the framework\'s. `culprit` is that frame, and it is the line to open first.',
2346
+ "",
2347
+ "Counts are exact; occurrence samples are not. `occurrenceCount` is the true number of times it happened. A bounded number of full occurrences is retained per issue (see get_error_issue), and `droppedCount` is how many were counted but not stored because the service exceeded its hourly ingest quota.",
2348
+ "",
2349
+ 'Defaults to status=unresolved, because the list exists to answer "what is broken". Pass status=resolved or status=ignored for the others.',
2350
+ "",
2351
+ "Inputs (all optional): serviceId, status (unresolved|resolved|ignored), q (substring match on title/culprit), limit (default 50, max 200), offset, sort (last_seen|first_seen|count).",
2352
+ "",
2353
+ 'Returns: { issues: Array, total: number }. Each issue has id, publicId, serviceId, serviceName, type, title, culprit, level, status, occurrenceCount, droppedCount, affectedUsers (capped at 500 \u2014 500 means "500 or more"), firstSeenAt, lastSeenAt, firstSeenRelease, lastSeenRelease, environment, sourceTaskPublicId (a dev-box task already open for it).',
2354
+ "",
2355
+ "Example: list_error_issues({ serviceId: 48, sort: 'count' }) \u2192 { issues: [{ id: 12, type: 'TypeError', title: 'TypeError: cart.total is not a function', culprit: 'src/checkout.ts:12 in checkout', occurrenceCount: 4187, affectedUsers: 96, lastSeenRelease: 'a91f3c2', \u2026 }], total: 3 }."
2356
+ ].join("\n"),
2357
+ input: {
2358
+ serviceId: z13.number().int().positive().optional().describe("Only issues for this service."),
2359
+ status: z13.enum(["unresolved", "resolved", "ignored"]).optional().describe("Default unresolved."),
2360
+ q: z13.string().max(200).optional().describe("Substring match on title or culprit."),
2361
+ limit: z13.number().int().positive().max(200).optional().describe("Default 50, cap 200."),
2362
+ offset: z13.number().int().min(0).optional(),
2363
+ sort: z13.enum(["last_seen", "first_seen", "count"]).optional().describe("Default last_seen.")
2364
+ },
2365
+ handler: async (args, ctx) => {
2366
+ const teamId = await ctx.resolveTeamId();
2367
+ const params = {};
2368
+ for (const key of ["serviceId", "status", "q", "limit", "offset", "sort"]) {
2369
+ const value = args[key];
2370
+ if (value !== void 0) params[key] = String(value);
2371
+ }
2372
+ const response = await ctx.api.get(`/api/errors/${teamId}/issues`, params);
2373
+ const items = Array.isArray(response.issues) ? response.issues.map(shape) : [];
2374
+ const summary = items.length === 0 ? `No ${args.status ?? "unresolved"} error issues${args.serviceId ? " for that service" : ""}.` : `Returned ${items.length} of ${response.total} ${args.status ?? "unresolved"} issue${response.total === 1 ? "" : "s"}.`;
2375
+ return respond({ summary, data: { issues: items, total: response.total } });
2376
+ }
2377
+ });
2378
+ defineTool({
2379
+ name: "get_error_issue",
2380
+ category: "errors",
2381
+ description: [
2382
+ "Fetch one error issue plus its most recent stored occurrences \u2014 the stack traces, request context and releases behind the aggregate.",
2383
+ "",
2384
+ "When to use: after list_error_issues has told you WHICH problem to look at, and you need the actual stack to reason about the cause.",
2385
+ "",
2386
+ "Occurrences are SAMPLES, not the full history: a bounded number is kept per issue while the count stays exact, and they age out after 30 days while the issue itself remains. An issue whose samples have expired returns an empty occurrences array \u2014 that is normal, not an error.",
2387
+ "",
2388
+ "Each occurrence has stack (raw, as the runtime printed it), context (tenant-supplied JSON, with sensitive keys already redacted), requestId, release, environment and createdAt.",
2389
+ "",
2390
+ "Inputs: issueId (required), occurrences (how many samples, default 5, max 50).",
2391
+ "",
2392
+ "Returns: { issue: {...}, occurrences: Array }.",
2393
+ "",
2394
+ "Example: get_error_issue({ issueId: 12 }) \u2192 { issue: { title: 'TypeError: cart.total is not a function', occurrenceCount: 4187, \u2026 }, occurrences: [{ stack: ' at checkout (/app/src/checkout.ts:12:9)\u2026', requestId: 'req_9f3c', release: 'a91f3c2', createdAt: '\u2026' }] }."
2395
+ ].join("\n"),
2396
+ input: {
2397
+ issueId: z13.number().int().positive().describe("Numeric issue id from list_error_issues."),
2398
+ occurrences: z13.number().int().positive().max(50).optional().describe("How many samples to include. Default 5.")
2399
+ },
2400
+ handler: async (args, ctx) => {
2401
+ const teamId = await ctx.resolveTeamId();
2402
+ const [issueRes, occRes] = await Promise.all([
2403
+ ctx.api.get(`/api/errors/${teamId}/issues/${args.issueId}`),
2404
+ ctx.api.get(
2405
+ `/api/errors/${teamId}/issues/${args.issueId}/occurrences`,
2406
+ { limit: String(args.occurrences ?? 5) }
2407
+ )
2408
+ ]);
2409
+ const occurrences = Array.isArray(occRes.occurrences) ? occRes.occurrences.map(shape) : [];
2410
+ const issue = shape(issueRes.issue);
2411
+ return respond({
2412
+ summary: `${String(issue["title"] ?? "Issue")} \u2014 ${String(issue["occurrenceCount"] ?? 0)} occurrence(s), ${occurrences.length} sample(s) available.`,
2413
+ data: { issue, occurrences }
2414
+ });
2415
+ }
2416
+ });
2417
+ defineTool({
2418
+ name: "update_error_issue",
2419
+ category: "errors",
2420
+ description: [
2421
+ "Resolve, ignore or reopen an error issue.",
2422
+ "",
2423
+ "When to use: after fixing a bug (resolve, so a recurrence is reported as a regression), or to silence noise you have decided to live with (ignore).",
2424
+ "",
2425
+ "`resolved` records the release it was resolved in. If the issue occurs again afterwards it reopens itself and fires an `error.issue_regressed` alert \u2014 which is the point of resolving rather than ignoring, and the reason not to resolve something you have not actually fixed.",
2426
+ "",
2427
+ "`ignored` keeps counting occurrences and stops telling anyone. An ignored issue never reopens itself, so this is the right choice for noise you have decided to live with, and the wrong choice for something you intend to fix.",
2428
+ "",
2429
+ "`unresolved` reopens it.",
2430
+ "",
2431
+ "Inputs: issueId (required), status (required).",
2432
+ "",
2433
+ "Returns: { issue: {...} } with the updated row.",
2434
+ "",
2435
+ "Example: update_error_issue({ issueId: 12, status: 'resolved' }) \u2192 { issue: { status: 'resolved', resolvedInRelease: 'a91f3c2', \u2026 } }."
2436
+ ].join("\n"),
2437
+ input: {
2438
+ issueId: z13.number().int().positive(),
2439
+ status: z13.enum(["unresolved", "resolved", "ignored"])
2440
+ },
2441
+ handler: async (args, ctx) => {
2442
+ const teamId = await ctx.resolveTeamId();
2443
+ const response = await ctx.api.patch(
2444
+ `/api/errors/${teamId}/issues/${args.issueId}`,
2445
+ { status: args.status }
2446
+ );
2447
+ return respond({
2448
+ summary: `Issue ${args.issueId} is now ${args.status}.`,
2449
+ data: { issue: shape(response.issue) }
2450
+ });
2451
+ }
2452
+ });
2453
+ defineTool({
2454
+ name: "fix_error_in_dev_box",
2455
+ category: "errors",
2456
+ description: [
2457
+ "Turn an error issue into a coding-agent task in the project's dev box, with the repository already checked out.",
2458
+ "",
2459
+ "When to use: the issue is real, it is in the team's own code, and somebody is going to have to open the repository anyway. This writes the whole briefing so nobody has to reconstruct it from the dashboard.",
2460
+ "",
2461
+ "This is the thing a third-party error tracker structurally cannot do. The task carries the exception, the stack with the team's OWN frames marked (`>>`), the release it happened on, how often and to how many users, and a real request context \u2014 plus hard boundaries: work on a branch, do not deploy, do not delete tests, and stop and say so if the cause turns out not to be in this repository.",
2462
+ "",
2463
+ "It CREATES the task; it does not start the agent. Running spends the team's own agent tokens and is a separate decision made in the dev box UI.",
2464
+ "",
2465
+ "Refused with 422 when the cause cannot be attributed to the repository \u2014 every stack frame inside a dependency, no usable stack at all, a browser extension, or a connection failure with no in-app frame. That gate is deliberate: an agent told to fix something it cannot reach does not refuse, it produces a confident and useless diff.",
2466
+ "",
2467
+ "Pressing this twice for one issue returns the existing task (alreadyExisted=true) rather than queueing a duplicate run.",
2468
+ "",
2469
+ "Inputs: issueId (required), serviceId (optional \u2014 pin to a specific dev box; omitted, the project's box is used).",
2470
+ "",
2471
+ "Returns: { task, alreadyExisted, box: { serviceId, name, asleep }, automodeEnabled }.",
2472
+ "",
2473
+ "Example: fix_error_in_dev_box({ issueId: 12 }) \u2192 { task: { title: 'Fix error: TypeError in src/checkout.ts:12' }, alreadyExisted: false, box: { name: 'shop-dev', asleep: true }, automodeEnabled: false }."
2474
+ ].join("\n"),
2475
+ input: {
2476
+ issueId: z13.number().int().positive(),
2477
+ serviceId: z13.number().int().positive().optional().describe("Dev box to pin the task to. Omitted, the project's box is used.")
2478
+ },
2479
+ handler: async (args, ctx) => {
2480
+ const teamId = await ctx.resolveTeamId();
2481
+ const body = { issueId: args.issueId };
2482
+ if (args.serviceId !== void 0) body["serviceId"] = args.serviceId;
2483
+ const response = await ctx.api.post(
2484
+ `/api/dev-env-tasks/${teamId}/from-issue`,
2485
+ body
2486
+ );
2487
+ const verb = response.alreadyExisted ? "Already queued" : "Queued";
2488
+ const note = response.box.asleep ? " That box is asleep \u2014 resume it before running the task." : "";
2489
+ return respond({
2490
+ summary: `${verb} in dev box "${response.box.name}": ${response.task.title ?? "task"}.${note}`,
2491
+ data: shape(response)
2492
+ });
2493
+ }
2494
+ });
2495
+ defineTool({
2496
+ name: "list_ingest_keys",
2497
+ category: "errors",
2498
+ description: [
2499
+ "List a service's error-ingest keys. Only prefixes and last-used timestamps \u2014 the key itself is stored as a hash and is never readable again.",
2500
+ "",
2501
+ "When to use: checking whether a service is wired up for error reporting at all, or whether an old key is still in use before revoking it (`lastUsedAt` is stamped lazily, at most once a minute).",
2502
+ "",
2503
+ "Inputs: serviceId (required).",
2504
+ "",
2505
+ "Returns: { keys: Array } with id, publicId, name, prefix, lastUsedAt, createdAt.",
2506
+ "",
2507
+ "Example: list_ingest_keys({ serviceId: 48 }) \u2192 { keys: [{ id: 3, name: 'default', prefix: 'ing_9f3c1ab2', lastUsedAt: '2026-08-21T09:14:00Z' }] }."
2508
+ ].join("\n"),
2509
+ input: { serviceId: z13.number().int().positive() },
2510
+ handler: async (args, ctx) => {
2511
+ const teamId = await ctx.resolveTeamId();
2512
+ const response = await ctx.api.get(
2513
+ `/api/services/${teamId}/${args.serviceId}/ingest-keys`
2514
+ );
2515
+ const keys = Array.isArray(response.keys) ? response.keys.map(shape) : [];
2516
+ return respond({
2517
+ summary: keys.length === 0 ? "No ingest keys on this service \u2014 it cannot report errors yet." : `${keys.length} ingest key${keys.length === 1 ? "" : "s"} on this service.`,
2518
+ data: { keys }
2519
+ });
2520
+ }
2521
+ });
2522
+ defineTool({
2523
+ name: "create_ingest_key",
2524
+ category: "errors",
2525
+ description: [
2526
+ "Mint a write-only error-ingest key for a service, so its application can report exceptions.",
2527
+ "",
2528
+ "When to use: setting a service up for error tracking for the first time, or rotating a key that has leaked or is being retired.",
2529
+ "",
2530
+ "The response is the ONLY place the plaintext key ever exists \u2014 it is stored as a SHA-256 hash and cannot be shown again. Put it wherever the application reads it from (an env var, usually) before discarding the response.",
2531
+ "",
2532
+ "The key is deliberately low-privilege: it can create error events for this ONE service and can do nothing else \u2014 it cannot read the issues it created, list services, or touch anything on the team. That is why shipping it inside the application, including a browser bundle where it is world-readable, is expected rather than a mistake.",
2533
+ "",
2534
+ 'Reporting is a plain HTTP POST, no SDK required: POST {baseUrl}/api/ingest/errors/{key} with {"events":[{"type","value","stack","level","context"}]}, up to 100 events per request.',
2535
+ "",
2536
+ 'Inputs: serviceId (required), name (optional label, default "default"). Max 5 keys per service \u2014 the extras exist so a key can be rotated without downtime (create the second, ship it, delete the first).',
2537
+ "",
2538
+ "Returns: { key: { id, publicId, name, prefix, key } } where `key` is the plaintext.",
2539
+ "",
2540
+ "Example: create_ingest_key({ serviceId: 48 }) \u2192 { id: 4, name: 'default', prefix: 'ing_1b7d40ae', key: 'ing_1b7d40ae\u2026' }."
2541
+ ].join("\n"),
2542
+ input: {
2543
+ serviceId: z13.number().int().positive(),
2544
+ name: z13.string().min(1).max(100).optional().describe('Label. Default "default".')
2545
+ },
2546
+ handler: async (args, ctx) => {
2547
+ const teamId = await ctx.resolveTeamId();
2548
+ const response = await ctx.api.post(
2549
+ `/api/services/${teamId}/${args.serviceId}/ingest-keys`,
2550
+ { name: args.name ?? "default" }
2551
+ );
2552
+ return respond({
2553
+ summary: "Ingest key created. The plaintext key is in the payload and is not retrievable again \u2014 store it now.",
2554
+ data: shape(response.key)
2555
+ });
2556
+ }
2557
+ });
2558
+ defineTool({
2559
+ name: "delete_ingest_key",
2560
+ category: "errors",
2561
+ description: [
2562
+ "Revoke an error-ingest key. It stops working immediately, including on API replicas that had it cached.",
2563
+ "",
2564
+ "When to use: finishing a key rotation, or containing a key that leaked somewhere it should not have.",
2565
+ "",
2566
+ "Anything still posting with it starts getting 401s, so revoke the OLD key after the new one is deployed, not before.",
2567
+ "",
2568
+ "Inputs: serviceId, keyId (both required).",
2569
+ "",
2570
+ "Returns: { success: true }.",
2571
+ "",
2572
+ "Example: delete_ingest_key({ serviceId: 48, keyId: 3 }) \u2192 { success: true }."
2573
+ ].join("\n"),
2574
+ input: {
2575
+ serviceId: z13.number().int().positive(),
2576
+ keyId: z13.number().int().positive()
2577
+ },
2578
+ handler: async (args, ctx) => {
2579
+ const teamId = await ctx.resolveTeamId();
2580
+ await ctx.api.delete(`/api/services/${teamId}/${args.serviceId}/ingest-keys/${args.keyId}`);
2581
+ return respond({ summary: `Ingest key ${args.keyId} revoked.` });
2582
+ }
2583
+ });
2584
+
2051
2585
  // src/tools/github.ts
2052
2586
  defineTool({
2053
2587
  name: "sync_github_repos",
@@ -2155,7 +2689,7 @@ defineTool({
2155
2689
  });
2156
2690
 
2157
2691
  // src/tools/notifications.ts
2158
- import { z as z11 } from "zod";
2692
+ import { z as z14 } from "zod";
2159
2693
  var NOTIFICATION_EVENTS = [
2160
2694
  "deploy.started",
2161
2695
  "deploy.succeeded",
@@ -2169,9 +2703,25 @@ var NOTIFICATION_EVENTS = [
2169
2703
  "service.auto_suspended",
2170
2704
  "service.acme_cert_failed",
2171
2705
  "service.resource_alert",
2706
+ "service.uptime_down",
2707
+ "service.uptime_recovered",
2708
+ "error.issue_new",
2709
+ "error.issue_regressed",
2172
2710
  "git.auth_failed",
2173
2711
  "cron.execution_failed",
2174
- "workflow.failed"
2712
+ "workflow.failed",
2713
+ "devenv.agent.needs_input",
2714
+ "devenv.agent.finished",
2715
+ "devenv.task.created",
2716
+ "devenv.task.needs_input",
2717
+ "devenv.task.finished",
2718
+ "database.backup_failed",
2719
+ "database.restore_failed",
2720
+ "machine.offline",
2721
+ "machine.online",
2722
+ "billing.invoice",
2723
+ "billing.payment_failed",
2724
+ "billing.spend_limit"
2175
2725
  ];
2176
2726
  defineTool({
2177
2727
  name: "list_notification_channels",
@@ -2210,17 +2760,21 @@ defineTool({
2210
2760
  " - webhook_url: Slack/Discord webhook URL OR email address.",
2211
2761
  " - events: list of event names to subscribe to. Pass an empty list to create a channel that fires for nothing (manual subscribe later with update_notification_channel).",
2212
2762
  "",
2213
- "Valid events: deploy.started, deploy.succeeded, deploy.failed, deploy.failed_consecutive, service.created, service.deleted, service.suspended, service.resumed, service.restart_failed, service.auto_suspended, service.acme_cert_failed, service.resource_alert, git.auth_failed, cron.execution_failed, workflow.failed.",
2763
+ // Rendered from the enum instead of retyped: the hand-written copy of
2764
+ // this sentence went stale the same way the enum did, and a description
2765
+ // that disagrees with the schema teaches the model to send values the
2766
+ // tool then rejects.
2767
+ `Valid events: ${NOTIFICATION_EVENTS.join(", ")}.`,
2214
2768
  "",
2215
2769
  "Returns: { channel: Channel }.",
2216
2770
  "",
2217
2771
  "Example: create_notification_channel({ type: 'slack', name: 'eng-alerts', webhook_url: 'https://hooks.slack.com/\u2026', events: ['deploy.failed', 'git.auth_failed', 'service.restart_failed'] })"
2218
2772
  ].join("\n"),
2219
2773
  input: {
2220
- type: z11.enum(["slack", "discord", "email"]).describe("Channel type."),
2221
- name: z11.string().min(1).max(128).describe("Human-readable label."),
2222
- webhook_url: z11.string().max(500).describe("Slack/Discord webhook URL or email address (when type=email)."),
2223
- events: z11.array(z11.enum(NOTIFICATION_EVENTS)).describe(
2774
+ type: z14.enum(["slack", "discord", "email"]).describe("Channel type."),
2775
+ name: z14.string().min(1).max(128).describe("Human-readable label."),
2776
+ webhook_url: z14.string().max(500).describe("Slack/Discord webhook URL or email address (when type=email)."),
2777
+ events: z14.array(z14.enum(NOTIFICATION_EVENTS)).describe(
2224
2778
  "List of events the channel subscribes to. Empty list = subscribe to nothing."
2225
2779
  )
2226
2780
  },
@@ -2258,10 +2812,10 @@ defineTool({
2258
2812
  "Example: update_notification_channel({ channel_id: 3, events: ['deploy.failed', 'service.restart_failed', 'git.auth_failed'] })"
2259
2813
  ].join("\n"),
2260
2814
  input: {
2261
- channel_id: z11.number().int().positive().describe("Numeric channel id from list_notification_channels."),
2262
- name: z11.string().min(1).max(128).optional().describe("New label."),
2263
- active: z11.boolean().optional().describe("false silences without deleting."),
2264
- events: z11.array(z11.enum(NOTIFICATION_EVENTS)).optional().describe("Replaces the full subscription list.")
2815
+ channel_id: z14.number().int().positive().describe("Numeric channel id from list_notification_channels."),
2816
+ name: z14.string().min(1).max(128).optional().describe("New label."),
2817
+ active: z14.boolean().optional().describe("false silences without deleting."),
2818
+ events: z14.array(z14.enum(NOTIFICATION_EVENTS)).optional().describe("Replaces the full subscription list.")
2265
2819
  },
2266
2820
  handler: async (args, ctx) => {
2267
2821
  const teamId = await ctx.resolveTeamId();
@@ -2300,7 +2854,7 @@ defineTool({
2300
2854
  "Example: delete_notification_channel({ channel_id: 3 }) \u2192 { ok: true }"
2301
2855
  ].join("\n"),
2302
2856
  input: {
2303
- channel_id: z11.number().int().positive().describe("Numeric channel id.")
2857
+ channel_id: z14.number().int().positive().describe("Numeric channel id.")
2304
2858
  },
2305
2859
  handler: async (args, ctx) => {
2306
2860
  const teamId = await ctx.resolveTeamId();
@@ -2327,7 +2881,7 @@ defineTool({
2327
2881
  "Example: test_notification_channel({ channel_id: 3 }) \u2192 { success: true }"
2328
2882
  ].join("\n"),
2329
2883
  input: {
2330
- channel_id: z11.number().int().positive().describe("Numeric channel id.")
2884
+ channel_id: z14.number().int().positive().describe("Numeric channel id.")
2331
2885
  },
2332
2886
  handler: async (args, ctx) => {
2333
2887
  const teamId = await ctx.resolveTeamId();
@@ -2342,7 +2896,7 @@ defineTool({
2342
2896
  });
2343
2897
 
2344
2898
  // src/tools/projects.ts
2345
- import { z as z12 } from "zod";
2899
+ import { z as z15 } from "zod";
2346
2900
  var AVAILABLE_REGION_IDS = ["eu-central-1"];
2347
2901
  defineTool({
2348
2902
  name: "list_projects",
@@ -2383,9 +2937,9 @@ defineTool({
2383
2937
  'Example: create_project({ name: "billing-api", description: "Stripe webhooks", region: "eu-central-1" }) \u2192 { project: { id: 12, publicId: "prj_\u2026", \u2026 } }'
2384
2938
  ].join("\n"),
2385
2939
  input: {
2386
- name: z12.string().min(1).max(60).describe("Project name (1\u201360 chars)."),
2387
- description: z12.string().max(500).optional().describe("Short description (\u2264500 chars)."),
2388
- region: z12.enum(AVAILABLE_REGION_IDS).optional().describe("Region: eu-central-1 (Falkenstein) \u2014 currently the only available region.")
2940
+ name: z15.string().min(1).max(60).describe("Project name (1\u201360 chars)."),
2941
+ description: z15.string().max(500).optional().describe("Short description (\u2264500 chars)."),
2942
+ region: z15.enum(AVAILABLE_REGION_IDS).optional().describe("Region: eu-central-1 (Falkenstein) \u2014 currently the only available region.")
2389
2943
  },
2390
2944
  handler: async (args, ctx) => {
2391
2945
  const teamId = await ctx.resolveTeamId();
@@ -2418,9 +2972,9 @@ defineTool({
2418
2972
  'Example: update_project({ project_id: "prj_abc", name: "billing-prod" }) \u2192 { project: { name: "billing-prod", \u2026 } }'
2419
2973
  ].join("\n"),
2420
2974
  input: {
2421
- project_id: z12.string().describe("Project publicId."),
2422
- name: z12.string().min(1).max(60).optional().describe("New name (1\u201360 chars)."),
2423
- description: z12.string().max(500).optional().describe("New description (\u2264500 chars).")
2975
+ project_id: z15.string().describe("Project publicId."),
2976
+ name: z15.string().min(1).max(60).optional().describe("New name (1\u201360 chars)."),
2977
+ description: z15.string().max(500).optional().describe("New description (\u2264500 chars).")
2424
2978
  },
2425
2979
  handler: async (args, ctx) => {
2426
2980
  if (args.name === void 0 && args.description === void 0) {
@@ -2454,7 +3008,7 @@ defineTool({
2454
3008
  'Example: get_project({ project_id: "prj_abc" }) \u2192 { project: { id: 12, name: "billing", \u2026 } }'
2455
3009
  ].join("\n"),
2456
3010
  input: {
2457
- project_id: z12.string().describe("Project publicId (e.g. prj_abc123).")
3011
+ project_id: z15.string().describe("Project publicId (e.g. prj_abc123).")
2458
3012
  },
2459
3013
  handler: async (args, ctx) => {
2460
3014
  const teamId = await ctx.resolveTeamId();
@@ -2466,7 +3020,7 @@ defineTool({
2466
3020
  });
2467
3021
 
2468
3022
  // src/tools/resource-links.ts
2469
- import { z as z13 } from "zod";
3023
+ import { z as z16 } from "zod";
2470
3024
  var RESOURCE_LINK_TYPES = [
2471
3025
  "database",
2472
3026
  "object_storage",
@@ -2527,7 +3081,7 @@ defineTool({
2527
3081
  'Example: list_service_resources({ service_id: "svc_abc" }) \u2192 { items: [{ id: 7, resourceType: "database", resourceId: 42, alias: "APP_DB" }] }'
2528
3082
  ].join("\n"),
2529
3083
  input: {
2530
- service_id: z13.union([z13.number().int().positive(), z13.string()]).describe('Service \u2014 publicId ("svc_\u2026") or numeric id.')
3084
+ service_id: z16.union([z16.number().int().positive(), z16.string()]).describe('Service \u2014 publicId ("svc_\u2026") or numeric id.')
2531
3085
  },
2532
3086
  handler: async (args, ctx) => {
2533
3087
  const teamId = await ctx.resolveTeamId();
@@ -2564,10 +3118,10 @@ defineTool({
2564
3118
  'Example: link_resource_to_service({ service_id: "svc_abc", resource_type: "database", resource_id: 42, alias: "APP_DB" }) \u2192 { link: { id: 7, alias: "APP_DB" } }'
2565
3119
  ].join("\n"),
2566
3120
  input: {
2567
- service_id: z13.union([z13.number().int().positive(), z13.string()]).describe('Consuming service \u2014 publicId ("svc_\u2026") or numeric id.'),
2568
- resource_type: z13.enum(RESOURCE_LINK_TYPES).describe("Kind of resource being linked."),
2569
- resource_id: z13.number().int().positive().describe("NUMERIC id of the resource (e.g. database.id) \u2014 not the publicId."),
2570
- alias: z13.string().min(1).max(48).regex(
3121
+ service_id: z16.union([z16.number().int().positive(), z16.string()]).describe('Consuming service \u2014 publicId ("svc_\u2026") or numeric id.'),
3122
+ resource_type: z16.enum(RESOURCE_LINK_TYPES).describe("Kind of resource being linked."),
3123
+ resource_id: z16.number().int().positive().describe("NUMERIC id of the resource (e.g. database.id) \u2014 not the publicId."),
3124
+ alias: z16.string().min(1).max(48).regex(
2571
3125
  /^[A-Z][A-Z0-9_]*$/,
2572
3126
  "Alias must be uppercase letters, digits and underscores, starting with a letter."
2573
3127
  ).describe('Uppercase env-var prefix, e.g. "APP_DB". Unique within the service.')
@@ -2603,8 +3157,8 @@ defineTool({
2603
3157
  'Example: unlink_resource_from_service({ service_id: "svc_abc", link_id: 7 }) \u2192 { ok: true }'
2604
3158
  ].join("\n"),
2605
3159
  input: {
2606
- service_id: z13.union([z13.number().int().positive(), z13.string()]).describe('Service \u2014 publicId ("svc_\u2026") or numeric id.'),
2607
- link_id: z13.number().int().positive().describe("Numeric linkId from list_service_resources (the link's own `id`).")
3160
+ service_id: z16.union([z16.number().int().positive(), z16.string()]).describe('Service \u2014 publicId ("svc_\u2026") or numeric id.'),
3161
+ link_id: z16.number().int().positive().describe("Numeric linkId from list_service_resources (the link's own `id`).")
2608
3162
  },
2609
3163
  handler: async (args, ctx) => {
2610
3164
  const teamId = await ctx.resolveTeamId();
@@ -2616,9 +3170,217 @@ defineTool({
2616
3170
  });
2617
3171
 
2618
3172
  // src/tools/services.ts
2619
- import { z as z14 } from "zod";
3173
+ import { z as z17 } from "zod";
3174
+
3175
+ // src/lib/app-templates.ts
3176
+ var MCP_APP_TEMPLATES = [
3177
+ {
3178
+ id: "node-express",
3179
+ name: "Node.js Express",
3180
+ description: "HTTP server with Express.js",
3181
+ type: "web_service",
3182
+ runtime: "node",
3183
+ installCommand: "npm install",
3184
+ startCommand: "node index.js"
3185
+ },
3186
+ {
3187
+ id: "python-fastapi",
3188
+ name: "Python FastAPI",
3189
+ description: "Modern Python API framework",
3190
+ type: "web_service",
3191
+ runtime: "python",
3192
+ installCommand: "pip install -r requirements.txt",
3193
+ startCommand: "uvicorn main:app --host 0.0.0.0 --port $PORT"
3194
+ },
3195
+ {
3196
+ id: "go-api",
3197
+ name: "Go HTTP Server",
3198
+ description: "Lightweight Go web service",
3199
+ type: "web_service",
3200
+ runtime: "go",
3201
+ installCommand: "go mod download",
3202
+ buildCommand: "go build -o server .",
3203
+ startCommand: "./server"
3204
+ },
3205
+ {
3206
+ id: "bun-hono",
3207
+ name: "Bun + Hono",
3208
+ description: "Fast TypeScript API with Bun runtime",
3209
+ type: "web_service",
3210
+ runtime: "bun",
3211
+ installCommand: "bun install",
3212
+ startCommand: "bun run src/index.ts"
3213
+ },
3214
+ {
3215
+ id: "nextjs-ssr",
3216
+ name: "Next.js",
3217
+ description: "Server-rendered Next.js started with next start",
3218
+ type: "web_service",
3219
+ runtime: "node",
3220
+ installCommand: "npm install",
3221
+ buildCommand: "npm run build",
3222
+ startCommand: "npm run start"
3223
+ },
3224
+ {
3225
+ id: "react-router-ssr",
3226
+ name: "React Router / Remix",
3227
+ description: "Server build served by react-router-serve or remix-serve",
3228
+ type: "web_service",
3229
+ runtime: "node",
3230
+ installCommand: "npm install",
3231
+ buildCommand: "npm run build",
3232
+ startCommand: "npm run start"
3233
+ },
3234
+ {
3235
+ id: "sveltekit-node",
3236
+ name: "SvelteKit",
3237
+ description: "SvelteKit server build produced by adapter-node",
3238
+ type: "web_service",
3239
+ runtime: "node",
3240
+ installCommand: "npm install",
3241
+ buildCommand: "npm run build",
3242
+ startCommand: "node build"
3243
+ },
3244
+ {
3245
+ id: "nuxt",
3246
+ name: "Nuxt",
3247
+ description: "Nuxt server build running on the Nitro output",
3248
+ type: "web_service",
3249
+ runtime: "node",
3250
+ installCommand: "npm install",
3251
+ buildCommand: "npm run build",
3252
+ startCommand: "node .output/server/index.mjs"
3253
+ },
3254
+ {
3255
+ id: "django",
3256
+ name: "Django",
3257
+ description: "Django project served by Gunicorn",
3258
+ type: "web_service",
3259
+ runtime: "python",
3260
+ installCommand: "pip install -r requirements.txt",
3261
+ buildCommand: "python manage.py collectstatic --noinput || true",
3262
+ startCommand: "gunicorn --bind 0.0.0.0:$PORT --workers 2 $(ls */wsgi.py | head -n1 | cut -d/ -f1).wsgi:application"
3263
+ },
3264
+ {
3265
+ id: "flask",
3266
+ name: "Flask",
3267
+ description: "Flask app served by Gunicorn",
3268
+ type: "web_service",
3269
+ runtime: "python",
3270
+ installCommand: "pip install -r requirements.txt",
3271
+ startCommand: "gunicorn --bind 0.0.0.0:$PORT --workers 2 app:app"
3272
+ },
3273
+ {
3274
+ id: "spring-boot",
3275
+ name: "Spring Boot",
3276
+ description: "Spring Boot fat JAR built with Maven or Gradle",
3277
+ type: "web_service",
3278
+ runtime: "java",
3279
+ // No install/build on purpose: the agent inspects the repo and picks
3280
+ // Maven vs Gradle with the matching toolchain image. Sending either one
3281
+ // here would break the other half of the split.
3282
+ startCommand: "java -jar /app/app.jar --server.port=$PORT"
3283
+ },
3284
+ {
3285
+ id: "static-react",
3286
+ name: "React SPA",
3287
+ description: "Single-page React application",
3288
+ type: "static_site",
3289
+ runtime: "node",
3290
+ installCommand: "npm install",
3291
+ buildCommand: "npm run build",
3292
+ publishPath: "./dist"
3293
+ },
3294
+ {
3295
+ id: "static-nextjs",
3296
+ name: "Next.js Static",
3297
+ description: "Next.js with static export",
3298
+ type: "static_site",
3299
+ runtime: "node",
3300
+ installCommand: "npm install",
3301
+ buildCommand: "npm run build",
3302
+ publishPath: "./out"
3303
+ },
3304
+ {
3305
+ id: "astro",
3306
+ name: "Astro",
3307
+ description: "Astro site built to Astro's default static output",
3308
+ type: "static_site",
3309
+ runtime: "node",
3310
+ installCommand: "npm install",
3311
+ buildCommand: "npm run build",
3312
+ publishPath: "./dist"
3313
+ },
3314
+ {
3315
+ id: "worker-bullmq",
3316
+ name: "BullMQ Worker",
3317
+ description: "Background job processor",
3318
+ type: "worker",
3319
+ runtime: "node",
3320
+ installCommand: "npm install",
3321
+ startCommand: "node worker.js"
3322
+ },
3323
+ {
3324
+ id: "uptime-kuma",
3325
+ name: "Uptime Kuma",
3326
+ description: "Self-hosted uptime monitoring and status pages, with its own SQLite store",
3327
+ type: "web_service",
3328
+ dockerImage: "louislam/uptime-kuma:1",
3329
+ port: 3e3
3330
+ },
3331
+ {
3332
+ id: "vaultwarden",
3333
+ name: "Vaultwarden",
3334
+ description: "Self-hosted Bitwarden-compatible password manager (unofficial server)",
3335
+ type: "web_service",
3336
+ dockerImage: "vaultwarden/server:1.32.7-alpine",
3337
+ port: 3e3
3338
+ },
3339
+ {
3340
+ id: "n8n",
3341
+ name: "n8n",
3342
+ description: "Self-hosted workflow automation \u2014 visual editor, 400+ integrations",
3343
+ type: "web_service",
3344
+ dockerImage: "n8nio/n8n:1",
3345
+ port: 5678
3346
+ },
3347
+ {
3348
+ id: "wordpress",
3349
+ name: "WordPress",
3350
+ description: "PHP 8.3 + Apache, with a managed MySQL database (billed separately)",
3351
+ type: "web_service",
3352
+ dockerImage: "wordpress:php8.3-apache",
3353
+ port: 80
3354
+ },
3355
+ {
3356
+ id: "ghost",
3357
+ name: "Ghost",
3358
+ description: "Blogs and newsletters, with a managed MySQL database (billed separately)",
3359
+ type: "web_service",
3360
+ dockerImage: "ghost:5-alpine",
3361
+ port: 2368
3362
+ },
3363
+ {
3364
+ id: "cron-cleanup",
3365
+ name: "Cleanup Cron",
3366
+ description: "Daily maintenance task",
3367
+ type: "cron_job",
3368
+ runtime: "node",
3369
+ installCommand: "npm install",
3370
+ startCommand: "node cleanup.js",
3371
+ cronSchedule: "0 3 * * *"
3372
+ }
3373
+ ];
3374
+
3375
+ // src/tools/services.ts
2620
3376
  var DEV_ENV_IMAGE = "registry.hoststack.dev/hoststack/dev-env:latest";
2621
3377
  var DEV_ENV_VOLUME = { name: "workspace", mountPath: "/workspace", sizeGb: 10 };
3378
+ var DEV_BOX_INSIDE = [
3379
+ "INSIDE the box (no Docker daemon \u2014 do not try `docker run`, and runtime `apt-get` is blocked too; it is all preinstalled):",
3380
+ ' - Databases/engines via `dev-services up`: Postgres 17 (:5432, user "dev", trust auth), Redis (:6379), Meilisearch (:7700). MariaDB/MySQL (:3306, user "dev", no password, client `mariadb`) and MongoDB (:27017, client `mongosh`) are OPT-IN \u2014 `dev-services up mysql` / `dev-services up mongodb` \u2014 so a box does not pay RAM for engines it never uses. `dev-services createdb <name>` makes a Postgres role + database in one step. Data lives on /workspace, so it survives restarts.',
3381
+ " - Language runtimes: node, bun, python and php 8.3 are built in. go, java, ruby, rust, elixir and dotnet install on demand with `dev-runtime add <name>` (persisted to /workspace). Together that covers every runtime the platform itself deploys \u2014 a WordPress/Laravel/Rails stack runs in the box. elixir needs `dev-runtime add erlang` first: it is a BEAM distribution with no OTP of its own, and Ubuntu ships one too old to use, so mise builds a current one (takes a few minutes).",
3382
+ " - `hoststack-status` prints what is running, the box dev URL and agent login state at any time."
3383
+ ].join("\n");
2622
3384
  var SERVICE_TYPES = [
2623
3385
  "web_service",
2624
3386
  "private_service",
@@ -2665,11 +3427,11 @@ defineTool({
2665
3427
  'Example: list_services({ status: "failed" }) \u2192 only services that need attention.'
2666
3428
  ].join("\n"),
2667
3429
  input: {
2668
- project_id: z14.union([z14.number().int().positive(), z14.string()]).optional().describe("Project filter \u2014 numeric id or publicId."),
2669
- environment_id: z14.union([z14.number().int().positive(), z14.string()]).optional().describe("Environment filter \u2014 numeric id or publicId."),
2670
- status: z14.enum(["active", "deploying", "suspended", "failed", "not_deployed"]).optional().describe("Filter by current runtime status."),
2671
- type: z14.enum(["web_service", "private_service", "worker", "cron_job", "static_site"]).optional().describe("Filter by service type."),
2672
- dev_environment: z14.boolean().optional().describe(
3430
+ project_id: z17.union([z17.number().int().positive(), z17.string()]).optional().describe("Project filter \u2014 numeric id or publicId."),
3431
+ environment_id: z17.union([z17.number().int().positive(), z17.string()]).optional().describe("Environment filter \u2014 numeric id or publicId."),
3432
+ status: z17.enum(["active", "deploying", "suspended", "failed", "not_deployed"]).optional().describe("Filter by current runtime status."),
3433
+ type: z17.enum(["web_service", "private_service", "worker", "cron_job", "static_site"]).optional().describe("Filter by service type."),
3434
+ dev_environment: z17.boolean().optional().describe(
2673
3435
  "Include agentic Dev Boxes in the results (excluded by default; see list_dev_environments)."
2674
3436
  )
2675
3437
  },
@@ -2714,6 +3476,8 @@ defineTool({
2714
3476
  "",
2715
3477
  "When to use: the user wants to deploy something new. For a one-command AI dev environment specifically, prefer create_dev_environment (it also attaches the /workspace volume and sets the MCP keys).",
2716
3478
  "",
3479
+ "*** For a packaged app (WordPress, Ghost, n8n, Uptime Kuma, Vaultwarden), start at list_templates and pass template_id. *** Those templates are prebuilt images that only boot with the volume, scratch dirs, uid and companion database the platform attaches from the template id \u2014 the same image passed as a bare docker_image crash-loops on the read-only rootfs, and the fix is a redeploy away rather than an edit away.",
3480
+ "",
2717
3481
  '*** NOT for databases. *** If the user wants Postgres, Redis, MySQL, MariaDB or MongoDB, call create_database \u2014 do NOT create a service with docker_image "postgres:16" / "redis:7" / "mongo" / "mysql". A database deployed as a service is unmanaged: no backups, no version upgrades, no HA, no credential rotation, no metrics, no persistent volume, and nothing injects its URL into your app. `docker_image` here is for YOUR application images (or sidecars), not for datastores the platform already manages.',
2718
3482
  "",
2719
3483
  "Inputs:",
@@ -2727,32 +3491,43 @@ defineTool({
2727
3491
  " - cron_schedule (optional): cron expression \u2014 required for cron_job.",
2728
3492
  ' - publish_path (optional): static-site output dir (e.g. "dist").',
2729
3493
  ' - runtime (optional): "node" | "bun" | "python" | \u2026 (auto-detected from a repo when omitted).',
3494
+ " - port (optional): the port the container listens on (1\u201365535). A source-built service should omit it \u2014 the platform injects $PORT and expects the app to bind that. Set it for a docker_image whose listen port is fixed by the image (WordPress 80, Ghost 2368, n8n 5678): the platform publishes and health-checks this port and never re-reads what the process actually bound, so an image listening elsewhere fails its first deploy on a container that is perfectly healthy.",
3495
+ " - template_id (optional): create from a quickstart template \u2014 an id from list_templates and nothing else. Everything the template brings (volumes, scratch dirs, uid, generated secrets, companion managed database) is resolved server-side and attached before the first deploy fires; there is no way to send those in the body. For an image template, pass its docker_image and port alongside, exactly as list_templates returns them.",
2730
3496
  ' - plan (optional): service size (default "micro").',
2731
3497
  " - environment_id (optional): bind to a specific environment; defaults to the project Production env.",
2732
3498
  " - auto_deploy (optional, default true): trigger the first deploy immediately when a source is present.",
3499
+ " - machine (optional): run it on one of the team's OWN enrolled machines (name or id, see list_machines) instead of HostStack compute. Pinned at creation and never moved afterwards, and the service is up only while that machine is.",
2733
3500
  "",
2734
3501
  "Returns: { service: Service, deployId: number | null }.",
2735
3502
  "",
2736
- 'Example: create_service({ project_id: "prj_abc", name: "api", type: "web_service", github_repo_id: 42 }) \u2192 { service: { publicId: "svc_\u2026" }, deployId: 1234 }'
3503
+ 'Example: create_service({ project_id: "prj_abc", name: "api", type: "web_service", github_repo_id: 42 }) \u2192 { service: { publicId: "svc_\u2026" }, deployId: 1234 }',
3504
+ 'Example (one-click app): create_service({ project_id: "prj_abc", name: "blog", type: "web_service", template_id: "wordpress", docker_image: "wordpress:php8.3-apache", port: 80 }) \u2014 the wp-content volume, the www-data uid, the Apache scratch dirs and the managed MySQL come from the template id.'
2737
3505
  ].join("\n"),
2738
3506
  input: {
2739
- project_id: z14.union([z14.number().int().positive(), z14.string()]).describe("Target project \u2014 numeric id or publicId."),
2740
- name: z14.string().min(1).max(100).describe("Service name (1\u2013100 chars)."),
2741
- type: z14.enum(SERVICE_TYPES).describe("Service type."),
2742
- docker_image: z14.string().max(500).optional().describe(
3507
+ project_id: z17.union([z17.number().int().positive(), z17.string()]).describe("Target project \u2014 numeric id or publicId."),
3508
+ name: z17.string().min(1).max(100).describe("Service name (1\u2013100 chars)."),
3509
+ type: z17.enum(SERVICE_TYPES).describe("Service type."),
3510
+ docker_image: z17.string().max(500).optional().describe(
2743
3511
  "Pre-built APPLICATION image ref. Mutually exclusive with github_repo_id. Not for databases \u2014 use create_database for postgres/redis/mysql/mariadb/mongodb."
2744
3512
  ),
2745
- github_repo_id: z14.number().int().positive().optional().describe("Linked GitHub repo numeric id. Mutually exclusive with docker_image."),
2746
- branch: z14.string().max(200).optional().describe('Git branch (default "main").'),
2747
- install_command: z14.string().max(1e3).optional().describe("Install shell command."),
2748
- build_command: z14.string().max(1e3).optional().describe("Build shell command."),
2749
- start_command: z14.string().max(1e3).optional().describe("Start shell command (required for web/private services without an image)."),
2750
- cron_schedule: z14.string().max(100).optional().describe("Cron expression \u2014 required for cron_job."),
2751
- publish_path: z14.string().max(500).optional().describe("Static-site output dir."),
2752
- runtime: z14.string().max(50).optional().describe("Runtime hint (node/bun/python/\u2026)."),
2753
- plan: z14.enum(SERVICE_PLANS).optional().describe('Service size (default "micro").'),
2754
- environment_id: z14.union([z14.number().int().positive(), z14.string()]).optional().describe("Bind to a specific environment; defaults to Production."),
2755
- auto_deploy: z14.boolean().optional().describe("Trigger the first deploy immediately (default true).")
3513
+ github_repo_id: z17.number().int().positive().optional().describe("Linked GitHub repo numeric id. Mutually exclusive with docker_image."),
3514
+ branch: z17.string().max(200).optional().describe('Git branch (default "main").'),
3515
+ install_command: z17.string().max(1e3).optional().describe("Install shell command."),
3516
+ build_command: z17.string().max(1e3).optional().describe("Build shell command."),
3517
+ start_command: z17.string().max(1e3).optional().describe("Start shell command (required for web/private services without an image)."),
3518
+ cron_schedule: z17.string().max(100).optional().describe("Cron expression \u2014 required for cron_job."),
3519
+ publish_path: z17.string().max(500).optional().describe("Static-site output dir."),
3520
+ runtime: z17.string().max(50).optional().describe("Runtime hint (node/bun/python/\u2026)."),
3521
+ port: z17.number().int().min(1).max(65535).optional().describe(
3522
+ "Listen port, for a prebuilt image whose port is fixed by the image. Omit for a source-built service \u2014 it binds the injected $PORT."
3523
+ ),
3524
+ template_id: z17.string().max(64).optional().describe(
3525
+ "Quickstart template id from list_templates. Its volumes, scratch dirs, uid, secrets and companion database are resolved server-side; for an image template also pass its docker_image and port."
3526
+ ),
3527
+ plan: z17.enum(SERVICE_PLANS).optional().describe('Service size (default "micro").'),
3528
+ environment_id: z17.union([z17.number().int().positive(), z17.string()]).optional().describe("Bind to a specific environment; defaults to Production."),
3529
+ auto_deploy: z17.boolean().optional().describe("Trigger the first deploy immediately (default true)."),
3530
+ machine: machineInput
2756
3531
  },
2757
3532
  handler: async (args, ctx) => {
2758
3533
  const teamId = await ctx.resolveTeamId();
@@ -2774,6 +3549,8 @@ defineTool({
2774
3549
  if (args.cron_schedule !== void 0) input.cronSchedule = args.cron_schedule;
2775
3550
  if (args.publish_path !== void 0) input.publishPath = args.publish_path;
2776
3551
  if (args.runtime !== void 0) input.runtime = args.runtime;
3552
+ if (args.port !== void 0) input.port = args.port;
3553
+ if (args.template_id !== void 0) input.templateId = args.template_id;
2777
3554
  if (args.plan !== void 0) input.plan = args.plan;
2778
3555
  if (args.auto_deploy !== void 0) input.autoDeploy = args.auto_deploy;
2779
3556
  if (args.environment_id !== void 0) {
@@ -2782,6 +3559,9 @@ defineTool({
2782
3559
  teamId
2783
3560
  });
2784
3561
  }
3562
+ if (args.machine !== void 0) {
3563
+ input.machineId = await resolveMachineId(ctx, teamId, args.machine);
3564
+ }
2785
3565
  const response = await ctx.hoststack.services.create(teamId, input);
2786
3566
  const data = {
2787
3567
  service: shapeService(response.service),
@@ -2805,28 +3585,31 @@ defineTool({
2805
3585
  ' - project_id: numeric id or publicId ("prj_\u2026") of the target project.',
2806
3586
  ' - name (optional): service name (default "dev-environment").',
2807
3587
  ' - plan (optional): box size. Defaults to "standard" (2 GB) \u2014 the OOM-safe floor (DEV_ENV_MIN_SIZE); a coding agent + build OOMs below it. A smaller plan is clamped up to "standard".',
2808
- " - disk_gb (optional): /workspace volume size in GB (default 10, 1\u2013100).",
3588
+ " - disk_gb (optional): /workspace volume size in GB (default 10, min 10, max 10240).",
2809
3589
  " - hoststack_api_key (optional): sets HOSTSTACK_API_KEY so the hoststack MCP works inside the container.",
2810
3590
  " - poststack_api_key (optional): sets POSTSTACK_API_KEY so the poststack MCP works inside the container.",
2811
3591
  " - repo_url (optional): clone this git URL into /workspace on first boot (with optional branch).",
2812
3592
  "",
3593
+ DEV_BOX_INSIDE,
3594
+ "",
2813
3595
  "Returns: { service: Service, volumeAttached: boolean, deployId: number | null }. Open the Terminal tab on the service (dashboard or phone) once it is running; log in once with `claude /login` inside the container.",
2814
3596
  "",
2815
3597
  'Example: create_dev_environment({ project_id: "prj_abc", name: "scratch", hoststack_api_key: "hs_live_\u2026" })'
2816
3598
  ].join("\n"),
2817
3599
  input: {
2818
- project_id: z14.union([z14.number().int().positive(), z14.string()]).describe("Target project \u2014 numeric id or publicId."),
2819
- name: z14.string().min(1).max(100).optional().describe('Service name (default "dev-environment").'),
2820
- plan: z14.enum(SERVICE_PLANS).optional().describe(
3600
+ project_id: z17.union([z17.number().int().positive(), z17.string()]).describe("Target project \u2014 numeric id or publicId."),
3601
+ name: z17.string().min(1).max(100).optional().describe('Service name (default "dev-environment").'),
3602
+ plan: z17.enum(SERVICE_PLANS).optional().describe(
2821
3603
  'Box size (default "standard" \u2014 2 GB, the OOM-safe floor; a smaller plan is clamped up to "standard").'
2822
3604
  ),
2823
- disk_gb: z14.number().int().min(1).max(100).optional().describe("/workspace volume size in GB (default 10)."),
2824
- hoststack_api_key: z14.string().optional().describe("Value for HOSTSTACK_API_KEY (enables the hoststack MCP in-container)."),
2825
- poststack_api_key: z14.string().optional().describe("Value for POSTSTACK_API_KEY (enables the poststack MCP in-container)."),
2826
- repo_url: z14.string().max(500).optional().describe(
3605
+ disk_gb: z17.number().int().min(10).max(10240).optional().describe("/workspace volume size in GB (default 10, min 10, max 10240)."),
3606
+ hoststack_api_key: z17.string().optional().describe("Value for HOSTSTACK_API_KEY (enables the hoststack MCP in-container)."),
3607
+ poststack_api_key: z17.string().optional().describe("Value for POSTSTACK_API_KEY (enables the poststack MCP in-container)."),
3608
+ repo_url: z17.string().max(500).optional().describe(
2827
3609
  "Clone this git URL into /workspace on first boot (HTTPS, or SSH once a key is set)."
2828
3610
  ),
2829
- branch: z14.string().max(200).optional().describe("Branch to clone (with repo_url).")
3611
+ branch: z17.string().max(200).optional().describe("Branch to clone (with repo_url)."),
3612
+ machine: machineInput
2830
3613
  },
2831
3614
  handler: async (args, ctx) => {
2832
3615
  const teamId = await ctx.resolveTeamId();
@@ -2845,6 +3628,9 @@ defineTool({
2845
3628
  autoDeploy: false,
2846
3629
  plan
2847
3630
  };
3631
+ if (args.machine !== void 0) {
3632
+ createInput.machineId = await resolveMachineId(ctx, teamId, args.machine);
3633
+ }
2848
3634
  const created = await ctx.hoststack.services.create(teamId, createInput);
2849
3635
  const service = created.service;
2850
3636
  const rollback = async () => {
@@ -2932,14 +3718,16 @@ defineTool({
2932
3718
  " - include_database_clone (optional): clone the linked database so the app runs on a copy of real data (default true).",
2933
3719
  ' - name (optional): dev box name (default "<source>-dev").',
2934
3720
  "",
3721
+ DEV_BOX_INSIDE,
3722
+ "",
2935
3723
  "Returns: { service, devUrl, deployId }. Once it is live: open the Terminal tab, run `claude`, start the dev server (it must bind $PORT), and view the app at https://<devUrl>. Tear it all down later with delete_dev_environment.",
2936
3724
  "",
2937
3725
  'Example: spin_up_dev_environment({ service_id: "svc_api" }) \u2192 a dev box running a clone of the api service (repo + env-vars + cloned DB) with a public dev URL.'
2938
3726
  ].join("\n"),
2939
3727
  input: {
2940
- service_id: z14.union([z14.number().int().positive(), z14.string()]).describe("Source service to debug \u2014 numeric id or publicId."),
2941
- include_database_clone: z14.boolean().optional().describe("Clone the linked database so the app runs on copied data (default true)."),
2942
- name: z14.string().min(1).max(100).optional().describe('Dev box name (default "<source>-dev").')
3728
+ service_id: z17.union([z17.number().int().positive(), z17.string()]).describe("Source service to debug \u2014 numeric id or publicId."),
3729
+ include_database_clone: z17.boolean().optional().describe("Clone the linked database so the app runs on copied data (default true)."),
3730
+ name: z17.string().min(1).max(100).optional().describe('Dev box name (default "<source>-dev").')
2943
3731
  },
2944
3732
  handler: async (args, ctx) => {
2945
3733
  const teamId = await ctx.resolveTeamId();
@@ -2980,7 +3768,7 @@ defineTool({
2980
3768
  'Example: delete_dev_environment({ service_id: "svc_api_dev" }) \u2192 removes the dev box, its cloned database, and the /workspace volume.'
2981
3769
  ].join("\n"),
2982
3770
  input: {
2983
- service_id: z14.union([z14.number().int().positive(), z14.string()]).describe("The dev box to tear down \u2014 numeric id or publicId.")
3771
+ service_id: z17.union([z17.number().int().positive(), z17.string()]).describe("The dev box to tear down \u2014 numeric id or publicId.")
2984
3772
  },
2985
3773
  handler: async (args, ctx) => {
2986
3774
  const teamId = await ctx.resolveTeamId();
@@ -3016,8 +3804,8 @@ defineTool({
3016
3804
  'Example: resize_dev_environment({ service_id: "svc_skyskraber_dev", size: "large" }) \u2192 bumps the box to the large tier, applied live.'
3017
3805
  ].join("\n"),
3018
3806
  input: {
3019
- service_id: z14.union([z14.number().int().positive(), z14.string()]).describe("The box to resize \u2014 numeric id or publicId."),
3020
- size: z14.enum(SERVICE_PLANS).describe(
3807
+ service_id: z17.union([z17.number().int().positive(), z17.string()]).describe("The box to resize \u2014 numeric id or publicId."),
3808
+ size: z17.enum(SERVICE_PLANS).describe(
3021
3809
  'Target size tier (service catalog size, e.g. "standard", "large", "xlarge").'
3022
3810
  )
3023
3811
  },
@@ -3071,35 +3859,62 @@ defineTool({
3071
3859
  name: "list_templates",
3072
3860
  category: "services",
3073
3861
  description: [
3074
- "List the canonical Dev Box (AI dev environment) preset so an agent can see, without guessing, what a `create_standalone_dev_environment` / `create_dev_environment` actually provisions: the container image, the persistent /workspace volume (mount + default size), the OOM-safe size floor, and the companion database options.",
3862
+ "List the app quickstart templates the dashboard New-Service wizard offers, plus the separate Dev Box preset. Two kinds live in one list: a stack template (Next.js, Django, SvelteKit, Spring Boot, \u2026) is a pre-filled install/build/start command set you pair with a Git repo, and a one-click app (WordPress, Ghost, n8n, Uptime Kuma, Vaultwarden) is a prebuilt image that needs no repo at all.",
3075
3863
  "",
3076
- "When to use: before creating a Dev Box, to confirm the image, the default /workspace size, the minimum plan, or which companion engines can be attached \u2014 instead of hand-duplicating those constants.",
3864
+ 'When to use: whenever asked to deploy a known stack ("deploy my Next.js app", "put this Django project on HostStack"), before hand-writing a start command; whenever asked for a packaged app ("deploy WordPress", "I want a Ghost blog"), before reaching for a bare docker_image; and before creating a Dev Box, to confirm the image, /workspace size, plan floor, and companion engines instead of duplicating those constants.',
3077
3865
  "",
3078
- 'Returns: { templates: [{ id, name, image, volume: { name, mountPath, sizeGb }, minPlan, companions }] }. Today there is one preset ("dev-environment").',
3866
+ "Returns: { templates: [{ id, name, description, type, runtime?, installCommand?, buildCommand?, startCommand?, publishPath?, cronSchedule?, dockerImage?, port?, requiresTemplateId? }], devBox: { id, name, image, volume: { name, mountPath, sizeGb }, minPlan, createWith, companions, inBox } }. A template WITHOUT `dockerImage` is source-built \u2014 pass its commands to create_service with a `github_repo_id`. A template WITH `dockerImage` is flagged `requiresTemplateId` and must be created as create_service({ template_id, docker_image, port, \u2026 }): the volume, scratch dirs, uid, generated secrets and companion managed database it needs are attached server-side from the id, and the same image sent without it crash-loops on the read-only rootfs. The Dev Box is NOT in `templates`: it is created with create_standalone_dev_environment / create_dev_environment, never create_service. `companions` are SEPARATE managed databases you can attach; `inBox` is what the box already runs on its own (engines via `dev-services`, language runtimes via `dev-runtime`) \u2014 check it before concluding a box cannot run something.",
3079
3867
  "",
3080
- 'Example: list_templates() \u2192 { templates: [{ id: "dev-environment", image: "registry.hoststack.dev/hoststack/dev-env:latest", volume: { mountPath: "/workspace", sizeGb: 10 }, minPlan: "standard", companions: ["postgres","redis","meilisearch"] }] }'
3868
+ 'Example: list_templates() \u2192 { templates: [{ id: "nextjs-ssr", name: "Next.js", type: "web_service", runtime: "node", installCommand: "npm install", buildCommand: "npm run build", startCommand: "npm run start" }, { id: "wordpress", name: "WordPress", type: "web_service", dockerImage: "wordpress:php8.3-apache", port: 80, requiresTemplateId: true }, \u2026], devBox: { id: "dev-environment", image: "registry.hoststack.dev/hoststack/dev-env:latest", volume: { mountPath: "/workspace", sizeGb: 10 }, minPlan: "standard", companions: ["postgres","redis","meilisearch"] } }'
3081
3869
  ].join("\n"),
3082
3870
  input: {},
3083
3871
  handler: async () => {
3084
- const templates = [
3085
- {
3086
- id: "dev-environment",
3087
- name: "AI Dev Environment",
3088
- image: DEV_ENV_IMAGE,
3089
- volume: {
3090
- name: DEV_ENV_VOLUME.name,
3091
- mountPath: DEV_ENV_VOLUME.mountPath,
3092
- sizeGb: DEV_ENV_VOLUME.sizeGb
3872
+ const devBox = {
3873
+ id: "dev-environment",
3874
+ name: "AI Dev Environment",
3875
+ image: DEV_ENV_IMAGE,
3876
+ volume: {
3877
+ name: DEV_ENV_VOLUME.name,
3878
+ mountPath: DEV_ENV_VOLUME.mountPath,
3879
+ sizeGb: DEV_ENV_VOLUME.sizeGb
3880
+ },
3881
+ /** OOM-safe plan floor — a coding agent + build needs at least this. */
3882
+ minPlan: DEV_ENV_MIN_SIZE,
3883
+ /** Create it with these, never create_service. */
3884
+ createWith: ["create_standalone_dev_environment", "create_dev_environment"],
3885
+ /** Companion engines you can attach (fresh + empty), like local `make db-up`. */
3886
+ companions: ["postgres", "redis", "meilisearch"],
3887
+ /**
3888
+ * What the box can already run without attaching anything. Reported
3889
+ * so an agent picking a template can see that "it needs MySQL" or
3890
+ * "it's a PHP app" is already satisfied, instead of concluding the
3891
+ * box is unsuitable and reaching for Docker (there is no daemon).
3892
+ */
3893
+ inBox: {
3894
+ engines: {
3895
+ default: ["postgres", "redis", "meilisearch"],
3896
+ optIn: ["mysql", "mongodb"],
3897
+ start: "dev-services up [mysql|mongodb]"
3093
3898
  },
3094
- /** OOM-safe plan floor — a coding agent + build needs at least this. */
3095
- minPlan: DEV_ENV_MIN_SIZE,
3096
- /** Companion engines you can attach (fresh + empty), like local `make db-up`. */
3097
- companions: ["postgres", "redis", "meilisearch"]
3899
+ runtimes: {
3900
+ builtin: ["node", "bun", "python", "php"],
3901
+ // erlang is listed because elixir cannot run without it —
3902
+ // see DEV_BOX_INSIDE. Ordering matters for a caller acting
3903
+ // on this: add erlang, then elixir.
3904
+ onDemand: ["go", "java", "ruby", "rust", "erlang", "elixir", "dotnet"],
3905
+ install: "dev-runtime add <name>"
3906
+ }
3098
3907
  }
3099
- ];
3908
+ };
3909
+ const templates = MCP_APP_TEMPLATES.map(
3910
+ (t) => t.dockerImage ? { ...t, requiresTemplateId: true } : t
3911
+ );
3912
+ const byType = /* @__PURE__ */ new Map();
3913
+ for (const t of templates) byType.set(t.type, (byType.get(t.type) ?? 0) + 1);
3914
+ const breakdown = [...byType].map(([type, n]) => `${n} ${type}`).join(", ");
3100
3915
  return respond({
3101
- summary: `${templates.length} Dev Box template${templates.length === 1 ? "" : "s"} available (image ${DEV_ENV_IMAGE}, /workspace ${DEV_ENV_VOLUME.sizeGb} GB, floor "${DEV_ENV_MIN_SIZE}").`,
3102
- data: { templates }
3916
+ summary: `${templates.length} app templates (${breakdown}) \u2014 pick one by id, then either pass its commands to create_service with a github_repo_id, or, if it has a dockerImage, pass template_id + docker_image + port. Plus the Dev Box preset (image ${DEV_ENV_IMAGE}, /workspace ${DEV_ENV_VOLUME.sizeGb} GB, floor "${DEV_ENV_MIN_SIZE}"), which is created with create_standalone_dev_environment, not create_service.`,
3917
+ data: { templates, devBox }
3103
3918
  });
3104
3919
  }
3105
3920
  });
@@ -3111,7 +3926,9 @@ defineTool({
3111
3926
  "",
3112
3927
  "This makes a cloud Dev Box, NOT a project deploy environment (create_environment \u2192 Production / Staging / Preview). It is a workspace you code in, not a deployment target.",
3113
3928
  "",
3114
- 'Every Dev Box \u2014 with or without companions \u2014 also ships NATIVE Postgres 17, Redis and Meilisearch INSIDE the box, started with `dev-services up` (postgres :5432 as user "dev" with trust auth, redis :6379, meilisearch :7700). That is the no-Docker replacement for `make db-up` and is the right answer for local development inside the box; there is no Docker daemon available in there. The `companions` option is different \u2014 it attaches SEPARATE managed databases to the box\'s environment for when the box needs a real, persistent, backed-up datastore.',
3929
+ DEV_BOX_INSIDE,
3930
+ "",
3931
+ "Those in-box engines are the no-Docker replacement for a local `make db-up`, and are the right answer for development inside the box. The `companions` option is a DIFFERENT thing: it attaches SEPARATE managed databases to the box's environment, for when the box needs a real, persistent, backed-up datastore rather than a scratch one.",
3115
3932
  "",
3116
3933
  'When to use: "create a dev environment for <repo>", "spin me up a cloud dev box with a Postgres". Distinct from spin_up_dev_environment (which clones an EXISTING service) and create_dev_environment (a bare box in a chosen project).',
3117
3934
  "",
@@ -3122,6 +3939,7 @@ defineTool({
3122
3939
  " - clone_url (for url): an http(s) git clone URL.",
3123
3940
  " - branch (optional): branch to clone.",
3124
3941
  ' - databases (optional): companion services to attach \u2014 any of "postgres", "redis", "meilisearch".',
3942
+ " - machine (optional): run the box on one of the team's OWN enrolled machines (name or id, see list_machines) instead of HostStack compute. /workspace then lives on that machine's disk, so the box is reachable only while it is switched on, and any companion databases are created there too.",
3125
3943
  ' - plan (optional): box size. Defaults to "standard" (2 GB) \u2014 the OOM-safe floor (DEV_ENV_MIN_SIZE); a smaller plan is floored up to "standard" server-side.',
3126
3944
  " - agent_accounts (optional): bind specific saved agent logins by account id per provider. OMIT to auto-inherit the box owner's default logins (claude/codex/opencode), so `claude` is already authenticated on first boot \u2014 no manual login.",
3127
3945
  "",
@@ -3130,25 +3948,26 @@ defineTool({
3130
3948
  'Example: create_standalone_dev_environment({ name: "app-dev", source_kind: "github_repo", github_repo_id: 42, databases: ["postgres","redis"] })'
3131
3949
  ].join("\n"),
3132
3950
  input: {
3133
- name: z14.string().min(1).max(100).optional().describe(
3951
+ name: z17.string().min(1).max(100).optional().describe(
3134
3952
  'Dev Box name. Omit to have it named after the source (the repo name, or "dev-box" for a blank one), de-duplicated against existing boxes.'
3135
3953
  ),
3136
- source_kind: z14.enum(["github_repo", "url", "blank"]).describe("Where the code comes from."),
3137
- github_repo_id: z14.number().int().positive().optional().describe('Connected GitHub repo id (required when source_kind="github_repo").'),
3138
- clone_url: z14.string().url().optional().describe('http(s) git clone URL (required when source_kind="url").'),
3139
- branch: z14.string().min(1).max(255).optional().describe("Branch to clone."),
3140
- databases: z14.array(z14.enum(["postgres", "redis", "meilisearch"])).optional().describe("Companion services to attach (fresh + empty)."),
3141
- plan: z14.enum(SERVICE_PLANS).optional().describe(
3954
+ source_kind: z17.enum(["github_repo", "url", "blank"]).describe("Where the code comes from."),
3955
+ github_repo_id: z17.number().int().positive().optional().describe('Connected GitHub repo id (required when source_kind="github_repo").'),
3956
+ clone_url: z17.string().url().optional().describe('http(s) git clone URL (required when source_kind="url").'),
3957
+ branch: z17.string().min(1).max(255).optional().describe("Branch to clone."),
3958
+ databases: z17.array(z17.enum(["postgres", "redis", "meilisearch"])).optional().describe("Companion services to attach (fresh + empty)."),
3959
+ plan: z17.enum(SERVICE_PLANS).optional().describe(
3142
3960
  'Box size (default "standard" \u2014 2 GB; a smaller plan is floored to "standard").'
3143
3961
  ),
3144
- agent_accounts: z14.array(
3145
- z14.object({
3146
- provider: z14.enum(["claude", "codex", "opencode"]),
3147
- account_id: z14.number().int().positive()
3962
+ agent_accounts: z17.array(
3963
+ z17.object({
3964
+ provider: z17.enum(["claude", "codex", "opencode"]),
3965
+ account_id: z17.number().int().positive()
3148
3966
  })
3149
3967
  ).max(3).optional().describe(
3150
3968
  "Bind saved agent logins by account id per provider. Omit to inherit the box owner's default logins automatically."
3151
- )
3969
+ ),
3970
+ machine: machineInput
3152
3971
  },
3153
3972
  handler: async (args, ctx) => {
3154
3973
  const teamId = await ctx.resolveTeamId();
@@ -3180,9 +3999,11 @@ defineTool({
3180
3999
  } else {
3181
4000
  source = { kind: "blank" };
3182
4001
  }
4002
+ const machineId = args.machine !== void 0 ? await resolveMachineId(ctx, teamId, args.machine) : void 0;
3183
4003
  const input = {
3184
4004
  ...args.name ? { name: args.name } : {},
3185
4005
  source,
4006
+ ...machineId !== void 0 ? { machineId } : {},
3186
4007
  ...args.databases ? { databases: args.databases } : {},
3187
4008
  ...args.plan ? { plan: args.plan } : {},
3188
4009
  ...args.agent_accounts && args.agent_accounts.length > 0 ? {
@@ -3219,7 +4040,7 @@ defineTool({
3219
4040
  'Example: get_service({ service_id: "svc_abc" }) \u2192 { service: { type: "web", status: "running", \u2026 }, config: { healthCheckGracePeriodSec: 120, \u2026 } }'
3220
4041
  ].join("\n"),
3221
4042
  input: {
3222
- service_id: z14.string().describe("Service publicId (e.g. svc_abc123).")
4043
+ service_id: z17.string().describe("Service publicId (e.g. svc_abc123).")
3223
4044
  },
3224
4045
  handler: async (args, ctx) => {
3225
4046
  const teamId = await ctx.resolveTeamId();
@@ -3251,7 +4072,7 @@ defineTool({
3251
4072
  'Example: get_service_metrics({ service_id: "svc_abc" }) \u2192 { metrics: { cpu: 0.42, memory: 0.71, \u2026 } }'
3252
4073
  ].join("\n"),
3253
4074
  input: {
3254
- service_id: z14.string().describe("Service publicId.")
4075
+ service_id: z17.string().describe("Service publicId.")
3255
4076
  },
3256
4077
  handler: async (args, ctx) => {
3257
4078
  const teamId = await ctx.resolveTeamId();
@@ -3280,9 +4101,9 @@ defineTool({
3280
4101
  'Example: get_service_metrics_history({ service_id: "svc_abc", from: "-1h" }) \u2192 60-ish points for the last hour.'
3281
4102
  ].join("\n"),
3282
4103
  input: {
3283
- service_id: z14.string().describe("Service publicId."),
3284
- from: z14.string().optional().describe('ISO-8601 lower bound or relative offset (e.g. "-1h", "-2d").'),
3285
- to: z14.string().optional().describe("ISO-8601 upper bound; defaults to now.")
4104
+ service_id: z17.string().describe("Service publicId."),
4105
+ from: z17.string().optional().describe('ISO-8601 lower bound or relative offset (e.g. "-1h", "-2d").'),
4106
+ to: z17.string().optional().describe("ISO-8601 upper bound; defaults to now.")
3286
4107
  },
3287
4108
  handler: async (args, ctx) => {
3288
4109
  const teamId = await ctx.resolveTeamId();
@@ -3326,8 +4147,8 @@ defineTool({
3326
4147
  'Example: update_service({ service_id: "svc_abc", name: "api-prod" }) \u2192 { service: { name: "api-prod", \u2026 } }'
3327
4148
  ].join("\n"),
3328
4149
  input: {
3329
- service_id: z14.string().describe("Service publicId."),
3330
- name: z14.string().min(1).max(60).describe("New service name (1\u201360 chars).")
4150
+ service_id: z17.string().describe("Service publicId."),
4151
+ name: z17.string().min(1).max(60).describe("New service name (1\u201360 chars).")
3331
4152
  },
3332
4153
  handler: async (args, ctx) => {
3333
4154
  const teamId = await ctx.resolveTeamId();
@@ -3376,40 +4197,40 @@ defineTool({
3376
4197
  'Example: update_service_config({ service_id: "svc_abc", health_check_grace_period_sec: 180 }) \u2192 { config: { healthCheckGracePeriodSec: 180, \u2026 } }'
3377
4198
  ].join("\n"),
3378
4199
  input: {
3379
- service_id: z14.string().describe("Service publicId."),
3380
- install_command: z14.string().nullable().optional().describe("Install shell command. Null clears."),
3381
- build_command: z14.string().nullable().optional().describe("Build shell command. Null clears."),
3382
- start_command: z14.string().nullable().optional().describe("Start shell command. Null clears."),
3383
- branch: z14.string().optional().describe("Git branch to track."),
3384
- root_directory: z14.string().optional().describe("Build context root."),
3385
- dockerfile_path: z14.string().nullable().optional().describe("Path to Dockerfile relative to root. Null clears."),
3386
- auto_deploy: z14.boolean().optional().describe("Auto-deploy on push."),
3387
- health_check_path: z14.string().nullable().optional().describe('HTTP health-check path (e.g. "/health"). Null = TCP-only check.'),
3388
- health_check_enabled: z14.boolean().optional().describe("Toggle health checking on/off."),
3389
- health_check_interval: z14.number().int().min(5).max(300).optional().describe("How often the check runs, in seconds (5\u2013300)."),
3390
- health_check_timeout: z14.number().int().min(1).max(60).optional().describe("Single-attempt timeout in seconds (1\u201360)."),
3391
- health_check_grace_period_sec: z14.number().int().min(1).max(1800).optional().describe(
4200
+ service_id: z17.string().describe("Service publicId."),
4201
+ install_command: z17.string().nullable().optional().describe("Install shell command. Null clears."),
4202
+ build_command: z17.string().nullable().optional().describe("Build shell command. Null clears."),
4203
+ start_command: z17.string().nullable().optional().describe("Start shell command. Null clears."),
4204
+ branch: z17.string().optional().describe("Git branch to track."),
4205
+ root_directory: z17.string().optional().describe("Build context root."),
4206
+ dockerfile_path: z17.string().nullable().optional().describe("Path to Dockerfile relative to root. Null clears."),
4207
+ auto_deploy: z17.boolean().optional().describe("Auto-deploy on push."),
4208
+ health_check_path: z17.string().nullable().optional().describe('HTTP health-check path (e.g. "/health"). Null = TCP-only check.'),
4209
+ health_check_enabled: z17.boolean().optional().describe("Toggle health checking on/off."),
4210
+ health_check_interval: z17.number().int().min(5).max(300).optional().describe("How often the check runs, in seconds (5\u2013300)."),
4211
+ health_check_timeout: z17.number().int().min(1).max(60).optional().describe("Single-attempt timeout in seconds (1\u201360)."),
4212
+ health_check_grace_period_sec: z17.number().int().min(1).max(1800).optional().describe(
3392
4213
  "Startup grace period in seconds (1\u20131800). Raise this if the app needs more time to boot before health checks start counting failures."
3393
4214
  ),
3394
- memory_mb: z14.number().int().min(128).max(16384).optional().describe("Container memory cap in MB (128\u201316384)."),
3395
- cpu_shares: z14.number().int().min(128).max(4096).optional().describe("Relative CPU weight (128\u20134096)."),
3396
- disk_size_gb: z14.number().int().min(1).max(100).optional().describe("Ephemeral disk size in GB (1\u2013100)."),
3397
- port: z14.number().int().min(1).max(65535).optional().describe("Container port the platform forwards traffic to."),
3398
- protocol: z14.enum(["http", "tcp"]).optional().describe("Traffic protocol."),
3399
- restart_policy: z14.enum(["always", "on-failure", "no"]).optional().describe("Docker restart policy."),
3400
- deploy_strategy: z14.enum(["rolling", "recreate"]).optional().describe(
4215
+ memory_mb: z17.number().int().min(128).max(16384).optional().describe("Container memory cap in MB (128\u201316384)."),
4216
+ cpu_shares: z17.number().int().min(128).max(4096).optional().describe("Relative CPU weight (128\u20134096)."),
4217
+ disk_size_gb: z17.number().int().min(1).max(100).optional().describe("Ephemeral disk size in GB (1\u2013100)."),
4218
+ port: z17.number().int().min(1).max(65535).optional().describe("Container port the platform forwards traffic to."),
4219
+ protocol: z17.enum(["http", "tcp"]).optional().describe("Traffic protocol."),
4220
+ restart_policy: z17.enum(["always", "on-failure", "no"]).optional().describe("Docker restart policy."),
4221
+ deploy_strategy: z17.enum(["rolling", "recreate"]).optional().describe(
3401
4222
  'How a deploy replaces the container. "rolling" (default) = start new, wait for healthy, switch traffic, stop old (zero downtime). "recreate" = stop old first, then start new (brief outage) \u2014 required for a container holding an exclusive lock on a mounted volume, which cannot deploy at all under rolling.'
3402
4223
  ),
3403
- pre_deploy_command: z14.string().optional().describe("Shell command run before the new release accepts traffic."),
3404
- instance_count: z14.number().int().positive().max(50).optional().describe("Pin min and max instances to this value (1\u201350)."),
3405
- min_instances: z14.number().int().min(0).max(50).optional().describe("Autoscale lower bound. Use with max_instances for a range."),
3406
- max_instances: z14.number().int().min(1).max(50).optional().describe("Autoscale upper bound. Use with min_instances for a range."),
3407
- scale_cpu_threshold: z14.number().int().min(10).max(100).optional().describe("Autoscale CPU trigger percentage (10\u2013100)."),
3408
- scale_memory_threshold: z14.number().int().min(10).max(100).optional().describe("Autoscale memory trigger percentage (10\u2013100)."),
3409
- log_filter_rules: z14.array(
3410
- z14.object({
3411
- pattern: z14.string().min(1).max(200),
3412
- action: z14.enum(["drop", "downgrade"])
4224
+ pre_deploy_command: z17.string().optional().describe("Shell command run before the new release accepts traffic."),
4225
+ instance_count: z17.number().int().positive().max(50).optional().describe("Pin min and max instances to this value (1\u201350)."),
4226
+ min_instances: z17.number().int().min(0).max(50).optional().describe("Autoscale lower bound. Use with max_instances for a range."),
4227
+ max_instances: z17.number().int().min(1).max(50).optional().describe("Autoscale upper bound. Use with min_instances for a range."),
4228
+ scale_cpu_threshold: z17.number().int().min(10).max(100).optional().describe("Autoscale CPU trigger percentage (10\u2013100)."),
4229
+ scale_memory_threshold: z17.number().int().min(10).max(100).optional().describe("Autoscale memory trigger percentage (10\u2013100)."),
4230
+ log_filter_rules: z17.array(
4231
+ z17.object({
4232
+ pattern: z17.string().min(1).max(200),
4233
+ action: z17.enum(["drop", "downgrade"])
3413
4234
  })
3414
4235
  ).max(50).optional().describe(
3415
4236
  "Runtime-log filter rules. Empty array [] clears all rules. Each pattern is case-insensitive substring match against the message."
@@ -3506,7 +4327,7 @@ defineTool({
3506
4327
  'Example: suspend_service({ service_id: "svc_dev" }) \u2192 { ok: true }'
3507
4328
  ].join("\n"),
3508
4329
  input: {
3509
- service_id: z14.string().describe("Service publicId.")
4330
+ service_id: z17.string().describe("Service publicId.")
3510
4331
  },
3511
4332
  handler: async (args, ctx) => {
3512
4333
  const teamId = await ctx.resolveTeamId();
@@ -3530,7 +4351,7 @@ defineTool({
3530
4351
  'Example: resume_service({ service_id: "svc_dev" }) \u2192 { ok: true }'
3531
4352
  ].join("\n"),
3532
4353
  input: {
3533
- service_id: z14.string().describe("Service publicId.")
4354
+ service_id: z17.string().describe("Service publicId.")
3534
4355
  },
3535
4356
  handler: async (args, ctx) => {
3536
4357
  const teamId = await ctx.resolveTeamId();
@@ -3556,7 +4377,7 @@ defineTool({
3556
4377
  'Example: delete_service({ service_id: "svc_abandoned" }) \u2192 { ok: true }'
3557
4378
  ].join("\n"),
3558
4379
  input: {
3559
- service_id: z14.string().describe("Service publicId.")
4380
+ service_id: z17.string().describe("Service publicId.")
3560
4381
  },
3561
4382
  handler: async (args, ctx) => {
3562
4383
  const teamId = await ctx.resolveTeamId();
@@ -3593,16 +4414,16 @@ defineTool({
3593
4414
  ' - Just count error lines without fetching them: get_service_logs({ service_id: "svc_abc", level: "error", since: "-5m", count_only: true }) \u2192 { count: 47 }'
3594
4415
  ].join("\n"),
3595
4416
  input: {
3596
- service_id: z14.string().describe("Service publicId."),
3597
- lines: z14.number().int().positive().max(1e3).optional().describe("Tail size; default 200, hard cap 1000."),
3598
- since: z14.string().optional().describe('ISO-8601 timestamp or relative offset (e.g. "-5m", "-1h").'),
3599
- until: z14.string().optional().describe("ISO-8601 timestamp or relative offset upper bound."),
3600
- stream: z14.enum(["stdout", "stderr"]).optional().describe("Restrict to one stream."),
3601
- level: z14.enum(["stdout", "stderr", "trace", "debug", "info", "warn", "error", "fatal"]).optional().describe(
4417
+ service_id: z17.string().describe("Service publicId."),
4418
+ lines: z17.number().int().positive().max(1e3).optional().describe("Tail size; default 200, hard cap 1000."),
4419
+ since: z17.string().optional().describe('ISO-8601 timestamp or relative offset (e.g. "-5m", "-1h").'),
4420
+ until: z17.string().optional().describe("ISO-8601 timestamp or relative offset upper bound."),
4421
+ stream: z17.enum(["stdout", "stderr"]).optional().describe("Restrict to one stream."),
4422
+ level: z17.enum(["stdout", "stderr", "trace", "debug", "info", "warn", "error", "fatal"]).optional().describe(
3602
4423
  "Filter by structured JSON log level (pino/bunyan/severity). Falls back to a stream-alias hint for plain-text logs (info/debug\u2192stdout, warn/error/fatal\u2192stderr)."
3603
4424
  ),
3604
- search: z14.string().max(100).optional().describe("Case-insensitive substring filter."),
3605
- count_only: z14.boolean().optional().describe("When true, return only { count } \u2014 skips the log payload.")
4425
+ search: z17.string().max(100).optional().describe("Case-insensitive substring filter."),
4426
+ count_only: z17.boolean().optional().describe("When true, return only { count } \u2014 skips the log payload.")
3606
4427
  },
3607
4428
  handler: async (args, ctx) => {
3608
4429
  const teamId = await ctx.resolveTeamId();
@@ -3651,14 +4472,14 @@ defineTool({
3651
4472
  'Example: get_service_logs_bulk({ service_ids: ["svc_api", "svc_worker"], level: "error", since: "-15m", count_only: true }) \u2192 { results: { svc_api: { count: 0 }, svc_worker: { count: 12 } } }.'
3652
4473
  ].join("\n"),
3653
4474
  input: {
3654
- service_ids: z14.array(z14.string()).min(1).max(10).describe("Service publicIds (1\u201310). Hard cap 10 to bound parallel work."),
3655
- lines_per_service: z14.number().int().positive().max(500).optional().describe("Tail size per service; default 100, hard cap 500."),
3656
- since: z14.string().optional().describe('ISO-8601 timestamp or relative offset (e.g. "-5m", "-1h").'),
3657
- until: z14.string().optional().describe("ISO-8601 timestamp or relative offset upper bound."),
3658
- stream: z14.enum(["stdout", "stderr"]).optional().describe("Restrict to one stream."),
3659
- level: z14.enum(["stdout", "stderr", "trace", "debug", "info", "warn", "error", "fatal"]).optional().describe("Structured log level filter (same as get_service_logs)."),
3660
- search: z14.string().max(100).optional().describe("Case-insensitive substring filter."),
3661
- count_only: z14.boolean().optional().describe("When true, return only counts per service \u2014 skips the log payload.")
4475
+ service_ids: z17.array(z17.string()).min(1).max(10).describe("Service publicIds (1\u201310). Hard cap 10 to bound parallel work."),
4476
+ lines_per_service: z17.number().int().positive().max(500).optional().describe("Tail size per service; default 100, hard cap 500."),
4477
+ since: z17.string().optional().describe('ISO-8601 timestamp or relative offset (e.g. "-5m", "-1h").'),
4478
+ until: z17.string().optional().describe("ISO-8601 timestamp or relative offset upper bound."),
4479
+ stream: z17.enum(["stdout", "stderr"]).optional().describe("Restrict to one stream."),
4480
+ level: z17.enum(["stdout", "stderr", "trace", "debug", "info", "warn", "error", "fatal"]).optional().describe("Structured log level filter (same as get_service_logs)."),
4481
+ search: z17.string().max(100).optional().describe("Case-insensitive substring filter."),
4482
+ count_only: z17.boolean().optional().describe("When true, return only counts per service \u2014 skips the log payload.")
3662
4483
  },
3663
4484
  handler: async (args, ctx) => {
3664
4485
  const teamId = await ctx.resolveTeamId();
@@ -3703,8 +4524,117 @@ defineTool({
3703
4524
  }
3704
4525
  });
3705
4526
 
4527
+ // src/tools/uptime.ts
4528
+ import { z as z18 } from "zod";
4529
+ var STATUS_MEANING = [
4530
+ "Status vocabulary: `up` answering as expected \xB7 `down` failed the threshold and an alert is open \xB7 `unknown` not probed yet \xB7 `unresolvable` the service has no active domain to request \xB7 `paused` the service is not meant to be answering (suspended, mid-deploy, never deployed) OR it sleeps when idle and probing it would keep it awake."
4531
+ ].join("\n");
4532
+ defineTool({
4533
+ name: "get_uptime_check",
4534
+ category: "uptime",
4535
+ description: [
4536
+ "Read a service's uptime check \u2014 HostStack requesting the service's public URL on a schedule and alerting when it stops answering.",
4537
+ "",
4538
+ 'When to use: "is this service actually reachable", or before changing a check to see what it currently does. This is NOT the deploy-time health check: that one watches the container from inside the host and stops mattering once a deploy is live. This one runs from the control plane against the public URL, so it also catches DNS, TLS, edge and routing failures \u2014 and a service that accepts the connection and then answers nothing.',
4539
+ "",
4540
+ STATUS_MEANING,
4541
+ "",
4542
+ "Inputs: serviceId (required).",
4543
+ "",
4544
+ 'Returns: { check } or { check: null } when none is configured. The check carries path, method, expectedStatus, intervalSeconds, failureThreshold, status, consecutiveFailures, lastCheckedAt, lastStatusCode, lastLatencyMs, lastError, lastChangedAt (the "down since" timestamp).',
4545
+ "",
4546
+ "Example: get_uptime_check({ serviceId: 48 }) \u2192 { check: { path: '/healthz', status: 'down', consecutiveFailures: 5, lastError: 'No response within 10000ms', lastChangedAt: '2026-08-21T04:12:00Z' } }."
4547
+ ].join("\n"),
4548
+ input: { serviceId: z18.number().int().positive() },
4549
+ handler: async (args, ctx) => {
4550
+ const teamId = await ctx.resolveTeamId();
4551
+ const response = await ctx.api.get(
4552
+ `/api/services/${teamId}/${args.serviceId}/uptime-check`
4553
+ );
4554
+ if (response.check === null) {
4555
+ return respond({
4556
+ summary: "No uptime check on this service \u2014 nothing is watching its public URL.",
4557
+ data: { check: null }
4558
+ });
4559
+ }
4560
+ const check = shape(response.check);
4561
+ return respond({
4562
+ summary: `Uptime check is ${String(check["status"])}${check["lastError"] ? ` \u2014 ${String(check["lastError"])}` : ""}.`,
4563
+ data: { check }
4564
+ });
4565
+ }
4566
+ });
4567
+ defineTool({
4568
+ name: "set_uptime_check",
4569
+ category: "uptime",
4570
+ description: [
4571
+ "Create or update a service's uptime check.",
4572
+ "",
4573
+ "When to use: turning monitoring on for a service that has just gone live, or adjusting a check that is too noisy (raise failureThreshold) or too slow to notice (lower intervalSeconds).",
4574
+ "",
4575
+ 'Only service types with a public URL can be checked (web services and static sites). A worker, cron job or private service is refused with 400 \u2014 a check on one could only ever report "no domain to check", which reads as a broken feature rather than an inapplicable one.',
4576
+ "",
4577
+ "IMPORTANT: changing the shape of a check RESETS its accumulated state (status, consecutive failures, open alert). A check whose path or expected status just changed has not observed the new check failing, so carrying failures forward would alert about a condition that was never measured. Pass the full shape you want, not a partial edit of an unknown current state \u2014 read it with get_uptime_check first if that matters.",
4578
+ "",
4579
+ "`path` is a path, not a URL: the host comes from the service's primary domain at probe time, so moving the service to a new domain moves the check with it.",
4580
+ "",
4581
+ "Method is GET or HEAD only. A probe fires unattended every interval forever, so it has to be safe to repeat \u2014 a check that could POST would be a scheduled writer against the team's own API.",
4582
+ "",
4583
+ "Redirects are NOT followed: a 301 is an answer, and following one can walk the probe onto a marketing site and report a dead service as healthy. If a redirect is expected, set expectedStatus to it.",
4584
+ "",
4585
+ 'Inputs (all optional except serviceId): enabled, path (default "/"), method (GET|HEAD), expectedStatus (default 200), timeoutMs (1000\u201360000, default 10000 \u2014 this is what catches a hung server), intervalSeconds (30\u20133600, default 60), failureThreshold (1\u201310, default 3 \u2014 one failed request is usually a restart, not an outage).',
4586
+ "",
4587
+ "Returns: { check } with the saved check.",
4588
+ "",
4589
+ "Example: set_uptime_check({ serviceId: 48, path: '/healthz', intervalSeconds: 60, failureThreshold: 3 }) \u2192 { check: { status: 'unknown', \u2026 } }."
4590
+ ].join("\n"),
4591
+ input: {
4592
+ serviceId: z18.number().int().positive(),
4593
+ enabled: z18.boolean().optional(),
4594
+ path: z18.string().max(500).optional().describe('Must start with /. Default "/".'),
4595
+ method: z18.enum(["GET", "HEAD"]).optional(),
4596
+ expectedStatus: z18.number().int().min(100).max(599).optional(),
4597
+ timeoutMs: z18.number().int().min(1e3).max(6e4).optional(),
4598
+ intervalSeconds: z18.number().int().min(30).max(3600).optional(),
4599
+ failureThreshold: z18.number().int().min(1).max(10).optional()
4600
+ },
4601
+ handler: async (args, ctx) => {
4602
+ const teamId = await ctx.resolveTeamId();
4603
+ const { serviceId, ...body } = args;
4604
+ const response = await ctx.api.put(
4605
+ `/api/services/${teamId}/${serviceId}/uptime-check`,
4606
+ body
4607
+ );
4608
+ return respond({
4609
+ summary: `Uptime check saved. It will start reporting within a minute or two.`,
4610
+ data: { check: shape(response.check) }
4611
+ });
4612
+ }
4613
+ });
4614
+ defineTool({
4615
+ name: "delete_uptime_check",
4616
+ category: "uptime",
4617
+ description: [
4618
+ 'Stop checking a service. Any open "not answering" alert is left as it stands rather than being silently resolved \u2014 removing the monitor is not evidence the service came back.',
4619
+ "",
4620
+ "When to use: the service is being retired, or monitoring has moved somewhere else. To pause a check without losing its configuration, call set_uptime_check with enabled=false instead.",
4621
+ "",
4622
+ "Inputs: serviceId (required).",
4623
+ "",
4624
+ "Returns: { success: true }.",
4625
+ "",
4626
+ "Example: delete_uptime_check({ serviceId: 48 }) \u2192 { success: true }."
4627
+ ].join("\n"),
4628
+ input: { serviceId: z18.number().int().positive() },
4629
+ handler: async (args, ctx) => {
4630
+ const teamId = await ctx.resolveTeamId();
4631
+ await ctx.api.delete(`/api/services/${teamId}/${args.serviceId}/uptime-check`);
4632
+ return respond({ summary: "Uptime check removed. Nothing is watching this service now." });
4633
+ }
4634
+ });
4635
+
3706
4636
  // src/tools/volumes.ts
3707
- import { z as z15 } from "zod";
4637
+ import { z as z19 } from "zod";
3708
4638
  var MIN_VOLUME_SIZE_GB = 10;
3709
4639
  defineTool({
3710
4640
  name: "list_volumes",
@@ -3722,7 +4652,7 @@ defineTool({
3722
4652
  'Example: list_volumes({ service_id: "svc_abc" }) \u2192 { items: [{ name: "data", mountPath: "/var/data", sizeGb: 10, status: "active" }] }'
3723
4653
  ].join("\n"),
3724
4654
  input: {
3725
- service_id: z15.string().describe("Service publicId (e.g. svc_abc123).")
4655
+ service_id: z19.string().describe("Service publicId (e.g. svc_abc123).")
3726
4656
  },
3727
4657
  handler: async (args, ctx) => {
3728
4658
  const teamId = await ctx.resolveTeamId();
@@ -3751,15 +4681,15 @@ defineTool({
3751
4681
  'Example: create_volume({ service_id: "svc_abc", name: "data", mount_path: "/var/data", size_gb: 10 }) \u2192 { volume: { name: "data", mountPath: "/var/data", sizeGb: 10, status: "pending" } }'
3752
4682
  ].join("\n"),
3753
4683
  input: {
3754
- service_id: z15.string().describe("Service publicId."),
3755
- name: z15.string().min(1).max(64).regex(/^[a-z0-9-]+$/).describe("Volume name (lowercase alphanumeric + hyphens)."),
3756
- mount_path: z15.string().startsWith("/").max(500).describe("In-container mount path (absolute)."),
4684
+ service_id: z19.string().describe("Service publicId."),
4685
+ name: z19.string().min(1).max(64).regex(/^[a-z0-9-]+$/).describe("Volume name (lowercase alphanumeric + hyphens)."),
4686
+ mount_path: z19.string().startsWith("/").max(500).describe("In-container mount path (absolute)."),
3757
4687
  // 10 GB is the real floor: the block-storage backend rejects anything
3758
4688
  // smaller. Advertising 1 GB here (and defaulting to it) meant taking the
3759
4689
  // defaults produced a volume that provisioned with `Hetzner API error:
3760
4690
  // 422` on the NEXT deploy, with nothing tying the failure back to the
3761
4691
  // size. Reject it at the call instead.
3762
- size_gb: z15.number().int().min(MIN_VOLUME_SIZE_GB).max(100).optional().describe(
4692
+ size_gb: z19.number().int().min(MIN_VOLUME_SIZE_GB).max(100).optional().describe(
3763
4693
  `Disk size in GB (minimum ${MIN_VOLUME_SIZE_GB}, default ${MIN_VOLUME_SIZE_GB}, max 100 via MCP).`
3764
4694
  )
3765
4695
  },
@@ -3797,10 +4727,10 @@ defineTool({
3797
4727
  'Example: update_volume({ service_id: "svc_abc", volume_id: "vol_xyz", size_gb: 20 }) \u2192 { volume: { sizeGb: 20, \u2026 } }'
3798
4728
  ].join("\n"),
3799
4729
  input: {
3800
- service_id: z15.string().describe("Service publicId."),
3801
- volume_id: z15.string().describe("Volume publicId (e.g. vol_\u2026)."),
3802
- mount_path: z15.string().startsWith("/").max(500).optional().describe("New mount path."),
3803
- size_gb: z15.number().int().min(MIN_VOLUME_SIZE_GB).max(100).optional().describe(`New size in GB (minimum ${MIN_VOLUME_SIZE_GB}, grow-only).`)
4730
+ service_id: z19.string().describe("Service publicId."),
4731
+ volume_id: z19.string().describe("Volume publicId (e.g. vol_\u2026)."),
4732
+ mount_path: z19.string().startsWith("/").max(500).optional().describe("New mount path."),
4733
+ size_gb: z19.number().int().min(MIN_VOLUME_SIZE_GB).max(100).optional().describe(`New size in GB (minimum ${MIN_VOLUME_SIZE_GB}, grow-only).`)
3804
4734
  },
3805
4735
  handler: async (args, ctx) => {
3806
4736
  const teamId = await ctx.resolveTeamId();
@@ -3838,8 +4768,8 @@ defineTool({
3838
4768
  'Example: delete_volume({ service_id: "svc_abc", volume_id: "vol_xyz" }) \u2192 { ok: true }'
3839
4769
  ].join("\n"),
3840
4770
  input: {
3841
- service_id: z15.string().describe("Service publicId."),
3842
- volume_id: z15.string().describe("Volume publicId.")
4771
+ service_id: z19.string().describe("Service publicId."),
4772
+ volume_id: z19.string().describe("Volume publicId.")
3843
4773
  },
3844
4774
  handler: async (args, ctx) => {
3845
4775
  const teamId = await ctx.resolveTeamId();