webcake-storefront-mcp 1.40.0 → 1.42.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/http.js CHANGED
@@ -10,6 +10,8 @@ import { randomUUID } from "node:crypto";
10
10
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
11
11
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
12
12
  import { createServer } from "./server.js";
13
+ import { runWithConfigScope } from "./db.js";
14
+ import { accountOf, loadPrefs, savePref } from "./persistence/prefs.js";
13
15
  import { makeApi, resolveEnv, ENVIRONMENTS, DEFAULT_ENV } from "./config.js";
14
16
  import { landingHtml, faviconSvg, ogImageSvg, normalizeLang, ICON_PNG } from "./web-guide.js";
15
17
  import { privacyHtml, termsHtml } from "./legal.js";
@@ -291,8 +293,7 @@ async function handleOAuth(req, res, path) {
291
293
  return false;
292
294
  }
293
295
  export async function startHttpServer(port) {
294
- const transports = new Map();
295
- const apis = new Map();
296
+ const sessions = new Map();
296
297
  const httpServer = createHttpServer(async (req, res) => {
297
298
  const path = (req.url ?? "").split("?")[0];
298
299
  // ---- Favicon / brand icon ----
@@ -363,17 +364,23 @@ export async function startHttpServer(port) {
363
364
  }
364
365
  const sidHeader = header(req, "mcp-session-id");
365
366
  const jwt = header(req, "x-webcake-jwt");
367
+ const session = sidHeader ? sessions.get(sidHeader) : undefined;
368
+ // Unknown session (server restarted, or the request landed on another instance): the
369
+ // spec says 404 so the client silently re-initializes — a 400 leaves it stuck.
370
+ if (sidHeader && !session) {
371
+ rpcError(res, 404, "Session not found (expired or server restarted) — send a new initialize request.");
372
+ return;
373
+ }
366
374
  // An open session picks up a renewed credential in place (no re-initialize needed).
367
- const sessionApi = sidHeader ? apis.get(sidHeader) : undefined;
368
- if (sessionApi && jwt && jwt !== sessionApi.token && !isDeadJwt(jwt)) {
369
- sessionApi.switchToken(jwt);
375
+ if (session && jwt && jwt !== session.api.token && !(await isDeadJwt(jwt))) {
376
+ session.api.switchToken(jwt);
370
377
  const wsid = header(req, "x-webcake-session-id");
371
378
  if (wsid)
372
- sessionApi.switchSession(wsid);
379
+ session.api.switchSession(wsid);
373
380
  }
374
381
  // Enforce OAuth when enabled: no credential, or an expired/rejected WebCake token, gets
375
382
  // 401 + WWW-Authenticate so the client (re)opens the Connect page by itself.
376
- const dead = isDeadJwt(sessionApi ? sessionApi.token : jwt);
383
+ const dead = await isDeadJwt(session ? session.api.token : jwt);
377
384
  if (OAUTH_ENFORCED && (jwt == null || dead)) {
378
385
  res.writeHead(401, {
379
386
  "www-authenticate": `Bearer error="invalid_token", resource_metadata="${publicBase(req)}${WELL_KNOWN_PR}"`,
@@ -384,45 +391,64 @@ export async function startHttpServer(port) {
384
391
  return;
385
392
  }
386
393
  try {
387
- // Reuse an existing session.
388
- if (sidHeader && transports.has(sidHeader)) {
389
- const transport = transports.get(sidHeader);
394
+ if (session) {
390
395
  const body = req.method === "POST" ? await readBody(req) : undefined;
391
- await transport.handleRequest(req, res, body);
396
+ await runWithConfigScope(session.scope, () => session.transport.handleRequest(req, res, body));
392
397
  return;
393
398
  }
394
399
  // New session: must be an initialize POST.
395
400
  if (req.method === "POST") {
396
401
  const body = await readBody(req);
397
- if (!sidHeader && isInitializeRequest(body)) {
398
- const transport = new StreamableHTTPServerTransport({
399
- sessionIdGenerator: () => randomUUID(),
400
- onsessioninitialized: (id) => {
401
- transports.set(id, transport);
402
- apis.set(id, api);
402
+ if (isInitializeRequest(body)) {
403
+ // This session's config = its account's saved choices (site, confirm mode), shared
404
+ // by every instance; never the server's own config file.
405
+ const account = accountOf(jwt);
406
+ let api;
407
+ // Writes go to account_id only after /@me accepted the token (AuthPlug checks the
408
+ // signature), so a forged JWT can't write into someone else's preferences.
409
+ let verified;
410
+ const scope = {
411
+ values: account ? await loadPrefs(account) : {},
412
+ persist: (key, value) => {
413
+ const a = api;
414
+ if (!account || !a)
415
+ return;
416
+ if (verified?.token !== a.token) {
417
+ const t = a.token;
418
+ verified = { token: t, ok: a.getMe().then(() => accountOf(t) === account, () => false) };
419
+ }
420
+ void verified.ok.then((ok) => ok && savePref(account, key, value));
403
421
  },
404
- });
405
- transport.onclose = () => {
406
- if (transport.sessionId) {
407
- transports.delete(transport.sessionId);
408
- apis.delete(transport.sessionId);
409
- }
410
422
  };
411
- const api = apiFromRequest(req);
412
- // Backend rejected the token → remember it, so the next request 401s into Connect.
413
- api.onAuthExpired = async () => {
414
- markJwtDead(api.token);
415
- return null;
416
- };
417
- const server = createServer(api, { allowLocalFiles: false, tools: header(req, "x-webcake-tools") }); // remote: never read server-side files
418
- await server.connect(transport);
419
- await transport.handleRequest(req, res, body);
423
+ await runWithConfigScope(scope, async () => {
424
+ const transport = new StreamableHTTPServerTransport({
425
+ sessionIdGenerator: () => randomUUID(),
426
+ onsessioninitialized: (id) => {
427
+ sessions.set(id, { transport, api: api, scope });
428
+ },
429
+ });
430
+ transport.onclose = () => {
431
+ if (transport.sessionId)
432
+ sessions.delete(transport.sessionId);
433
+ };
434
+ const sessionApi = apiFromRequest(req);
435
+ api = sessionApi;
436
+ // Backend rejected the token → mark it dead on every instance, so the next
437
+ // request 401s into Connect.
438
+ sessionApi.onAuthExpired = async () => {
439
+ await markJwtDead(sessionApi.token);
440
+ return null;
441
+ };
442
+ const server = createServer(sessionApi, { allowLocalFiles: false, tools: header(req, "x-webcake-tools") }); // remote: never read server-side files
443
+ await server.connect(transport);
444
+ await transport.handleRequest(req, res, body);
445
+ });
420
446
  return;
421
447
  }
422
448
  rpcError(res, 400, "Bad Request: send an initialize request first (no valid mcp-session-id).");
423
449
  return;
424
450
  }
425
- rpcError(res, 400, "Bad Request: missing or unknown mcp-session-id.");
451
+ rpcError(res, 400, "Bad Request: missing mcp-session-id.");
426
452
  }
427
453
  catch (e) {
428
454
  const msg = e instanceof Error ? e.message : String(e);
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Per-ACCOUNT preferences for the remote server (the saved site, confirm mode). In stdio
3
+ * these live in the local config file; on a shared server that file would be shared by
4
+ * every user, so remote sessions keep them here instead, keyed by the JWT's account_id.
5
+ * Postgres (durable, shared by every instance) → Redis → process memory.
6
+ *
7
+ * Only an allowlist is stored — never tokens or session ids.
8
+ */
9
+ import { getPg } from "./postgres.js";
10
+ import { getRedis } from "./redis.js";
11
+ const KEYS = new Set(["site_id", "site_name", "site_domain", "confirm_mode"]);
12
+ const REDIS_PREFIX = "wc:sf:prefs:";
13
+ const mem = new Map();
14
+ let tableReady;
15
+ function ensureTable() {
16
+ const pool = getPg();
17
+ if (!pool)
18
+ return Promise.resolve(false);
19
+ tableReady ??= pool
20
+ .query(`CREATE TABLE IF NOT EXISTS mcp_account_prefs (account_id text PRIMARY KEY, prefs jsonb NOT NULL, updated_at bigint NOT NULL)`)
21
+ .then(() => true)
22
+ .catch((e) => {
23
+ console.error("[prefs] table init failed, using redis/memory:", e?.message ?? e);
24
+ return false;
25
+ });
26
+ return tableReady;
27
+ }
28
+ /** The account a WebCake JWT belongs to (payload.account_id), unverified — the backend verifies the token itself. */
29
+ export function accountOf(jwt) {
30
+ try {
31
+ const id = JSON.parse(Buffer.from(String(jwt).split(".")[1], "base64url").toString()).account_id;
32
+ return typeof id === "string" && id ? id : undefined;
33
+ }
34
+ catch {
35
+ return undefined;
36
+ }
37
+ }
38
+ export async function loadPrefs(account) {
39
+ try {
40
+ if (await ensureTable()) {
41
+ const { rows } = await getPg().query(`SELECT prefs FROM mcp_account_prefs WHERE account_id=$1`, [account]);
42
+ return { ...(rows[0]?.prefs ?? {}) };
43
+ }
44
+ const redis = getRedis();
45
+ if (redis)
46
+ return JSON.parse((await redis.get(REDIS_PREFIX + account)) || "{}");
47
+ }
48
+ catch (e) {
49
+ console.error("[prefs] load failed:", e?.message ?? e);
50
+ }
51
+ return { ...(mem.get(account) ?? {}) };
52
+ }
53
+ /** Persist one allowlisted key (null = delete). Fire-and-forget; never throws. */
54
+ export function savePref(account, key, value) {
55
+ if (!KEYS.has(key))
56
+ return;
57
+ const patch = value === null ? {} : { [key]: value };
58
+ (async () => {
59
+ if (await ensureTable()) {
60
+ // Merge in SQL so two instances writing different keys don't clobber each other.
61
+ await getPg().query(`INSERT INTO mcp_account_prefs (account_id, prefs, updated_at) VALUES ($1, $2::jsonb, $3)
62
+ ON CONFLICT (account_id) DO UPDATE SET prefs = (mcp_account_prefs.prefs - $4) || $2::jsonb, updated_at = $3`, [account, JSON.stringify(patch), Date.now(), key]);
63
+ return;
64
+ }
65
+ const redis = getRedis();
66
+ if (redis) {
67
+ // ponytail: read-modify-write, last writer wins; Postgres path is the atomic one.
68
+ const cur = JSON.parse((await redis.get(REDIS_PREFIX + account)) || "{}");
69
+ if (value === null)
70
+ delete cur[key];
71
+ else
72
+ cur[key] = value;
73
+ await redis.set(REDIS_PREFIX + account, JSON.stringify(cur));
74
+ return;
75
+ }
76
+ const cur = mem.get(account) ?? {};
77
+ if (value === null)
78
+ delete cur[key];
79
+ else
80
+ cur[key] = value;
81
+ mem.set(account, cur);
82
+ })().catch((e) => console.error("[prefs] save failed:", e?.message ?? e));
83
+ }
package/dist/server.js CHANGED
@@ -16,7 +16,7 @@ const INSTRUCTIONS = `You are an AI assistant connected to the WebCake/StoreCake
16
16
 
17
17
  IMPORTANT: When the user asks ANY question about their website, store, products, orders, pages, or code — you MUST use the available tools to look up real data before answering. Never guess.
18
18
 
19
- Tool discovery: the common tools (pages, builder, products, orders, blog, customers, apps, publishing) are loaded directly. MANY more capabilities are available on demand — marketing/CRM (email, contacts, subscribers, employees), translations, media library, appointments, affiliate, product reviews, custom domains / SEO redirects / shipping, brands / tags / ribbons / materials, courses, sale channels, automation, and more. If you don't see a directly-loaded tool for the task, call search_tools("keywords") to find it, then run it with invoke_read_tool(name, arguments) if it only reads (list_/get_/search_…), otherwise invoke_tool(name, arguments). Use list_tool_groups to see everything available.
19
+ Tool discovery: the common tools (pages, builder, products, orders, blog, customers, apps, publishing) are loaded directly. MANY more capabilities are available on demand — marketing/CRM (email, contacts, subscribers, employees), translations, media library, appointments, affiliate, product reviews, custom domains / SEO redirects / shipping, brands / tags / ribbons / materials, courses, sale channels, automation, and more. If you don't see a directly-loaded tool for the task, call search_tools("keywords") to find it, then run it with invoke_read_tool(name, arguments) if it only reads (list_/get_/search_…), otherwise invoke_tool(name, arguments). Use list_tool_groups to see everything available. If NO tool covers it, the whole backend API is reachable: api_find("keywords") → api_get (reads) / api_call (writes, dry_run first).
20
20
 
21
21
  You can also BUILD pages: use get_build_guide, list_elements, get_element to learn the BuilderX component model, new_section/new_element to compose, validate_page to check, then build_page (dry_run first) to create. Publishing is site-level via publish_site.
22
22
 
@@ -0,0 +1,178 @@
1
+ // api_find / api_get / api_call: the whole builderx_api surface the storefront JWT can reach,
2
+ // from src/api-catalog.generated.json (scripts/gen-api-catalog.mjs reads the Phoenix routers and
3
+ // controllers). The hand-written tools stay the way to do anything they cover: a write to a route
4
+ // one of them owns is refused here and names that tool, since those tools carry the guards
5
+ // (settings merge, page-source validation, native-first, CMS tokens, by_ai…).
6
+ import { readFileSync } from "node:fs";
7
+ import { z } from "zod";
8
+ let CATALOG = { meta: {}, ops: [] };
9
+ try {
10
+ CATALOG = JSON.parse(readFileSync(new URL("../api-catalog.generated.json", import.meta.url), "utf8"));
11
+ }
12
+ catch {
13
+ /* catalog missing: the tools answer with an empty list */
14
+ }
15
+ export const API_OPS = CATALOG.ops;
16
+ const BY_ID = new Map(API_OPS.map((o) => [o.id, o]));
17
+ /** Irreversible account-level operations: never through the generic gateway. */
18
+ const DENY = {
19
+ "post:/api/v1/dashboard/site/delete": "deleting a site is done by the owner in the WebCake dashboard",
20
+ "post:/api/v1/dashboard/site/:site_id/settings/employee/move_owner_permission": "transferring site ownership is done by the owner in the WebCake dashboard",
21
+ };
22
+ const pathParams = (path) => [...path.matchAll(/:(\w+)/g)].map((m) => m[1]);
23
+ const words = (s) => s.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
24
+ /** One line per operation — what api_find returns for a query. */
25
+ export function opLine(o) {
26
+ const keys = o.params ? Object.keys(o.params) : [];
27
+ const shown = keys.slice(0, 6).map((k) => (o.required?.includes(k) ? `${k}*` : k));
28
+ return `${o.id} — ${o.handler}${shown.length ? ` (${shown.join(", ")}${keys.length > 6 ? ", …" : ""})` : ""}${o.tools ? ` ⇒ tool: ${o.tools.slice(0, 3).join(", ")}` : ""}`;
29
+ }
30
+ export function searchOps(query, limit = 15, method) {
31
+ const terms = words(query);
32
+ const scored = API_OPS.filter((o) => !method || o.method === method.toUpperCase())
33
+ .map((o) => {
34
+ const segs = words(o.path.replace(/:\w+/g, ""));
35
+ const hw = words(o.handler);
36
+ const pw = Object.keys(o.params || {}).flatMap(words);
37
+ let s = 0;
38
+ for (const t of terms) {
39
+ if (segs.includes(t))
40
+ s += 3;
41
+ else if (segs.some((w) => w.startsWith(t) || t.startsWith(w) && w.length > 3))
42
+ s += 2;
43
+ if (hw.includes(t))
44
+ s += 2;
45
+ if (pw.includes(t))
46
+ s += 1;
47
+ }
48
+ if (s && o.path.includes("/dashboard/site/:site_id/"))
49
+ s += 0.5; // the site-scoped admin API
50
+ return { o, s };
51
+ })
52
+ .filter((x) => x.s > 0)
53
+ .sort((a, b) => b.s - a.s || a.o.path.length - b.o.path.length);
54
+ return scored.slice(0, limit).map((x) => x.o);
55
+ }
56
+ /** The call sheet: everything needed to call one operation correctly. */
57
+ export function describeOp(o) {
58
+ const where = o.method === "GET" ? "query" : "body";
59
+ return {
60
+ id: o.id,
61
+ method: o.method,
62
+ path: o.path,
63
+ handler: o.handler,
64
+ path_params: pathParams(o.path),
65
+ [where]: o.params || "not readable from the controller — send a modified copy of the matching GET",
66
+ ...(o.required ? { required: o.required } : {}),
67
+ ...(o.perms ? { needs_permission: o.perms } : {}),
68
+ ...(o.tools
69
+ ? { prefer_tool: o.tools, note: o.method === "GET" ? "A dedicated tool covers this route and returns a cleaner result." : "Writes to this route go through the dedicated tool (it carries the guards); api_call refuses them." }
70
+ : {}),
71
+ ...(DENY[o.id] ? { refused: DENY[o.id] } : {}),
72
+ };
73
+ }
74
+ const LIST_KEYS = ["data", "items", "products", "orders", "customers", "articles", "results", "list", "records", "entries"];
75
+ /** Trim a response for the model: keep `pick` fields per item, cap list length. */
76
+ export function trimResult(res, pick, maxItems = 50) {
77
+ const pickOne = (x) => pick && x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(pick.filter((k) => k in x).map((k) => [k, x[k]])) : x;
78
+ const trimList = (arr) => {
79
+ const items = arr.slice(0, maxItems).map(pickOne);
80
+ return arr.length > maxItems ? { items, total_items: arr.length, truncated: true } : items;
81
+ };
82
+ if (Array.isArray(res))
83
+ return trimList(res);
84
+ if (res && typeof res === "object") {
85
+ for (const k of LIST_KEYS) {
86
+ if (Array.isArray(res[k]))
87
+ return { ...res, [k]: trimList(res[k]) };
88
+ if (res[k] && typeof res[k] === "object")
89
+ for (const k2 of LIST_KEYS)
90
+ if (Array.isArray(res[k][k2]))
91
+ return { ...res, [k]: { ...res[k], [k2]: trimList(res[k][k2]) } };
92
+ }
93
+ return pick ? pickOne(res) : res;
94
+ }
95
+ return res;
96
+ }
97
+ const MAX_CHARS = 30_000;
98
+ export function registerApiGatewayTools(server, api, handle) {
99
+ server.tool("api_find", `Search the FULL WebCake backend API (${API_OPS.length} operations the storefront account can call — far more than the dedicated tools cover). With \`query\`: one line per match \`id — Controller.action (body/query keys, * = required) ⇒ tool: dedicated tool if one exists\`. With \`id\`: the call sheet (path params, body/query keys with their nested fields, required keys, permission needed). Prefer a dedicated tool when one is listed; use api_get / api_call for the rest.`, {
100
+ query: z.string().optional().describe("English keywords from the path/controller, e.g. 'shipping fee', 'product tag', 'customer point'"),
101
+ id: z.string().optional().describe("Exact operation id from a previous search, e.g. 'post:/api/v1/dashboard/site/:site_id/products/create'"),
102
+ method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).optional().describe("Only this HTTP method"),
103
+ limit: z.number().int().min(1).max(40).optional().describe("Max lines (default 15)"),
104
+ }, ({ query, id, method, limit }) => handle(async () => {
105
+ if (id) {
106
+ const o = BY_ID.get(id);
107
+ if (!o)
108
+ throw new Error(`Unknown operation "${id}". Search with api_find({ query }).`);
109
+ return describeOp(o);
110
+ }
111
+ if (!query)
112
+ throw new Error("Pass query (keywords) or id (an operation id).");
113
+ const hits = searchOps(query, limit ?? 15, method);
114
+ return hits.length ? hits.map(opLine) : `No operation matches "${query}". Try other English words from the path (e.g. 'promotion', 'shipping', 'tag').`;
115
+ }));
116
+ const call = async (args, readOnly) => {
117
+ const o = args.id ? BY_ID.get(args.id) : API_OPS.find((x) => x.method === String(args.method || "").toUpperCase() && x.path === args.path);
118
+ if (!o)
119
+ throw new Error(`Unknown operation${args.id ? ` "${args.id}"` : ""}. Find it with api_find({ query }) and pass its id.`);
120
+ if (readOnly && o.method !== "GET")
121
+ throw new Error(`${o.id} is a ${o.method} — run it with api_call.`);
122
+ if (DENY[o.id])
123
+ throw new Error(`Refused: ${DENY[o.id]}.`);
124
+ if (o.method !== "GET" && o.tools)
125
+ throw new Error(`Refused: ${o.id} is written through ${o.tools.join(" / ")} — that tool validates and guards this write. Use it instead.`);
126
+ const params = { ...(args.path_params || {}) };
127
+ if (params.site_id == null && pathParams(o.path).includes("site_id")) {
128
+ if (!api.siteId)
129
+ throw new Error("No site selected — call list_my_sites + switch_site, or pass path_params.site_id.");
130
+ params.site_id = api.siteId;
131
+ }
132
+ const missingPath = pathParams(o.path).filter((p) => params[p] == null || params[p] === "");
133
+ if (missingPath.length)
134
+ throw new Error(`Missing path_params: ${missingPath.join(", ")}. Call sheet: api_find({ id: "${o.id}" }).`);
135
+ const path = o.path.replace(/:(\w+)/g, (_, p) => encodeURIComponent(String(params[p])));
136
+ const input = o.method === "GET" ? args.query || {} : args.body || {};
137
+ const missing = (o.required || []).filter((k) => input[k] === undefined);
138
+ if (missing.length)
139
+ throw new Error(`Missing required ${o.method === "GET" ? "query" : "body"} keys: ${missing.join(", ")}. Call sheet: api_find({ id: "${o.id}" }).`);
140
+ const unknown = o.params ? Object.keys(input).filter((k) => !(k in o.params)) : [];
141
+ if (o.method !== "GET" && args.dry_run !== false)
142
+ return {
143
+ dry_run: true,
144
+ would_send: { method: o.method, path, ...(args.query ? { query: args.query } : {}), body: input },
145
+ ...(unknown.length ? { unknown_keys: unknown, note: "the action never reads these keys" } : {}),
146
+ next: "Show the user what will change; on their OK call again with dry_run:false.",
147
+ };
148
+ let res;
149
+ try {
150
+ res = await api.request(o.method === "ANY" ? "POST" : o.method, path, o.method === "GET" ? { query: input } : { body: input, query: args.query });
151
+ }
152
+ catch (e) {
153
+ const msg = e?.message || String(e);
154
+ throw new Error(/API 403/.test(msg) && o.perms ? `${msg} — needs site permission ${o.perms.join(" / ")}.` : msg);
155
+ }
156
+ const out = trimResult(res, args.pick, args.max_items ?? 50);
157
+ const text = JSON.stringify(out);
158
+ return {
159
+ ...(unknown.length ? { unknown_keys: unknown } : {}),
160
+ result: text.length > MAX_CHARS ? `${text.slice(0, MAX_CHARS)}… (cut at ${MAX_CHARS} chars — narrow with pick / max_items / query filters)` : out,
161
+ };
162
+ };
163
+ const shared = {
164
+ id: z.string().optional().describe("Operation id from api_find (preferred)"),
165
+ method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "ANY"]).optional().describe("With path, when id is not given"),
166
+ path: z.string().optional().describe("Catalog path with :params, e.g. /api/v1/dashboard/site/:site_id/product_tags/all"),
167
+ path_params: z.record(z.string()).optional().describe("Values for :params in the path; site_id defaults to the current site"),
168
+ query: z.record(z.any()).optional().describe("Query-string values"),
169
+ pick: z.array(z.string()).optional().describe("Keep only these fields on each item of a list result (or on a single object)"),
170
+ max_items: z.number().int().min(1).max(500).optional().describe("Cap list results (default 50)"),
171
+ };
172
+ server.tool("api_get", "Run a READ-ONLY (GET) operation from api_find by id. site_id is filled from the current site. Use pick / max_items to keep the result small. Refuses anything that is not a GET.", shared, (args) => handle(() => call(args, true)));
173
+ server.tool("api_call", "Run any operation from api_find by id (GET, POST, PUT, PATCH, DELETE). Writes default to dry_run:true and return exactly what would be sent — show the user, then repeat with dry_run:false. Refuses writes to routes a dedicated tool owns (it names the tool) and irreversible account operations. Required keys are checked against the call sheet before sending.", {
174
+ ...shared,
175
+ body: z.any().optional().describe("JSON body for POST/PUT/PATCH/DELETE (keys from the call sheet)"),
176
+ dry_run: z.boolean().optional().describe("Default true for writes: describe, don't send"),
177
+ }, (args) => handle(() => call(args, false)));
178
+ }
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { withCode } from "../builder/element-schema.js";
2
3
  import { resolvePreviewUrl, draftPreviewUrl } from "../config.js";
3
4
  import { captureScreenshot, resolveMicrolinkKey, resolveScreenshotProxyBase } from "../persistence/screenshot-client.js";
4
5
  import { validatePage, missingBreakpoints } from "../builder/page.js";
@@ -22,7 +23,8 @@ export async function preflightSite(api) {
22
23
  // write (missing/duplicate id, native-first volume…) already publishes today, so it only warns.
23
24
  const judge = (name, src, v) => {
24
25
  const shape = checkShape(src);
25
- const crash = shape.errors.filter((e) => !shape.editorOnly.includes(e)); // the live site blanks
26
+ // validatePage tags shape errors "[SHAPE] …"; compare in that form.
27
+ const crash = shape.errors.filter((e) => !shape.editorOnly.includes(e)).map((e) => withCode("SHAPE", e)); // the live site blanks
26
28
  const fatal = (v.errors || []).filter((e) => crash.includes(e));
27
29
  const rest = (v.errors || []).filter((e) => !crash.includes(e));
28
30
  errors.push(...fatal.slice(0, 10).map((e) => `${name}: ${e}`));
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { elementSchema, suggestType, valueRules } from "../builder/element-schema.js";
2
3
  import { z } from "zod";
3
4
  import { BUILD_GUIDE } from "../builder/guide.js";
4
5
  import { PAGE_SCHEMA } from "../builder/page-schema.js";
@@ -173,9 +174,17 @@ export function registerBuilderTools(server, api, handle) {
173
174
  server.tool("get_build_guide", "Get the BuilderX page authoring guide: page shape, the grid layout model, styling, breakpoints, forms/data, and the build workflow. Read this before building or heavily editing a page.", {}, () => handle(async () => ({ guide: BUILD_GUIDE })));
174
175
  server.tool("get_page_schema", "Get the authoritative JSON Schema (Draft 2020-12) for a page source `{ sections: [...] }` — the structural contract for every node (id/type/specials/runtime{style,config}/children/events/bindings) in the CSS-grid model. Use it as the shape to emit; validate_page enforces the semantic rules.", {}, () => handle(async () => PAGE_SCHEMA));
175
176
  server.tool("list_elements", "List all BuilderX element/component types you can place on a page, grouped by category with a one-line summary and whether each is a container.", {}, () => handle(async () => listElements()));
176
- server.tool("get_element", "Get the full detail of an element type: category, container flag, summary, an ATTRIBUTES reference (the meaningful specials/config keys + their purpose/allowed values, events, and dataset binding targets), and a live skeleton node (the authoritative default shape) you can copy and edit. Read this before authoring/editing an element so you set the right keys.", {
177
+ server.tool("get_element", "Get the full detail of an element type: category, container flag, summary, an ATTRIBUTES reference (the meaningful specials/config keys + their purpose, events, and dataset binding targets), VALUE_RULES (per key: allowed values `one of …` that validate_page enforces, values `seen` on real pages, and non-string value types), PARENTS when it must sit inside a given container, and a live skeleton node (the authoritative default shape) you can copy and edit. Read this before authoring/editing an element so you set the right keys.", {
177
178
  type: z.string().describe("Element type, e.g. 'text', 'button', 'grid-product'"),
178
- }, ({ type }) => handle(async () => getElement(type)));
179
+ }, ({ type }) => handle(async () => {
180
+ const el = getElement(type);
181
+ if (el.error) {
182
+ const guess = suggestType(type);
183
+ return guess ? { ...el, did_you_mean: guess } : el;
184
+ }
185
+ const parents = elementSchema(type)?.parents;
186
+ return { ...el, ...(parents ? { parents } : {}), value_rules: valueRules(type) };
187
+ }));
179
188
  server.tool("list_events", "List every interaction EVENT you can attach to a node: the triggers (eventName: click/hover/success/submit/…) and the actions (open_page, scroll_to, toggle, open_popup, add_to_cart, buy_now, phone_call, open_link, …) with the exact extra fields each action needs. Attach via new_element/new_section opts.events (ids are auto-minted, e.g. opts.events=[{ action:'add_to_cart', open_page:'cart' }]).", {}, () => handle(async () => describeEventsCatalog()));
180
189
  server.tool("list_bindings", "List every dynamic-data BINDING target: the datasets (product, cart_item, order, order_item, post, category, customer, customer_address, …) and their exact field names ('product::product_price', …), which page type each needs (store/member/blog), and how repeater children (grid-product, cart-items, post-list) bind per-item. Attach via new_element opts.bindings (ids auto-minted, e.g. opts.bindings=[{ target:'product::product_price' }]).", {}, () => handle(async () => describeBindingsCatalog()));
181
190
  server.tool("new_element", "Build a single structurally-valid element node from the real builder factory. Returns the node — edit its specials/style, then place it in a section's children.", {
@@ -207,7 +216,7 @@ Example children: [{ "type":"container", "children":[{"type":"image","opts":{...
207
216
  containerOpts: container_opts || {},
208
217
  })));
209
218
  server.tool("new_page_skeleton", "Return an empty but valid page source: { sections: [] }. Add sections built with new_section, then save with build_page.", {}, () => handle(async () => newPageSkeleton()));
210
- server.tool("validate_page", "Validate a page source ({ sections: [...] }). Returns errors (block saving: duplicate/missing ids, missing types) and warnings (unknown types, form fields without field_name, dangling event targets) plus stats. Always run this before build_page.", {
219
+ server.tool("validate_page", "Validate a page source ({ sections: [...] }) against every element's schema. Each message reads `[CODE] #id (type) where: problem → fix`. errors block saving (duplicate/missing ids, renderer-crash shapes…); warnings render wrong (UNKNOWN_KEY invented/misspelled key, STYLE_KEY not a CSS property, TYPE_MISMATCH, BAD_VALUE outside the allowed values, BAD_PARENT, OUTSIDE_FORM, FIELD_NAME, EVENT/BINDING problems…). Repeated warnings are collapsed per code; summary.by_code counts all. Always run this before build_page and fix by code.", {
211
220
  source: z.any().describe("Page source object or JSON string"),
212
221
  }, ({ source }) => handle(async () => {
213
222
  const parsed = parseSource(source);
@@ -33,6 +33,7 @@ import { registerBuilderTools } from "./builder.js";
33
33
  import { registerBuilderExtraTools } from "./builder-extras.js";
34
34
  import { registerPageDraftTools } from "./page-draft.js";
35
35
  import { registerSitePlanTools } from "./site-plans.js";
36
+ import { registerApiGatewayTools } from "./api-gateway.js";
36
37
  /** Tool groups. `core` groups load natively; the rest are reached via search_tools + invoke_tool. */
37
38
  export const GROUPS = [
38
39
  { name: "session", title: "Session & apps", core: true, desc: "Connection context, site switch, app install/list, result cache" },
@@ -87,6 +88,7 @@ const MODULES = [
87
88
  ["web", registerBuilderExtraTools],
88
89
  ["web", registerPageDraftTools],
89
90
  ["site_config", registerSitePlanTools],
91
+ ["session", registerApiGatewayTools],
90
92
  ];
91
93
  /** Captures server.tool(...) calls into a registry instead of registering them. */
92
94
  class ToolCollector {
@@ -129,7 +131,7 @@ const READ_ONLY = /^(list|get|search|read|query|find|count|semantic|check|valida
129
131
  const DESTRUCTIVE = /^(delete|remove|uninstall|empty|clear|block|unblock|refuse)_/;
130
132
  const ADDITIVE = /^(create|add|upload|install|invite|duplicate|save)_/;
131
133
  export function toolAnnotations(name) {
132
- if (READ_ONLY.test(name))
134
+ if (READ_ONLY.test(name) || name === "api_find" || name === "api_get")
133
135
  return { readOnlyHint: true };
134
136
  if (DESTRUCTIVE.test(name))
135
137
  return { readOnlyHint: false, destructiveHint: true };
@@ -168,7 +170,9 @@ export function installTools(server, api, handle, opts = {}) {
168
170
  let nativeCount = 0;
169
171
  for (const e of collector.entries) {
170
172
  if (native.has(e.group)) {
171
- server.tool(e.name, e.description, e.shape, toolAnnotations(e.name), e.handler);
173
+ // .strict(): an argument the tool doesn't take is REFUSED with its name, not silently
174
+ // dropped (a dropped page_id/site_id made a call act on the wrong page).
175
+ server.registerTool(e.name, { description: e.description, inputSchema: z.object(e.shape).strict(), annotations: toolAnnotations(e.name) }, e.handler);
172
176
  nativeCount++;
173
177
  }
174
178
  }
@@ -260,7 +264,7 @@ courses, sale channels, automation…). Returns name, group, description and JSO
260
264
  if (readOnlyOnly && !toolAnnotations(name).readOnlyHint) {
261
265
  return errorResult(`Error: "${name}" is not read-only — run it with invoke_tool.`);
262
266
  }
263
- const parsed = z.object(e.shape).safeParse(args ?? {});
267
+ const parsed = z.object(e.shape).strict().safeParse(args ?? {});
264
268
  if (!parsed.success) {
265
269
  const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
266
270
  return errorResult(`Error: invalid arguments for "${name}": ${issues}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webcake-storefront-mcp",
3
- "version": "1.40.0",
3
+ "version": "1.42.0",
4
4
  "description": "MCP server for the WebCake/StoreCake storefront builder — page CRUD, page authoring, products, orders, and more",
5
5
  "mcpName": "io.github.vuluu2k/webcake-storefront-mcp",
6
6
  "license": "MIT",
@@ -30,6 +30,8 @@
30
30
  "dev": "tsc --watch",
31
31
  "dev:guide": "node scripts/preview-guide.mjs",
32
32
  "smoke": "node dist/smoke.js",
33
+ "mine-elements": "node scripts/mine-element-keys.mjs",
34
+ "gen-api": "node scripts/gen-api-catalog.mjs",
33
35
  "prepare": "npm run build",
34
36
  "prepublishOnly": "npm run build && npm run smoke",
35
37
  "test": "node --test \"test/*.test.mjs\""