webcake-storefront-mcp 1.42.0 → 2.0.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.
@@ -39,16 +39,13 @@ export function registerAppointmentTools(server, api, handle) {
39
39
  term: z.string().optional().describe("Search term"),
40
40
  };
41
41
  const unwrap = (res, key) => res?.data?.[key] ?? res?.[key] ?? res?.data ?? res;
42
- // ── Calendars ──
43
- server.tool("list_appointment_calendars", "List booking calendars (services with availability rules) for the current site.", listShape, (query) => handle(async () => unwrap(await api.listAppointmentCalendars(query), "appointment_calendars")));
44
42
  server.tool("create_appointment_calendar", `Create a booking calendar = ONE employee's (technician's) working schedule. A calendar is per
45
43
  employee, not per service: one employee has at most one calendar per site, tied to one address.
46
- To set up staff schedules: list/create_appointment_employee → list/create_appointment_address →
47
- list/create_appointment_classify (services) → one calendar per employee with its own hours.
48
- Same hours for many staff? Create one, then duplicate_appointment_calendars and change assignee_id.`, {
44
+ To set up staff schedules: employees, addresses and classifies (services) come first — api_find("appointment employee" / "appointment address" / "appointment classify") → api_get / api_call — then one calendar per employee with its own hours.
45
+ Same hours for many staff? Create one, then duplicate it (api_find "appointment calendar duplicate") and change assignee_id.`, {
49
46
  name: z.string().describe("Calendar title, e.g. the technician's name"),
50
- assignee_id: z.string().describe("Employee id (list_appointment_employees) — one calendar per employee"),
51
- appointment_address_id: z.string().describe("Address/location id (list_appointment_addresses)"),
47
+ assignee_id: z.string().describe("Employee id (api_find 'appointment employee') — one calendar per employee"),
48
+ appointment_address_id: z.string().describe("Address/location id (api_find 'appointment address')"),
52
49
  appointment_classifies: z.array(z.object({ id: z.string() })).optional().describe('Services this employee takes, e.g. [{ "id": "..." }]'),
53
50
  range_appointment: z.number().int().min(1).max(60).optional().describe("How many days ahead customers can book, 1–60 (default 7)"),
54
51
  duration_appointment: z.number().int().optional().describe("Appointment length in minutes; also the slot step (default 30)"),
@@ -73,49 +70,8 @@ Same hours for many staff? Create one, then duplicate_appointment_calendars and
73
70
  }));
74
71
  server.tool("update_appointment_calendar", `Update a booking calendar (an employee's schedule). Pass \`id\` plus any fields to change, same shape
75
72
  as create_appointment_calendar. config_weekdays / config_days REPLACE the whole list — to add one
76
- day-off, read the calendar (list_appointment_calendars), append, and send the full config_days.`, {
73
+ day-off, read the calendar (api_find "appointment calendar" → api_get), append, and send the full config_days.`, {
77
74
  id: z.string().describe("Calendar id"),
78
75
  fields: z.record(z.any()).describe("Fields to update (name, config_weekdays, config_days, assignee_id, appointment_classifies, …)"),
79
76
  }, ({ id, fields }) => handle(async () => unwrap(await api.updateAppointmentCalendar({ id, ...normalizeHours(fields) }), "appointment_calendar")));
80
- server.tool("delete_appointment_calendars", "Delete booking calendars by id.", { ids: z.array(z.string()).min(1).describe("Calendar ids") }, ({ ids }) => handle(() => api.deleteAppointmentCalendars(ids)));
81
- server.tool("duplicate_appointment_calendars", "Duplicate booking calendars by id (creates copies).", { ids: z.array(z.string()).min(1).describe("Calendar ids to duplicate") }, ({ ids }) => handle(() => api.duplicateAppointmentCalendars(ids)));
82
- // ── Appointments (bookings) ──
83
- server.tool("list_appointments", "List booked appointments for the current site.", listShape, (query) => handle(async () => unwrap(await api.listAppointments(query), "appointments")));
84
- // ── Addresses (locations) ──
85
- server.tool("list_appointment_addresses", "List appointment locations/addresses.", listShape, (query) => handle(async () => unwrap(await api.listAppointmentAddresses(query), "appointment_addresses")));
86
- server.tool("create_appointment_address", "Create an appointment location. Region ids are optional (Vietnamese geo ids).", {
87
- address: z.string().describe("Street / full address text"),
88
- province_id: z.string().optional().describe("Province geo id"),
89
- district_id: z.string().optional().describe("District geo id"),
90
- commune_id: z.string().optional().describe("Commune/ward geo id"),
91
- }, (fields) => handle(async () => unwrap(await api.createAppointmentAddress(fields), "appointment_address")));
92
- server.tool("update_appointment_address", "Update an appointment location. Pass `id` plus fields to change.", {
93
- id: z.string().describe("Address id"),
94
- fields: z.record(z.any()).describe("Fields to update (address, province_id, district_id, commune_id)"),
95
- }, ({ id, fields }) => handle(async () => unwrap(await api.updateAppointmentAddress({ id, ...fields }), "appointment_address")));
96
- server.tool("delete_appointment_addresses", "Delete appointment locations by id.", { ids: z.array(z.string()).min(1).describe("Address ids") }, ({ ids }) => handle(() => api.deleteAppointmentAddresses(ids)));
97
- // ── Classifies (service types) ──
98
- server.tool("list_appointment_classifies", "List appointment classifies (service categories/types).", listShape, (query) => handle(async () => unwrap(await api.listAppointmentClassifies(query), "appointment_classifies")));
99
- server.tool("create_appointment_classify", "Create an appointment classify (service type).", {
100
- name: z.string().describe("Classify name"),
101
- description: z.string().optional().describe("Optional description"),
102
- }, (fields) => handle(async () => unwrap(await api.createAppointmentClassify(fields), "appointment_classify")));
103
- server.tool("update_appointment_classify", "Update an appointment classify. Pass `id` plus fields to change.", {
104
- id: z.string().describe("Classify id"),
105
- fields: z.record(z.any()).describe("Fields to update (name, description)"),
106
- }, ({ id, fields }) => handle(async () => unwrap(await api.updateAppointmentClassify({ id, ...fields }), "appointment_classify")));
107
- server.tool("delete_appointment_classifies", "Delete appointment classifies by id.", { ids: z.array(z.string()).min(1).describe("Classify ids") }, ({ ids }) => handle(() => api.deleteAppointmentClassifies(ids)));
108
- // ── Employees (assignees) ──
109
- server.tool("list_appointment_employees", "List appointment employees (people that appointments can be assigned to).", listShape, (query) => handle(async () => unwrap(await api.listAppointmentEmployees(query), "appointment_employees")));
110
- server.tool("create_appointment_employee", "Create an appointment employee (assignee).", {
111
- full_name: z.string().describe("Employee full name"),
112
- email: z.string().optional().describe("Email"),
113
- phone_number: z.string().optional().describe("Phone number"),
114
- avatar: z.string().optional().describe("Avatar image URL"),
115
- }, (fields) => handle(async () => unwrap(await api.createAppointmentEmployee(fields), "appointment_employee")));
116
- server.tool("update_appointment_employee", "Update an appointment employee. Pass `id` plus fields to change.", {
117
- id: z.string().describe("Employee id"),
118
- fields: z.record(z.any()).describe("Fields to update (full_name, email, phone_number, avatar)"),
119
- }, ({ id, fields }) => handle(async () => unwrap(await api.updateAppointmentEmployee({ id, ...fields }), "appointment_employee")));
120
- server.tool("delete_appointment_employees", "Delete appointment employees by id.", { ids: z.array(z.string()).min(1).describe("Employee ids") }, ({ ids }) => handle(() => api.deleteAppointmentEmployees(ids)));
121
77
  }
@@ -3,25 +3,6 @@ import { z } from "zod";
3
3
  // (per-variation print templates), and the Course app. Each requires its app installed.
4
4
  export function registerAppsExtraTools(server, api, handle) {
5
5
  const unwrap = (res, key) => (key && (res?.data?.[key] ?? res?.[key])) ?? res?.data ?? res;
6
- // ── Product Design ──
7
- server.tool("get_device_templates", "Get the device-template groups for the Product Design app.", {}, () => handle(async () => unwrap(await api.getDeviceTemplates(), "group_device")));
8
- server.tool("create_products_from_device_templates", "Create products from selected device-template groups (Product Design app).", { groups: z.array(z.string()).min(1).describe("Device-template group identifiers") }, ({ groups }) => handle(async () => unwrap(await api.createProductsByDeviceTemplate(groups), "device_templates")));
9
- // ── Personal Product Design (PPD) ──
10
- server.tool("list_ppd", "List Personal Product Design assignments (products enabled for personalization).", {
11
- page: z.number().optional().describe("Page number"),
12
- limit: z.number().optional().describe("Items per page"),
13
- term: z.string().optional().describe("Search by product name"),
14
- }, (query) => handle(async () => unwrap(await api.getAllPpd(query), "result")));
15
- server.tool("upsert_ppd", "Enable/update Personal Product Design for products (bulk).", { ppds: z.array(z.record(z.any())).min(1).describe("PPD entries, e.g. [{ product_id }]") }, ({ ppds }) => handle(() => api.upsertPpd(ppds)));
16
- server.tool("remove_ppd", "Disable Personal Product Design for the given ids.", { ids: z.array(z.string()).min(1).describe("PPD ids") }, ({ ids }) => handle(() => api.removePpd(ids)));
17
- server.tool("get_ppd_variation_template", "Get the per-variation print/design templates for a product (PPD app).", { product_id: z.string().describe("Product id") }, ({ product_id }) => handle(async () => unwrap(await api.getProductVariationTemplate(product_id), "result")));
18
- // ── Course app ──
19
- server.tool("list_courses", "List courses (Course app).", {
20
- page: z.number().optional().describe("Page number"),
21
- limit: z.number().optional().describe("Items per page"),
22
- term: z.string().optional().describe("Search term"),
23
- }, (query) => handle(async () => unwrap(await api.listCourses(query))));
24
- server.tool("get_course", "Get a course by id (tracks, downloads, etc.).", { id: z.string().describe("Course id") }, ({ id }) => handle(async () => unwrap(await api.getCourse(id))));
25
6
  server.tool("create_course", `Create a course linked to a product. \`tracks\` are lessons; \`file_downloads\` are attachments.
26
7
  Note: video tracks trigger async HLS processing. A product can only link to one course.`, {
27
8
  name: z.string().describe("Course name"),
@@ -32,13 +13,4 @@ Note: video tracks trigger async HLS processing. A product can only link to one
32
13
  file_downloads: z.array(z.record(z.any())).optional().describe("Downloadable files"),
33
14
  video_demo: z.string().optional().describe("Demo video URL"),
34
15
  }, (body) => handle(() => api.createCourse(body)));
35
- server.tool("update_course", "Update a course by id (partial). Pass `id` plus fields to change.", { id: z.string().describe("Course id"), fields: z.record(z.any()).describe("Fields to update") }, ({ id, fields }) => handle(() => api.updateCourse(id, fields)));
36
- server.tool("delete_course", "Delete a course by id (also deletes its tracks).", { id: z.string().describe("Course id") }, ({ id }) => handle(() => api.deleteCourse(id)));
37
- server.tool("delete_courses", "Delete multiple courses by id.", { ids: z.array(z.string()).min(1).describe("Course ids") }, ({ ids }) => handle(() => api.deleteManyCourses(ids)));
38
- server.tool("get_course_members", "List members (enrolled customers) of a course.", {
39
- course_id: z.string().describe("Course id"),
40
- page: z.number().optional().describe("Page number"),
41
- limit: z.number().optional().describe("Items per page"),
42
- term: z.string().optional().describe("Search term"),
43
- }, (query) => handle(async () => unwrap(await api.getCourseMembers(query))));
44
16
  }
@@ -55,15 +55,4 @@ Pass the app's subscription id — get it from list_apps (the \`id\` field) or g
55
55
  await api.uninstallApp(id);
56
56
  return { id, uninstalled: true };
57
57
  }));
