webcake-storefront-mcp 1.42.0 → 2.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.
@@ -0,0 +1,132 @@
1
+ // Tool families: one MCP tool per domain, the operation picked by `action` — the way sbuilder's
2
+ // sb_store / sb_collection keep ~40 tools for a whole platform. The action names ARE the old tool
3
+ // names, so every guide and description that says "call new_section" still reads right, and
4
+ // invoke_tool keeps accepting the old names. Members are registered exactly as before (the
5
+ // collector in registry.ts); a family only changes how they are exposed.
6
+ import { z } from "zod";
7
+ import { zodToJsonSchema } from "zod-to-json-schema";
8
+ /** family tool name → [one-line purpose, member tool names]. Order = order shown to the model. */
9
+ export const FAMILIES = {
10
+ page: ["Pages of the current site: list, create, rename/SEO, delete, read and save the source, content text, preview", [
11
+ "list_pages", "create_page", "update_page", "delete_page", "get_page_source", "update_page_source", "list_page_contents", "update_page_content", "preview_page",
12
+ ]],
13
+ page_element: ["Read and edit single elements on a saved page, or append a section", [
14
+ "search_page_elements", "get_page_element", "update_page_element", "update_page_elements", "add_section",
15
+ ]],
16
+ page_draft: ["Build a page section by section in a draft, then commit it as one save", [
17
+ "start_page_draft", "add_draft_section", "get_page_draft", "list_page_drafts", "commit_page_draft", "clear_page_draft",
18
+ ]],
19
+ builder_ref: ["Reference for composing pages: elements, attributes, events, bindings, schema, guides, section templates", [
20
+ "get_build_guide", "get_intake_guide", "list_elements", "get_element", "list_events", "list_bindings", "get_page_schema", "list_section_templates",
21
+ ]],
22
+ compose: ["Create element nodes from the factory (never hand-write nodes)", [
23
+ "new_element", "new_section", "new_row", "new_page_skeleton",
24
+ ]],
25
+ global_source: ["Site-wide sources (popups, cart drawer, header/footer sources): list, read, create, edit, translate", [
26
+ "list_global_sources", "get_global_source_detail", "create_global_source", "update_global_source", "delete_global_source",
27
+ "search_global_source_elements", "get_global_source_element", "update_global_source_element", "update_global_source_elements",
28
+ "get_global_source_contents", "update_global_source_contents",
29
+ ]],
30
+ global_section: ["Global header/footer/custom sections shown on every page", [
31
+ "list_global_sections", "get_global_section", "create_global_section", "delete_global_section", "search_global_section_elements", "get_global_section_element",
32
+ ]],
33
+ site_code: ["Custom code, site-wide or for ONE page (native first: refused when an element can do it)", [
34
+ "get_site_custom_code", "update_site_custom_code", "append_site_custom_code", "get_page_custom_code", "update_page_custom_code",
35
+ ]],
36
+ theme: ["Site themes and templates", ["list_themes", "semantic_search_themes", "list_template_themes", "create_site_from_template"]],
37
+ product: ["Products of the store", ["list_products", "get_product", "create_product", "update_product", "delete_product", "set_product_published"]],
38
+ product_category: ["Product categories", ["list_categories", "create_product_category", "update_product_category", "delete_product_category"]],
39
+ promotion: ["Promotions and combos", ["list_promotions", "search_promotions", "get_promotion", "get_promotion_items", "get_active_promotions", "list_combos", "get_combo_items"]],
40
+ order: ["Orders and customers", ["list_orders", "get_order", "list_customers", "find_customer"]],
41
+ blog: ["Blog articles and blog categories", ["list_articles", "get_article", "create_article", "update_article", "delete_article", "create_blog_category", "update_blog_category"]],
42
+ collection: ["CMS collections (custom data tables) and their records", ["list_collections", "get_collection", "create_collection", "update_collection_columns", "delete_collection", "query_collection_records"]],
43
+ cms_function: ["CMS files and HTTP functions (backend code): read, edit, version, run", [
44
+ "get_http_function", "get_http_function_snippet", "edit_http_function", "update_http_function", "create_cms_file", "update_cms_file",
45
+ "save_file_version", "restore_file_version", "run_function",
46
+ ]],
47
+ app: ["Apps of the site (install, configure, remove)", ["list_apps", "get_app", "install_app", "uninstall_app"]],
48
+ cached_result: ["Large results kept server-side: list and page through them", ["list_cached_results", "read_cached_result"]],
49
+ };
50
+ /** First sentence of a description, capped — the per-action line in the family description. */
51
+ const firstSentence = (d) => {
52
+ const one = d.replace(/\s+/g, " ").trim();
53
+ const cut = one.search(/(?<=[a-z0-9)\]"'])\.\s/i);
54
+ const s = cut > 20 ? one.slice(0, cut + 1) : one;
55
+ return s.length > 180 ? `${s.slice(0, 177)}…` : s;
56
+ };
57
+ const typeName = (s) => s?._def?.typeName === "ZodOptional" || s?._def?.typeName === "ZodDefault" ? typeName(s._def.innerType) : s?._def?.typeName;
58
+ const unwrap = (s) => (["ZodOptional", "ZodDefault", "ZodNullable"].includes(s?._def?.typeName) ? unwrap(s._def.innerType) : s);
59
+ /** Top-level type only: nested object/array schemas are re-checked per action and shown by help. */
60
+ function shallow(s) {
61
+ const t = unwrap(s)?._def?.typeName;
62
+ if (t === "ZodObject" || t === "ZodRecord")
63
+ return z.record(z.any());
64
+ if (t === "ZodArray")
65
+ return z.array(z.any());
66
+ if (t === "ZodString" || t === "ZodNumber" || t === "ZodBoolean" || t === "ZodEnum" || t === "ZodLiteral")
67
+ return unwrap(s);
68
+ return z.any();
69
+ }
70
+ const shortDesc = (d) => {
71
+ if (!d)
72
+ return undefined;
73
+ const one = d.replace(/\s+/g, " ").trim();
74
+ const cut = one.search(/(?<=[a-z0-9)\]"'])\.\s/i);
75
+ const s = cut > 10 ? one.slice(0, cut + 1) : one;
76
+ return s.length > 100 ? `${s.slice(0, 97)}…` : s;
77
+ };
78
+ /** The union of the members' arguments, all optional, each at its top-level type (each action
79
+ * re-checks its own full shape). A name two members type differently becomes z.any(). */
80
+ function unionShape(members) {
81
+ const shape = {};
82
+ const desc = {};
83
+ const owners = {};
84
+ for (const m of members)
85
+ for (const [k, v] of Object.entries(m.shape)) {
86
+ (owners[k] ||= []).push(m.name);
87
+ const sv = shallow(v);
88
+ if (!(k in shape)) {
89
+ shape[k] = sv;
90
+ desc[k] = v?.description ?? unwrap(v)?.description;
91
+ }
92
+ else if (typeName(shape[k]) !== typeName(sv))
93
+ shape[k] = z.any();
94
+ }
95
+ for (const k of Object.keys(shape)) {
96
+ const who = owners[k].length === members.length ? "" : ` [${owners[k].join(", ")}]`;
97
+ shape[k] = shape[k].optional().describe(`${shortDesc(desc[k]) || k}${who}`);
98
+ }
99
+ return shape;
100
+ }
101
+ export function familyTool(name, purpose, members) {
102
+ const actions = members.map((m) => m.name);
103
+ const byName = new Map(members.map((m) => [m.name, m]));
104
+ const description = `${purpose}. Pick the operation with \`action\` and pass that action's arguments (help:true returns its full documentation and schema).\n` +
105
+ members.map((m) => `- ${m.name}: ${firstSentence(m.description)}`).join("\n");
106
+ const shape = {
107
+ action: z.enum(actions).describe("Which operation to run"),
108
+ help: z.boolean().optional().describe("Return the action's full documentation and argument schema instead of running it"),
109
+ ...unionShape(members),
110
+ };
111
+ const handler = async (args, extra) => {
112
+ const { action, help, ...rest } = args || {};
113
+ const m = byName.get(action);
114
+ if (help) {
115
+ const schema = zodToJsonSchema(z.object(m.shape), { $refStrategy: "none" });
116
+ return { content: [{ type: "text", text: JSON.stringify({ action, description: m.description, input_schema: schema }) }] };
117
+ }
118
+ const parsed = z.object(m.shape).strict().safeParse(rest);
119
+ if (!parsed.success) {
120
+ const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
121
+ const allowed = Object.keys(m.shape);
122
+ return {
123
+ content: [{ type: "text", text: `Error: invalid arguments for ${name}{action:"${action}"}: ${issues}. It takes: ${allowed.join(", ") || "no arguments"} (help:true for details).` }],
124
+ isError: true,
125
+ };
126
+ }
127
+ return m.handler(parsed.data, extra);
128
+ };
129
+ return { description, shape, handler };
130
+ }
131
+ /** Family name for a member tool (for the system prompt / search results). */
132
+ export const FAMILY_OF = Object.fromEntries(Object.entries(FAMILIES).flatMap(([fam, [, members]]) => members.map((m) => [m, fam])));
@@ -14,61 +14,16 @@ export function registerMarketingTools(server, api, handle) {
14
14
  content: z.string().optional(),
15
15
  status: z.boolean().optional(),
16
16
  }).passthrough();
17
- // ── Transactional email templates ──
18
- server.tool("get_email_templates", "Get the site's transactional email templates (order confirmation, receipt, shop notice).", {}, () => handle(async () => unwrap(await api.getSendEmail(), "send_email")));
19
- server.tool("save_email_templates", "Create/update the transactional email templates. Each block is { title, content, status }.", {
20
- id: z.string().optional().describe("Existing record id (omit to create)"),
21
- email: z.string().optional().describe("Sender/site email"),
22
- email_customer_order: emailBlock.optional().describe("Email to customer on new order"),
23
- email_customer_recieve: emailBlock.optional().describe("Email to customer on receipt"),
24
- email_order_to_shop: emailBlock.optional().describe("Email to shop on new order"),
25
- }, (body) => handle(() => api.saveSendEmail(body)));
26
- // ── Contacts ──
27
- server.tool("list_contacts", "List contact-form submissions.", { ...list, status: z.number().optional().describe("Filter by status code") }, (query) => handle(async () => unwrap(await api.listContacts(query), "contact")));
28
17
  server.tool("create_contact", "Create a contact entry.", {
29
18
  name: z.string().describe("Contact name"),
30
19
  number_phone: z.string().optional().describe("Phone number"),
31
20
  email: z.string().optional().describe("Email"),
32
21
  note: z.string().optional().describe("Note"),
33
22
  }, (body) => handle(() => api.createContact(body)));
34
- server.tool("delete_contacts", "Delete contacts by id.", { ids: z.array(z.string()).min(1).describe("Contact ids") }, ({ ids }) => handle(() => api.deleteContacts(ids)));
35
- // ── Subscribers ──
36
- server.tool("list_subscribers", "List newsletter subscribers.", list, (query) => handle(async () => unwrap(await api.listSubscribers(query), "subscriber")));
37
- server.tool("create_subscriber", "Add a newsletter subscriber (upsert by email or phone).", {
38
- email: z.string().optional().describe("Email"),
39
- phone_number: z.string().optional().describe("Phone number"),
40
- first_name: z.string().optional().describe("First name"),
41
- last_name: z.string().optional().describe("Last name"),
42
- note: z.string().optional().describe("Note"),
43
- utm_source: z.string().optional(),
44
- utm_medium: z.string().optional(),
45
- utm_campaign: z.string().optional(),
46
- ref: z.string().optional().describe("Referral code"),
47
- }, (body) => handle(async () => unwrap(await api.createSubscriber(body), "subscriber")));
48
- server.tool("delete_subscribers", "Delete subscribers by id.", { ids: z.array(z.string()).min(1).describe("Subscriber ids") }, ({ ids }) => handle(() => api.deleteSubscribers(ids)));
49
- // ── Customer tags ──
50
- server.tool("list_customer_tags", "List customer tags for the site.", {}, () => handle(async () => unwrap(await api.listCustomerTags(), "customer_tags")));
51
23
  server.tool("upsert_customer_tag", "Create or update a customer tag. Omit `id` to create.", { id: z.string().optional().describe("Tag id (omit to create)"), name: z.string().describe("Tag name") }, (body) => handle(async () => unwrap(await api.upsertCustomerTag(body), "tag")));
52
24
  server.tool("assign_customer_tags", "Add or remove tags on multiple customers at once.", {
53
25
  customer_ids: z.array(z.string()).min(1).describe("Customer ids"),
54
26
  tags: z.array(z.string()).min(1).describe("Tag ids/names"),
55
27
  type: z.enum(["add", "remove"]).optional().describe('"add" (default) or "remove"'),
56
28
  }, (body) => handle(() => api.assignCustomerTags(body)));
57
- // ── Employees / team ──
58
- server.tool("list_employees", "List the site's employees (team members with permissions).", {}, () => handle(async () => unwrap(await api.listEmployees(), "employees")));
59
- server.tool("invite_employee", "Invite an employee to the site by email.", { email: z.string().describe("Invitee email") }, ({ email }) => handle(() => api.inviteEmployee(email)));
60
- server.tool("update_employee_permissions", "Change an employee's permission bitmask. Cannot change self or owner.", {
61
- id: z.string().describe("site_permission id"),
62
- permissions: z.number().describe("Permission bitmask integer"),
63
- }, ({ id, permissions }) => handle(() => api.updateEmployeePermissions({ id, permissions })));
64
- server.tool("delete_employees", "Remove employees (and any pending invitations) by site_permission id.", { ids: z.array(z.string()).min(1).describe("site_permission ids") }, ({ ids }) => handle(() => api.deleteEmployees(ids)));
65
- // ── Invitations (account-level) ──
66
- server.tool("list_invitations", "List site invitations for the current account.", {}, () => handle(async () => unwrap(await api.listInvitations(), "invitations")));
67
- server.tool("accept_invitation", "Accept a site invitation.", { invitation_id: z.string().describe("Invitation id") }, ({ invitation_id }) => handle(() => api.acceptInvitation(invitation_id)));
68
- server.tool("refuse_invitation", "Refuse a site invitation.", { invitation_id: z.string().describe("Invitation id") }, ({ invitation_id }) => handle(() => api.refuseInvitation(invitation_id)));
69
- // ── Insight / notifications ──
70
- server.tool("get_insight_today", "Get today's insight snapshot (orders, customers, conversion).", {}, () => handle(async () => unwrap(await api.getInsightToday(), "insight_data_today")));
71
- server.tool("get_insight", "Get analytics insight over a time range (defaults to last 7 days on the UI).", { start_time: z.string().optional().describe("ISO start time"), end_time: z.string().optional().describe("ISO end time") }, (query) => handle(async () => unwrap(await api.getInsight(query), "statistic")));
72
- server.tool("list_notifications", "List notifications for the current account.", {}, () => handle(async () => unwrap(await api.listNotifications(), "notifications")));
73
- server.tool("mark_notification_read", "Mark a notification as read.", { notification_id: z.string().describe("Notification id") }, ({ notification_id }) => handle(() => api.markNotificationRead(notification_id)));
74
29
  }
