webcake-storefront-mcp 1.36.2 → 1.38.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.
@@ -3,7 +3,8 @@ 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
+ import { checkContentPlaceholders, checkElementPatch, checkNativeContent } from "../builder/page.js";
7
+ import { SITE_CODE_FIELDS, checkSiteCode, codeGuard, codeUsage } from "../builder/native-first.js";
7
8
  import { PAGE_TYPE_NUM, PAGE_KINDS, applyPageMeta, normalizeSlug, checkPageCreateConflict } from "./builder.js";
8
9
  const pageSeoSchema = z.object({
9
10
  title: z.string().optional(),
@@ -263,6 +264,14 @@ async function getPageWithSource(api, pageId) {
263
264
  const source = parseSource(page.source && page.source.source);
264
265
  return { page, source };
265
266
  }
267
+ async function readSiteCode(api) {
268
+ const values = await Promise.all(SITE_CODE_FIELDS.map((f) => api.getSiteSettingField(f)));
269
+ return Object.fromEntries(SITE_CODE_FIELDS.map((f, i) => [f, values[i] || ""]));
270
+ }
271
+ const ALLOW_SHRINK = z.boolean().optional()
272
+ .describe("Allow the source to shrink by more than half: set it when native elements replaced an oversized embed or custom_css and you have read it first.");
273
+ const NATIVE_GAP = z.string().min(30).optional()
274
+ .describe("Only when the code was refused and no native way exists: the need, the elements/apps you checked, and what each one lacks. Tell the user first.");
266
275
  export function registerPageTools(server, api, handle) {
267
276
  server.tool("list_pages", "List all pages of the site (metadata only, without source)", {}, () => handle(async () => {
268
277
  const pages = await getCachedPages(api);
@@ -361,7 +370,8 @@ seo / settings are MERGED into the page's current settings — fields you don't
361
370
  server.tool("get_site_custom_code", `Get custom code of the site (CSS/JS). Two modes:
362
371
  - Default: returns ALL 4 code fields (full content)
363
372
  - With field filter: returns only the specified field(s) — saves tokens when you only need CSS or JS
364
- Add include_guide=true on first call to get the coding guide`, {
373
+ Add include_guide=true on first call to get the coding guide.
374
+ Custom code is the last resort: see get_build_guide → NATIVE FIRST before adding any. All-fields reads include _budget (usage vs limits).`, {
365
375
  fields: z.array(z.enum(["code_before_head", "code_before_body", "code_custom_css", "code_custom_javascript"]))
366
376
  .optional()
367
377
  .describe("Only return specific fields (e.g. ['code_custom_css']). Omit to get all 4 fields"),
@@ -379,12 +389,14 @@ Add include_guide=true on first call to get the coding guide`, {
379
389
  for (const f of allFields) {
380
390
  res._sizes[f] = (res[f] || "").length;
381
391
  }
392
+ res._budget = codeUsage(res);
382
393
  }
383
394
  if (include_guide)
384
395
  res.guide = CUSTOM_CODE_GUIDE;
385
396
  return res;
386
397
  }));
387
398
  server.tool("update_site_custom_code", `Update custom code (CSS/JS) for the entire site. Only sends fields you specify — others remain unchanged.
399
+ LAST RESORT: use native elements, their settings or an app first; a special feature uses the CMS app (collection + HTTP function) with only a small glue script here. See get_build_guide → NATIVE FIRST. Oversized code or UI/data in code is refused unless native_gap explains why.
388
400
  IMPORTANT: Before calling, you MUST read existing code with get_site_custom_code first, then show the user what will change and get explicit confirmation. NEVER update without user approval.
389
401
  - code_before_head: HTML/script inserted before </head>
390
402
  - code_before_body: HTML/script inserted before </body>
@@ -394,7 +406,9 @@ IMPORTANT: Before calling, you MUST read existing code with get_site_custom_code
394
406
  code_before_body: z.string().optional().describe("HTML/script to insert before </body>"),
395
407
  code_custom_css: z.string().optional().describe("Custom CSS for the site"),
396
408
  code_custom_javascript: z.string().optional().describe("Custom JavaScript for the site"),
397
- }, (codes) => {
409
+ native_gap: NATIVE_GAP,
410
+ allow_shrink: z.boolean().optional().describe("Allow removing more than half of a field: set it when native elements or the CMS replaced that code and you have read it first."),
411
+ }, ({ native_gap, allow_shrink, ...codes }) => {
398
412
  const settings = {};
399
413
  for (const [k, v] of Object.entries(codes)) {
400
414
  if (v != null)
@@ -405,17 +419,19 @@ IMPORTANT: Before calling, you MUST read existing code with get_site_custom_code
405
419
  if (fieldsToUpdate.length === 0)
406
420
  return { error: "No fields specified" };
407
421
  // Safeguard: read existing values and compare before overwriting
408
- const existingValues = await Promise.all(fieldsToUpdate.map((f) => api.getSiteSettingField(f)));
422
+ const current = await readSiteCode(api);
423
+ const blocked = codeGuard(checkSiteCode(current, settings), native_gap);
424
+ if (blocked)
425
+ return blocked;
409
426
  const comparison = {};
410
- for (let i = 0; i < fieldsToUpdate.length; i++) {
411
- const field = fieldsToUpdate[i];
412
- const existing = existingValues[i] || "";
427
+ for (const field of fieldsToUpdate) {
428
+ const existing = current[field] || "";
413
429
  const newVal = settings[field] || "";
414
430
  comparison[field] = { existing_length: existing.length, new_length: newVal.length };
415
431
  // Block if existing content is substantial and new content is much smaller (likely data loss)
416
- if (existing.length > 100 && newVal.length < existing.length * 0.5) {
432
+ if (!allow_shrink && existing.length > 100 && newVal.length < existing.length * 0.5) {
417
433
  return {
418
- error: `BLOCKED: Field "${field}" would shrink from ${existing.length} to ${newVal.length} chars (${Math.round((newVal.length / existing.length) * 100)}% of original). This may indicate data loss. Read existing content with get_site_custom_code first, then merge your changes.`,
434
+ error: `BLOCKED: Field "${field}" would shrink from ${existing.length} to ${newVal.length} chars (${Math.round((newVal.length / existing.length) * 100)}% of original). This may indicate data loss. Read existing content with get_site_custom_code first, then merge your changes. If native elements or the CMS replaced this code, pass allow_shrink:true.`,
419
435
  existing_preview: existing.substring(0, 500),
420
436
  comparison,
421
437
  };
@@ -425,22 +441,26 @@ IMPORTANT: Before calling, you MUST read existing code with get_site_custom_code
425
441
  return { success: true, comparison };
426
442
  });
427
443
  });
428
- server.tool("append_site_custom_code", `Append or prepend code to a custom code field WITHOUT reading the existing content first.
429
- Use this when you need to ADD new CSS rules, JS code, or script tags — no need to read first.
444
+ server.tool("append_site_custom_code", `Append or prepend code to a custom code field.
445
+ LAST RESORT: use native elements, their settings or an app first; a special feature uses the CMS app (collection + HTTP function) with only a small glue script here. See get_build_guide → NATIVE FIRST. Oversized code or UI/data in code is refused unless native_gap explains why.
430
446
  For full rewrites, use update_site_custom_code instead.`, {
431
447
  field: z.enum(["code_before_head", "code_before_body", "code_custom_css", "code_custom_javascript"])
432
448
  .describe("Which code field to modify"),
433
449
  code: z.string().describe("Code to add"),
434
450
  position: z.enum(["append", "prepend"]).default("append").describe("Add to end (append) or beginning (prepend)"),
435
- }, ({ field, code, position }) => handle(async () => {
436
- const existing = await api.getSiteSettingField(field);
437
- let content = existing || "";
451
+ native_gap: NATIVE_GAP,
452
+ }, ({ field, code, position, native_gap }) => handle(async () => {
453
+ const current = await readSiteCode(api);
454
+ let content = current[field] || "";
438
455
  if (position === "prepend") {
439
456
  content = code.trimEnd() + "\n\n" + content.trimStart();
440
457
  }
441
458
  else {
442
459
  content = content.trimEnd() + "\n\n" + code.trimEnd() + "\n";
443
460
  }
461
+ const blocked = codeGuard(checkSiteCode(current, { [field]: content }), native_gap);
462
+ if (blocked)
463
+ return blocked;
444
464
  await api.updateSiteSettings({ [field]: content });
445
465
  return { success: true, field, position, new_length: content.length };
446
466
  }));
@@ -478,6 +498,9 @@ IMPORTANT: Before calling, you MUST read existing content with list_page_content
478
498
  // Safeguard: read existing content and block if new content is suspiciously smaller
479
499
  const existingRes = await api.getPageContent(page_id, language_code);
480
500
  const existing = existingRes?.data ?? existingRes;
501
+ const placeholders = checkContentPlaceholders(content, existing?.content);
502
+ if (placeholders.length)
503
+ return { error: "BLOCKED: not saving.", errors: placeholders };
481
504
  if (existing && existing.content) {
482
505
  const existingStr = JSON.stringify(existing.content);
483
506
  const newStr = JSON.stringify(content);
@@ -528,7 +551,8 @@ events/bindings = REPLACE the whole array — pass the COMPLETE list (read it fi
528
551
  events: z.array(z.record(z.any())).optional().describe("Complete events array (replaces existing)"),
529
552
  bindings: z.array(z.record(z.any())).optional().describe("Complete bindings array (replaces existing)"),
530
553
  responsive: z.record(z.any()).optional().describe("Responsive breakpoint overrides (e.g. {bp1: {style: {...}, config: {...}}})"),
531
- }, ({ page_id, element_id, dry_run: dryRunParam, ...updates }) => handle(async () => {
554
+ allow_shrink: ALLOW_SHRINK,
555
+ }, ({ page_id, element_id, dry_run: dryRunParam, allow_shrink, ...updates }) => handle(async () => {
532
556
  const dry_run = dryRunParam !== undefined ? dryRunParam : getConfirmMode() === "always_confirm";
533
557
  invalidatePageCache();
534
558
  const { page, source, error } = await getPageWithSource(api, page_id);
@@ -541,6 +565,9 @@ events/bindings = REPLACE the whole array — pass the COMPLETE list (read it fi
541
565
  return { error: `Element "${element_id}" not found` };
542
566
  const beforeNode = JSON.parse(JSON.stringify(node));
543
567
  applyNodeUpdates(node, updates);
568
+ const codeErrors = checkElementPatch(source, node, beforeNode, updates.specials);
569
+ if (codeErrors.length)
570
+ return { error: "BLOCKED: not saving.", element_id, errors: codeErrors };
544
571
  const diff = computeNodeDiff(beforeNode, node);
545
572
  if (!diff)
546
573
  return { info: "No changes detected", element_id };
@@ -555,7 +582,7 @@ events/bindings = REPLACE the whole array — pass the COMPLETE list (read it fi
555
582
  // Actual save — send source as OBJECT (not string) because backend does Jason.encode!
556
583
  const newLen = JSON.stringify(source).length;
557
584
  const existingLen = JSON.stringify(parseSource(page.source && page.source.source)).length;
558
- if (existingLen > 200 && newLen < existingLen * 0.5) {
585
+ if (!allow_shrink && existingLen > 200 && newLen < existingLen * 0.5) {
559
586
  return {
560
587
  error: `BLOCKED: Page source would shrink from ${existingLen} to ${newLen} chars. This indicates data loss.`,
561
588
  existing_length: existingLen,
@@ -586,7 +613,8 @@ Same merge rules: style/config/specials = shallow merge, events/bindings = repla
586
613
  bindings: z.array(z.record(z.any())).optional(),
587
614
  responsive: z.record(z.any()).optional(),
588
615
  })).describe("Array of element updates"),
589
- }, ({ page_id, dry_run: dryRunParam, updates: elementUpdates }) => handle(async () => {
616
+ allow_shrink: ALLOW_SHRINK,
617
+ }, ({ page_id, dry_run: dryRunParam, updates: elementUpdates, allow_shrink }) => handle(async () => {
590
618
  const dry_run = dryRunParam !== undefined ? dryRunParam : getConfirmMode() === "always_confirm";
591
619
  invalidatePageCache();
592
620
  const { page, source, error } = await getPageWithSource(api, page_id);
@@ -604,6 +632,9 @@ Same merge rules: style/config/specials = shallow merge, events/bindings = repla
604
632
  const beforeNode = JSON.parse(JSON.stringify(node));
605
633
  const { element_id, ...updates } = upd;
606
634
  applyNodeUpdates(node, updates);
635
+ const codeErrors = checkElementPatch(source, node, beforeNode, updates.specials);
636
+ if (codeErrors.length)
637
+ return { error: "BLOCKED: not saving any of this batch.", element_id, errors: codeErrors };
607
638
  const diff = computeNodeDiff(beforeNode, node);
608
639
  results.push({ element_id, diff: diff || "no changes" });
609
640
  }
@@ -617,7 +648,7 @@ Same merge rules: style/config/specials = shallow merge, events/bindings = repla
617
648
  // Actual save — send source as OBJECT (not string) because backend does Jason.encode!
618
649
  const newLen = JSON.stringify(source).length;
619
650
  const existingLen = JSON.stringify(parseSource(page.source && page.source.source)).length;
620
- if (existingLen > 200 && newLen < existingLen * 0.5) {
651
+ if (!allow_shrink && existingLen > 200 && newLen < existingLen * 0.5) {
621
652
  return {
622
653
  error: `BLOCKED: Page source would shrink from ${existingLen} to ${newLen} chars. This indicates data loss.`,
623
654
  existing_length: existingLen,
@@ -639,27 +670,35 @@ IMPORTANT: Before calling this tool, you MUST:
639
670
  Safeguarded: blocks if new source is <50% of existing size.`, {
640
671
  page_id: z.string().describe("Page ID"),
641
672
  source: z.any().describe("Full page source object (sections tree) or JSON string"),
642
- custom_code: z.string().optional().describe("Custom code (CSS/JS) for this page"),
643
- }, ({ page_id, source, custom_code }) => handle(async () => {
673
+ custom_code: z.string().optional().describe("Custom code (CSS/JS) for this page. Last resort, same rules as update_site_custom_code."),
674
+ native_gap: NATIVE_GAP,
675
+ allow_shrink: ALLOW_SHRINK,
676
+ }, ({ page_id, source, custom_code, native_gap, allow_shrink }) => handle(async () => {
644
677
  const body = {};
645
678
  if (source != null) {
646
679
  // Ensure source is an object — backend does Jason.encode! so we must send object, not string
647
680
  body.source = typeof source === "string" ? JSON.parse(source) : source;
648
681
  }
649
682
  if (custom_code != null) {
683
+ invalidatePageCache();
684
+ const { page } = await getPageWithSource(api, page_id);
685
+ const old = page?.source?.custom_code;
686
+ const blocked = codeGuard(checkSiteCode({ code_custom_javascript: typeof old === "string" ? old : JSON.stringify(old ?? "") }, { code_custom_javascript: custom_code }), native_gap);
687
+ if (blocked)
688
+ return blocked;
650
689
  body.custom_code = custom_code;
651
690
  }
652
691
  // Safeguard: force fresh read and block if new source is suspiciously smaller
653
692
  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 };
657
693
  invalidatePageCache();
658
694
  const { source: existingSource, error } = await getPageWithSource(api, page_id);
695
+ const code = checkNativeContent(body.source, existingSource || undefined);
696
+ if (code.errors.length)
697
+ return { error: "BLOCKED: not saving.", errors: code.errors };
659
698
  if (!error && existingSource) {
660
699
  const existingLen = JSON.stringify(existingSource).length;
661
700
  const newLen = JSON.stringify(body.source).length;
662
- if (existingLen > 200 && newLen < existingLen * 0.5) {
701
+ if (!allow_shrink && existingLen > 200 && newLen < existingLen * 0.5) {
663
702
  return {
664
703
  error: `BLOCKED: New source (${newLen} chars) is much smaller than existing (${existingLen} chars) — ${Math.round((newLen / existingLen) * 100)}% of original. This may indicate fabricated data or data loss. Read the page source with get_page_source/get_page_element first, then apply changes.`,
665
704
  existing_length: existingLen,
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { SITE_CODE_FIELDS } from "../builder/native-first.js";
2
3
  // Site-level configuration the dashboard manages: custom domains, SEO redirect URLs,
3
4
  // shipping rules, marketing UTM links, system logs, saved table filters, general site
4
5
  // settings, site rename/slug, fonts, API keys, and publish history.
@@ -79,7 +80,26 @@ export function registerSiteConfigTools(server, api, handle) {
79
80
  server.tool("delete_saved_filter", "Delete (or dismiss, if not owner) a saved filter by id.", { id: z.string().describe("Saved filter id") }, ({ id }) => handle(() => api.deleteSavedFilter(id)));
80
81
  // ── General settings / rename ──
81
82
  server.tool("update_site_settings", `Update general site settings. The \`settings\` object is shallow-merged onto existing settings;
82
- other top-level keys (currency, slugs, is_maintenance, robot_txt, …) replace directly.`, { settings: z.record(z.any()).describe("Top-level keys to update (nested settings:{...} merges; others replace)") }, ({ settings }) => handle(() => api.updateSiteRaw(settings)));
83
+ other top-level keys (currency, slugs, is_maintenance, robot_txt, …) replace directly.`, { settings: z.record(z.any()).describe("Top-level keys to update (nested settings:{...} merges; others replace)") }, ({ settings }) => handle(async () => {
84
+ // Custom code only changes through update_site_custom_code, where the native-first checks live.
85
+ // Sending it back unchanged is fine: that's a read-modify-write of the whole settings object.
86
+ const blocked = { error: "BLOCKED: custom code fields can't be changed here. Use update_site_custom_code." };
87
+ let nested = settings.settings;
88
+ if (typeof nested === "string") {
89
+ try {
90
+ nested = JSON.parse(nested);
91
+ }
92
+ catch {
93
+ nested = null;
94
+ }
95
+ }
96
+ const sent = { ...settings, ...(nested && typeof nested === "object" ? nested : {}) };
97
+ for (const field of SITE_CODE_FIELDS) {
98
+ if (field in sent && String(sent[field] ?? "") !== String((await api.getSiteSettingField(field)) ?? ""))
99
+ return blocked;
100
+ }
101
+ return api.updateSiteRaw(settings);
102
+ }));
83
103
  server.tool("rename_site", "Rename the site (display name).", { name: z.string().describe("New site name") }, ({ name }) => handle(() => api.updateSiteName(name)));
84
104
  server.tool("update_site_slug", "Change the site's slug (subdomain). Fails if the slug is already taken.", { slug: z.string().describe("New slug") }, ({ slug }) => handle(() => api.updateSiteSlug(slug)));
85
105
  // ── Fonts ──