58
- server.tool("update_app", `Update an installed app's configuration. Pass the app subscription id and an \`attrs\` object
59
- that is merged onto the subscription — usually \`{ settings: {...} }\`, optionally \`{ status }\`.
60
- For the product-review app, prefer update_app_review (it also propagates shop_info).`, {
61
- id: z.string().describe("App subscription id (from list_apps / get_app)"),
62
- attrs: z.record(z.any()).describe('Fields to update, e.g. { "settings": { ... }, "status": 1 }'),
63
- }, ({ id, attrs }) => handle(() => api.updateApp(id, attrs)));
64
- server.tool("update_app_review", `Update the product-review app's settings (e.g. shop_info, auto-approve, display options).
65
- Pass the review app's subscription id (get_app with type "product_review") and the full \`settings\` object.`, {
66
- id: z.string().describe("Review app subscription id (get_app type=product_review)"),
67
- settings: z.record(z.any()).describe('Review app settings object, e.g. { "shop_info": { ... }, "auto_approve": true }'),
68
- }, ({ id, settings }) => handle(() => api.updateAppReview(id, settings)));
69
58
  }
@@ -133,7 +133,6 @@ function buildSchemas(collections) {
133
133
  }));
134
134
  }
135
135
  export function registerCmsFileTools(server, api, handle) {
136
- server.tool("list_cms_files", "List all CMS files (HTTP functions, cron jobs, ...) for the site", {}, () => handle(() => api.listCmsFiles()));
137
136
  server.tool("create_cms_file", `Create a new CMS file. Types: "http_function", "jobs_config", "default"`, {
138
137
  name: z.string().describe("File name"),
139
138
  content: z.string().describe("Code content (JavaScript or JSON)"),
@@ -240,11 +239,6 @@ Example: "get_Products" → function_name="Products", method="GET"`, {
240
239
  method: z.enum(["GET", "POST", "PUT", "PATCH"]).default("POST").describe("HTTP method"),
241
240
  params: z.record(z.any()).optional().describe("Parameters"),
242
241
  }, ({ function_name, method, params }) => handle(() => api.runFunction(function_name, method, params)));
243
- server.tool("debug_function", "Run JS code in debug mode (without deploying). Returns execution result and console logs", {
244
- content: z.string().describe("JS code to debug"),
245
- function_name: z.string().describe("Function name to run"),
246
- params: z.record(z.any()).optional().describe("Test parameters"),
247
- }, ({ content, function_name, params }) => handle(() => api.debugFunction({ content, functionName: function_name, params })));
248
242
  server.tool("save_file_version", "Save a version snapshot of a CMS file for rollback", {
249
243
  cms_file_id: z.string().describe("CMS file ID"),
250
244
  content: z.string().describe("Content to save"),
@@ -252,10 +246,9 @@ Example: "get_Products" → function_name="Products", method="GET"`, {
252
246
  }, ({ cms_file_id, content, is_public }) =>
253
247
  // Backend reads `file_id` (it stores it as cms_file_id); a `cms_file_id` key alone is ignored.
254
248
  handle(() => api.saveFileVersion({ file_id: cms_file_id, content, is_public })));
255
- server.tool("get_file_versions", "View version history of a CMS file. Each version includes its saved content — to restore, pass that content back to update_http_function (the http_function file) or update_cms_file, or use restore_file_version.", { cms_file_id: z.string().describe("CMS file ID") }, ({ cms_file_id }) => handle(() => api.getFileVersions({ file_id: cms_file_id })));
256
249
  server.tool("restore_file_version", "Roll a CMS file back to a saved version in one step: reads the version's content and writes it back to the file. Omit version_id to restore the most recent snapshot. Tip: save_file_version on the current content first if you want an undo point.", {
257
250
  cms_file_id: z.string().describe("CMS file ID to restore"),
258
- version_id: z.string().optional().describe("Which version to restore (from get_file_versions). Omit = latest snapshot."),
251
+ version_id: z.string().optional().describe("Which version to restore (api_find 'file versions' → api_get). Omit = latest snapshot."),
259
252
  }, ({ cms_file_id, version_id }) => handle(async () => {
260
253
  const res = await api.getFileVersions({ file_id: cms_file_id });
261
254
  const body = res?.data ?? res;
@@ -264,7 +257,7 @@ Example: "get_Products" → function_name="Products", method="GET"`, {
264
257
  throw new Error("No saved versions for this file — nothing to restore.");
265
258
  const version = version_id ? list.find((v) => v.id === version_id) : list[0];
266
259
  if (!version)
267
- throw new Error(`Version "${version_id}" not found. Use get_file_versions to list available versions.`);
260
+ throw new Error(`Version "${version_id}" not found. List them with api_find("file versions") → api_get.`);
268
261
  const content = version.content;
269
262
  if (content == null)
270
263
  throw new Error("That version has no stored content; cannot restore.");
@@ -278,5 +271,4 @@ Example: "get_Products" → function_name="Products", method="GET"`, {
278
271
  note: "File reverted. Run/debug it to confirm, then publish if needed.",
279
272
  };
280
273
  }));
281
- server.tool("toggle_debug_render", "Toggle debug render mode for a CMS file", { cms_file_id: z.string().describe("CMS file ID") }, ({ cms_file_id }) => handle(() => api.toggleDebugRender({ cms_file_id })));
282
274
  }
@@ -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: ["Site-wide custom script/CSS (native first: refused when an element can do it)", [
34
+ "get_site_custom_code", "update_site_custom_code", "append_site_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
  }
@@ -420,9 +420,6 @@ For full rewrites, use update_site_custom_code instead.`, {
420
420
  return { ...res, warning: `Page deleted, but removing it from global sections' page lists failed: ${e?.message || e}` };
421
421
  }
422
422
  }));
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
423
  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