@@ -23,15 +23,6 @@ const SAVE = {
23
23
  };
24
24
  export function registerMultilingualTools(server, api, handle) {
25
25
  const unwrap = (res, key) => res?.data?.[key] ?? res?.[key] ?? res?.data ?? res;
26
- server.tool("add_site_languages", `Set the full list of enabled languages for the site (used to add, remove, toggle, or change currency —
27
- always send the complete updated list). Requires the multilingual app installed.`, {
28
- languages: z.array(z.object({
29
- lang: z.string().describe("Language code, e.g. 'en', 'vi'"),
30
- currency: z.string().optional().describe("Currency code for this language"),
31
- status: z.string().optional().describe("Status, e.g. 'ACTIVE'"),
32
- }).passthrough()).describe("Complete list of enabled languages"),
33
- }, ({ languages }) => handle(async () => unwrap(await api.mlAddLanguages(languages), "multiple_language")));
34
- server.tool("set_default_language", "Change which enabled language is the site default.", { language_code: z.string().describe("Language code to make default") }, ({ language_code }) => handle(() => api.mlChangeDefault(language_code)));
35
26
  server.tool("list_translations", `List translations for a resource type in a target language. Resources: ${RESOURCES.join(", ")}.
36
27
  'notification' takes no language filter; 'site' returns a flat key→value object.`, {
37
28
  resource: z.enum(RESOURCES).describe("Resource type to translate"),
@@ -95,11 +86,4 @@ translated name/slug/content are untouched; the translation row is created if mi
95
86
  await api.mlSaveTranslations(SAVE[resource].action, { [path]: [item], language_code });
96
87
  return { success: true, resource, id, language_code, meta_tags };
97
88
  }));
