webcake-storefront-mcp 1.35.0 → 1.36.1

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/api.js CHANGED
@@ -50,6 +50,7 @@ export class WebcakeCmsApi {
50
50
  const controller = new AbortController();
51
51
  const timer = setTimeout(() => controller.abort(), timeout || DEFAULT_TIMEOUT);
52
52
  let res;
53
+ let json;
53
54
  try {
54
55
  res = await fetch(url, {
55
56
  method,
@@ -57,11 +58,16 @@ export class WebcakeCmsApi {
57
58
  body: body ? JSON.stringify(body) : undefined,
58
59
  signal: controller.signal,
59
60
  });
61
+ // Read the body under the same timer — clearing it after the headers left a stalled body unbounded.
62
+ json = await res.json().catch((e) => {
63
+ if (controller.signal.aborted)
64
+ throw e; // timed out mid-body: an error, not an empty success
65
+ return null;
66
+ });
60
67
  }
61
68
  finally {
62
69
  clearTimeout(timer);
63
70
  }
64
- const json = await res.json().catch(() => null);
65
71
  if (!res.ok) {
66
72
  const msg = (json && json.message) || (json && json.error) || res.statusText;
67
73
  throw new Error(`API ${res.status}: ${msg}`);
@@ -661,6 +667,8 @@ export class WebcakeCmsApi {
661
667
  });
662
668
  }
663
669
  // ── Promotions ──
670
+ /** `{ success, data[], total_entries }`, 15 rows/page by default; accepts term + is_activated
671
+ * (search_promotions uses this too — the dedicated get_promotions_advance endpoint 404s on prod). */
664
672
  listPromotions(query) {
665
673
  return this.request("GET", `/api/v1/dashboard/site/${this.siteId}/promotion_advance/all`, { query });
666
674
  }
@@ -673,12 +681,6 @@ export class WebcakeCmsApi {
673
681
  getActivePromotions() {
674
682
  return this.request("GET", `/api/v1/dashboard/site/${this.siteId}/promotion_advance/get_promotions_actived`);
675
683
  }
676
- /** Search/list promotions. The dedicated get_promotions_advance endpoint 404s on prod, so
677
- * this uses the same /all list endpoint (which accepts a query); the tool filters the
678
- * returned page client-side for type/status/keyword. */
679
- searchPromotions(query) {
680
- return this.request("GET", `/api/v1/dashboard/site/${this.siteId}/promotion_advance/all`, { query });
681
- }
682
684
  // ── Combos ──
683
685
  listCombos(query) {
684
686
  return this.request("GET", `/api/v1/dashboard/site/${this.siteId}/combo_product/all`, { query });
@@ -166,7 +166,7 @@ export const ELEMENT_ATTRS = {
166
166
  carousel: { specials: { type: "slide_only | …", autoplay: "on|off.", autoplay_time: "Seconds per slide.", arrowColor: "Arrow colour.", slides: "Slide list [{id,name}]." }, config: { slideWidth: "Slide width (px).", slideItems: "Visible slides count.", slideWidthUnit: "px|%.", showPaginate: "Pagination style (bar-dot|…).", paginateMode: "auto|manual.", arrowWidth: "Arrow width.", navColor: "Nav colour." }, events: "none", notes: "Holds slide children." },
167
167
  swiper: { specials: { autoplay: "on|off.", autoplayDelay: "ms between slides.", paginate: "Show pagination (boolean).", paginateBar: "bullet|bar|fraction.", direction: "row|column.", infinity: "Loop (boolean).", transitionMode: "slide|fade.", transitionTime: "ms.", auto_hide_navigation: "Hide arrows until hover (boolean).", arrowIcon: "Arrow SVG." }, config: { navColor: "Arrow colour.", navSize: "Arrow size (px).", navBackground: "Arrow background.", bulletSizeRow: "Bullet size.", barWidth: "Progress bar width.", fractionFontSize: "Fraction text size." }, events: "tab — fires on slide change.", notes: "Full-width hero/banner slider — holds slide children. The most common homepage hero." },
168
168
  slide: { events: "none", notes: "A single slide inside a carousel/swiper." },
169
- embed: { specials: { iframe: "Raw HTML / iframe markup.", htmlCode: "Raw HTML/JS snippet (type='code').", type: "code | iframe." }, events: "none", notes: "Raw HTML/JS embed — set htmlCode (type:'code') or iframe." },
169
+ embed: { specials: { iframe: "Raw HTML / iframe markup.", htmlCode: "Raw HTML/JS snippet (type='code').", type: "code | iframe." }, events: "none", notes: "Raw HTML/JS embed — set htmlCode (type:'code') or iframe. Renders as a sandboxed fixed-height iframe: not SEO-indexed, links can't navigate the site, forms don't reach WebCake. LAST RESORT: only for the one piece no native element can build (third-party widget, tracking snippet, custom animation) — everything else, incl. Stitch/Figma pages, is rebuilt natively." },
170
170
  googlemap: { specials: { iframe: "Google Maps embed iframe string.", type: "code | place." }, config: { maxHeight: "Map max height (px)." }, events: "none" },
171
171
  countdown: { specials: { time: "Target date/time.", type: "Countdown mode.", duration: "Countdown length (s).", repeat: "Restart when finished (boolean).", typeShow: "Largest unit shown (day|minute|…).", showDay: "Show days (boolean).", showHours: "Show hours (boolean).", showSecond: "Show seconds (boolean).", isPromotion: "Tie to a promotion (boolean).", durationStart: "Start datetime.", durationEnd: "End datetime.", dailyStart: "Daily reset start (HH:MM:SS).", dailyEnd: "Daily reset end.", positionTitle: "Title position (top|bottom).", showText: "Show the title text (boolean)." }, config: { bgTop: "Top-digit background.", bgBottom: "Bottom-digit background.", sizeDot: "Separator dot size.", spacingTitle: "Gap to title." }, events: "none", notes: "Countdown timer (flash sale / launch). Set duration or durationStart/End." },
172
172
  breadcrumb: { specials: { options: "Per-context paths (search/product/category/blog/post/default).", icon: "Separator string e.g. '>'." }, config: { hoverColor: "Link hover colour." }, events: "none", notes: "Auto-builds the trail (Home › Category › Product) from the current page — common on category/product pages." },
@@ -224,6 +224,14 @@ You can still hand-set a final \`node.bpN\` when editing an already-saved page.
224
224
  - Form: wrap inputs in a \`form\`; set \`form.specials.type\`
225
225
  (form_order | form_login | form_signup | form_discount | order_tracking). Each input
226
226
  needs \`specials.field_name\`.
227
+ - EMBED = LAST RESORT. Build everything native elements can build (text, image, button, form,
228
+ container, gallery, swiper, video, googlemap, countdown…) natively. Use \`embed\` ONLY for the
229
+ one piece no element can do (a third-party widget, a tracking/chat snippet, a custom
230
+ animation/canvas) — and embed just THAT piece, sized to it, inside a native section.
231
+ An embed renders as a sandboxed fixed-height iframe: Google can't index it, its links can't
232
+ open site pages, its forms never reach WebCake. So reference HTML (Google Stitch / Figma /
233
+ any exported page) is REBUILT natively section by section (ingest_html → new_section) —
234
+ never pasted whole into an embed (a whole HTML document in an embed is rejected on save).
227
235
  - Dataset elements (text-dataset, image-dataset, rectangle-dataset…) and the CHILDREN of
228
236
  a repeater (grid-product, cart-items, order-items, post-list, grid-category, customer-address)
229
237
  pull live data via a \`bindings\` array. Each binding is
@@ -300,6 +300,31 @@ export function buildFromSpec(spec) {
300
300
  return node;
301
301
  }
302
302
  /** Validate a page source. Errors block a save; warnings are fixable design issues. */
303
+ /** Embeds render as a sandboxed, fixed-height `<iframe src="blob:…">` (builderx_api
304
+ * assets/render/embed.js): invisible to SEO, links can't navigate the site, forms never reach
305
+ * WebCake. A whole exported page (Google Stitch / Figma / Tailwind-CDN HTML) dumped into one is
306
+ * therefore a broken page, not a shortcut. Errors block the save; warnings are a fix list. */
307
+ export function checkEmbeds(source) {
308
+ const errors = [];
309
+ const warnings = [];
310
+ walk(source, (node) => {
311
+ if (node.type !== "embed")
312
+ return;
313
+ const code = String((node.specials && node.specials.htmlCode) || "");
314
+ if (/<!doctype\s|<html[\s>]|<body[\s>]/i.test(code)) {
315
+ errors.push(`Embed "${node.id}" holds a whole HTML document (${code.length} chars). Embed is a last resort: build natively everything ` +
316
+ `native elements can (text/image/button/form/container… via ingest_html → new_section), and embed ONLY the one piece no element ` +
317
+ `can do (third-party widget, tracking snippet, custom animation). Embeds render as a sandboxed fixed-height iframe — ` +
318
+ `not indexed by Google, links can't open site pages, forms submit nowhere.`);
319
+ return;
320
+ }
321
+ if (/<form[\s>]/i.test(code))
322
+ warnings.push(`Embed "${node.id}" contains a <form> — native form elements can do this: its submissions never reach WebCake from the sandboxed iframe. Rebuild it as a native form.`);
323
+ if (/href\s*=\s*["']\/(?!\/)/i.test(code))
324
+ warnings.push(`Embed "${node.id}" has site links (href="/…") — native buttons/menus can do this: inside the embed's blob iframe they don't open your site. Rebuild them natively.`);
325
+ });
326
+ return { errors, warnings };
327
+ }
303
328
  export function validatePage(source) {
304
329
  const errors = [];
305
330
  const warnings = [];
@@ -370,6 +395,9 @@ export function validatePage(source) {
370
395
  };
371
396
  for (const s of source.sections)
372
397
  checkTree(s, []);
398
+ const embeds = checkEmbeds(source);
399
+ errors.push(...embeds.errors);
400
+ warnings.push(...embeds.warnings);
373
401
  return {
374
402
  valid: errors.length === 0,
375
403
  ...(errors.length ? { errors } : {}),
@@ -1,4 +1,18 @@
1
1
  [
2
+ {
3
+ "v": "1.36.1",
4
+ "d": "27/10/2026",
5
+ "type": "Changed",
6
+ "en": "get_build_guide and the ingest_html tool description now state that embed is a last resort: build everything native elements can with new_section,…",
7
+ "vi": "get_build_guide và mô tả tool ingest_html nay nêu rõ embed chỉ là phương án cuối: dựng native mọi thứ có thể bằng new_section, chỉ dùng embed cho…"
8
+ },
9
+ {
10
+ "v": "1.36.0",
11
+ "d": "22/10/2026",
12
+ "type": "Added",
13
+ "en": "New invoke_read_tool runs any read-only on-demand tool (list_*/get_*/search_*, i.e. tools with readOnlyHint) by name through the gateway, so clients…",
14
+ "vi": "Tool mới invoke_read_tool chạy bất kỳ tool chỉ-đọc nào (list_*/get_*/search_*, tức tool có readOnlyHint) qua gateway theo tên, nhờ đó client nào bắt…"
15
+ },
2
16
  {
3
17
  "v": "1.35.0",
4
18
  "d": "22/10/2026",
@@ -26,19 +40,5 @@
26
40
  "type": "Added",
27
41
  "en": "list_orders responses now include a status_name field alongside the numeric status.",
28
42
  "vi": "Kết quả trả về của list_orders nay có thêm trường status_name bên cạnh status dạng số."
29
- },
30
- {
31
- "v": "1.33.1",
32
- "d": "14/10/2026",
33
- "type": "Changed",
34
- "en": "create_product, create_product_category, create_blog_category, and create_article no longer accept a seo parameter; set SEO afterwards with…",
35
- "vi": "create_product, create_product_category, create_blog_category và create_article không còn nhận tham số seo; hãy đặt SEO sau khi tạo bằng…"
36
- },
37
- {
38
- "v": "1.33.0",
39
- "d": "14/10/2026",
40
- "type": "Added",
41
- "en": "Every tool, whether registered natively or reached through the search gateway (search_tools/invoke_tool/list_tool_groups), now reports readOnlyHint…",
42
- "vi": "Mọi tool, dù được đăng ký native hay được tiếp cận qua search gateway (search_tools/invoke_tool/list_tool_groups), nay đều có thêm annotation…"
43
43
  }
44
44
  ]
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_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.
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
 
package/dist/smoke.js CHANGED
@@ -76,6 +76,18 @@ console.log("== page: grid composition + validation ==");
76
76
  b.id = a.id;
77
77
  dup.sections.push(a, b);
78
78
  check("duplicate ids fail validation", validatePage(dup).valid === false);
79
+ // a whole exported HTML page dumped into an embed must fail; a small snippet must not
80
+ const embedPage = (htmlCode) => {
81
+ const p = newPageSkeleton();
82
+ const sec = buildElement("section");
83
+ const emb = buildElement("embed");
84
+ emb.specials = { ...emb.specials, type: "code", htmlCode };
85
+ sec.children = [emb];
86
+ p.sections.push(sec);
87
+ return validatePage(p);
88
+ };
89
+ check("whole-document embed fails validation", embedPage('<!DOCTYPE html><html><body><form></form></body></html>').valid === false);
90
+ check("small embed snippet passes", embedPage('<iframe src="https://www.youtube.com/embed/x"></iframe>').valid === true);
79
91
  // reassignIds gives a fresh id
80
92
  const before = a.id;
81
93
  reassignIds(a);
@@ -1,20 +1,31 @@
1
1
  import { z } from "zod";
2
2
  import { APP_TYPES, APP_NAMES, APP_TYPE_REFERENCE, APP_NAME_BY_TYPE } from "../enums.js";
3
+ /** Presence in /subcriptions/all = installed (that is what the dashboard shows). builderx_api get_app ignores
4
+ * is_active for every type except product_design (10), so is_active=false alone does not mean "off". */
5
+ export function summarizeApps(list) {
6
+ const installed = list.map((a) => ({
7
+ id: a.id,
8
+ type: a.type,
9
+ name: APP_NAME_BY_TYPE[a.type] ?? undefined,
10
+ enabled: a.type === APP_TYPES.product_design ? Boolean(a.is_active) : true,
11
+ is_active: a.is_active,
12
+ }));
13
+ const have = new Set(list.map((a) => a.type));
14
+ return {
15
+ installed_count: installed.length,
16
+ installed,
17
+ not_installed: APP_NAMES.filter((n) => !have.has(APP_TYPES[n])),
18
+ };
19
+ }
3
20
  export function registerAppTools(server, api, handle) {
4
- server.tool("list_apps", `List the site's installed applications (type, status, settings).
21
+ server.tool("list_apps", `Which applications are installed / enabled on the site — and which are not — in ONE call.
22
+ Returns installed[] (id, type, name, enabled) plus not_installed[] (app names). Do NOT call get_app per type
23
+ to answer "which apps are on"; use get_app only for one app's settings.
5
24
  App type codes: ${APP_TYPE_REFERENCE}.`, {}, () => handle(async () => {
6
25
  const res = await api.listApps();
26
+ // Real shape: { success, apps:[…] } — every non-removed AppSubscription row of the site.
7
27
  const list = res?.apps ?? res?.data?.apps ?? (Array.isArray(res?.data) ? res.data : []);
8
- return {
9
- apps: list.map((a) => ({
10
- type: a.type,
11
- type_name: APP_NAME_BY_TYPE[a.type] ?? undefined,
12
- status: a.status,
13
- is_active: a.is_active,
14
- id: a.id,
15
- })),
16
- app_types: APP_TYPES,
17
- };
28
+ return summarizeApps(list);
18
29
  }));
19
30
  server.tool("get_app", `Get one installed app by its type code (returns null if not installed).
20
31
  App type codes: ${APP_TYPE_REFERENCE}. You may pass the number or the name.`, {
@@ -291,7 +291,7 @@ Two-step safety: dry_run=true (default) describes what will happen; dry_run=fals
291
291
  hint: "Rebuild this as BuilderX sections: map each heading group + its text/image/button into a new_section call. Generate fresh copy where useful; re-host external images with upload_images if you want them on the site CDN. This is a structural blueprint, not a 1:1 clone.",
292
292
  };
293
293
  }
294
- server.tool("ingest_html", "Parse reference HTML into a structural blueprint (title, headings, paragraphs, images, buttons, colour palette) you can rebuild as BuilderX sections with new_section. Not a 1:1 clone.", {
294
+ server.tool("ingest_html", "Parse reference HTML (e.g. a Google Stitch / Figma / Codex export) into a structural blueprint (title, headings, paragraphs, images, buttons, colour palette) you can rebuild as native BuilderX sections with new_section. Not a 1:1 clone. Rebuild every part native elements can do; use an embed only for a piece no element can (third-party widget, custom animation) — never paste the whole HTML into one (sandboxed iframe: no SEO, broken links, dead forms; rejected on save).", {
295
295
  html: z.string().describe("Raw HTML to analyse"),
296
296
  }, ({ html }) => handle(async () => blueprintFromHtml(html)));
297
297
  server.tool("ingest_url", "Fetch a public URL and parse it into a structural blueprint (see ingest_html). Note: client-rendered (React/Vue) pages may return little content.", {
@@ -3,6 +3,7 @@ import { CUSTOM_CODE_GUIDE } from "../guides.js";
3
3
  import { getConfirmMode } from "./context.js";
4
4
  import { normalizeEvents } from "../builder/events.js";
5
5
  import { normalizeBindings } from "../builder/bindings.js";
6
+ import { checkEmbeds } from "../builder/page.js";
6
7
  import { PAGE_TYPE_NUM, PAGE_KINDS, applyPageMeta, normalizeSlug, checkPageCreateConflict } from "./builder.js";
7
8
  const pageSeoSchema = z.object({
8
9
  title: z.string().optional(),
@@ -650,6 +651,9 @@ Safeguarded: blocks if new source is <50% of existing size.`, {
650
651
  }
651
652
  // Safeguard: force fresh read and block if new source is suspiciously smaller
652
653
  if (body.source) {
654
+ const embeds = checkEmbeds(body.source);
655
+ if (embeds.errors.length)
656
+ return { error: "BLOCKED: whole-page HTML embed — not saving.", errors: embeds.errors };
653
657
  invalidatePageCache();
654
658
  const { source: existingSource, error } = await getPageWithSource(api, page_id);
655
659
  if (!error && existingSource) {
@@ -33,34 +33,61 @@ const PROMOTION_TYPES = `
33
33
  - is_detail_time: has specific day/time scheduling
34
34
  - is_hidden: hidden from storefront but still active
35
35
  `;
36
+ /** /promotion_advance/all pages at 15 rows by default (builderx_api Tools.get_page_limit_from_params),
37
+ * so one call used to show 15 of 46 promotions — walk every page instead. */
38
+ const PAGE_SIZE = 100;
39
+ const MAX_ROWS = 2000; // ponytail: 20 pages max; a site past 2000 promotions gets `truncated: true`
40
+ export async function fetchAllPromotions(api, query = {}) {
41
+ const rows = [];
42
+ let total = 0;
43
+ for (let page = 1; rows.length < MAX_ROWS; page++) {
44
+ const res = await api.listPromotions({ ...query, page, limit: PAGE_SIZE });
45
+ const data = Array.isArray(res?.data) ? res.data : [];
46
+ total = Number(res?.total_entries) || total;
47
+ rows.push(...data);
48
+ if (data.length < PAGE_SIZE || (total && rows.length >= total))
49
+ break;
50
+ }
51
+ return { rows: rows.slice(0, MAX_ROWS), total: total || rows.length };
52
+ }
53
+ /** Compact row: the list endpoint already carries pos_id + is_activated, so nobody needs get_promotion per row. */
54
+ export const promotionRow = (p) => ({
55
+ id: p.id,
56
+ name: p.name,
57
+ type: p.type,
58
+ promotion_classify: p.promotion_classify || undefined,
59
+ is_activated: p.is_activated,
60
+ pos_id: p.pos_id || null, // non-null = linked/synced with Pancake POS
61
+ start_time: p.start_time || undefined,
62
+ end_time: p.end_time || undefined,
63
+ priority_level: p.priority_level ?? undefined,
64
+ is_free_shipping: p.is_free_shipping || undefined,
65
+ is_hidden: p.is_hidden || undefined,
66
+ used_count: p.used_count || 0,
67
+ inserted_at: p.inserted_at,
68
+ });
69
+ /** Totals the model is usually asked for, so it never has to count rows itself. */
70
+ export function summarizePromotions(rows, total) {
71
+ const linked = rows.filter((p) => p.pos_id).length;
72
+ return {
73
+ total,
74
+ returned: rows.length,
75
+ ...(rows.length < total ? { truncated: true } : {}),
76
+ linked_pos: linked,
77
+ not_linked_pos: rows.length - linked,
78
+ activated: rows.filter((p) => p.is_activated).length,
79
+ };
80
+ }
36
81
  export function registerPromotionTools(server, api, handle) {
37
- server.tool("list_promotions", "List all promotions/discounts of the site (metadata only). Use get_promotion for full details", {
38
- page: z.number().optional().describe("Page number (default: 1)"),
39
- limit: z.number().optional().describe("Items per page (default: 20)"),
82
+ server.tool("list_promotions", `List ALL promotions/discounts of the site (every page is fetched for you). Each row has id, name, type,
83
+ is_activated, pos_id (non-null = linked/synced with POS), start/end time. The summary answers "how many promotions /
84
+ how many synced with POS / how many active" in ONE call — do not call get_promotion per row for that.
85
+ Use get_promotion only for one promotion's full rules.`, {
40
86
  include_guide: z.boolean().optional().describe("Include promotion type reference guide"),
41
- }, ({ page, limit, include_guide }) => handle(async () => {
42
- const res = await api.listPromotions({ page, limit });
43
- const promotions = (res && res.data) || [];
44
- const result = {
45
- data: Array.isArray(promotions)
46
- ? promotions.map((p) => ({
47
- id: p.id,
48
- name: p.name,
49
- type: p.type,
50
- promotion_classify: p.promotion_classify || undefined,
51
- is_activated: p.is_activated,
52
- start_time: p.start_time || undefined,
53
- end_time: p.end_time || undefined,
54
- priority_level: p.priority_level,
55
- is_free_shipping: p.is_free_shipping || undefined,
56
- is_hidden: p.is_hidden || undefined,
57
- coupon_info: p.coupon_info || undefined,
58
- used_count: p.used_count || 0,
59
- inserted_at: p.inserted_at,
60
- }))
61
- : promotions,
62
- total: res.total_entries || res.total || (Array.isArray(promotions) ? promotions.length : 0),
63
- };
87
+ }, ({ include_guide }) => handle(async () => {
88
+ const { rows, total } = await fetchAllPromotions(api);
89
+ const data = rows.map(promotionRow);
90
+ const result = { summary: summarizePromotions(data, total), data };
64
91
  if (include_guide)
65
92
  result.guide = PROMOTION_TYPES.trim();
66
93
  return result;
@@ -104,40 +131,25 @@ export function registerPromotionTools(server, api, handle) {
104
131
  total: Array.isArray(promotions) ? promotions.length : 0,
105
132
  };
106
133
  }));
107
- server.tool("search_promotions", "Search/filter promotions with advanced filters: by type, status (coming_soon/in_progress/finished), keyword, date range", {
134
+ server.tool("search_promotions", "Search/filter ALL promotions (every page): by keyword, type, time status (coming_soon/in_progress/finished), active flag. Rows carry pos_id (non-null = synced with POS)", {
108
135
  term: z.string().optional().describe("Search by promotion name"),
109
136
  type: z.string().optional().describe("Filter by type: normal, same_price, coupon, coupon_id_multiple_times, discount_by_coupon_id, promotion_order, promotion_category, x_get_y_prod, x_get_y_category"),
110
137
  status: z.number().optional().describe("Filter by time status: 1=coming_soon, 2=in_progress, 3=finished"),
111
138
  is_activated: z.boolean().optional().describe("Filter by active status"),
112
- page: z.number().optional().describe("Page number"),
113
- limit: z.number().optional().describe("Items per page"),
114
- }, ({ term, type, status, is_activated, page, limit }) => handle(async () => {
139
+ }, ({ term, type, status, is_activated }) => handle(async () => {
140
+ // term + is_activated filter server-side; type/status are applied here (the backend's `types`
141
+ // filter wants a list, which a query string can't carry).
115
142
  const query = {};
116
- if (term)
117
- query.term = term;
118
- if (type)
119
- query.type = type;
120
- if (status != null)
121
- query.status = status;
143
+ if (term && term.trim())
144
+ query.term = term.trim();
122
145
  if (is_activated != null)
123
146
  query.is_activated = is_activated;
124
- if (page)
125
- query.page = page;
126
- if (limit)
127
- query.limit = limit;
128
- const res = await api.searchPromotions({ page: page ?? 1, limit: limit ?? 50 });
129
- let list = (res && (res.data?.result || res.data)) || [];
130
- if (!Array.isArray(list))
131
- return res;
132
- // The /all endpoint doesn't filter, so apply the requested filters client-side.
133
- if (term)
134
- list = list.filter((p) => (p.name || "").toLowerCase().includes(term.toLowerCase()));
147
+ let list = (await fetchAllPromotions(api, query)).rows;
135
148
  if (type)
136
149
  list = list.filter((p) => p.type === type);
137
150
  if (status != null)
138
151
  list = list.filter((p) => p.time_status === status || p.status === status);
139
- if (is_activated != null)
140
- list = list.filter((p) => Boolean(p.is_activated) === is_activated);
141
- return { data: list, total: list.length, total_unfiltered: res.total_entries };
152
+ const data = list.map(promotionRow);
153
+ return { summary: summarizePromotions(data, data.length), data };
142
154
  }));
143
155
  }
@@ -146,7 +146,7 @@ export function buildToolGroupIndex(spec) {
146
146
  return `## Capability map (WebCake tool groups)
147
147
  Every capability below exists. Groups marked [loaded] are available as direct tools right now.
148
148
  Groups marked [on-demand] are NOT loaded to save context — to use one, call search_tools("english keywords")
149
- then invoke_tool(name, arguments). NEVER tell the user a capability is missing without searching first;
149
+ then invoke_read_tool(name, arguments) for read-only tools (list_/get_/search_…) or invoke_tool for the rest. NEVER tell the user a capability is missing without searching first;
150
150
  if the user's request touches an [on-demand] area (or you're unsure), search_tools BEFORE concluding.
151
151
  Tip: search_tools matches English tool names/descriptions — translate the user's intent into English keywords.
152
152
 
@@ -194,7 +194,7 @@ export function installTools(server, api, handle, opts = {}) {
194
194
  }))));
195
195
  server.tool("search_tools", `Find WebCake tools by keyword across the FULL catalog — including capabilities NOT loaded natively
196
196
  (marketing/CRM, translations, media, appointments, affiliate, reviews, domains/SEO/shipping, brands/tags/ribbons,
197
- courses, sale channels, automation…). Returns name, group, description and JSON input schema. Then run one with invoke_tool.`, {
197
+ courses, sale channels, automation…). Returns name, group, description and JSON input schema. Then run one with invoke_read_tool (read-only) or invoke_tool.`, {
198
198
  query: z.string().describe("Keywords, e.g. 'affiliate payout', 'translate product', 'add domain ssl', 'block phone'"),
199
199
  group: z.string().optional().describe("Restrict to a group name (see list_tool_groups)"),
200
200
  limit: z.number().optional().describe("Max results (default 8)"),
@@ -253,21 +253,31 @@ courses, sale channels, automation…). Returns name, group, description and JSO
253
253
  input_schema: jsonSchema(e),
254
254
  }));
255
255
  }));
256
- server.tool("invoke_tool", `Run any WebCake tool by exact name with its arguments (discover names + schemas via search_tools).
257
- Arguments are validated before running. Use this for tools that are not loaded natively.`, {
258
- name: z.string().describe("Exact tool name (from search_tools)"),
259
- arguments: z.record(z.any()).optional().describe("Arguments object matching the tool's input schema"),
260
- }, toolAnnotations("invoke_tool"), // runs any tool, so never read-only
261
- async ({ name, arguments: args }) => {
256
+ const runTool = async (name, args, readOnlyOnly) => {
262
257
  const e = registry.get(name);
263
258
  if (!e)
264
259
  return errorResult(`Error: unknown tool "${name}". Use search_tools to find available tools.`);
260
+ if (readOnlyOnly && !toolAnnotations(name).readOnlyHint) {
261
+ return errorResult(`Error: "${name}" is not read-only — run it with invoke_tool.`);
262
+ }
265
263
  const parsed = z.object(e.shape).safeParse(args ?? {});
266
264
  if (!parsed.success) {
267
265
  const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
268
266
  return errorResult(`Error: invalid arguments for "${name}": ${issues}`);
269
267
  }
270
268
  return e.handler(parsed.data, {});
271
- });
269
+ };
270
+ const gatewayArgs = {
271
+ name: z.string().describe("Exact tool name (from search_tools)"),
272
+ arguments: z.record(z.any()).optional().describe("Arguments object matching the tool's input schema"),
273
+ };
274
+ // invoke_tool can run writes, so it is never read-only — and clients that gate non-read-only tools
275
+ // behind a human approval (e.g. "ask before running") then stall EVERY on-demand read on a click.
276
+ // invoke_read_tool runs only read-only tools, so it can carry readOnlyHint and be auto-allowed.
277
+ server.tool("invoke_read_tool", `Run a READ-ONLY WebCake tool (list_*/get_*/search_*/count_*… — annotations.readOnlyHint in search_tools)
278
+ by exact name with its arguments. Prefer this over invoke_tool for lookups. Refuses tools that change data.`, gatewayArgs, { readOnlyHint: true }, ({ name, arguments: args }) => runTool(name, args, true));
279
+ server.tool("invoke_tool", `Run any WebCake tool by exact name with its arguments (discover names + schemas via search_tools).
280
+ Arguments are validated before running. For read-only tools prefer invoke_read_tool.`, gatewayArgs, toolAnnotations("invoke_tool"), // runs any tool, so never read-only
281
+ ({ name, arguments: args }) => runTool(name, args, false));
272
282
  return { total: collector.entries.length, native: nativeCount, groups: GROUPS.length };
273
283
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webcake-storefront-mcp",
3
- "version": "1.35.0",
3
+ "version": "1.36.1",
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",