424
  page_id: z.string().optional().describe("Page ID — narrows the result to that page"),
428
425
  language_code: z.string().optional().describe("With page_id: return just that language's content map"),
@@ -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,29 @@ 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 { readFileSync } from "node:fs";
34
+ import { FAMILIES, familyTool } from "./families.js";
35
+ /** Tool names folded into api_get / api_call → their route (invoke_tool points callers there). */
36
+ const retired = (() => {
37
+ try {
38
+ return JSON.parse(readFileSync(new URL("./retired-tools.json", import.meta.url), "utf8"));
39
+ }
40
+ catch {
41
+ return {};
42
+ }
43
+ })();
37
44
  /** Tool groups. `core` groups load natively; the rest are reached via search_tools + invoke_tool. */
38
45
  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" },
46
+ { 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)" },
47
+ { name: "web", title: "Page building", core: true, desc: "Pages, elements, drafts, global sources/sections, site code, themes, images, validate/build/publish" },
41
48
  { name: "store", title: "Store", core: true, desc: "Products, categories, collections, orders, promotions, combos" },
42
49
  { 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" },
50
+ { name: "site_config", title: "Site configuration", desc: "Site settings (merged safely), font groups, site plans/subscriptions (gói cước), site counts" },
51
+ { name: "marketing", title: "Marketing & CRM", desc: "Create contacts, customer tags and tag assignment" },
52
+ { name: "i18n", title: "Multilingual", desc: "Translations for products/categories/articles/etc. and their SEO" },
53
+ { name: "appointment", title: "Appointment booking", desc: "Create and update booking calendars (weekly hours, overrides)" },
54
+ { name: "reviews", title: "Product reviews", desc: "List, read and write product reviews" },
55
+ { name: "apps_advanced", title: "Advanced apps", desc: "Create a course (course app)" },
53
56
  { name: "automation", title: "Automation", desc: "Marketing automations and send-mail" },
54
57
  { name: "image_seo", title: "Image alt / SEO audit", desc: "Scan site images, read them, bulk-fill and set alt text" },
55
58
  ];