98
- server.tool("auto_translate", `Machine-translate a JSON blob from one language to another. \`type\` must be a valid translation
99
- type (e.g. 'product', 'category'). Returns { trans, count }.`, {
100
- type: z.string().describe("Translation type, e.g. 'product'"),
101
- source_language: z.string().describe("Source language code"),
102
- target_language: z.string().describe("Target language code"),
103
- json: z.record(z.any()).describe("Key→text object to translate"),
104
- }, (body) => handle(async () => unwrap(await api.mlTranslateJson(body), "translate_json")));
105
89
  }
@@ -38,5 +38,4 @@ export function registerOrderTools(server, api, handle) {
38
38
  server.tool("get_order", "Get full order details by ID: customer info, items, payment, shipping, discounts, etc.", {
39
39
  id: z.string().describe("Order ID"),
40
40
  }, ({ id }) => handle(() => api.getOrder(id)));
41
- server.tool("count_orders_by_status", "Get order count grouped by status. Useful for dashboard overview", {}, () => handle(() => api.countOrdersByStatus()));
42
41
  }
@@ -0,0 +1,114 @@
1
+ // get_page_custom_code / update_page_custom_code: custom code for ONE page (page.settings.custom_code).
2
+ // writePageCode is the single writer — update_page_source.custom_code and build_page go through it.
3
+ import { z } from "zod";
4
+ import { checkSiteCode, codeGuard } from "../builder/native-first.js";
5
+ import { PAGE_CODE_BUDGET, PAGE_CODE_FIELDS, PAGE_CODE_GUIDE, codeTargets, lintPageCode, mergePageCode, readPageCode, } from "../builder/page-code.js";
6
+ import { getConfirmMode } from "./context.js";
7
+ const parse = (v) => {
8
+ if (typeof v !== "string")
9
+ return v;
10
+ try {
11
+ return JSON.parse(v);
12
+ }
13
+ catch {
14
+ return null;
15
+ }
16
+ };
17
+ /** The page (fresh from the backend), its settings object and parsed source. */
18
+ async function loadPage(api, pageId) {
19
+ const res = await api.listPages();
20
+ const list = res?.data || res?.pages || res;
21
+ const page = (Array.isArray(list) ? list : []).find((p) => p.id === pageId);
22
+ if (!page)
23
+ throw new Error(`Page "${pageId}" not found on this site (list_pages).`);
24
+ const settings = parse(page.settings);
25
+ const source = parse(page.source?.source) || { sections: [] };
26
+ return { page, settings: settings && typeof settings === "object" ? settings : {}, source };
27
+ }
28
+ const sizes = (c) => Object.fromEntries(PAGE_CODE_FIELDS.map((f) => [f, (c[f] || "").length]));
29
+ const usage = (c) => {
30
+ const script = ["code_before_head", "code_before_body", "code_custom_javascript"].reduce((n, f) => n + (c[f] || "").length, 0);
31
+ const css = (c.code_custom_css || "").length;
32
+ return { script: { used: script, budget: PAGE_CODE_BUDGET.script.soft }, css: { used: css, budget: PAGE_CODE_BUDGET.css.soft } };
33
+ };
34
+ /** Validate and save a page's custom code. Returns the result object a tool hands back. */
35
+ export async function writePageCode(api, pageId, input, opts = {}) {
36
+ const { settings, source } = await loadPage(api, pageId);
37
+ const before = readPageCode(settings);
38
+ const { after, notes } = mergePageCode(before, input, opts.mode ?? "replace");
39
+ const { ids } = codeTargets(source);
40
+ const lint = lintPageCode(after, ids);
41
+ if (lint.errors.length)
42
+ return { error: "BLOCKED: the code has errors — not saved.", errors: lint.errors, ...(lint.warnings.length ? { warnings: lint.warnings } : {}) };
43
+ const blocked = codeGuard(checkSiteCode(before, after, { label: "Page", budget: PAGE_CODE_BUDGET }), opts.native_gap);
44
+ if (blocked)
45
+ return blocked;
46
+ if (!opts.allow_shrink)
47
+ for (const f of PAGE_CODE_FIELDS) {
48
+ const was = (before[f] || "").length;
49
+ const now = (after[f] || "").length;
50
+ if (was > 200 && now < was * 0.5)
51
+ return {
52
+ error: `BLOCKED: ${f} would shrink from ${was} to ${now} chars — that looks like lost code. Read it with get_page_custom_code and merge (or mode:"append"); pass allow_shrink:true if the removal is deliberate.`,
53
+ };
54
+ }
55
+ const changed = PAGE_CODE_FIELDS.filter((f) => (before[f] || "") !== (after[f] || ""));
56
+ const report = {
57
+ page_id: pageId,
58
+ changed,
59
+ before: sizes(before),
60
+ after: sizes(after),
61
+ usage: usage(after),
62
+ ...(notes.length ? { notes } : {}),
63
+ ...(lint.warnings.length ? { warnings: lint.warnings } : {}),
64
+ };
65
+ if (!changed.length)
66
+ return { ...report, saved: false, note: "Nothing changed." };
67
+ if (opts.dry_run)
68
+ return { ...report, dry_run: true, would_save: after, next: "Show the user the code; on their OK call again with dry_run:false." };
69
+ // Top-level settings keys replace: the whole custom_code object goes in, every other key stays.
70
+ const next = { ...settings, custom_code: after };
71
+ if (!Object.keys(after).length)
72
+ delete next.custom_code;
73
+ await api.updatePage(pageId, { settings: next });
74
+ return { ...report, saved: true, next: "Check it with preview_page, then publish_site to take it live (settings are copied on publish)." };
75
+ }
76
+ const codeArgs = {
77
+ code_custom_css: z.string().optional().describe("CSS for this page (no <style> needed). Target #ELEMENT-ID or .custom_class. \"\" clears."),
78
+ code_custom_javascript: z.string().optional().describe("Plain JS for this page, NO <script> tag; runs at the end of <body>. \"\" clears."),
79
+ code_before_head: z.string().optional().describe("HTML for <head> on this page only (<script src>, <link>, <meta>). \"\" clears."),
80
+ code_before_body: z.string().optional().describe("HTML after this page's content, before its scripts (noscript pixel, widget mount point). \"\" clears."),
81
+ };
82
+ export const PAGE_CODE_ARG = z.object(codeArgs).optional()
83
+ .describe("Per-page custom code saved with the page (same slots as update_page_custom_code). Last resort — native first.");
84
+ export function registerPageCodeTools(server, api, handle) {
85
+ server.tool("get_page_custom_code", "Read the custom code of ONE page (CSS / JS / head / body slots in page.settings.custom_code), its budget usage, the element ids and custom classes the code can target on that page, and the rules for per-page code. Read this before update_page_custom_code.", { page_id: z.string().describe("Page ID (list_pages)") }, ({ page_id }) => handle(async () => {
86
+ const { page, settings, source } = await loadPage(api, page_id);
87
+ const code = readPageCode(settings);
88
+ const t = codeTargets(source);
89
+ return {
90
+ page: { id: page.id, name: page.name, slug: page.slug ?? null },
91
+ custom_code: code,
92
+ usage: usage(code),
93
+ targets: t.targets,
94
+ ...(t.truncated ? { targets_note: `${t.total} elements; first ${t.targets.length} listed — search_page_elements for the rest.` } : {}),
95
+ guide: PAGE_CODE_GUIDE,
96
+ };
97
+ }));
98
+ server.tool("update_page_custom_code", `Save custom code for ONE page — only when the element schema can't do what the user asked (NATIVE FIRST: element → its settings/events/bindings → an app → code). Slots: code_custom_css, code_custom_javascript (plain JS, own <script>), code_before_head, code_before_body; rendered on that page only, after the site's code. mode "replace" (default) sets the slots you pass, "append" adds to them; "" clears a slot. JS syntax and CSS braces are checked before saving, #ids not on the page are flagged, oversized or UI-building code is refused unless native_gap names the gap, and a large shrink needs allow_shrink. Read get_page_custom_code first; dry_run shows what would be saved.`, {
99
+ page_id: z.string().describe("Page ID (list_pages)"),
100
+ ...codeArgs,
101
+ mode: z.enum(["replace", "append"]).optional().describe("replace (default): set the given slots; append: add after the current code"),
102
+ native_gap: z.string().min(30).optional().describe("Only when refused and no native way exists: the need, the elements/apps you checked, what each lacks. Tell the user first."),
103
+ allow_shrink: z.boolean().optional().describe("Allow a slot to lose more than half its code (deliberate removal)"),
104
+ dry_run: z.boolean().optional().describe("Validate and show what would be saved, without saving (default: on in confirm mode)"),
105
+ }, ({ page_id, mode, native_gap, allow_shrink, dry_run, ...code }) => handle(async () => {
106
+ const input = Object.fromEntries(Object.entries(code).filter(([, v]) => v !== undefined));
107
+ if (!Object.keys(input).length)
108
+ throw new Error("Pass at least one slot: code_custom_css, code_custom_javascript, code_before_head or code_before_body.");
109
+ return writePageCode(api, page_id, input, {
110
+ mode, native_gap, allow_shrink,
111
+ dry_run: dry_run !== undefined ? dry_run : getConfirmMode() === "always_confirm",
112
+ });
113
+ }));
114
+ }
@@ -1,4 +1,6 @@
1
1
  import { z } from "zod";
