webcake-storefront-mcp 1.34.1 → 1.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -181,6 +181,7 @@ in chat via `update_auth` and `switch_site` — saved to a local config file at
181
181
  | **Content & store** | blog articles · themes / site style · apps · customers · `send_mail` | token + session |
182
182
  | **Backend code** | HTTP-function CRUD (`get_http_function`, `edit_http_function`, `run_function`, `debug_function`…) | token + session |
183
183
  | **Context** | `get_current_context` · `list_my_sites` · `switch_site` · `update_auth` · `toggle_confirm_mode` | token |
184
+ | **Site plans** | `get_site_subscription` (current plan, status, days left) · `count_my_sites` (by plan / custom domain / trash) · `list_plans` | token |
184
185
 
185
186
  Every write **defaults to `dry_run=true`** — it previews the exact change and only touches your site when you re-run with `dry_run=false`.
186
187
 
package/README.vi.md CHANGED
@@ -180,6 +180,7 @@ trong chat bằng `update_auth` và `switch_site` — lưu vào file cấu hình
180
180
  | **Nội dung & store** | bài blog · theme / site style · app · khách hàng · `send_mail` | token + session |
181
181
  | **Code backend** | CRUD HTTP-function (`get_http_function`, `edit_http_function`, `run_function`, `debug_function`…) | token + session |
182
182
  | **Ngữ cảnh** | `get_current_context` · `list_my_sites` · `switch_site` · `update_auth` · `toggle_confirm_mode` | token |
183
+ | **Gói cước site** | `get_site_subscription` (gói hiện tại, trạng thái, số ngày còn lại) · `count_my_sites` (theo gói / tên miền riêng / thùng rác) · `list_plans` | token |
183
184
 
184
185
  Mọi thao tác ghi **mặc định `dry_run=true`** — xem trước thay đổi, chỉ đụng site khi bạn chạy lại với `dry_run=false`.
185
186
 
