@zimmerstack/connect 0.6.0 → 0.9.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.
Files changed (51) hide show
  1. package/AGENTS.md +269 -15
  2. package/README.md +451 -18
  3. package/dist/cjs/client.d.ts +503 -13
  4. package/dist/cjs/client.js +743 -45
  5. package/dist/cjs/doctor.d.ts +86 -0
  6. package/dist/cjs/doctor.js +689 -0
  7. package/dist/cjs/errors.d.ts +6 -2
  8. package/dist/cjs/errors.js +7 -2
  9. package/dist/cjs/generated.d.ts +2921 -207
  10. package/dist/cjs/generated.js +222 -8
  11. package/dist/cjs/grid.d.ts +6 -1
  12. package/dist/cjs/grid.js +8 -0
  13. package/dist/cjs/index.d.ts +14 -5
  14. package/dist/cjs/index.js +41 -1
  15. package/dist/cjs/key.d.ts +39 -0
  16. package/dist/cjs/key.js +85 -0
  17. package/dist/cjs/money.d.ts +81 -0
  18. package/dist/cjs/money.js +172 -0
  19. package/dist/cjs/notices.d.ts +44 -0
  20. package/dist/cjs/notices.js +64 -0
  21. package/dist/cjs/shownOnce.d.ts +42 -0
  22. package/dist/cjs/shownOnce.js +83 -0
  23. package/dist/cjs/webhooks.d.ts +182 -3
  24. package/dist/cjs/webhooks.js +75 -1
  25. package/dist/esm/client.d.ts +503 -13
  26. package/dist/esm/client.js +741 -45
  27. package/dist/esm/doctor.d.ts +86 -0
  28. package/dist/esm/doctor.js +685 -0
  29. package/dist/esm/errors.d.ts +6 -2
  30. package/dist/esm/errors.js +7 -2
  31. package/dist/esm/generated.d.ts +2921 -207
  32. package/dist/esm/generated.js +221 -7
  33. package/dist/esm/grid.d.ts +6 -1
  34. package/dist/esm/grid.js +7 -0
  35. package/dist/esm/index.d.ts +14 -5
  36. package/dist/esm/index.js +8 -3
  37. package/dist/esm/key.d.ts +39 -0
  38. package/dist/esm/key.js +81 -0
  39. package/dist/esm/mcp/cli.js +88 -9
  40. package/dist/esm/mcp/reference.generated.js +4464 -974
  41. package/dist/esm/mcp/server.d.ts +14 -6
  42. package/dist/esm/mcp/server.js +451 -25
  43. package/dist/esm/money.d.ts +81 -0
  44. package/dist/esm/money.js +161 -0
  45. package/dist/esm/notices.d.ts +44 -0
  46. package/dist/esm/notices.js +56 -0
  47. package/dist/esm/shownOnce.d.ts +42 -0
  48. package/dist/esm/shownOnce.js +77 -0
  49. package/dist/esm/webhooks.d.ts +182 -3
  50. package/dist/esm/webhooks.js +69 -0
  51. package/package.json +1 -1
@@ -1,13 +1,21 @@
1
1
  /**
2
- * The package's MCP server: four tools a developer's coding agent can call while it builds on the
2
+ * The package's MCP server: the tools a developer's coding agent can call while it builds on the
3
3
  * Connect API. It runs on the developer's own machine, over stdin and stdout (src/mcp/cli.ts).
4
4
  *
5
- * zimmerstack_rules the rules for building on the API (this package's AGENTS.md)
6
- * zimmerstack_reference look up an operation, a type, a topic, or search, from the contract
7
- * zimmerstack_sandbox_read one read on the project's SANDBOX
8
- * zimmerstack_sandbox_write one write on the project's SANDBOX
5
+ * zimmerstack_rules the rules for building on the API (this package's AGENTS.md)
6
+ * zimmerstack_reference look up an operation, a type, a topic, or search, from the contract
7
+ * zimmerstack_sandbox_read one read on the project's SANDBOX
8
+ * zimmerstack_sandbox_write one write on the project's SANDBOX
9
+ * zimmerstack_doctor the doctor's checks on the sandbox key: what is wrong, and what to do
10
+ * zimmerstack_sandbox_limits every budget the sandbox key sits under, and how full each is
11
+ * zimmerstack_sandbox_events the sandbox's ordered event log, from a sequence
12
+ * zimmerstack_sandbox_simulate make one real event of any type on the sandbox
13
+ * zimmerstack_sandbox_explain one night of one room type on the sandbox, explained
14
+ * zimmerstack_sandbox_dry_run what a write to the sandbox would do, with nothing written
15
+ * zimmerstack_sandbox_fault make the sandbox's pretend channel refuse, throttle or go down; end it; read it
16
+ * zimmerstack_sandbox_close close a room type on the sandbox everywhere, or reopen it
9
17
  *
10
- * The two sandbox tools use a zsk_test_ key and nothing else: a sandbox is a copy of a hotel's rooms
18
+ * Every tool that calls the API uses a zsk_test_ key and nothing else: a sandbox is a copy of a hotel's rooms
11
19
  * and plans that no booking site ever sees. A live key is refused before anything is sent, so an agent
12
20
  * can never change a real hotel through this server, whatever it is asked. Every call goes through the
13
21
  * package's own client, so the pacing, retry and idempotency rules hold here too.
@@ -1,6 +1,9 @@
1
- import { ZimmerStack } from "../client.js";
1
+ import { ZimmerStack, aboutHowLong } from "../client.js";
2
+ import { diagnose, formatDoctorReport } from "../doctor.js";
2
3
  import { ZimmerStackError, ZimmerStackUsageError } from "../errors.js";
4
+ import { addDays } from "../grid.js";
3
5
  import { OPERATIONS, SDK_VERSION } from "../generated.js";
6
+ import { noticesOf, noticesOmittedFrom } from "../notices.js";
4
7
  import { RULES } from "./reference.generated.js";
5
8
  import { TOPICS, describeOperation, describeTopic, describeType, findOperation, referenceIndex, searchReference } from "./reference.js";
6
9
  /** The protocol revisions this server speaks, newest first. A client asking for another gets the newest. */