2
+ import { writePageCode } from "./page-code.js";
3
+ import { readPageCode } from "../builder/page-code.js";
2
4
  import { CUSTOM_CODE_GUIDE } from "../guides.js";
3
5
  import { getConfirmMode } from "./context.js";
4
6
  import { addedErrors, applyNodeUpdates, computeNodeDiff, checkContentPlaceholders, checkElementPatch, finalizeForRender } from "../builder/page.js";
@@ -237,7 +239,8 @@ export function registerPageTools(server, api, handle) {
237
239
  const overview = source ? buildOverview(source) : null;
238
240
  return {
239
241
  page: { id: page.id, name: page.name, slug: page.slug, type: page.type },
240
- custom_code: (page.source && page.source.custom_code) || null,
242
+ custom_code: readPageCode(page.settings),
243
+ ...(page.source?.custom_code ? { legacy_devmode_code: "page_source.custom_code is set but the storefront never renders it — move it with update_page_custom_code." } : {}),
241
244
  overview,
242
245
  hint: "Use search_page_elements to query specific elements by type, class, text, etc. Target via CSS: #ELEMENT-ID or .custom-class. Sections have class 'x-section', elements have 'x-element'.",
243
246
  };
@@ -420,9 +423,6 @@ For full rewrites, use update_site_custom_code instead.`, {
420
423
  return { ...res, warning: `Page deleted, but removing it from global sections' page lists failed: ${e?.message || e}` };
421
424
  }
