@zimmerstack/connect 0.0.0-stage → 0.1.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/AGENTS.md +99 -0
- package/LICENSE +21 -0
- package/README.md +225 -2
- package/dist/cjs/client.d.ts +260 -0
- package/dist/cjs/client.js +562 -0
- package/dist/cjs/errors.d.ts +46 -0
- package/dist/cjs/errors.js +51 -0
- package/dist/cjs/generated.d.ts +1153 -0
- package/dist/cjs/generated.js +135 -0
- package/dist/cjs/grid.d.ts +105 -0
- package/dist/cjs/grid.js +135 -0
- package/dist/cjs/index.d.ts +16 -0
- package/dist/cjs/index.js +30 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/webhooks.d.ts +60 -0
- package/dist/cjs/webhooks.js +103 -0
- package/dist/esm/client.d.ts +260 -0
- package/dist/esm/client.js +558 -0
- package/dist/esm/errors.d.ts +46 -0
- package/dist/esm/errors.js +46 -0
- package/dist/esm/generated.d.ts +1153 -0
- package/dist/esm/generated.js +132 -0
- package/dist/esm/grid.d.ts +105 -0
- package/dist/esm/grid.js +127 -0
- package/dist/esm/index.d.ts +16 -0
- package/dist/esm/index.js +11 -0
- package/dist/esm/mcp/cli.d.ts +2 -0
- package/dist/esm/mcp/cli.js +86 -0
- package/dist/esm/mcp/key.d.ts +9 -0
- package/dist/esm/mcp/key.js +31 -0
- package/dist/esm/mcp/reference.d.ts +11 -0
- package/dist/esm/mcp/reference.generated.d.ts +33 -0
- package/dist/esm/mcp/reference.generated.js +2084 -0
- package/dist/esm/mcp/reference.js +137 -0
- package/dist/esm/mcp/server.d.ts +29 -0
- package/dist/esm/mcp/server.js +223 -0
- package/dist/esm/webhooks.d.ts +60 -0
- package/dist/esm/webhooks.js +98 -0
- package/package.json +61 -4
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { REFERENCE } from "./reference.generated.js";
|
|
2
|
+
/**
|
|
3
|
+
* Lookups over the reference the generator wrote from the API's contract: an operation, a type, a
|
|
4
|
+
* topic, or a search across all three. Pure text in, text out; the MCP server only wraps these.
|
|
5
|
+
*/
|
|
6
|
+
const json = (value) => JSON.stringify(value, null, 2);
|
|
7
|
+
const withoutComments = (text) => text.replace(/\/\*\*[^]*?\*\//g, "");
|
|
8
|
+
export const TOPICS = Object.keys(REFERENCE.topics);
|
|
9
|
+
/** The types an expression names, then the types those name, each once, in the order met. */
|
|
10
|
+
function typesNamed(expression, seen = new Set()) {
|
|
11
|
+
for (const name of Object.keys(REFERENCE.types)) {
|
|
12
|
+
if (seen.has(name) || !new RegExp(`\\b${name}\\b`).test(expression))
|
|
13
|
+
continue;
|
|
14
|
+
seen.add(name);
|
|
15
|
+
typesNamed(withoutComments(REFERENCE.types[name] ?? ""), seen);
|
|
16
|
+
}
|
|
17
|
+
return [...seen];
|
|
18
|
+
}
|
|
19
|
+
const typeBlock = (expression) => expression === null
|
|
20
|
+
? ""
|
|
21
|
+
: typesNamed(expression)
|
|
22
|
+
.map((name) => REFERENCE.types[name])
|
|
23
|
+
.join("\n\n");
|
|
24
|
+
/** An operation by its contract name ("PUT /rates", any letter case), its path alone when one method has it, or the client's call ("zs.rates.set"). */
|
|
25
|
+
export function findOperation(input) {
|
|
26
|
+
const wanted = input.trim().replace(/\s+/g, " ");
|
|
27
|
+
if (!wanted)
|
|
28
|
+
return undefined;
|
|
29
|
+
if (/^zs\./.test(wanted)) {
|
|
30
|
+
const call = wanted.split("(")[0];
|
|
31
|
+
return REFERENCE.operations.find((op) => op.call.split("(")[0] === call);
|
|
32
|
+
}
|
|
33
|
+
const [first = "", second] = wanted.split(" ");
|
|
34
|
+
if (second !== undefined)
|
|
35
|
+
return REFERENCE.operations.find((op) => op.key === `${first.toUpperCase()} ${second}`);
|
|
36
|
+
const byPath = REFERENCE.operations.filter((op) => op.key.split(" ")[1] === first);
|
|
37
|
+
return byPath.length === 1 ? byPath[0] : undefined;
|
|
38
|
+
}
|
|
39
|
+
export function describeOperation(op) {
|
|
40
|
+
const lines = [
|
|
41
|
+
`${op.key}: ${op.summary}`,
|
|
42
|
+
"",
|
|
43
|
+
`With the package: ${op.call}`,
|
|
44
|
+
`Scope: ${op.scope ?? "none (every key may call it)"}`,
|
|
45
|
+
op.key.startsWith("GET ")
|
|
46
|
+
? "A read: safe to repeat."
|
|
47
|
+
: op.idempotent
|
|
48
|
+
? "A write the server keeps an idempotency record for: the client sends a key and reuses it on its own retries."
|
|
49
|
+
: "A write with no idempotency record: the client does not resend it when its outcome is unknown.",
|
|
50
|
+
];
|
|
51
|
+
if (op.description)
|
|
52
|
+
lines.push("", op.description);
|
|
53
|
+
if (op.path.length)
|
|
54
|
+
lines.push("", `Path values: ${op.path.join(", ")}`);
|
|
55
|
+
if (op.query.length) {
|
|
56
|
+
lines.push("", "Query:");
|
|
57
|
+
for (const q of op.query)
|
|
58
|
+
lines.push(`- ${q.name}${q.required ? "" : "?"}: ${q.type}${q.description ? `. ${q.description}` : ""}`);
|
|
59
|
+
}
|
|
60
|
+
if (op.body !== null) {
|
|
61
|
+
lines.push("", `Body: ${/^[A-Za-z]+$/.test(op.body) ? op.body : "an object"}`, "", "```ts", typeBlock(op.body) || op.body, "```");
|
|
62
|
+
if (op.request !== null)
|
|
63
|
+
lines.push("", "Sample body:", "```json", json(op.request), "```");
|
|
64
|
+
}
|
|
65
|
+
lines.push("", `Answers ${op.answerStatus.join(" or ")} with data: ${op.response}`);
|
|
66
|
+
const answerTypes = typeBlock(op.response);
|
|
67
|
+
if (answerTypes)
|
|
68
|
+
lines.push("", "```ts", answerTypes, "```");
|
|
69
|
+
if (op.answer !== null)
|
|
70
|
+
lines.push("", "Sample answer (data):", "```json", json(op.answer), "```");
|
|
71
|
+
if (op.refusals.length) {
|
|
72
|
+
lines.push("", "Refusals:");
|
|
73
|
+
for (const r of op.refusals)
|
|
74
|
+
lines.push(`- ${r.status}: ${r.description}`);
|
|
75
|
+
}
|
|
76
|
+
return lines.join("\n");
|
|
77
|
+
}
|
|
78
|
+
export function describeType(name) {
|
|
79
|
+
const exact = Object.keys(REFERENCE.types).find((n) => n.toLowerCase() === name.trim().toLowerCase());
|
|
80
|
+
return exact ? ["```ts", typeBlock(exact), "```"].join("\n") : undefined;
|
|
81
|
+
}
|
|
82
|
+
export function describeTopic(name) {
|
|
83
|
+
const text = REFERENCE.topics[name.trim().toLowerCase()];
|
|
84
|
+
return text === undefined ? undefined : `# ${name.trim().toLowerCase()}\n\n${text}`;
|
|
85
|
+
}
|
|
86
|
+
/** What there is to look up. */
|
|
87
|
+
export function referenceIndex() {
|
|
88
|
+
const lines = [
|
|
89
|
+
`${REFERENCE.api}. Base URL: ${REFERENCE.base}`,
|
|
90
|
+
"",
|
|
91
|
+
"Operations (ask for one by its name, e.g. operation: \"PUT /rates\"):",
|
|
92
|
+
...REFERENCE.operations.map((op) => `- ${op.key}: ${op.summary} [${op.scope ?? "any key"}] → ${op.call}`),
|
|
93
|
+
"",
|
|
94
|
+
`Topics (ask with topic): ${TOPICS.join(", ")}`,
|
|
95
|
+
"",
|
|
96
|
+
`Types (ask with type): ${Object.keys(REFERENCE.types).join(", ")}`,
|
|
97
|
+
"",
|
|
98
|
+
"Or search across all of it with search: \"minimum stay\", \"429\", \"RATE_OUT_OF_BAND\", …",
|
|
99
|
+
];
|
|
100
|
+
return lines.join("\n");
|
|
101
|
+
}
|
|
102
|
+
const SMALL_WORDS = new Set(["a", "an", "the", "to", "of", "in", "on", "for", "and", "or", "is", "it", "do", "how", "what", "can", "with", "my"]);
|
|
103
|
+
/** The operations, topics and types that mention the most words of the query, best first. */
|
|
104
|
+
export function searchReference(query) {
|
|
105
|
+
const words = [...new Set(query.toLowerCase().split(/[^a-z0-9_:/{}.-]+/).filter((w) => w.length > 1 && !SMALL_WORDS.has(w)))];
|
|
106
|
+
if (words.length === 0)
|
|
107
|
+
return referenceIndex();
|
|
108
|
+
const entries = [
|
|
109
|
+
...REFERENCE.operations.map((op) => ({ label: `${op.key}: ${op.summary}`, open: `operation: "${op.key}"`, text: [op.key, op.summary, op.description, op.call, op.scope ?? "", REFERENCE.types[op.body ?? ""] ?? op.body ?? "", ...op.refusals.map((r) => r.description), ...op.query.map((q) => `${q.name} ${q.description}`)].join(" ") })),
|
|
110
|
+
...Object.entries(REFERENCE.topics).map(([name, text]) => ({ label: `topic ${name}`, open: `topic: "${name}"`, text: `${name} ${text}` })),
|
|
111
|
+
...Object.entries(REFERENCE.types).map(([name, text]) => ({ label: `type ${name}`, open: `type: "${name}"`, text: `${name} ${text}` })),
|
|
112
|
+
];
|
|
113
|
+
// A word in the name counts double: "rates" should find PUT /rates before a topic that mentions rates in passing.
|
|
114
|
+
const scored = entries
|
|
115
|
+
.map((e) => {
|
|
116
|
+
const text = e.text.toLowerCase();
|
|
117
|
+
const label = e.label.toLowerCase();
|
|
118
|
+
const found = words.filter((w) => text.includes(w));
|
|
119
|
+
return { ...e, found, score: found.length + found.filter((w) => label.includes(w)).length };
|
|
120
|
+
})
|
|
121
|
+
.filter((e) => e.found.length > 0)
|
|
122
|
+
.sort((a, b) => b.found.length - a.found.length || b.score - a.score);
|
|
123
|
+
if (scored.length === 0)
|
|
124
|
+
return `Nothing in the reference mentions "${query}". The index:\n\n${referenceIndex()}`;
|
|
125
|
+
const best = scored[0].found.length;
|
|
126
|
+
const shown = scored.filter((e) => e.found.length >= Math.max(1, best - 1)).slice(0, 8);
|
|
127
|
+
const lines = [`${best === words.length ? "Mentions" : "Closest to"} "${query}":`, ""];
|
|
128
|
+
for (const e of shown) {
|
|
129
|
+
lines.push(`- ${e.label} (open with ${e.open})`);
|
|
130
|
+
// The words around the first one found, so the answer is often on this line already.
|
|
131
|
+
const at = e.text.toLowerCase().indexOf(e.found[0] ?? "");
|
|
132
|
+
const snippet = withoutComments(e.text.slice(Math.max(0, at - 90), at + 170)).replace(/\s+/g, " ").trim();
|
|
133
|
+
if (snippet)
|
|
134
|
+
lines.push(` …${snippet}…`);
|
|
135
|
+
}
|
|
136
|
+
return lines.join("\n");
|
|
137
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The package's MCP server: four tools a developer's coding agent can call while it builds on the
|
|
3
|
+
* Connect API. It runs on the developer's own machine, over stdin and stdout (src/mcp/cli.ts).
|
|
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
|
|
9
|
+
*
|
|
10
|
+
* The two sandbox tools use a zsk_test_ key and nothing else: a sandbox is a copy of a hotel's rooms
|
|
11
|
+
* and plans that no booking site ever sees. A live key is refused before anything is sent, so an agent
|
|
12
|
+
* can never change a real hotel through this server, whatever it is asked. Every call goes through the
|
|
13
|
+
* package's own client, so the pacing, retry and idempotency rules hold here too.
|
|
14
|
+
*
|
|
15
|
+
* Transport-free on purpose: `handle` takes one decoded JSON-RPC message and returns the answer, if the
|
|
16
|
+
* message expects one. The tests call it directly.
|
|
17
|
+
*/
|
|
18
|
+
export interface McpServerOptions {
|
|
19
|
+
/** The key the project holds, if any. Only a zsk_test_ key is ever used; a live one is never sent. */
|
|
20
|
+
apiKey?: string | undefined;
|
|
21
|
+
/** Where that key was found ("the environment", ".env.local"), for the messages. */
|
|
22
|
+
keySource?: string | undefined;
|
|
23
|
+
/** For tests: a stand-in for the API. */
|
|
24
|
+
fetch?: typeof fetch | undefined;
|
|
25
|
+
baseUrl?: string | undefined;
|
|
26
|
+
}
|
|
27
|
+
export declare function createMcpServer(options?: McpServerOptions): {
|
|
28
|
+
handle(message: unknown): Promise<unknown>;
|
|
29
|
+
};
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { ZimmerStack } from "../client.js";
|
|
2
|
+
import { ZimmerStackError, ZimmerStackUsageError } from "../errors.js";
|
|
3
|
+
import { OPERATIONS, SDK_VERSION } from "../generated.js";
|
|
4
|
+
import { RULES } from "./reference.generated.js";
|
|
5
|
+
import { TOPICS, describeOperation, describeTopic, describeType, findOperation, referenceIndex, searchReference } from "./reference.js";
|
|
6
|
+
/** The protocol revisions this server speaks, newest first. A client asking for another gets the newest. */
|
|
7
|
+
const PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
|
|
8
|
+
const MAX_TEXT = 24_000;
|
|
9
|
+
const READS = Object.keys(OPERATIONS).filter((key) => key.startsWith("GET "));
|
|
10
|
+
const WRITES = Object.keys(OPERATIONS).filter((key) => !key.startsWith("GET "));
|
|
11
|
+
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
|
+
"Before writing code that calls ZimmerStack, call zimmerstack_rules once and follow it. " +
|
|
13
|
+
"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.";
|
|
15
|
+
const objectOf = (description) => ({ type: "object", description, additionalProperties: true });
|
|
16
|
+
const TOOLS = [
|
|
17
|
+
{
|
|
18
|
+
name: "zimmerstack_rules",
|
|
19
|
+
title: "ZimmerStack: the rules",
|
|
20
|
+
description: "The rules for building on the ZimmerStack Connect API with @zimmerstack/connect: where the key lives, what the package already handles (pacing, retries, idempotency), money and dates, a channel's price modifier, errors, and a checklist to finish with. Read it once before writing code that calls ZimmerStack.",
|
|
21
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
22
|
+
annotations: { title: "ZimmerStack: the rules", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
name: "zimmerstack_reference",
|
|
26
|
+
title: "ZimmerStack: look it up",
|
|
27
|
+
description: "Look something up in the Connect API's reference, generated from the API's own contract. With no arguments: the index of every operation, topic and type. operation: one route with its scope, the client's call, its types, a sample and its refusals. type: one shape. topic: limits, keys, errors and so on. search: every place a word or an error code is mentioned.",
|
|
28
|
+
inputSchema: {
|
|
29
|
+
type: "object",
|
|
30
|
+
properties: {
|
|
31
|
+
operation: { type: "string", description: 'An operation as the contract names it ("PUT /rates"), or the client\'s call ("zs.rates.set").' },
|
|
32
|
+
type: { type: "string", description: 'A shape of the contract, e.g. "RatesWrite" or "Booking".' },
|
|
33
|
+
topic: { type: "string", enum: TOPICS, description: "One of the reference's topics." },
|
|
34
|
+
search: { type: "string", description: 'Words or a code to find anywhere in the reference, e.g. "minimum stay" or "RATE_OUT_OF_BAND".' },
|
|
35
|
+
},
|
|
36
|
+
additionalProperties: false,
|
|
37
|
+
},
|
|
38
|
+
annotations: { title: "ZimmerStack: look it up", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
name: "zimmerstack_sandbox_read",
|
|
42
|
+
title: "ZimmerStack sandbox: read",
|
|
43
|
+
description: "Make one read (GET) on the project's ZimmerStack SANDBOX and return the answer's data. Uses the sandbox key (zsk_test_…) from the project's environment; refuses a live key. Use it to see real ids and shapes: start with GET /property and GET /catalog.",
|
|
44
|
+
inputSchema: {
|
|
45
|
+
type: "object",
|
|
46
|
+
properties: {
|
|
47
|
+
operation: { type: "string", enum: READS, description: "The read to make." },
|
|
48
|
+
path: objectOf('Values for the {names} in the operation, e.g. { "batchId": "…" }.'),
|
|
49
|
+
query: objectOf('Query values, e.g. { "from": "2026-12-01", "to": "2026-12-14" }. Dates are YYYY-MM-DD.'),
|
|
50
|
+
propertyId: { type: "integer", minimum: 1, description: "A software vendor's company key only: the hotel to act on (GET /properties lists them)." },
|
|
51
|
+
},
|
|
52
|
+
required: ["operation"],
|
|
53
|
+
additionalProperties: false,
|
|
54
|
+
},
|
|
55
|
+
annotations: { title: "ZimmerStack sandbox: read", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
name: "zimmerstack_sandbox_write",
|
|
59
|
+
title: "ZimmerStack sandbox: write",
|
|
60
|
+
description: "Make one write (PUT, POST or DELETE) on the project's ZimmerStack SANDBOX and return the answer. A sandbox is a copy of a hotel's rooms and plans that no booking site sees, so this cannot change a real hotel; it refuses a live key. Use it to try a body before writing the code that sends it. Look the body up first with zimmerstack_reference.",
|
|
61
|
+
inputSchema: {
|
|
62
|
+
type: "object",
|
|
63
|
+
properties: {
|
|
64
|
+
operation: { type: "string", enum: WRITES, description: "The write to make." },
|
|
65
|
+
path: objectOf('Values for the {names} in the operation, e.g. { "channelId": "…" }.'),
|
|
66
|
+
body: { description: "The JSON body, as zimmerstack_reference shows it for this operation." },
|
|
67
|
+
propertyId: { type: "integer", minimum: 1, description: "A software vendor's company key only: the hotel to act on." },
|
|
68
|
+
},
|
|
69
|
+
required: ["operation"],
|
|
70
|
+
additionalProperties: false,
|
|
71
|
+
},
|
|
72
|
+
annotations: { title: "ZimmerStack sandbox: write", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
73
|
+
},
|
|
74
|
+
];
|
|
75
|
+
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
|
+
const refuse = (text) => ({ ...say(text), isError: true });
|
|
77
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
78
|
+
class BadArguments extends Error {
|
|
79
|
+
}
|
|
80
|
+
export function createMcpServer(options = {}) {
|
|
81
|
+
const key = options.apiKey?.trim();
|
|
82
|
+
const where = options.keySource ?? "the environment";
|
|
83
|
+
let client;
|
|
84
|
+
/** The one client of this server, made on first use. Throws the sentence to show when there is no sandbox key. */
|
|
85
|
+
function sandbox() {
|
|
86
|
+
if (client)
|
|
87
|
+
return client;
|
|
88
|
+
if (!key) {
|
|
89
|
+
throw new BadArguments("No sandbox key was found, so nothing was sent. Put ZIMMERSTACK_CONNECT_KEY=zsk_test_… in the project's .env (the hotel's owner makes a sandbox and a key for it under Admin → Developers → API keys), then restart this server. The rules and the reference work without a key.");
|
|
90
|
+
}
|
|
91
|
+
if (key.startsWith("zsk_live_")) {
|
|
92
|
+
throw new BadArguments(`The key in ${where} is a live key (zsk_live_…): it acts on a real hotel. This server calls a sandbox only, so nothing was sent. Ask the hotel's owner for a sandbox key (zsk_test_…), put it in the project's .env while you build, and keep the live key for production.`);
|
|
93
|
+
}
|
|
94
|
+
if (!key.startsWith("zsk_test_"))
|
|
95
|
+
throw new BadArguments(`The value of ZIMMERSTACK_CONNECT_KEY in ${where} is not a ZimmerStack sandbox key (zsk_test_…). Nothing was sent.`);
|
|
96
|
+
// Short waits: an agent is better served by the refusal itself than by a tool call held open.
|
|
97
|
+
client = new ZimmerStack({ apiKey: key, fetch: options.fetch, baseUrl: options.baseUrl, timeoutMs: 20_000, maxRetries: 1, maxWaitSeconds: 15 });
|
|
98
|
+
return client;
|
|
99
|
+
}
|
|
100
|
+
function reference(args) {
|
|
101
|
+
const given = ["operation", "type", "topic", "search"].filter((name) => typeof args[name] === "string" && args[name].trim() !== "");
|
|
102
|
+
if (given.length === 0)
|
|
103
|
+
return say(referenceIndex());
|
|
104
|
+
const parts = [];
|
|
105
|
+
for (const name of given) {
|
|
106
|
+
const value = args[name].trim();
|
|
107
|
+
if (name === "operation") {
|
|
108
|
+
const op = findOperation(value);
|
|
109
|
+
parts.push(op ? describeOperation(op) : `There is no operation "${value}". ${searchReference(value)}`);
|
|
110
|
+
}
|
|
111
|
+
else if (name === "type") {
|
|
112
|
+
parts.push(describeType(value) ?? `There is no type "${value}". ${searchReference(value)}`);
|
|
113
|
+
}
|
|
114
|
+
else if (name === "topic") {
|
|
115
|
+
parts.push(describeTopic(value) ?? `There is no topic "${value}". The topics: ${TOPICS.join(", ")}.`);
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
parts.push(searchReference(value));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return say(parts.join("\n\n---\n\n"));
|
|
122
|
+
}
|
|
123
|
+
async function call(kind, args) {
|
|
124
|
+
const operation = args.operation;
|
|
125
|
+
const allowed = kind === "read" ? READS : WRITES;
|
|
126
|
+
if (typeof operation !== "string" || !allowed.includes(operation)) {
|
|
127
|
+
const other = typeof operation === "string" && operation in OPERATIONS;
|
|
128
|
+
throw new BadArguments(other
|
|
129
|
+
? `${operation} is a ${kind === "read" ? "write" : "read"}: use zimmerstack_sandbox_${kind === "read" ? "write" : "read"}.`
|
|
130
|
+
: `"${String(operation)}" is not an operation of the Connect API. The ${kind}s: ${allowed.join(", ")}.`);
|
|
131
|
+
}
|
|
132
|
+
for (const name of ["path", "query"])
|
|
133
|
+
if (args[name] !== undefined && !isRecord(args[name]))
|
|
134
|
+
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 {
|
|
140
|
+
const data = await zs.request(operation, { path: args.path, query: args.query, body: args.body });
|
|
141
|
+
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
|
+
}
|
|
158
|
+
}
|
|
159
|
+
async function callTool(name, args) {
|
|
160
|
+
try {
|
|
161
|
+
if (name === "zimmerstack_rules")
|
|
162
|
+
return say(RULES);
|
|
163
|
+
if (name === "zimmerstack_reference")
|
|
164
|
+
return reference(args);
|
|
165
|
+
if (name === "zimmerstack_sandbox_read")
|
|
166
|
+
return await call("read", args);
|
|
167
|
+
return await call("write", args);
|
|
168
|
+
}
|
|
169
|
+
catch (err) {
|
|
170
|
+
if (err instanceof BadArguments)
|
|
171
|
+
return refuse(err.message);
|
|
172
|
+
// Whatever went wrong, the answer is words for the agent, and never the key.
|
|
173
|
+
return refuse(`The tool failed before it had an answer: ${err instanceof Error ? err.name : "an unexpected error"}. Nothing can be assumed about whether a write was applied; read the current state before trying again.`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async function one(message) {
|
|
177
|
+
if (!isRecord(message))
|
|
178
|
+
return { jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request" } };
|
|
179
|
+
const id = message.id;
|
|
180
|
+
const expectsAnswer = typeof id === "string" || typeof id === "number";
|
|
181
|
+
const fail = (code, text) => (expectsAnswer ? { jsonrpc: "2.0", id, error: { code, message: text } } : undefined);
|
|
182
|
+
const ok = (result) => (expectsAnswer ? { jsonrpc: "2.0", id, result } : undefined);
|
|
183
|
+
if (message.jsonrpc !== "2.0" || typeof message.method !== "string") {
|
|
184
|
+
// A client's answer to something we never asked, or a malformed line: nothing to say unless it wants a reply.
|
|
185
|
+
return "result" in message || "error" in message ? undefined : fail(-32600, "Invalid Request");
|
|
186
|
+
}
|
|
187
|
+
const params = isRecord(message.params) ? message.params : {};
|
|
188
|
+
switch (message.method) {
|
|
189
|
+
case "initialize": {
|
|
190
|
+
const asked = typeof params.protocolVersion === "string" ? params.protocolVersion : "";
|
|
191
|
+
return ok({
|
|
192
|
+
protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
|
|
193
|
+
capabilities: { tools: { listChanged: false } },
|
|
194
|
+
serverInfo: { name: "zimmerstack-connect", title: "ZimmerStack Connect", version: SDK_VERSION },
|
|
195
|
+
instructions: INSTRUCTIONS,
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
case "ping":
|
|
199
|
+
return ok({});
|
|
200
|
+
case "tools/list":
|
|
201
|
+
return ok({ tools: TOOLS });
|
|
202
|
+
case "tools/call": {
|
|
203
|
+
const name = params.name;
|
|
204
|
+
if (typeof name !== "string" || !TOOLS.some((tool) => tool.name === name))
|
|
205
|
+
return fail(-32602, `Unknown tool: ${String(name)}`);
|
|
206
|
+
if (params.arguments !== undefined && !isRecord(params.arguments))
|
|
207
|
+
return fail(-32602, "arguments must be an object");
|
|
208
|
+
return ok(await callTool(name, isRecord(params.arguments) ? params.arguments : {}));
|
|
209
|
+
}
|
|
210
|
+
default:
|
|
211
|
+
return fail(-32601, `Method not found: ${message.method}`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
/** One decoded JSON-RPC message in; its answer out, or undefined when it expects none (a notification). */
|
|
216
|
+
async handle(message) {
|
|
217
|
+
if (!Array.isArray(message))
|
|
218
|
+
return one(message);
|
|
219
|
+
const answers = (await Promise.all(message.map(one))).filter((answer) => answer !== undefined);
|
|
220
|
+
return answers.length ? answers : undefined;
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { ChannelBooking } from "./generated.js";
|
|
2
|
+
/**
|
|
3
|
+
* Verifying a webhook ZimmerStack sent you (Standard Webhooks: the `webhook-id`, `webhook-timestamp` and
|
|
4
|
+
* `webhook-signature` headers). Uses Web Crypto, so it runs on Node and on edge runtimes alike.
|
|
5
|
+
*/
|
|
6
|
+
/** What every delivery carries. Deliveries are at-least-once: dedupe on `id`, order on `occurredAt`. */
|
|
7
|
+
export interface WebhookEvent {
|
|
8
|
+
/** "evt_<uuid>", the same on every retry and on every endpoint. */
|
|
9
|
+
id: string;
|
|
10
|
+
/** channel.booking.created · channel.booking.modified · channel.booking.cancelled · channel.sync.* · zimmerstack.ping */
|
|
11
|
+
type: string;
|
|
12
|
+
apiVersion: string;
|
|
13
|
+
occurredAt: string;
|
|
14
|
+
/** "test" for events from a sandbox or the "send test" button. */
|
|
15
|
+
mode: "live" | "test";
|
|
16
|
+
property: {
|
|
17
|
+
id: number;
|
|
18
|
+
name: string;
|
|
19
|
+
currency: string;
|
|
20
|
+
timezone: string;
|
|
21
|
+
[key: string]: unknown;
|
|
22
|
+
};
|
|
23
|
+
data: {
|
|
24
|
+
booking?: ChannelBooking;
|
|
25
|
+
[key: string]: unknown;
|
|
26
|
+
};
|
|
27
|
+
/** Dotted paths that changed, on a modification ("stay.checkOut"). */
|
|
28
|
+
changes?: string[] | null;
|
|
29
|
+
/** What those fields held before, on a modification. */
|
|
30
|
+
previous?: Record<string, unknown> | null;
|
|
31
|
+
truncated?: boolean;
|
|
32
|
+
}
|
|
33
|
+
export declare class ZimmerStackWebhookError extends Error {
|
|
34
|
+
/** Why the delivery was refused. Answer 400 and do not act on the body. */
|
|
35
|
+
readonly reason: "missing_headers" | "stale_timestamp" | "bad_signature" | "bad_body";
|
|
36
|
+
constructor(reason: ZimmerStackWebhookError["reason"], message: string);
|
|
37
|
+
}
|
|
38
|
+
type HeaderBag = {
|
|
39
|
+
get(name: string): string | null;
|
|
40
|
+
} | Record<string, string | string[] | undefined>;
|
|
41
|
+
/**
|
|
42
|
+
* Check a delivery and return its event. Throws `ZimmerStackWebhookError` when the delivery is not
|
|
43
|
+
* ZimmerStack's, is older than five minutes, or does not parse.
|
|
44
|
+
*
|
|
45
|
+
* `rawBody` must be the request body exactly as it arrived (the bytes, or the text before any JSON
|
|
46
|
+
* parsing): a body that was parsed and written out again will not match its signature.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* // Next.js route handler
|
|
50
|
+
* export async function POST(req: Request) {
|
|
51
|
+
* const event = await verifyWebhook(await req.text(), req.headers, process.env.ZIMMERSTACK_WEBHOOK_SECRET!);
|
|
52
|
+
* // … dedupe on event.id, then act on event.type
|
|
53
|
+
* return new Response(null, { status: 204 });
|
|
54
|
+
* }
|
|
55
|
+
*/
|
|
56
|
+
export declare function verifyWebhook(rawBody: string | Uint8Array, headers: HeaderBag, secret: string, options?: {
|
|
57
|
+
toleranceSeconds?: number;
|
|
58
|
+
now?: number;
|
|
59
|
+
}): Promise<WebhookEvent>;
|
|
60
|
+
export {};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
export class ZimmerStackWebhookError extends Error {
|
|
2
|
+
/** Why the delivery was refused. Answer 400 and do not act on the body. */
|
|
3
|
+
reason;
|
|
4
|
+
constructor(reason, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "ZimmerStackWebhookError";
|
|
7
|
+
this.reason = reason;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
function header(headers, name) {
|
|
11
|
+
if (typeof headers.get === "function")
|
|
12
|
+
return headers.get(name) ?? undefined;
|
|
13
|
+
const bag = headers;
|
|
14
|
+
const value = bag[name] ?? bag[Object.keys(bag).find((key) => key.toLowerCase() === name) ?? ""];
|
|
15
|
+
return Array.isArray(value) ? value[0] : value;
|
|
16
|
+
}
|
|
17
|
+
function fromBase64(text) {
|
|
18
|
+
const raw = atob(text);
|
|
19
|
+
const bytes = new Uint8Array(raw.length);
|
|
20
|
+
for (let i = 0; i < raw.length; i++)
|
|
21
|
+
bytes[i] = raw.charCodeAt(i);
|
|
22
|
+
return bytes;
|
|
23
|
+
}
|
|
24
|
+
/** Compares every byte whatever the first difference, so the time taken says nothing about the signature. */
|
|
25
|
+
function equalBytes(a, b) {
|
|
26
|
+
if (a.length !== b.length)
|
|
27
|
+
return false;
|
|
28
|
+
let diff = 0;
|
|
29
|
+
for (let i = 0; i < a.length; i++)
|
|
30
|
+
diff |= a[i] ^ b[i];
|
|
31
|
+
return diff === 0;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Check a delivery and return its event. Throws `ZimmerStackWebhookError` when the delivery is not
|
|
35
|
+
* ZimmerStack's, is older than five minutes, or does not parse.
|
|
36
|
+
*
|
|
37
|
+
* `rawBody` must be the request body exactly as it arrived (the bytes, or the text before any JSON
|
|
38
|
+
* parsing): a body that was parsed and written out again will not match its signature.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* // Next.js route handler
|
|
42
|
+
* export async function POST(req: Request) {
|
|
43
|
+
* const event = await verifyWebhook(await req.text(), req.headers, process.env.ZIMMERSTACK_WEBHOOK_SECRET!);
|
|
44
|
+
* // … dedupe on event.id, then act on event.type
|
|
45
|
+
* return new Response(null, { status: 204 });
|
|
46
|
+
* }
|
|
47
|
+
*/
|
|
48
|
+
export async function verifyWebhook(rawBody, headers, secret, options = {}) {
|
|
49
|
+
const id = header(headers, "webhook-id");
|
|
50
|
+
const timestamp = header(headers, "webhook-timestamp");
|
|
51
|
+
const signature = header(headers, "webhook-signature");
|
|
52
|
+
if (!id || !timestamp || !signature)
|
|
53
|
+
throw new ZimmerStackWebhookError("missing_headers", "The webhook-id, webhook-timestamp and webhook-signature headers are required");
|
|
54
|
+
if (!secret)
|
|
55
|
+
throw new ZimmerStackWebhookError("bad_signature", "No webhook secret was given to verify against");
|
|
56
|
+
const sent = Number(timestamp);
|
|
57
|
+
const now = options.now ?? Math.floor(Date.now() / 1000);
|
|
58
|
+
if (!Number.isFinite(sent) || Math.abs(now - sent) > (options.toleranceSeconds ?? 300)) {
|
|
59
|
+
throw new ZimmerStackWebhookError("stale_timestamp", "The delivery's timestamp is outside the allowed window");
|
|
60
|
+
}
|
|
61
|
+
const encoder = new TextEncoder();
|
|
62
|
+
const body = typeof rawBody === "string" ? encoder.encode(rawBody) : rawBody;
|
|
63
|
+
const prefix = encoder.encode(`${id}.${timestamp}.`);
|
|
64
|
+
const content = new Uint8Array(prefix.length + body.length);
|
|
65
|
+
content.set(prefix, 0);
|
|
66
|
+
content.set(body, prefix.length);
|
|
67
|
+
let expected;
|
|
68
|
+
try {
|
|
69
|
+
const key = await crypto.subtle.importKey("raw", fromBase64(secret.trim().replace(/^whsec_/, "")), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
70
|
+
expected = new Uint8Array(await crypto.subtle.sign("HMAC", key, content));
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
throw new ZimmerStackWebhookError("bad_signature", "The webhook secret is not a valid whsec_ secret");
|
|
74
|
+
}
|
|
75
|
+
// During a secret rotation the header carries one signature per secret, space-separated.
|
|
76
|
+
const matches = signature.split(/\s+/).some((part) => {
|
|
77
|
+
const [version, value] = part.split(",");
|
|
78
|
+
if (version !== "v1" || !value)
|
|
79
|
+
return false;
|
|
80
|
+
try {
|
|
81
|
+
return equalBytes(fromBase64(value), expected);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
if (!matches)
|
|
88
|
+
throw new ZimmerStackWebhookError("bad_signature", "The delivery's signature does not match");
|
|
89
|
+
try {
|
|
90
|
+
const event = JSON.parse(typeof rawBody === "string" ? rawBody : new TextDecoder().decode(rawBody));
|
|
91
|
+
if (!event || typeof event !== "object" || typeof event.id !== "string" || typeof event.type !== "string")
|
|
92
|
+
throw new Error("not an event");
|
|
93
|
+
return event;
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
throw new ZimmerStackWebhookError("bad_body", "The delivery is signed correctly but its body is not an event");
|
|
97
|
+
}
|
|
98
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zimmerstack/connect",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Official Node.js client for the ZimmerStack Connect API: rates, availability, stay rules, prices per channel and bookings, with pacing, safe retries and idempotency built in. Ships an MCP server for coding agents.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://docs.zimmerstack.com/sdk",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"zimmerstack",
|
|
9
|
+
"channel-manager",
|
|
10
|
+
"hotel",
|
|
11
|
+
"pms",
|
|
12
|
+
"ota",
|
|
13
|
+
"rates",
|
|
14
|
+
"availability",
|
|
15
|
+
"sdk",
|
|
16
|
+
"mcp",
|
|
17
|
+
"model-context-protocol"
|
|
18
|
+
],
|
|
19
|
+
"type": "module",
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=20"
|
|
23
|
+
},
|
|
24
|
+
"main": "./dist/cjs/index.js",
|
|
25
|
+
"module": "./dist/esm/index.js",
|
|
26
|
+
"types": "./dist/cjs/index.d.ts",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"import": {
|
|
30
|
+
"types": "./dist/esm/index.d.ts",
|
|
31
|
+
"default": "./dist/esm/index.js"
|
|
32
|
+
},
|
|
33
|
+
"require": {
|
|
34
|
+
"types": "./dist/cjs/index.d.ts",
|
|
35
|
+
"default": "./dist/cjs/index.js"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"./package.json": "./package.json"
|
|
39
|
+
},
|
|
40
|
+
"bin": {
|
|
41
|
+
"zimmerstack-connect": "./dist/esm/mcp/cli.js"
|
|
42
|
+
},
|
|
43
|
+
"files": [
|
|
44
|
+
"dist",
|
|
45
|
+
"AGENTS.md"
|
|
46
|
+
],
|
|
47
|
+
"scripts": {
|
|
48
|
+
"generate": "node scripts/generate.mjs",
|
|
49
|
+
"typecheck": "tsc -p tsconfig.json && tsc -p examples/next-app/tsconfig.json",
|
|
50
|
+
"test": "node --test \"test/*.test.ts\"",
|
|
51
|
+
"build": "node scripts/build.mjs",
|
|
52
|
+
"smoke": "node scripts/smoke.mjs",
|
|
53
|
+
"gates": "node scripts/generate.mjs --check && pnpm run typecheck && pnpm run test && node scripts/build.mjs && node scripts/smoke.mjs",
|
|
54
|
+
"prepack": "node scripts/build.mjs"
|
|
55
|
+
},
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@types/node": "^22.0.0",
|
|
58
|
+
"typescript": "^5.6.0"
|
|
59
|
+
},
|
|
60
|
+
"publishConfig": {
|
|
61
|
+
"access": "public"
|
|
62
|
+
}
|
|
63
|
+
}
|