@@ -11,8 +14,30 @@ const WRITES = Object.keys(OPERATIONS).filter((key) => !key.startsWith("GET "));
11
14
  const INSTRUCTIONS = "Tools for building on the ZimmerStack Connect API, a hotel's channel manager: what is written through it reaches booking sites such as Booking.com within a minute. " +
12
15
  "Before writing code that calls ZimmerStack, call zimmerstack_rules once and follow it. " +
13
16
  "Look up routes, fields, limits and error codes with zimmerstack_reference instead of guessing: if it is not there, it does not exist. " +
14
- "zimmerstack_sandbox_read and zimmerstack_sandbox_write call the API with the project's sandbox key (zsk_test_…) only. Nothing they send reaches a booking site, and they refuse a live key.";
17
+ "zimmerstack_sandbox_read and zimmerstack_sandbox_write call the API with the project's sandbox key (zsk_test_…) only. Nothing they send reaches a booking site, and they refuse a live key. " +
18
+ "When a call is refused or a webhook does not arrive, call zimmerstack_doctor before guessing. zimmerstack_sandbox_simulate makes a real booking or channel event on the sandbox, and zimmerstack_sandbox_events reads the ordered log your code should keep its place in. " +
19
+ "Before writing code that sends prices, room counts or stay rules, try the body with zimmerstack_sandbox_dry_run and read its notices: they say what the write would NOT do. zimmerstack_sandbox_explain tells one night's whole story, zimmerstack_sandbox_close closes or reopens a room type everywhere, and zimmerstack_sandbox_fault makes the sandbox's pretend channel fail so the code that handles a refused value or an outage can be tried.";
15
20
  const objectOf = (description) => ({ type: "object", description, additionalProperties: true });