422
425
  }));
423
- server.tool("get_page_versions", "View version history of a page", {
424
- page_id: z.string().describe("Page ID"),
425
- }, ({ page_id }) => handle(() => api.getPageVersions(page_id)));
426
426
  server.tool("list_page_contents", "List multi-language contents (translations) of the site's pages and global sections. Pass page_id + language_code to read one page's translation.", {
427
427
  page_id: z.string().optional().describe("Page ID — narrows the result to that page"),
428
428
  language_code: z.string().optional().describe("With page_id: return just that language's content map"),
@@ -628,7 +628,7 @@ IMPORTANT: Before calling this tool, you MUST:
628
628
  Safeguarded: blocks if new source is <50% of existing size.`, {
629
629
  page_id: z.string().describe("Page ID"),
630
630
  source: z.any().describe("Full page source object (sections tree) or JSON string"),
631
- custom_code: z.string().optional().describe("Custom code (CSS/JS) for this page. Last resort, same rules as update_site_custom_code."),
631
+ custom_code: z.string().optional().describe("JS for this page only → page.settings.custom_code.code_custom_javascript (same as update_page_custom_code; use that tool for CSS/head/body slots). Last resort."),
632
632
  native_gap: NATIVE_GAP,
633
633
  allow_shrink: ALLOW_SHRINK,
634
634
  }, ({ page_id, source, custom_code, native_gap, allow_shrink }) => handle(async () => {
@@ -640,14 +640,16 @@ Safeguarded: blocks if new source is <50% of existing size.`, {
640
640
  // per-breakpoint keys like every other writer; nodes already in bp shape are untouched.
641
641
  finalizeForRender(body.source, await api.getSiteBreakpoints(), await api.getSiteDefaultGrid());
642
642
  }
643
+ // page_source.custom_code is stored but never rendered; per-page code lives in
644
+ // page.settings.custom_code (update_page_custom_code). This param writes there.
645
+ let pageCode;
643
646
  if (custom_code != null) {
647
+ pageCode = await writePageCode(api, page_id, { code_custom_javascript: custom_code }, { native_gap, dry_run: false });
644
648
  invalidatePageCache();
645
- const { page } = await getPageWithSource(api, page_id);
646
- const old = page?.source?.custom_code;
647
- const blocked = codeGuard(checkSiteCode({ code_custom_javascript: typeof old === "string" ? old : JSON.stringify(old ?? "") }, { code_custom_javascript: custom_code }), native_gap);
648
- if (blocked)
649
- return blocked;
650
- body.custom_code = custom_code;
649
+ if (pageCode.error)
650
+ return pageCode;
651
+ if (body.source == null)
652
+ return { success: true, custom_code: pageCode };
651
653
  }
652
654
  // Safeguard: force fresh read and block if new source is suspiciously smaller
653
655
  if (body.source) {
@@ -679,6 +681,7 @@ Safeguarded: blocks if new source is <50% of existing size.`, {
679
681
  page_source_id: saved.id,
680
682
  page_id: saved.page_id,
681
683
  source_length: (saved.source || "").length,
684
+ ...(pageCode ? { custom_code: pageCode } : {}),
682
685
  };
683
686
  }));
684
687
  }
@@ -35,10 +35,5 @@ export function registerProductTools(server, api, handle) {
35
35
  server.tool("get_product", "Get full product details by ID: name, description, price, variations, images, attributes, SEO, etc.", {
36
36
  id: z.string().describe("Product ID"),
37
37
  }, ({ id }) => handle(() => api.getProduct(id)));
38
- server.tool("search_products", "Search products by keyword. Returns matching products with basic info", {
39
- term: z.string().describe("Search keyword"),
40
- page: z.number().optional().describe("Page number"),
41
- limit: z.number().optional().describe("Items per page"),
42
- }, ({ term, page, limit }) => handle(() => api.searchProducts({ term, page, limit })));
43
38
  server.tool("list_categories", "List all product categories of the site", {}, () => handle(() => api.listCategories()));
44
39
  }
@@ -14,14 +14,10 @@ import { registerSiteStyleTools } from "./site-style.js";
14
14
  import { registerAppTools } from "./apps.js";
15
15
  import { registerReviewTools } from "./reviews.js";
16
16
  import { registerAppointmentTools } from "./appointment.js";
17
- import { registerAffiliateTools } from "./affiliate.js";
18
- import { registerCatalogExtraTools } from "./catalog-extras.js";
19
17
  import { registerSiteConfigTools } from "./site-config.js";
20
18
  import { registerMarketingTools } from "./marketing.js";
21
19
  import { registerMultilingualTools } from "./multilingual.js";
22
- import { registerMediaTools } from "./media.js";
23
20
  import { registerAppsExtraTools } from "./apps-extra.js";
24
- import { registerSaleChannelTools } from "./sale-channels.js";
25
21
  import { registerPromotionTools } from "./promotions.js";
26
22
  import { registerComboTools } from "./combos.js";
27
23
  import { registerGlobalSourceTools } from "./global-sources.js";
@@ -34,22 +30,30 @@ import { registerBuilderExtraTools } from "./builder-extras.js";
34
30
  import { registerPageDraftTools } from "./page-draft.js";
35
31
  import { registerSitePlanTools } from "./site-plans.js";
36
32
  import { registerApiGatewayTools } from "./api-gateway.js";
33
+ import { registerPageCodeTools } from "./page-code.js";
34
+ import { readFileSync } from "node:fs";
35
+ import { FAMILIES, familyTool } from "./families.js";
36
+ /** Tool names folded into api_get / api_call → their route (invoke_tool points callers there). */
37
+ const retired = (() => {
38
+ try {
39
+ return JSON.parse(readFileSync(new URL("./retired-tools.json", import.meta.url), "utf8"));
40
+ }
41
+ catch {
42
+ return {};
43
+ }
44
+ })();
37
45
  /** Tool groups. `core` groups load natively; the rest are reached via search_tools + invoke_tool. */
38
46
  export const GROUPS = [
39
- { name: "session", title: "Session & apps", core: true, desc: "Connection context, site switch, app install/list, result cache" },
40
- { name: "web", title: "Page building", core: true, desc: "Pages, builder elements, sections, global sources/sections, styles, images, publish" },
47
+ { name: "session", title: "Session & apps", core: true, desc: "Connection context, site switch/create, apps, cached results, the backend API gateway (api_find / api_get / api_call)" },
48
+ { name: "web", title: "Page building", core: true, desc: "Pages, elements, drafts, global sources/sections, site code, themes, images, validate/build/publish" },
41
49
  { name: "store", title: "Store", core: true, desc: "Products, categories, collections, orders, promotions, combos" },
42
50
  { name: "content", title: "Content & customers", core: true, desc: "Blog articles, customers, CMS files / HTTP functions" },
43
- { name: "catalog", title: "Catalog extras", desc: "Brands, suppliers, product tags, ribbons, materials, variations, measurement, price-contact" },
44
- { name: "site_config", title: "Site configuration", desc: "Custom domains, SEO redirects, shipping, UTM links, fonts, site settings, API keys, publish history, site plans/subscriptions (gói cước), site counts" },
45
- { name: "marketing", title: "Marketing & CRM", desc: "Email templates, contacts, subscribers, customer tags, employees, invitations, insight, notifications" },
46
- { name: "i18n", title: "Multilingual", desc: "Enable languages and manage translations for products/categories/articles/etc." },
47
- { name: "media", title: "Media & PWA", desc: "Media library folders/content, capacity, base64 upload, PWA manifest" },
48
- { name: "appointment", title: "Appointment booking", desc: "Booking calendars, appointments, employees, addresses, classifies" },
49
- { name: "affiliate", title: "Affiliate", desc: "Affiliate programs, products, orders, accounts, payouts, statistics" },
50
- { name: "reviews", title: "Product reviews", desc: "List, create, reply, moderate, delete product reviews" },
51
- { name: "apps_advanced", title: "Advanced apps", desc: "Product design, personal product design (PPD), course app" },
52
- { name: "channels", title: "Sale channels", desc: "Sitemap sync, partner product feeds, Google merchants" },
51
+ { name: "site_config", title: "Site configuration", desc: "Site settings (merged safely), font groups, site plans/subscriptions (gói cước), site counts" },
52
+ { name: "marketing", title: "Marketing & CRM", desc: "Create contacts, customer tags and tag assignment" },
53
+ { name: "i18n", title: "Multilingual", desc: "Translations for products/categories/articles/etc. and their SEO" },
54
+ { name: "appointment", title: "Appointment booking", desc: "Create and update booking calendars (weekly hours, overrides)" },
55
+ { name: "reviews", title: "Product reviews", desc: "List, read and write product reviews" },
56
+ { name: "apps_advanced", title: "Advanced apps", desc: "Create a course (course app)" },
53
57
  { name: "automation", title: "Automation", desc: "Marketing automations and send-mail" },
54
58
  { name: "image_seo", title: "Image alt / SEO audit", desc: "Scan site images, read them, bulk-fill and set alt text" },
55
59
  ];
@@ -69,14 +73,10 @@ const MODULES = [
69
73
  ["session", registerAppTools],
70
74
  ["reviews", registerReviewTools],
71
75
  ["appointment", registerAppointmentTools],
72
- ["affiliate", registerAffiliateTools],
73
- ["catalog", registerCatalogExtraTools],
74
76
  ["site_config", registerSiteConfigTools],
75
77
  ["marketing", registerMarketingTools],
76
78
  ["i18n", registerMultilingualTools],
77
- ["media", registerMediaTools],
78
79
  ["apps_advanced", registerAppsExtraTools],
79
- ["channels", registerSaleChannelTools],
80
80
  ["store", registerPromotionTools],
81
81
  ["store", registerComboTools],
82
82
  ["web", registerGlobalSourceTools],
@@ -89,7 +89,13 @@ const MODULES = [
89
89
  ["web", registerPageDraftTools],
90
90
  ["site_config", registerSitePlanTools],
91
91
  ["session", registerApiGatewayTools],
92
+ ["web", registerPageCodeTools],
92
93
  ];
94
+ /** Every collected tool of a server, by name — members of a family included (tests, gateway). */
95
+ const ENTRIES = new WeakMap();
96
+ export function toolEntries(server) {
97
+ return ENTRIES.get(server) ?? new Map();
98
+ }
93
99
  /** Captures server.tool(...) calls into a registry instead of registering them. */
94
100
  class ToolCollector {
95
101
  entries = [];
@@ -152,7 +158,8 @@ then invoke_read_tool(name, arguments) for read-only tools (list_/get_/search_
152
158
  if the user's request touches an [on-demand] area (or you're unsure), search_tools BEFORE concluding.
153
159
  Tip: search_tools matches English tool names/descriptions — translate the user's intent into English keywords.
154
160
 
155
- ${lines.join("\n")}`;
161
+ ${lines.join("\n")}
162
+ Anything else the backend does (domains, redirects, shipping, UTM, brands/tags/ribbons, media library, PWA, affiliate, partner feeds, employees, email templates…) has no dedicated tool: api_find("keywords") → api_get / api_call.`;
156
163
  }
157
164
  /** Build the full registry, register native (core) tools, and add the search gateway.
158
165
  * Returns counts for diagnostics. */
@@ -166,10 +173,24 @@ export function installTools(server, api, handle, opts = {}) {
166
173
  for (const e of collector.entries)
167
174
  registry.set(e.name, e);
168
175
  const native = resolveNativeGroups(opts.tools ?? process.env.WEBCAKE_TOOLS);
169
- // Register native (core/enabled) tools directly on the MCP server.
176
+ // Register native (core/enabled) tools directly on the MCP server. Tools of a family are
177
+ // exposed once, as that family's actions (see families.ts).
170
178
  let nativeCount = 0;
179
+ const folded = new Map(); // member → family
180
+ for (const [fam, [purpose, names]] of Object.entries(FAMILIES)) {
181
+ const members = names.map((n) => registry.get(n)).filter((e) => !!e && native.has(e.group));
182
+ if (members.length < 2)
183
+ continue;
184
+ members.forEach((m) => folded.set(m.name, fam));
185
+ const t = familyTool(fam, purpose, members);
186
+ const ann = members.map((m) => toolAnnotations(m.name));
187
+ const annotations = ann.every((a) => a.readOnlyHint) ? { readOnlyHint: true } : ann.some((a) => a.destructiveHint) ? { readOnlyHint: false, destructiveHint: true } : { readOnlyHint: false };
188
+ server.registerTool(fam, { description: t.description, inputSchema: z.object(t.shape).strict(), annotations }, t.handler);
189
+ nativeCount++;
190
+ }
191
+ ENTRIES.set(server, registry);
171
192
  for (const e of collector.entries) {
172
- if (native.has(e.group)) {
193
+ if (native.has(e.group) && !folded.has(e.name)) {
173
194
  // .strict(): an argument the tool doesn't take is REFUSED with its name, not silently
174
195
  // dropped (a dropped page_id/site_id made a call act on the wrong page).
175
196
  server.registerTool(e.name, { description: e.description, inputSchema: z.object(e.shape).strict(), annotations: toolAnnotations(e.name) }, e.handler);
@@ -254,11 +275,15 @@ courses, sale channels, automation…). Returns name, group, description and JSO
254
275
  native: native.has(e.group),
255
276
  annotations: toolAnnotations(e.name),
256
277
  description: e.description,
278
+ ...(folded.has(e.name) ? { call_as: `${folded.get(e.name)}({ action: "${e.name}", … })` } : {}),
257
279
  input_schema: jsonSchema(e),
258
280
  }));
259
281
  }));
260
282
  const runTool = async (name, args, readOnlyOnly) => {
261
283
  const e = registry.get(name);
284
+ const route = retired[name];
285
+ if (!e && route)
286
+ return errorResult(`Error: "${name}" was folded into the API gateway — run ${route.startsWith("get:") ? "api_get" : "api_call"}({ id: "${route}", … }) (call sheet: api_find({ id: "${route}" })).`);
262
287
  if (!e)
263
288
  return errorResult(`Error: unknown tool "${name}". Use search_tools to find available tools.`);
264
289
  if (readOnlyOnly && !toolAnnotations(name).readOnlyHint) {