package/dist/api.js CHANGED
@@ -50,6 +50,7 @@ export class WebcakeCmsApi {
50
50
  const controller = new AbortController();
51
51
  const timer = setTimeout(() => controller.abort(), timeout || DEFAULT_TIMEOUT);
52
52
  let res;
53
+ let json;
53
54
  try {
54
55
  res = await fetch(url, {
55
56
  method,
@@ -57,11 +58,16 @@ export class WebcakeCmsApi {
57
58
  body: body ? JSON.stringify(body) : undefined,
58
59
  signal: controller.signal,
59
60
  });
61
+ // Read the body under the same timer — clearing it after the headers left a stalled body unbounded.
62
+ json = await res.json().catch((e) => {
63
+ if (controller.signal.aborted)
64
+ throw e; // timed out mid-body: an error, not an empty success
65
+ return null;
66
+ });
60
67
  }
61
68
  finally {
62
69
  clearTimeout(timer);
63
70
  }
64
- const json = await res.json().catch(() => null);
65
71
  if (!res.ok) {
66
72
  const msg = (json && json.message) || (json && json.error) || res.statusText;
67
73
  throw new Error(`API ${res.status}: ${msg}`);
@@ -72,9 +78,21 @@ export class WebcakeCmsApi {
72
78
  getMe() {
73
79
  return this.request("GET", `/api/v1/@me`);
74
80
  }
81
+ /** Personal sites only (persona_or_team==0). `filter` must be "all" (status 1) or "removed"
82
+ * (trash, status 0) — any other value makes the backend 500. */
75
83
  listMySites(query) {
76
84
  return this.request("GET", `/api/v1/dashboard/site/all`, { query });
77
85
  }
86
+ /** Plan purchase history of one site, `{ subscriptions: { data[], total_entries } }`.
87
+ * The path's misspelling is the real route. Rows carry payment secrets — whitelist before
88
+ * returning. 404 for a site in trash (SitePlug requires status 1). */
89
+ getSiteSubscriptions(siteId = this.siteId, query = { page: 1, limit: 100 }) {
90
+ return this.request("GET", `/api/v1/site/${siteId}/get_subsctription_package_by_site_id`, { query });
91
+ }
92
+ /** Plan catalog `{ packages: { data[] } }` (names are free text, no enum). */
93
+ listPackages(query = { page: 1, limit: 100 }) {
94
+ return this.request("GET", `/api/v1/site/${this.siteId}/get_packages`, { query });
95
+ }
78
96
  /** Create a brand-new personal site. The backend seeds sample categories/products/blog
79
97
  * but NO pages. Returns { data: { site: { id, site_slug:{slug}, ... } } }.
80
98
  * Fails with 403 when the account's site quota is reached (free plan: 4 sites). */
@@ -649,6 +667,8 @@ export class WebcakeCmsApi {
649
667
  });
650
668
  }
651
669
  // ── Promotions ──
670
+ /** `{ success, data[], total_entries }`, 15 rows/page by default; accepts term + is_activated
671
+ * (search_promotions uses this too — the dedicated get_promotions_advance endpoint 404s on prod). */
652
672
  listPromotions(query) {
653
673
  return this.request("GET", `/api/v1/dashboard/site/${this.siteId}/promotion_advance/all`, { query });
654
674
  }
@@ -661,12 +681,6 @@ export class WebcakeCmsApi {
661
681
  getActivePromotions() {
662
682
  return this.request("GET", `/api/v1/dashboard/site/${this.siteId}/promotion_advance/get_promotions_actived`);
663
683
  }
664
- /** Search/list promotions. The dedicated get_promotions_advance endpoint 404s on prod, so
665
- * this uses the same /all list endpoint (which accepts a query); the tool filters the
666
- * returned page client-side for type/status/keyword. */
667
- searchPromotions(query) {
668
- return this.request("GET", `/api/v1/dashboard/site/${this.siteId}/promotion_advance/all`, { query });
669
- }
670
684
  // ── Combos ──
671
685
  listCombos(query) {
672
686
  return this.request("GET", `/api/v1/dashboard/site/${this.siteId}/combo_product/all`, { query });
@@ -1,4 +1,18 @@
1
1
  [
2
+ {
3
+ "v": "1.36.0",
4
+ "d": "22/10/2026",
5
+ "type": "Added",
6
+ "en": "New invoke_read_tool runs any read-only on-demand tool (list_*/get_*/search_*, i.e. tools with readOnlyHint) by name through the gateway, so clients…",
7
+ "vi": "Tool mới invoke_read_tool chạy bất kỳ tool chỉ-đọc nào (list_*/get_*/search_*, tức tool có readOnlyHint) qua gateway theo tên, nhờ đó client nào bắt…"
8
+ },
9
+ {
10
+ "v": "1.35.0",
11
+ "d": "22/10/2026",
12
+ "type": "Added",
13
+ "en": "New get_site_subscription tool reads a site's plan (current/default site): plan_name, status (active | expired | pending_payment | none),…",
14
+ "vi": "Tool mới get_site_subscription đọc gói cước của site (mặc định site hiện tại): plan_name, status (active | expired | pending_payment | none),…"
15
+ },
2
16
  {
3
17
  "v": "1.34.1",
4
18
  "d": "14/10/2026",
@@ -26,19 +40,5 @@
26
40
  "type": "Changed",
27
41
  "en": "create_product, create_product_category, create_blog_category, and create_article no longer accept a seo parameter; set SEO afterwards with…",
28
42
  "vi": "create_product, create_product_category, create_blog_category và create_article không còn nhận tham số seo; hãy đặt SEO sau khi tạo bằng…"
29
- },
30
- {
31
- "v": "1.33.0",
32
- "d": "14/10/2026",
33
- "type": "Added",
34
- "en": "Every tool, whether registered natively or reached through the search gateway (search_tools/invoke_tool/list_tool_groups), now reports readOnlyHint…",
35
- "vi": "Mọi tool, dù được đăng ký native hay được tiếp cận qua search gateway (search_tools/invoke_tool/list_tool_groups), nay đều có thêm annotation…"
36
- },
37
- {
38
- "v": "1.32.0",
39
- "d": "14/10/2026",
40
- "type": "Changed",
41
- "en": "The server now serves a raster PNG icon (/favicon.ico, /favicon.png, /icon.png, /apple-touch-icon.png) alongside the existing SVG favicon, and…",
42
- "vi": "Server nay phục vụ thêm icon dạng raster PNG (/favicon.ico, /favicon.png, /icon.png, /apple-touch-icon.png) bên cạnh favicon SVG hiện có, và khai…"
43
43
  }
44
44
  ]
package/dist/server.js CHANGED
@@ -16,7 +16,7 @@ const INSTRUCTIONS = `You are an AI assistant connected to the WebCake/StoreCake
16
16
 
17
17
  IMPORTANT: When the user asks ANY question about their website, store, products, orders, pages, or code — you MUST use the available tools to look up real data before answering. Never guess.
18
18
 
19
- Tool discovery: the common tools (pages, builder, products, orders, blog, customers, apps, publishing) are loaded directly. MANY more capabilities are available on demand — marketing/CRM (email, contacts, subscribers, employees), translations, media library, appointments, affiliate, product reviews, custom domains / SEO redirects / shipping, brands / tags / ribbons / materials, courses, sale channels, automation, and more. If you don't see a directly-loaded tool for the task, call search_tools("keywords") to find it, then run it with invoke_tool(name, arguments). Use list_tool_groups to see everything available.
19
+ Tool discovery: the common tools (pages, builder, products, orders, blog, customers, apps, publishing) are loaded directly. MANY more capabilities are available on demand — marketing/CRM (email, contacts, subscribers, employees), translations, media library, appointments, affiliate, product reviews, custom domains / SEO redirects / shipping, brands / tags / ribbons / materials, courses, sale channels, automation, and more. If you don't see a directly-loaded tool for the task, call search_tools("keywords") to find it, then run it with invoke_read_tool(name, arguments) if it only reads (list_/get_/search_…), otherwise invoke_tool(name, arguments). Use list_tool_groups to see everything available.
20
20
 
21
21
  You can also BUILD pages: use get_build_guide, list_elements, get_element to learn the BuilderX component model, new_section/new_element to compose, validate_page to check, then build_page (dry_run first) to create. Publishing is site-level via publish_site.
22
22
 
@@ -1,20 +1,31 @@
1
1
  import { z } from "zod";
2
2
  import { APP_TYPES, APP_NAMES, APP_TYPE_REFERENCE, APP_NAME_BY_TYPE } from "../enums.js";
3
+ /** Presence in /subcriptions/all = installed (that is what the dashboard shows). builderx_api get_app ignores
4
+ * is_active for every type except product_design (10), so is_active=false alone does not mean "off". */
5
+ export function summarizeApps(list) {
6
+ const installed = list.map((a) => ({
7
+ id: a.id,
8
+ type: a.type,
9
+ name: APP_NAME_BY_TYPE[a.type] ?? undefined,
10
+ enabled: a.type === APP_TYPES.product_design ? Boolean(a.is_active) : true,
11
+ is_active: a.is_active,
12
+ }));
13
+ const have = new Set(list.map((a) => a.type));
14
+ return {
15
+ installed_count: installed.length,
16
+ installed,
17
+ not_installed: APP_NAMES.filter((n) => !have.has(APP_TYPES[n])),
18
+ };
19
+ }
3
20
  export function registerAppTools(server, api, handle) {
4
- server.tool("list_apps", `List the site's installed applications (type, status, settings).
21
+ server.tool("list_apps", `Which applications are installed / enabled on the site — and which are not — in ONE call.
22
+ Returns installed[] (id, type, name, enabled) plus not_installed[] (app names). Do NOT call get_app per type
23
+ to answer "which apps are on"; use get_app only for one app's settings.
5
24
  App type codes: ${APP_TYPE_REFERENCE}.`, {}, () => handle(async () => {
6
25
  const res = await api.listApps();
7
- const raw = res?.data ?? res ?? [];
8
- const list = Array.isArray(raw) ? raw : raw?.data || [];
9
- return {
10
- apps: list.map((a) => ({
11
- type: a.type,
12
- type_name: APP_NAME_BY_TYPE[a.type] ?? undefined,
13
- status: a.status,
14
- id: a.id,
15
- })),
16
- app_types: APP_TYPES,
17
- };
26
+ // Real shape: { success, apps:[…] } — every non-removed AppSubscription row of the site.
27
+ const list = res?.apps ?? res?.data?.apps ?? (Array.isArray(res?.data) ? res.data : []);
28
+ return summarizeApps(list);
18
29
  }));
19
30
  server.tool("get_app", `Get one installed app by its type code (returns null if not installed).
20
31
  App type codes: ${APP_TYPE_REFERENCE}. You may pass the number or the name.`, {
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { getConfig, setConfig } from "../db.js";
3
3
  import { resolvePreviewUrl } from "../config.js";
4
+ import { SITE_FILTERS, normalizeSiteFilter, hasCustomDomain } from "./site-plans.js";
4
5
  /** Read all saved credentials from the local config file for startup */
5
6
  export function getSavedConfig() {
6
7
  return {
@@ -110,18 +111,27 @@ export function registerContextTools(server, api, handle) {
110
111
  hint: "Use list_my_sites to see all sites, switch_site to change site. Use toggle_confirm_mode to switch between 'always_confirm' (safe) and 'auto_apply' (fast).",
111
112
  };
112
113
  }));
113
- server.tool("list_my_sites", "List all sites accessible by the current account. Use this to find a site_id before switching", {
114
+ server.tool("list_my_sites", `List the current account's PERSONAL sites (team sites are not included). Use this to find a site_id before switching.
115
+ filter: "all" = active sites (default), "removed" = sites in trash. Each site has status, published_at (set at
116
+ creation — not proof of publishing), slug, primary domain and has_custom_domain (verified, live, non-default domain).
117
+ For plans use get_site_subscription / count_my_sites.`, {
114
118
  page: z.number().default(1).describe("Page number"),
115
119
  limit: z.number().default(20).describe("Items per page"),
116
- term: z.string().optional().describe("Search by site name"),
117
- }, ({ page, limit, term }) => handle(async () => {
118
- const res = await api.listMySites({ page, limit, ...(term && { term }) });
120
+ term: z.string().optional().describe("Search by site name, site id or domain"),
121
+ filter: z.enum(SITE_FILTERS).optional().describe('"all" (active, default) or "removed" (trash)'),
122
+ }, ({ page, limit, term, filter }) => handle(async () => {
123
+ const res = await api.listMySites({ page, limit, filter: normalizeSiteFilter(filter), ...(term && { term }) });
119
124
  const raw = res?.data?.sites || res?.data || [];
120
125
  const list = Array.isArray(raw) ? raw : [];
121
126
  const sites = list.map((s) => ({
122
127
  id: s.id,
123
128
  name: s.name,
124
- domain: s.domain || s.sub_domain || null,
129
+ status: s.status,
130
+ slug: s.site_slug?.slug ?? null,
131
+ published_at: s.published_at ?? null,
132
+ domain: s.primary_domain?.domain ?? null,
133
+ custom_domain_verified: s.primary_domain?.is_verified ?? null,
134
+ has_custom_domain: hasCustomDomain(s),
125
135
  is_current: s.id === api.siteId,
126
136
  }));
127
137
  return {
@@ -129,6 +139,7 @@ export function registerContextTools(server, api, handle) {
129
139
  sites,
130
140
  total: res?.data?.total_entries || sites.length,
131
141
  page,
142
+ ...(res?.data?.has_site_in_trash && { has_site_in_trash: true }),
132
143
  };
133
144
  }));
134
145
  server.tool("create_site", `Create a brand-new storefront site for the current account, then (by default) switch to it
@@ -33,34 +33,61 @@ const PROMOTION_TYPES = `
33
33
  - is_detail_time: has specific day/time scheduling
34
34
  - is_hidden: hidden from storefront but still active
35
35
  `;
36
+ /** /promotion_advance/all pages at 15 rows by default (builderx_api Tools.get_page_limit_from_params),
37
+ * so one call used to show 15 of 46 promotions — walk every page instead. */
38
+ const PAGE_SIZE = 100;
39
+ const MAX_ROWS = 2000; // ponytail: 20 pages max; a site past 2000 promotions gets `truncated: true`
40
+ export async function fetchAllPromotions(api, query = {}) {
41
+ const rows = [];
42
+ let total = 0;
43
+ for (let page = 1; rows.length < MAX_ROWS; page++) {
44
+ const res = await api.listPromotions({ ...query, page, limit: PAGE_SIZE });
45
+ const data = Array.isArray(res?.data) ? res.data : [];
46
+ total = Number(res?.total_entries) || total;
47
+ rows.push(...data);
48
+ if (data.length < PAGE_SIZE || (total && rows.length >= total))
49
+ break;
50
+ }
51
+ return { rows: rows.slice(0, MAX_ROWS), total: total || rows.length };
52
+ }
53
+ /** Compact row: the list endpoint already carries pos_id + is_activated, so nobody needs get_promotion per row. */
54
+ export const promotionRow = (p) => ({
55
+ id: p.id,
56
+ name: p.name,
57
+ type: p.type,
58
+ promotion_classify: p.promotion_classify || undefined,
59
+ is_activated: p.is_activated,
60
+ pos_id: p.pos_id || null, // non-null = linked/synced with Pancake POS
61
+ start_time: p.start_time || undefined,
62
+ end_time: p.end_time || undefined,
63
+ priority_level: p.priority_level ?? undefined,
64
+ is_free_shipping: p.is_free_shipping || undefined,
65
+ is_hidden: p.is_hidden || undefined,
66
+ used_count: p.used_count || 0,
67
+ inserted_at: p.inserted_at,
68
+ });
69
+ /** Totals the model is usually asked for, so it never has to count rows itself. */
70
+ export function summarizePromotions(rows, total) {
71
+ const linked = rows.filter((p) => p.pos_id).length;
72
+ return {
73
+ total,
74
+ returned: rows.length,
75
+ ...(rows.length < total ? { truncated: true } : {}),
76
+ linked_pos: linked,
77
+ not_linked_pos: rows.length - linked,
78
+ activated: rows.filter((p) => p.is_activated).length,
79
+ };
80
+ }
36
81
  export function registerPromotionTools(server, api, handle) {
37
- server.tool("list_promotions", "List all promotions/discounts of the site (metadata only). Use get_promotion for full details", {
38
- page: z.number().optional().describe("Page number (default: 1)"),
39
- limit: z.number().optional().describe("Items per page (default: 20)"),
82
+ server.tool("list_promotions", `List ALL promotions/discounts of the site (every page is fetched for you). Each row has id, name, type,
83
+ is_activated, pos_id (non-null = linked/synced with POS), start/end time. The summary answers "how many promotions /
84
+ how many synced with POS / how many active" in ONE call — do not call get_promotion per row for that.
85
+ Use get_promotion only for one promotion's full rules.`, {
40
86
  include_guide: z.boolean().optional().describe("Include promotion type reference guide"),
41
- }, ({ page, limit, include_guide }) => handle(async () => {
42
- const res = await api.listPromotions({ page, limit });
43
- const promotions = (res && res.data) || [];
44
- const result = {
45
- data: Array.isArray(promotions)
46
- ? promotions.map((p) => ({
47
- id: p.id,
48
- name: p.name,
49
- type: p.type,
50
- promotion_classify: p.promotion_classify || undefined,
51
- is_activated: p.is_activated,
52
- start_time: p.start_time || undefined,
53
- end_time: p.end_time || undefined,
54
- priority_level: p.priority_level,
55
- is_free_shipping: p.is_free_shipping || undefined,
56
- is_hidden: p.is_hidden || undefined,
57
- coupon_info: p.coupon_info || undefined,
58
- used_count: p.used_count || 0,
59
- inserted_at: p.inserted_at,
60
- }))
61
- : promotions,
62
- total: res.total_entries || res.total || (Array.isArray(promotions) ? promotions.length : 0),
63
- };
87
+ }, ({ include_guide }) => handle(async () => {
88
+ const { rows, total } = await fetchAllPromotions(api);
89
+ const data = rows.map(promotionRow);
90
+ const result = { summary: summarizePromotions(data, total), data };
64
91
  if (include_guide)
65
92
  result.guide = PROMOTION_TYPES.trim();
66
93
  return result;
@@ -104,40 +131,25 @@ export function registerPromotionTools(server, api, handle) {
104
131
  total: Array.isArray(promotions) ? promotions.length : 0,
105
132
  };
106
133
  }));
107
- server.tool("search_promotions", "Search/filter promotions with advanced filters: by type, status (coming_soon/in_progress/finished), keyword, date range", {
134
+ server.tool("search_promotions", "Search/filter ALL promotions (every page): by keyword, type, time status (coming_soon/in_progress/finished), active flag. Rows carry pos_id (non-null = synced with POS)", {
108
135
  term: z.string().optional().describe("Search by promotion name"),
109
136
  type: z.string().optional().describe("Filter by type: normal, same_price, coupon, coupon_id_multiple_times, discount_by_coupon_id, promotion_order, promotion_category, x_get_y_prod, x_get_y_category"),
110
137
  status: z.number().optional().describe("Filter by time status: 1=coming_soon, 2=in_progress, 3=finished"),
111
138
  is_activated: z.boolean().optional().describe("Filter by active status"),
112
- page: z.number().optional().describe("Page number"),
113
- limit: z.number().optional().describe("Items per page"),
114
- }, ({ term, type, status, is_activated, page, limit }) => handle(async () => {
139
+ }, ({ term, type, status, is_activated }) => handle(async () => {
140
+ // term + is_activated filter server-side; type/status are applied here (the backend's `types`
141
+ // filter wants a list, which a query string can't carry).
115
142
  const query = {};
116
- if (term)
117
- query.term = term;
118
- if (type)
119
- query.type = type;
120
- if (status != null)
121
- query.status = status;
143
+ if (term && term.trim())
144
+ query.term = term.trim();
122
145
  if (is_activated != null)
123
146
  query.is_activated = is_activated;
124
- if (page)
125
- query.page = page;
126
- if (limit)
127
- query.limit = limit;
128
- const res = await api.searchPromotions({ page: page ?? 1, limit: limit ?? 50 });
129
- let list = (res && (res.data?.result || res.data)) || [];
130
- if (!Array.isArray(list))
131
- return res;
132
- // The /all endpoint doesn't filter, so apply the requested filters client-side.
133
- if (term)
134
- list = list.filter((p) => (p.name || "").toLowerCase().includes(term.toLowerCase()));
147
+ let list = (await fetchAllPromotions(api, query)).rows;
135
148
  if (type)
136
149
  list = list.filter((p) => p.type === type);
137
150
  if (status != null)
138
151
  list = list.filter((p) => p.time_status === status || p.status === status);
139
- if (is_activated != null)
140
- list = list.filter((p) => Boolean(p.is_activated) === is_activated);
141
- return { data: list, total: list.length, total_unfiltered: res.total_entries };
152
+ const data = list.map(promotionRow);
153
+ return { summary: summarizePromotions(data, data.length), data };
142
154
  }));
143
155
  }
@@ -32,6 +32,7 @@ import { registerImageTools } from "./images.js";
32
32
  import { registerBuilderTools } from "./builder.js";
33
33
  import { registerBuilderExtraTools } from "./builder-extras.js";
34
34
  import { registerPageDraftTools } from "./page-draft.js";
35
+ import { registerSitePlanTools } from "./site-plans.js";
35
36
  /** Tool groups. `core` groups load natively; the rest are reached via search_tools + invoke_tool. */
36
37
  export const GROUPS = [
37
38
  { name: "session", title: "Session & apps", core: true, desc: "Connection context, site switch, app install/list, result cache" },
@@ -39,7 +40,7 @@ export const GROUPS = [
39
40
  { name: "store", title: "Store", core: true, desc: "Products, categories, collections, orders, promotions, combos" },
40
41
  { name: "content", title: "Content & customers", core: true, desc: "Blog articles, customers, CMS files / HTTP functions" },
41
42
  { name: "catalog", title: "Catalog extras", desc: "Brands, suppliers, product tags, ribbons, materials, variations, measurement, price-contact" },
42
- { name: "site_config", title: "Site configuration", desc: "Custom domains, SEO redirects, shipping, UTM links, fonts, site settings, API keys, publish history" },
43
+ { 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" },
43
44
  { name: "marketing", title: "Marketing & CRM", desc: "Email templates, contacts, subscribers, customer tags, employees, invitations, insight, notifications" },
44
45
  { name: "i18n", title: "Multilingual", desc: "Enable languages and manage translations for products/categories/articles/etc." },
45
46
  { name: "media", title: "Media & PWA", desc: "Media library folders/content, capacity, base64 upload, PWA manifest" },
@@ -85,6 +86,7 @@ const MODULES = [
85
86
  ["web", registerBuilderTools],
86
87
  ["web", registerBuilderExtraTools],
87
88
  ["web", registerPageDraftTools],
89
+ ["site_config", registerSitePlanTools],
88
90
  ];
89
91
  /** Captures server.tool(...) calls into a registry instead of registering them. */
90
92
  class ToolCollector {
@@ -144,7 +146,7 @@ export function buildToolGroupIndex(spec) {
144
146
  return `## Capability map (WebCake tool groups)
145
147
  Every capability below exists. Groups marked [loaded] are available as direct tools right now.
146
148
  Groups marked [on-demand] are NOT loaded to save context — to use one, call search_tools("english keywords")
147
- then invoke_tool(name, arguments). NEVER tell the user a capability is missing without searching first;
149
+ then invoke_read_tool(name, arguments) for read-only tools (list_/get_/search_…) or invoke_tool for the rest. NEVER tell the user a capability is missing without searching first;
148
150
  if the user's request touches an [on-demand] area (or you're unsure), search_tools BEFORE concluding.
149
151
  Tip: search_tools matches English tool names/descriptions — translate the user's intent into English keywords.
150
152
 
@@ -192,7 +194,7 @@ export function installTools(server, api, handle, opts = {}) {
192
194
  }))));
193
195
  server.tool("search_tools", `Find WebCake tools by keyword across the FULL catalog — including capabilities NOT loaded natively
194
196
  (marketing/CRM, translations, media, appointments, affiliate, reviews, domains/SEO/shipping, brands/tags/ribbons,
195
- courses, sale channels, automation…). Returns name, group, description and JSON input schema. Then run one with invoke_tool.`, {
197
+ courses, sale channels, automation…). Returns name, group, description and JSON input schema. Then run one with invoke_read_tool (read-only) or invoke_tool.`, {
196
198
  query: z.string().describe("Keywords, e.g. 'affiliate payout', 'translate product', 'add domain ssl', 'block phone'"),
197
199
  group: z.string().optional().describe("Restrict to a group name (see list_tool_groups)"),
198
200
  limit: z.number().optional().describe("Max results (default 8)"),
@@ -251,21 +253,31 @@ courses, sale channels, automation…). Returns name, group, description and JSO
251
253
  input_schema: jsonSchema(e),
252
254
  }));
253
255
  }));
254
- server.tool("invoke_tool", `Run any WebCake tool by exact name with its arguments (discover names + schemas via search_tools).
255
- Arguments are validated before running. Use this for tools that are not loaded natively.`, {
256
- name: z.string().describe("Exact tool name (from search_tools)"),
257
- arguments: z.record(z.any()).optional().describe("Arguments object matching the tool's input schema"),
258
- }, toolAnnotations("invoke_tool"), // runs any tool, so never read-only
259
- async ({ name, arguments: args }) => {
256
+ const runTool = async (name, args, readOnlyOnly) => {
260
257
  const e = registry.get(name);
261
258
  if (!e)
262
259
  return errorResult(`Error: unknown tool "${name}". Use search_tools to find available tools.`);
260
+ if (readOnlyOnly && !toolAnnotations(name).readOnlyHint) {
261
+ return errorResult(`Error: "${name}" is not read-only — run it with invoke_tool.`);
262
+ }
263
263
  const parsed = z.object(e.shape).safeParse(args ?? {});
264
264
  if (!parsed.success) {
265
265
  const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
266
266
  return errorResult(`Error: invalid arguments for "${name}": ${issues}`);
267
267
  }
268
268
  return e.handler(parsed.data, {});
269
- });
269
+ };
270
+ const gatewayArgs = {
271
+ name: z.string().describe("Exact tool name (from search_tools)"),
272
+ arguments: z.record(z.any()).optional().describe("Arguments object matching the tool's input schema"),
273
+ };
274
+ // invoke_tool can run writes, so it is never read-only — and clients that gate non-read-only tools
275
+ // behind a human approval (e.g. "ask before running") then stall EVERY on-demand read on a click.
276
+ // invoke_read_tool runs only read-only tools, so it can carry readOnlyHint and be auto-allowed.
277
+ server.tool("invoke_read_tool", `Run a READ-ONLY WebCake tool (list_*/get_*/search_*/count_*… — annotations.readOnlyHint in search_tools)
278
+ by exact name with its arguments. Prefer this over invoke_tool for lookups. Refuses tools that change data.`, gatewayArgs, { readOnlyHint: true }, ({ name, arguments: args }) => runTool(name, args, true));
279
+ server.tool("invoke_tool", `Run any WebCake tool by exact name with its arguments (discover names + schemas via search_tools).
280
+ Arguments are validated before running. For read-only tools prefer invoke_read_tool.`, gatewayArgs, toolAnnotations("invoke_tool"), // runs any tool, so never read-only
281
+ ({ name, arguments: args }) => runTool(name, args, false));
270
282
  return { total: collector.entries.length, native: nativeCount, groups: GROUPS.length };
271
283
  }
@@ -0,0 +1,183 @@
1
+ // Site plans (gói cước): read a site's subscription, count the account's sites by plan /
2
+ // custom domain / trash, list the plan catalog. All account-token endpoints (no super-admin).
3
+ import { z } from "zod";
4
+ const DAY = 86_400_000;
5
+ /** Storefront keeps serving on the default link this long after expiry (time_live_active_site). */
6
+ export const GRACE_DAYS = 15;
7
+ const DEFAULT_DOMAIN_SUFFIXES = ["webcake.me", "mywebcake.com", "storecake.net", "storecake.io"];
8
+ export const SITE_FILTERS = ["all", "removed"];
9
+ export const PLAN_NOTES = [
10
+ `After expiry the storefront keeps running on the default link for ${GRACE_DAYS} days.`,
11
+ "A custom domain is removed right after the plan expires.",
12
+ "A site with no plan on a default domain is blocked 10 minutes after published_at.",
13
+ ];
14
+ /** Only "all" | "removed" are accepted — anything else makes the backend 500. */
15
+ export function normalizeSiteFilter(filter) {
16
+ const f = (filter ?? "all").trim().toLowerCase();
17
+ if (f === "all" || f === "removed")
18
+ return f;
19
+ throw new Error(`Invalid filter "${filter}": use "all" (active sites) or "removed" (trash).`);
20
+ }
21
+ export function isDefaultDomain(domain) {
22
+ const d = String(domain || "").trim().toLowerCase().replace(/\.$/, "");
23
+ return DEFAULT_DOMAIN_SUFFIXES.some((s) => d === s || d.endsWith(`.${s}`));
24
+ }
25
+ /** A site is "published on its own domain" when its primary domain is a verified, live, non-default domain. */
26
+ export function hasCustomDomain(site) {
27
+ const pd = site?.primary_domain;
28
+ return !!(pd?.domain && pd.is_verified && !pd.is_blocked && !pd.is_deleted && !isDefaultDomain(pd.domain));
29
+ }
30
+ /** Whitelist one subscription row — rows also carry stripe_client_secret, qr_data, virtual_account,
31
+ * infor_bill, phone_number, commissions and nested site/owner, none of which may leave this server. */
32
+ export function sanitizeSubscription(r) {
33
+ return {
34
+ plan_name: r?.package?.name ?? null,
35
+ package_id: r?.package_id ?? null,
36
+ duration: r?.duration ?? null,
37
+ payment_amount: r?.payment_amount ?? null,
38
+ currency: r?.currency ?? null,
39
+ is_paid: !!r?.is_paid,
40
+ is_activated: !!r?.is_activated,
41
+ activated_at: r?.activated_at ?? null,
42
+ expired_at: r?.expired_at ?? null,
43
+ upgrade_from: r?.upgrade_from ?? null,
44
+ inserted_at: r?.inserted_at ?? null,
45
+ };
46
+ }
47
+ const ts = (v) => (v ? Date.parse(v) || 0 : 0);
48
+ /** Current plan of a site from its (sanitized) subscription rows. Active = paid && activated && not expired. */
49
+ export function summarizePlan(rows, now = Date.now()) {
50
+ const byExpiry = (a, b) => ts(b.expired_at) - ts(a.expired_at);
51
+ const active = rows.filter((r) => r.is_paid && r.is_activated && ts(r.expired_at) > now).sort(byExpiry)[0];
52
+ const lastPaid = rows.filter((r) => r.is_paid && r.is_activated).sort(byExpiry)[0];
53
+ const latest = [...rows].sort((a, b) => ts(b.inserted_at) - ts(a.inserted_at))[0];
54
+ let status;
55
+ let row;
56
+ if (active)
57
+ [status, row] = ["active", active];
58
+ else if (latest && !(latest.is_paid && latest.is_activated))
59
+ [status, row] = ["pending_payment", latest];
60
+ else if (lastPaid)
61
+ [status, row] = ["expired", lastPaid];
62
+ else
63
+ [status, row] = ["none", null];
64
+ const exp = row ? ts(row.expired_at) : 0;
65
+ const out = {
66
+ plan_name: row?.plan_name ?? null,
67
+ status,
68
+ expired_at: row?.expired_at ?? null,
69
+ days_left: status === "active" && exp ? Math.ceil((exp - now) / DAY) : null,
70
+ };
71
+ if (status === "expired" && exp) {
72
+ out.grace_until = new Date(exp + GRACE_DAYS * DAY).toISOString();
73
+ out.in_grace = now < exp + GRACE_DAYS * DAY;
74
+ }
75
+ if (status === "pending_payment" && lastPaid)
76
+ out.last_expired_at = lastPaid.expired_at;
77
+ return out;
78
+ }
79
+ const unwrapSubs = (res) => {
80
+ const s = res?.subscriptions ?? res?.data?.subscriptions;
81
+ return Array.isArray(s?.data) ? s.data : [];
82
+ };
83
+ async function readSitePlan(api, siteId) {
84
+ try {
85
+ return unwrapSubs(await api.getSiteSubscriptions(siteId)).map(sanitizeSubscription);
86
+ }
87
+ catch (e) {
88
+ const msg = e instanceof Error ? e.message : String(e);
89
+ if (msg.includes("API 404")) {
90
+ throw new Error(`Site ${siteId} not found or deleted (in trash). The plan of a deleted site cannot be read — restore it first.`);
91
+ }
92
+ throw e;
93
+ }
94
+ }
95
+ /** Run `fn` over items with at most `limit` in flight. */
96
+ async function pool(items, limit, fn) {
97
+ const out = new Array(items.length);
98
+ let i = 0;
99
+ const worker = async () => {
100
+ while (i < items.length) {
101
+ const k = i++;
102
+ out[k] = await fn(items[k]);
103
+ }
104
+ };
105
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
106
+ return out;
107
+ }
108
+ const unwrapSites = (res) => {
109
+ const d = res?.data ?? res ?? {};
110
+ return { sites: Array.isArray(d.sites) ? d.sites : [], total: Number(d.total_entries) || 0 };
111
+ };
112
+ export function registerSitePlanTools(server, api, handle) {
113
+ server.tool("get_site_subscription", `Read a site's plan (gói cước): the current plan_name, status (active | expired | pending_payment | none),
114
+ expired_at and days_left, plus the purchase history (package name, duration, amount, paid/activated, dates).
115
+ Active = paid && activated && expired_at in the future. No row = the site has no plan (free).
116
+ ${PLAN_NOTES.join(" ")}
117
+ A site in trash cannot be read (backend 404).`, { site_id: z.string().optional().describe("Site id (default: current site)") }, ({ site_id }) => handle(async () => {
118
+ const id = site_id || api.siteId;
119
+ const rows = await readSitePlan(api, id);
120
+ return { site_id: id, ...summarizePlan(rows), history: rows, notes: PLAN_NOTES };
121
+ }));
122
+ server.tool("count_my_sites", `Count the account's PERSONAL sites: active total, deleted (in trash), active by plan (paid && activated && not expired)
123
+ with a per-plan breakdown, no plan, expired, pending payment, and sites on a verified custom domain.
124
+ Plans are read per site (≤5 in parallel, up to max_sites); beyond that the result says checked/total.
125
+ Notes: "published" is approximated by having a verified, non-blocked custom domain — published_at is set when the
126
+ site is CREATED, so it does not prove the site was published. Team sites (persona_or_team) are NOT included.`, { max_sites: z.number().int().min(1).max(500).default(200).describe("Max sites whose plan is read (default 200)") }, ({ max_sites }) => handle(async () => {
127
+ const all = [];
128
+ let total = 0;
129
+ for (let page = 1; page <= 100; page++) {
130
+ const r = unwrapSites(await api.listMySites({ page, limit: 100, filter: "all" }));
131
+ total = r.total;
132
+ all.push(...r.sites);
133
+ if (!r.sites.length || all.length >= total)
134
+ break;
135
+ }
136
+ const removed = unwrapSites(await api.listMySites({ page: 1, limit: 1, filter: "removed" })).total;
137
+ const checked = all.slice(0, max_sites);
138
+ const now = Date.now();
139
+ const plans = await pool(checked, 5, (s) => readSitePlan(api, s.id).then((rows) => summarizePlan(rows, now), () => null));
140
+ const by_plan_name = {};
141
+ const count = { active: 0, expired: 0, pending_payment: 0, none: 0 };
142
+ let errors = 0;
143
+ for (const p of plans) {
144
+ if (!p) {
145
+ errors++;
146
+ continue;
147
+ }
148
+ count[p.status]++;
149
+ if (p.status === "active")
150
+ by_plan_name[p.plan_name || "(unnamed)"] = (by_plan_name[p.plan_name || "(unnamed)"] || 0) + 1;
151
+ }
152
+ return {
153
+ total_active_sites: total || all.length,
154
+ deleted_sites: removed,
155
+ active_by_plan: count.active,
156
+ by_plan_name,
157
+ no_plan: count.none,
158
+ expired: count.expired,
159
+ pending_payment: count.pending_payment,
160
+ custom_domain_sites: all.filter(hasCustomDomain).length,
161
+ checked: checked.length,
162
+ total: total || all.length,
163
+ ...(errors && { plan_read_errors: errors }),
164
+ ...(checked.length < (total || all.length) && { partial: `Plans checked for ${checked.length}/${total} sites; raise max_sites for full coverage.` }),
165
+ notes: [
166
+ "Team sites are not included (personal sites only).",
167
+ "custom_domain_sites = verified, not blocked/deleted, not *.webcake.me / *.mywebcake.com / *.storecake.net / *.storecake.io. published_at is set at creation, so it is not used.",
168
+ ...PLAN_NOTES,
169
+ ],
170
+ };
171
+ }));
172
+ server.tool("list_plans", "List the plan catalog (gói cước): id, name, description, attributes. Plan names are free text, not an enum.", {}, () => handle(async () => {
173
+ const res = await api.listPackages();
174
+ const list = res?.packages?.data ?? res?.data?.packages?.data ?? [];
175
+ return list.map((p) => ({
176
+ id: p.id,
177
+ name: p.name,
178
+ description: p.description ?? null,
179
+ package_attributes: p.package_attributes ?? [],
180
+ is_hidden: !!p.is_hidden,
181
+ }));
182
+ }));
183
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webcake-storefront-mcp",
3
- "version": "1.34.1",
3
+ "version": "1.36.0",
4
4
  "description": "MCP server for the WebCake/StoreCake storefront builder — page CRUD, page authoring, products, orders, and more",
5
5
  "mcpName": "io.github.vuluu2k/webcake-storefront-mcp",
6
6
  "license": "MIT",