@@ -69,14 +72,10 @@ const MODULES = [
69
72
  ["session", registerAppTools],
70
73
  ["reviews", registerReviewTools],
71
74
  ["appointment", registerAppointmentTools],
72
- ["affiliate", registerAffiliateTools],
73
- ["catalog", registerCatalogExtraTools],
74
75
  ["site_config", registerSiteConfigTools],
75
76
  ["marketing", registerMarketingTools],
76
77
  ["i18n", registerMultilingualTools],
77
- ["media", registerMediaTools],
78
78
  ["apps_advanced", registerAppsExtraTools],
79
- ["channels", registerSaleChannelTools],
80
79
  ["store", registerPromotionTools],
81
80
  ["store", registerComboTools],
82
81
  ["web", registerGlobalSourceTools],
@@ -90,6 +89,11 @@ const MODULES = [
90
89
  ["site_config", registerSitePlanTools],
91
90
  ["session", registerApiGatewayTools],
92
91
  ];
92
+ /** Every collected tool of a server, by name — members of a family included (tests, gateway). */
93
+ const ENTRIES = new WeakMap();
94
+ export function toolEntries(server) {
95
+ return ENTRIES.get(server) ?? new Map();
96
+ }
93
97
  /** Captures server.tool(...) calls into a registry instead of registering them. */
94
98
  class ToolCollector {
95
99
  entries = [];
@@ -152,7 +156,8 @@ then invoke_read_tool(name, arguments) for read-only tools (list_/get_/search_
152
156
  if the user's request touches an [on-demand] area (or you're unsure), search_tools BEFORE concluding.
153
157
  Tip: search_tools matches English tool names/descriptions — translate the user's intent into English keywords.
154
158
 
155
- ${lines.join("\n")}`;
159
+ ${lines.join("\n")}
160
+ 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
161
  }
157
162
  /** Build the full registry, register native (core) tools, and add the search gateway.
158
163
  * Returns counts for diagnostics. */
@@ -166,10 +171,24 @@ export function installTools(server, api, handle, opts = {}) {
166
171
  for (const e of collector.entries)
167
172
  registry.set(e.name, e);
168
173
  const native = resolveNativeGroups(opts.tools ?? process.env.WEBCAKE_TOOLS);
169
- // Register native (core/enabled) tools directly on the MCP server.
174
+ // Register native (core/enabled) tools directly on the MCP server. Tools of a family are
175
+ // exposed once, as that family's actions (see families.ts).
170
176
  let nativeCount = 0;
177
+ const folded = new Map(); // member → family
178
+ for (const [fam, [purpose, names]] of Object.entries(FAMILIES)) {
179
+ const members = names.map((n) => registry.get(n)).filter((e) => !!e && native.has(e.group));
180
+ if (members.length < 2)
181
+ continue;
182
+ members.forEach((m) => folded.set(m.name, fam));
183
+ const t = familyTool(fam, purpose, members);
184
+ const ann = members.map((m) => toolAnnotations(m.name));
185
+ const annotations = ann.every((a) => a.readOnlyHint) ? { readOnlyHint: true } : ann.some((a) => a.destructiveHint) ? { readOnlyHint: false, destructiveHint: true } : { readOnlyHint: false };
186
+ server.registerTool(fam, { description: t.description, inputSchema: z.object(t.shape).strict(), annotations }, t.handler);
187
+ nativeCount++;
188
+ }
189
+ ENTRIES.set(server, registry);
171
190
  for (const e of collector.entries) {
172
- if (native.has(e.group)) {
191
+ if (native.has(e.group) && !folded.has(e.name)) {
173
192
  // .strict(): an argument the tool doesn't take is REFUSED with its name, not silently
174
193
  // dropped (a dropped page_id/site_id made a call act on the wrong page).
175
194
  server.registerTool(e.name, { description: e.description, inputSchema: z.object(e.shape).strict(), annotations: toolAnnotations(e.name) }, e.handler);
@@ -254,11 +273,15 @@ courses, sale channels, automation…). Returns name, group, description and JSO
254
273
  native: native.has(e.group),
255
274
  annotations: toolAnnotations(e.name),
256
275
  description: e.description,
276
+ ...(folded.has(e.name) ? { call_as: `${folded.get(e.name)}({ action: "${e.name}", … })` } : {}),
257
277
  input_schema: jsonSchema(e),
258
278
  }));
259
279
  }));
260
280
  const runTool = async (name, args, readOnlyOnly) => {
261
281
  const e = registry.get(name);
282
+ const route = retired[name];
283
+ if (!e && route)
284
+ 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
285
  if (!e)
263
286
  return errorResult(`Error: unknown tool "${name}". Use search_tools to find available tools.`);
264
287
  if (readOnlyOnly && !toolAnnotations(name).readOnlyHint) {