21
+ /** The events a sandbox can make, as zimmerstack_sandbox_simulate names them. */
22
+ const SIMULATIONS = [
23
+ "channel.booking.created",
24
+ "channel.booking.modified",
25
+ "channel.booking.cancelled",
26
+ "channel.booking.cancelled (no booking before it)",
27
+ "direct.booking.created",
28
+ "direct.booking.modified (no-show)",
29
+ "direct.booking.modified (no-show undone)",
30
+ "direct.booking.cancelled",
31
+ "channel.sync.alert",
32
+ "channel.sync.recovered",
33
+ ];
34
+ const PROBLEMS = ["rate_error", "sync_error", "disconnect_channel", "settings_changed", "inventory_out_of_sync"];
35
+ /** What zimmerstack_sandbox_dry_run can preview. */
36
+ const DRY_RUNS = ["availability", "rates", "restrictions", "close", "reopen"];
37
+ const FAULT_ACTIONS = ["set", "clear", "read"];
38
+ const FAULT_KINDS = ["refuse", "throttle", "outage"];
39
+ const DAYS = ["mo", "tu", "we", "th", "fr", "sa", "su"];
40
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
16
41
  const TOOLS = [
17
42
  {
18
43
  name: "zimmerstack_rules",
@@ -71,6 +96,137 @@ const TOOLS = [
71
96
  },
72
97
  annotations: { title: "ZimmerStack sandbox: write", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
73
98
  },
99
+ {
100
+ name: "zimmerstack_doctor",
101
+ title: "ZimmerStack: the doctor",
102
+ description: "Diagnose the project's ZimmerStack integration on its SANDBOX key, reading only: is the key the right shape and does it answer, which hotels and scopes it reaches, every budget and how full it is, the last day's refused requests grouped by reason, the webhook endpoints and their last failures, and sync and drift. Each finding is a plain sentence with what to do. Call it first when a call is refused or a webhook does not arrive. Refuses a live key; the developer runs `npx @zimmerstack/connect doctor` themselves for one.",
103
+ inputSchema: {
104
+ type: "object",
105
+ properties: { propertyId: { type: "integer", minimum: 1, description: "A software vendor's company key only: look at this sandbox (default: the first five)." } },
106
+ additionalProperties: false,
107
+ },
108
+ annotations: { title: "ZimmerStack: the doctor", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
109
+ },
110
+ {
111
+ name: "zimmerstack_sandbox_limits",
112
+ title: "ZimmerStack sandbox: budgets",
113
+ description: "Every budget the sandbox key sits under (GET /limits), one line each: how much is used, how much is left and when it has room again, plus where the integration stands and the most one request may carry. A sandbox has the same budgets as a live hotel, so this is the size a real job must fit in. Reading spends nothing but one request.",
114
+ inputSchema: {
115
+ type: "object",
116
+ properties: { propertyId: { type: "integer", minimum: 1, description: "A software vendor's company key only: the sandbox whose budgets to read." } },
117
+ additionalProperties: false,
118
+ },
119
+ annotations: { title: "ZimmerStack sandbox: budgets", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
120
+ },
121
+ {
122
+ name: "zimmerstack_sandbox_events",
123
+ title: "ZimmerStack sandbox: the event log",
124
+ description: "Read the sandbox's ordered event log (GET /events): every event a webhook carries for it, once, oldest first, each with its sequence. Pass after = the last sequence already seen (0 reads from the beginning of what is kept). Use it to see the exact body your webhook receiver will get, and to check that the code which keeps its place in the log is right. The answer says the next after to ask with.",
125
+ inputSchema: {
126
+ type: "object",
127
+ properties: {
128
+ after: { type: "integer", minimum: 0, description: "The last sequence already applied; default 0." },
129
+ limit: { type: "integer", minimum: 1, maximum: 100, description: "How many events at most; default 20." },
130
+ propertyId: { type: "integer", minimum: 1, description: "A software vendor's company key only: the sandbox whose log to read." },
131
+ },
132
+ additionalProperties: false,
133
+ },
134
+ annotations: { title: "ZimmerStack sandbox: the event log", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
135
+ },
136
+ {
137
+ name: "zimmerstack_sandbox_simulate",
138
+ title: "ZimmerStack sandbox: make an event",
139
+ description: "Make one REAL event of any type on the sandbox, so the project's webhook receiver and its event-log reader can be tried end to end: an OTA booking arriving, changing or being cancelled, a cancellation with no booking before it, a booking on the hotel's own website, its no-show and the undo, its cancellation, a channel problem and its end. The sandbox's availability moves as it would on a live hotel, the signed webhook goes to every endpoint registered on the sandbox, and the event is in the log with a sequence. Nothing reaches a booking site. A booking event that needs an earlier booking uses the newest suitable one unless bookingId names one; a new booking uses the sandbox's first room type, 30 days from today, unless told otherwise.",
140
+ inputSchema: {
141
+ type: "object",
142
+ properties: {
143
+ event: { type: "string", enum: SIMULATIONS, description: "Which event to make." },
144
+ bookingId: { type: "integer", minimum: 1, description: "The simulated booking to change, cancel or mark a no-show (from an earlier call). Default: the newest suitable one." },
145
+ roomTypeId: { type: "integer", minimum: 1, description: "For a new booking: the room type. Default: the sandbox's first." },
146
+ checkIn: { type: "string", description: "For a new booking: arrival, YYYY-MM-DD. Default: 30 days from today." },
147
+ nights: { type: "integer", minimum: 1, maximum: 30, description: "For a new booking: its length (default 2). For channel.booking.modified: the new length (default: one night longer)." },
148
+ otaName: { type: "string", enum: ["Booking.com", "Expedia", "Agoda", "Airbnb", "MakeMyTrip", "Goibibo"], description: "For a new OTA booking: the channel it pretends to arrive from. Default Booking.com." },
149
+ problem: { type: "string", enum: PROBLEMS, description: "For channel.sync.alert: which problem (default rate_error). For channel.sync.recovered: which problem to end (default: the newest open one)." },
150
+ propertyId: { type: "integer", minimum: 1, description: "A software vendor's company key only: the sandbox to act on." },
151
+ },
152
+ required: ["event"],
153
+ additionalProperties: false,
154
+ },
155
+ annotations: { title: "ZimmerStack sandbox: make an event", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
156
+ },
157
+ {
158
+ name: "zimmerstack_sandbox_explain",
159
+ title: "ZimmerStack sandbox: explain a night",
160
+ description: "Explain one night of one room type on the sandbox (GET /explain): what the software last sent, what ZimmerStack's record holds and who set it, what the channel manager was last seen holding, every send still on file and how it ended, a held value in the channel manager's words, the rules in force, and the same in plain sentences. Reads only. Use it after a write to see what the write did, and to learn the answer's shape before writing code that reads it. A sandbox has no booking site, so the parts about which connections sell a plan read unknown there.",
161
+ inputSchema: {
162
+ type: "object",
163
+ properties: {
164
+ roomTypeId: { type: "integer", minimum: 1, description: "The room type (GET /catalog). Default: the sandbox's first." },
165
+ date: { type: "string", description: "The night, YYYY-MM-DD, from 30 days back to the last writable night. Default: 30 days from today." },
166
+ ratePlanId: { type: "integer", minimum: 1, description: "One rate plan of that room type; leave out for every plan of the room." },
167
+ propertyId: { type: "integer", minimum: 1, description: "A software vendor's company key only: the sandbox to read." },
168
+ },
169
+ additionalProperties: false,
170
+ },
171
+ annotations: { title: "ZimmerStack sandbox: explain a night", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
172
+ },
173
+ {
174
+ name: "zimmerstack_sandbox_dry_run",
175
+ title: "ZimmerStack sandbox: dry-run a write",
176
+ description: 'See what a write to the sandbox WOULD do, with nothing written, queued or sent: the verdict (would-write, nothing-to-write, or would-refuse with the refusal a real write would get now), the ranges that would change, the ones already held, and the notices, which say what the write would not do (a stop-sell on one rate plan leaves the room on sale through its other plans; a room count of 0 is not a stop-sell). write: availability, rates or restrictions with updates (the same updates the real write takes; for rates the currency is filled in), or close or reopen with body ({ roomTypeId, dateFrom, dateTo }). A dry run spends the minute budgets like the write it previews, so it is not a way to read the calendar.',
177
+ inputSchema: {
178
+ type: "object",
179
+ properties: {
180
+ write: { type: "string", enum: DRY_RUNS, description: "Which write to preview." },
181
+ updates: { type: "array", items: { type: "object", additionalProperties: true }, description: "For availability, rates and restrictions: the updates, exactly as PUT /availability, PUT /rates or PUT /restrictions take them (zimmerstack_reference shows each)." },
182
+ body: objectOf('For close and reopen: { "roomTypeId": 412, "dateFrom": "2026-12-30", "dateTo": "2027-01-02" }, optionally "days", and for reopen "available".'),
183
+ propertyId: { type: "integer", minimum: 1, description: "A software vendor's company key only: the sandbox to preview on." },
184
+ },
185
+ required: ["write"],
186
+ additionalProperties: false,
187
+ },
188
+ // It writes nothing, but it is sent as the write it previews and spends that write's minute budgets.
189
+ annotations: { title: "ZimmerStack sandbox: dry-run a write", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
190
+ },
191
+ {
192
+ name: "zimmerstack_sandbox_fault",
193
+ title: "ZimmerStack sandbox: make the pretend channel fail",
194
+ description: 'Make the sandbox\'s pretend channel misbehave, so the project\'s code can be tried against a bad day. action "set" with kind: refuse (the next values nights of prices or stay rules are refused, with message as the channel manager\'s words: the nights are held, the batch reads failed, channel.sync.alert value_refused is sent), throttle ("too many requests" for minutes: batches wait and land by themselves) or outage (no answer for minutes: after five failed attempts, one a minute, channel.sync.alert rates_out_of_sync, then channel.sync.recovered when it ends). action "clear" ends it; action "read" shows the one in force. One fault at a time. Prices and stay rules only: room counts land as before. The answer lists what to do next and what the software should then see.',
195
+ inputSchema: {
196
+ type: "object",
197
+ properties: {
198
+ action: { type: "string", enum: FAULT_ACTIONS, description: "set a fault, clear it, or read the one in force." },
199
+ kind: { type: "string", enum: FAULT_KINDS, description: "For set: which fault." },
200
+ values: { type: "integer", minimum: 1, maximum: 500, description: "refuse only: how many nights (rate plan × night) to refuse. Default 1." },
201
+ minutes: { type: "integer", minimum: 1, maximum: 60, description: "throttle and outage only: how long. Default 5 for a throttle, 10 for an outage." },
202
+ message: { type: "string", description: "refuse only: the pretend channel's words for the refusal." },
203
+ propertyId: { type: "integer", minimum: 1, description: "A software vendor's company key only: the sandbox to act on." },
204
+ },
205
+ required: ["action"],
206
+ additionalProperties: false,
207
+ },
208
+ annotations: { title: "ZimmerStack sandbox: make the pretend channel fail", readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
209
+ },
210
+ {
211
+ name: "zimmerstack_sandbox_close",
212
+ title: "ZimmerStack sandbox: close or reopen a room type",
213
+ description: 'Close one room type of the sandbox on a range of nights everywhere (action "close": its room count goes to 0 and stop-sell is switched on for every one of its rate plans), or undo exactly that (action "reopen": the stop-sell is lifted on the plans the close switched on and each night gets back the count it held, or available if given). The answer says what was changed, what was already so, and notReached: what the action could not reach. To see what it would do without doing it, use zimmerstack_sandbox_dry_run with write close or reopen.',
214
+ inputSchema: {
215
+ type: "object",
216
+ properties: {
217
+ action: { type: "string", enum: ["close", "reopen"], description: "close the room type, or reopen what a close closed." },
218
+ roomTypeId: { type: "integer", minimum: 1, description: "The room type (GET /catalog). Default: the sandbox's first." },
219
+ dateFrom: { type: "string", description: "The first night, YYYY-MM-DD." },
220
+ dateTo: { type: "string", description: "The last night, YYYY-MM-DD." },
221
+ days: { type: "array", items: { type: "string", enum: DAYS }, description: "Only these weekdays of the range; leave out for every night." },
222
+ available: { type: "integer", minimum: 0, description: "reopen only: the count to put on sale on each reopened night. Leave out to put back the count each night held before the close." },
223
+ propertyId: { type: "integer", minimum: 1, description: "A software vendor's company key only: the sandbox to act on." },
224
+ },
225
+ required: ["action", "dateFrom", "dateTo"],
226
+ additionalProperties: false,
227
+ },
228
+ annotations: { title: "ZimmerStack sandbox: close or reopen a room type", readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
229
+ },
74
230
  ];
75
231
  const say = (text) => ({ content: [{ type: "text", text: text.length > MAX_TEXT ? `${text.slice(0, MAX_TEXT)}\n\n(cut at ${MAX_TEXT.toLocaleString("en-US")} characters: ask for a shorter window, a single id or a narrower lookup)` : text }] });
76
232
  const refuse = (text) => ({ ...say(text), isError: true });
@@ -97,6 +253,277 @@ export function createMcpServer(options = {}) {
97
253
  client = new ZimmerStack({ apiKey: key, fetch: options.fetch, baseUrl: options.baseUrl, timeoutMs: 20_000, maxRetries: 1, maxWaitSeconds: 15 });
98
254
  return client;
99
255
  }
256
+ /** The sandbox client for one tool call: the hotel a company key names, after the same checks every call makes. */
257
+ function sandboxFor(args) {
258
+ if (args.propertyId !== undefined && (!Number.isInteger(args.propertyId) || args.propertyId <= 0))
259
+ throw new BadArguments("propertyId must be a property's numeric id.");
260
+ const base = sandbox();
261
+ return typeof args.propertyId === "number" ? base.forProperty(args.propertyId) : base;
262
+ }
263
+ /** What the API refused, as words for the agent. Never the key. */
264
+ function refused(what, err) {
265
+ const lines = [`${what} was refused: ${err.code}${err.status ? ` (${err.status})` : ""}`, err.message];
266
+ if (err.scope)
267
+ lines.push(`Budget: ${err.scope}`);
268
+ if (err.details !== undefined)
269
+ lines.push(`Details: ${JSON.stringify(err.details)}`);
270
+ lines.push(err.retryable
271
+ ? `It may pass later${err.retryAfterSeconds ? `: in ${err.retryAfterSeconds} seconds` : ""}. The client has already retried what was worth waiting for.`
272
+ : "This is a verdict on the request: fix it; sending it again will be refused again. zimmerstack_reference explains the code (search for it).");
273
+ return refuse(lines.join("\n"));
274
+ }
275
+ /** Run one tool's calls on the sandbox; a refusal of the API becomes the tool's answer. */
276
+ async function onSandbox(what, run) {
277
+ try {
278
+ return await run();
279
+ }
280
+ catch (err) {
281
+ if (err instanceof ZimmerStackUsageError)
282
+ throw new BadArguments(`${err.message}. Nothing was sent.`);
283
+ if (!(err instanceof ZimmerStackError))
284
+ throw err;
285
+ return refused(what, err);
286
+ }
287
+ }
288
+ async function doctor(args) {
289
+ if (args.propertyId !== undefined && (!Number.isInteger(args.propertyId) || args.propertyId <= 0))
290
+ throw new BadArguments("propertyId must be a property's numeric id.");
291
+ sandbox(); // the same refusals as every sandbox call: no key, a live key, something that is no key
292
+ const report = await diagnose({ apiKey: key, fetch: options.fetch, baseUrl: options.baseUrl, propertyId: args.propertyId });
293
+ // A finding that needs attention is the tool doing its job, not a failed tool call.
294
+ return say(formatDoctorReport(report));
295
+ }
296
+ async function limits(args) {
297
+ const zs = sandboxFor(args);
298
+ return onSandbox("GET /limits", async () => {
299
+ const now = await zs.limits.get();
300
+ const line = (b) => {
301
+ const fill = b.used === null ? "not counted on this route (its quota still holds)" : `${b.used.toLocaleString("en-US")} used, ${(b.remaining ?? 0).toLocaleString("en-US")} left of ${b.quota.toLocaleString("en-US")} ${b.unit}`;
302
+ const frees = b.remaining === 0 && b.resetSeconds ? `; room again in ${aboutHowLong(b.resetSeconds * 1000)}` : "";
303
+ return `- ${b.scope}: ${fill}${frees}. ${b.window}, per ${b.per}.`;
304
+ };
305
+ const lines = [
306
+ `Budgets of the sandbox key (${now.key.kind} key${now.key.propertyId ? `, hotel #${now.key.propertyId}` : ""}), read ${now.asOf}:`,
307
+ "",
308
+ "Per minute and per rolling day:",
309
+ ...now.budgets.map(line),
310
+ ];
311
+ if (now.shield) {
312
+ lines.push("", `Per hour and per day (changed cells and structure), standing ${now.shield.standing.level}${now.shield.standing.reason ? `: ${now.shield.standing.reason}` : ""}:`, ...now.shield.budgets.map(line));
313
+ }
314
+ else
315
+ lines.push("", "A company key that names no hotel has no hourly and daily budgets to show: pass propertyId.");
316
+ lines.push("", "The most one request may carry, and the most of a thing that may exist:", ...now.caps.map((c) => `- ${c.scope}: ${c.quota.toLocaleString("en-US")} ${c.unit} per ${c.per}.`), "", now.note);
317
+ return say(lines.join("\n"));
318
+ });
319
+ }
320
+ async function events(args) {
321
+ for (const name of ["after", "limit"])
322
+ if (args[name] !== undefined && (!Number.isInteger(args[name]) || args[name] < 0))
323
+ throw new BadArguments(`${name} must be a whole number.`);
324
+ const zs = sandboxFor(args);
325
+ const after = args.after ?? 0;
326
+ return onSandbox("GET /events", async () => {
327
+ const page = await zs.events.list({ after, limit: Math.min(100, Math.max(1, args.limit ?? 20)) });
328
+ const head = [
329
+ page.items.length === 0 ? `No event after sequence ${after}.` : `${page.items.length} event${page.items.length === 1 ? "" : "s"} after sequence ${after}: ${page.items.map((e) => `#${e.sequence} ${e.type}`).join(", ")}.`,
330
+ `Your place is now ${page.nextAfter}: ask again with after = ${page.nextAfter}${page.more ? " (more events follow now)" : " when a webhook arrives or on a schedule"}.`,
331
+ ];
332
+ if (page.earliestSequence !== null && page.earliestSequence > after + 1) {
333
+ head.push(`The log now begins at sequence ${page.earliestSequence} (events are kept ${page.retentionDays} days): what came before is no longer here. Code that meets this reads the bookings again (zs.channelBookings.all, zs.directBookings.all), then carries on.`);
334
+ }
335
+ return say(`${head.join("\n")}\n\n${JSON.stringify(page.items, null, 2)}`);
336
+ });
337
+ }
338
+ async function simulate(args) {
339
+ const event = args.event;
340
+ if (typeof event !== "string" || !SIMULATIONS.includes(event))
341
+ throw new BadArguments(`event must be one of: ${SIMULATIONS.join("; ")}.`);
342
+ for (const name of ["bookingId", "roomTypeId", "nights"])
343
+ if (args[name] !== undefined && (!Number.isInteger(args[name]) || args[name] <= 0))
344
+ throw new BadArguments(`${name} must be a whole number above 0.`);
345
+ if (args.checkIn !== undefined && (typeof args.checkIn !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(args.checkIn)))
346
+ throw new BadArguments("checkIn must be a calendar date, YYYY-MM-DD.");
347
+ if (args.problem !== undefined && !PROBLEMS.includes(args.problem))
348
+ throw new BadArguments(`problem must be one of: ${PROBLEMS.join(", ")}.`);
349
+ const zs = sandboxFor(args);
350
+ const website = event.startsWith("direct.");
351
+ /** The booking an event acts on: the one named, or the newest one of the right family that is still standing. */
352
+ const target = async () => {
353
+ if (typeof args.bookingId === "number")
354
+ return args.bookingId;
355
+ const { bookings } = await zs.sandbox.bookings.list();
356
+ const hit = bookings.find((b) => (b.otaName === "Website") === website && b.status !== "CANCELLED");
357
+ if (!hit)
358
+ throw new BadArguments(`The sandbox has no ${website ? "website" : "OTA"} booking to act on. Make one first: event "${website ? "direct" : "channel"}.booking.created".`);
359
+ return hit.bookingId;
360
+ };
361
+ const after = (made, sent) => say(`Made on the sandbox: ${sent}. The signed webhook is on its way to every endpoint registered on the sandbox, and the event is in the log (zimmerstack_sandbox_events). Nothing reached a booking site.\n\n${JSON.stringify(made, null, 2)}`);
362
+ return onSandbox(`The simulation of ${event}`, async () => {
363
+ if (event === "channel.sync.alert" || event === "channel.sync.recovered") {
364
+ const made = await zs.sandbox.syncEvents.create({ type: event, ...(args.problem ? { event: args.problem } : {}) });
365
+ return after(made, `${event} (${made.event})`);
366
+ }
367
+ if (event === "channel.booking.created" || event === "direct.booking.created" || event === "channel.booking.cancelled (no booking before it)") {
368
+ const roomTypeId = args.roomTypeId ?? (await zs.catalog.get()).roomTypes[0]?.id;
369
+ if (!roomTypeId)
370
+ throw new BadArguments("The sandbox has no room type yet. Create one first (zimmerstack_sandbox_write, PUT /catalog/room-types).");
371
+ const made = await zs.sandbox.bookings.create({
372
+ roomTypeId,
373
+ checkIn: args.checkIn ?? addDays(new Date().toISOString().slice(0, 10), 30),
374
+ nights: args.nights ?? 2,
375
+ ...(website ? { otaName: "Website", paidByOta: true } : args.otaName ? { otaName: args.otaName } : {}),
376
+ ...(event.endsWith("(no booking before it)") ? { arrivesCancelled: true } : {}),
377
+ });
378
+ return after(made, made.webhook?.eventType ?? event);
379
+ }
380
+ const bookingId = await target();
381
+ if (event === "channel.booking.modified") {
382
+ const nights = args.nights ?? Math.min(30, ((await zs.sandbox.bookings.list()).bookings.find((b) => b.bookingId === bookingId)?.nights ?? 2) + 1);
383
+ return after(await zs.sandbox.bookings.modify(bookingId, { nights }), `channel.booking.modified (booking ${bookingId}, now ${nights} nights)`);
384
+ }
385
+ if (event === "channel.booking.cancelled" || event === "direct.booking.cancelled")
386
+ return after(await zs.sandbox.bookings.cancel(bookingId), `${event} (booking ${bookingId})`);
387
+ const undo = event.endsWith("(no-show undone)");
388
+ return after(await zs.sandbox.bookings.noShow(bookingId, undo ? { undo: true } : {}), `direct.booking.modified (booking ${bookingId}: ${undo ? "the no-show undone, the nights taken again" : "a no-show, the nights back on sale"})`);
389
+ });
390
+ }
391
+ /** The sandbox's first room type, for a tool that was not told which. */
392
+ async function firstRoomType(zs) {
393
+ const id = (await zs.catalog.get()).roomTypes[0]?.id;
394
+ if (!id)
395
+ throw new BadArguments("The sandbox has no room type yet. Create one first (zimmerstack_sandbox_write, PUT /catalog/room-types).");
396
+ return id;
397
+ }
398
+ const wholeId = (args, name) => {
399
+ if (args[name] === undefined)
400
+ return undefined;
401
+ if (!Number.isInteger(args[name]) || args[name] <= 0)
402
+ throw new BadArguments(`${name} must be a whole number above 0.`);
403
+ return args[name];
404
+ };
405
+ const aDate = (args, name) => {
406
+ if (args[name] === undefined)
407
+ return undefined;
408
+ if (typeof args[name] !== "string" || !DATE.test(args[name]))
409
+ throw new BadArguments(`${name} must be a calendar date, YYYY-MM-DD.`);
410
+ return args[name];
411
+ };
412
+ /** The notices of an answer, as lines an agent can act on. */
413
+ const noticeLines = (answers) => {
414
+ const notices = noticesOf(answers);
415
+ if (notices.length === 0)
416
+ return ["No notice: nothing our record knows says this write does less than it reads."];
417
+ const omitted = noticesOmittedFrom(answers);
418
+ return [`Notices (what it does NOT do), warnings first:`, ...notices.map((n) => `- ${n.level} ${n.code}: ${n.message} → ${n.action}`), ...(omitted ? [`(${omitted} more were left out of the answer)`] : [])];
419
+ };
420
+ async function explain(args) {
421
+ const roomTypeId = wholeId(args, "roomTypeId");
422
+ const ratePlanId = wholeId(args, "ratePlanId");
423
+ const date = aDate(args, "date") ?? addDays(new Date().toISOString().slice(0, 10), 30);
424
+ const zs = sandboxFor(args);
425
+ return onSandbox("GET /explain", async () => {
426
+ const night = await zs.explain.night({ roomTypeId: roomTypeId ?? (await firstRoomType(zs)), date, ...(ratePlanId === undefined ? {} : { ratePlanId }) });
427
+ const head = [
428
+ `${night.roomType.name} (#${night.roomType.id}) on ${night.date}, from ZimmerStack's record (read ${night.asOf}):`,
429
+ ...night.summary.map((sentence) => `- ${sentence}`),
430
+ "",
431
+ "This is our record and the channel manager's copy as last seen, never a booking site's own screen. Where a seenAt is null that part was never read back; where lastSent is null the write is older than the ones whose values are kept (searched says how far it looked).",
432
+ ];
433
+ return say(`${head.join("\n")}\n\n${JSON.stringify(night, null, 2)}`);
434
+ });
435
+ }
436
+ async function dryRun(args) {
437
+ const write = args.write;
438
+ if (typeof write !== "string" || !DRY_RUNS.includes(write))
439
+ throw new BadArguments(`write must be one of: ${DRY_RUNS.join(", ")}.`);
440
+ const zs = sandboxFor(args);
441
+ if (write === "close" || write === "reopen") {
442
+ if (!isRecord(args.body))
443
+ throw new BadArguments(`A dry run of ${write} takes body: { roomTypeId, dateFrom, dateTo }.`);
444
+ const body = args.body;
445
+ return onSandbox(`The dry run of POST /availability/${write}`, async () => {
446
+ // The client's own dry-run methods: they send dryRun: true themselves and refuse an answer that is not a preview.
447
+ const preview = write === "close" ? await zs.availability.closeDryRun(body) : await zs.availability.reopenDryRun(body);
448
+ const lines = [
449
+ `Nothing was done. A ${write} of room type ${preview.roomTypeId} from ${preview.dateFrom} to ${preview.dateTo} (${preview.nights} night${preview.nights === 1 ? "" : "s"}) would change the count on ${preview.count.changedNights} and leave ${preview.count.unchangedNights} as they are.`,
450
+ ...preview.ratePlans.map((p) => `- ${p.name} (#${p.ratePlanId}): stop-sell ${write === "close" ? "switched on" : "lifted"} on ${p.changedNights} night${p.changedNights === 1 ? "" : "s"}, ${p.unchangedNights} left as they are.`),
451
+ ...(preview.notReached.length ? ["Not reached:", ...preview.notReached.map((n) => `- ${n.what} (${n.reason}): ${n.message}`)] : []),
452
+ ];
453
+ return say(`${lines.join("\n")}\n\n${JSON.stringify(preview, null, 2)}`);
454
+ });
455
+ }
456
+ if (!Array.isArray(args.updates) || args.updates.length === 0 || !args.updates.every(isRecord))
457
+ throw new BadArguments(`A dry run of ${write} takes updates: the same list PUT /${write} takes.`);
458
+ const updates = args.updates;
459
+ return onSandbox(`The dry run of PUT /${write}`, async () => {
460
+ const previews = write === "availability" ? await zs.availability.dryRun(updates) : write === "rates" ? await zs.rates.dryRun(updates) : await zs.restrictions.dryRun(updates);
461
+ const lines = ["Nothing was written, queued or sent."];
462
+ for (const p of previews) {
463
+ lines.push(p.verdict === "would-refuse"
464
+ ? `Verdict: would-refuse. A real request would get ${p.refusal?.status} ${p.refusal?.code}: ${p.refusal?.message}`
465
+ : `Verdict: ${p.verdict}. Of ${p.requestedCells} cell${p.requestedCells === 1 ? "" : "s"}: ${p.wouldChangeCells} would change, ${p.unchangedCells} already held, ${p.heldCells} held after a refusal, ${p.wouldRejectCells} would be refused by our record.`);
466
+ for (const r of p.wouldReject)
467
+ lines.push(`- would refuse ${r.cells} cell${r.cells === 1 ? "" : "s"}: ${r.error}`);
468
+ for (const r of p.rounded ?? [])
469
+ lines.push(`- ${r.field}: ${r.sent} would be kept as ${r.kept} (${r.reason})`);
470
+ }
471
+ lines.push(...noticeLines(previews));
472
+ return say(`${lines.join("\n")}\n\n${JSON.stringify(previews.length === 1 ? previews[0] : previews, null, 2)}`);
473
+ });
474
+ }
475
+ async function fault(args) {
476
+ const action = args.action;
477
+ if (typeof action !== "string" || !FAULT_ACTIONS.includes(action))
478
+ throw new BadArguments(`action must be one of: ${FAULT_ACTIONS.join(", ")}.`);
479
+ const zs = sandboxFor(args);
480
+ const show = (did, view) => say(`${did}${view.watch.length ? `\n\nWhat to do next, and what the software should then see:\n${view.watch.map((step, i) => `${i + 1}. ${step}`).join("\n")}` : ""}\n\n${JSON.stringify(view, null, 2)}`);
481
+ if (action === "read")
482
+ return onSandbox("GET /sandbox/faults", async () => {
483
+ const view = await zs.sandbox.faults.get();
484
+ return show(view.active ? `A ${view.kind} fault is in force on the sandbox's pretend channel.` : "No fault is in force: the sandbox's pretend channel takes everything.", view);
485
+ });
486
+ if (action === "clear")
487
+ return onSandbox("DELETE /sandbox/faults", async () => show("The fault is ended: the pretend channel answers normally from the next push. Values already held stay held until a different value is sent.", await zs.sandbox.faults.clear()));
488
+ const kind = args.kind;
489
+ if (typeof kind !== "string" || !FAULT_KINDS.includes(kind))
490
+ throw new BadArguments(`To set a fault, kind must be one of: ${FAULT_KINDS.join(", ")}.`);
491
+ const values = wholeId(args, "values");
492
+ const minutes = wholeId(args, "minutes");
493
+ if (args.message !== undefined && typeof args.message !== "string")
494
+ throw new BadArguments("message must be text.");
495
+ if (kind === "refuse" ? minutes !== undefined : values !== undefined || args.message !== undefined) {
496
+ throw new BadArguments(kind === "refuse" ? "A refuse fault takes values and message, not minutes." : `A ${kind} fault takes minutes, not values or message.`);
497
+ }
498
+ const body = { kind: kind, ...(values === undefined ? {} : { values }), ...(minutes === undefined ? {} : { minutes }), ...(typeof args.message === "string" ? { message: args.message } : {}) };
499
+ return onSandbox("POST /sandbox/faults", async () => show(`Set on the sandbox's pretend channel: ${kind}. Nothing here reaches a live hotel.`, await zs.sandbox.faults.set(body)));
500
+ }
501
+ async function closeOrReopen(args) {
502
+ const action = args.action;
503
+ if (action !== "close" && action !== "reopen")
504
+ throw new BadArguments("action must be close or reopen.");
505
+ const roomTypeId = wholeId(args, "roomTypeId");
506
+ const dateFrom = aDate(args, "dateFrom");
507
+ const dateTo = aDate(args, "dateTo");
508
+ if (!dateFrom || !dateTo)
509
+ throw new BadArguments("dateFrom and dateTo are needed: the first and the last night, YYYY-MM-DD.");
510
+ if (args.days !== undefined && (!Array.isArray(args.days) || !args.days.every((d) => DAYS.includes(d))))
511
+ throw new BadArguments(`days must be a list of: ${DAYS.join(", ")}.`);
512
+ if (args.available !== undefined && (action !== "reopen" || !Number.isInteger(args.available) || args.available < 0))
513
+ throw new BadArguments("available is for a reopen only: the count to put on sale, a whole number from 0.");
514
+ const zs = sandboxFor(args);
515
+ return onSandbox(`POST /availability/${action}`, async () => {
516
+ const range = { roomTypeId: roomTypeId ?? (await firstRoomType(zs)), dateFrom, dateTo, ...(args.days ? { days: args.days } : {}) };
517
+ const done = action === "close" ? await zs.availability.close(range) : await zs.availability.reopen({ ...range, ...(typeof args.available === "number" ? { available: args.available } : {}) });
518
+ const lines = [
519
+ `Done on the sandbox: room type ${done.roomTypeId} ${action === "close" ? "closed" : "reopened"} from ${done.dateFrom} to ${done.dateTo}. The count changed on ${done.count.changedNights} night${done.count.changedNights === 1 ? "" : "s"} and was left on ${done.count.unchangedNights}${done.skippedNights ? `; ${done.skippedNights} were skipped because no close had closed them` : ""}.`,
520
+ ...done.ratePlans.map((p) => `- ${p.name} (#${p.ratePlanId}): stop-sell ${action === "close" ? "switched on" : "lifted"} on ${p.changedNights}, left on ${p.unchangedNights}.`),
521
+ ...(done.notReached.length ? ["Not reached (read these: a close that reads done can still leave something selling):", ...done.notReached.map((n) => `- ${n.what} (${n.reason}): ${n.message}`)] : []),
522
+ ...(done.batches.length ? [`Watch it land: ${done.batches.map((b) => `${b.resource} batch ${b.batchId}`).join(", ")} (zimmerstack_sandbox_read, GET /batches/{batchId}).`] : ["Nothing had to change, so there is no batch to watch."]),
523
+ ];
524
+ return say(`${lines.join("\n")}\n\n${JSON.stringify(done, null, 2)}`);
525
+ });
526
+ }
100
527
  function reference(args) {
101
528
  const given = ["operation", "type", "topic", "search"].filter((name) => typeof args[name] === "string" && args[name].trim() !== "");
102
529
  if (given.length === 0)
@@ -132,39 +559,38 @@ export function createMcpServer(options = {}) {
132
559
  for (const name of ["path", "query"])
133
560
  if (args[name] !== undefined && !isRecord(args[name]))
134
561
  throw new BadArguments(`${name} must be an object of names and values.`);
135
- if (args.propertyId !== undefined && (!Number.isInteger(args.propertyId) || args.propertyId <= 0))
136
- throw new BadArguments("propertyId must be a property's numeric id.");
137
- const base = sandbox();
138
- const zs = typeof args.propertyId === "number" ? base.forProperty(args.propertyId) : base;
139
- try {
562
+ const zs = sandboxFor(args);
563
+ return onSandbox(operation, async () => {
140
564
  const data = await zs.request(operation, { path: args.path, query: args.query, body: args.body });
141
565
  return say(`${operation} on the sandbox answered:\n\n${JSON.stringify(data, null, 2)}`);
142
- }
143
- catch (err) {
144
- if (err instanceof ZimmerStackUsageError)
145
- throw new BadArguments(`${err.message}. Nothing was sent.`);
146
- if (!(err instanceof ZimmerStackError))
147
- throw err;
148
- const lines = [`${operation} was refused: ${err.code}${err.status ? ` (${err.status})` : ""}`, err.message];
149
- if (err.scope)
150
- lines.push(`Budget: ${err.scope}`);
151
- if (err.details !== undefined)
152
- lines.push(`Details: ${JSON.stringify(err.details)}`);
153
- lines.push(err.retryable
154
- ? `It may pass later${err.retryAfterSeconds ? `: in ${err.retryAfterSeconds} seconds` : ""}. The client has already retried what was worth waiting for.`
155
- : "This is a verdict on the request: fix it; sending it again will be refused again. zimmerstack_reference explains the code (search for it).");
156
- return refuse(lines.join("\n"));
157
- }
566
+ });
158
567
  }
159
568
  async function callTool(name, args) {
160
569
  try {
570
+ // The rules are never cut: half a rules file is worse than none.
161
571
  if (name === "zimmerstack_rules")
162
- return say(RULES);
572
+ return { content: [{ type: "text", text: RULES }] };
163
573
  if (name === "zimmerstack_reference")
164
574
  return reference(args);
165
575
  if (name === "zimmerstack_sandbox_read")
166
576
  return await call("read", args);
167
- return await call("write", args);
577
+ if (name === "zimmerstack_sandbox_write")
578
+ return await call("write", args);
579
+ if (name === "zimmerstack_doctor")
580
+ return await doctor(args);
581
+ if (name === "zimmerstack_sandbox_limits")
582
+ return await limits(args);
583
+ if (name === "zimmerstack_sandbox_events")
584
+ return await events(args);
585
+ if (name === "zimmerstack_sandbox_explain")
586
+ return await explain(args);
587
+ if (name === "zimmerstack_sandbox_dry_run")
588
+ return await dryRun(args);
589
+ if (name === "zimmerstack_sandbox_fault")
590
+ return await fault(args);
591
+ if (name === "zimmerstack_sandbox_close")
592
+ return await closeOrReopen(args);
593
+ return await simulate(args);
168
594
  }
169
595
  catch (err) {
170
596
  if (err instanceof BadArguments)