webcake-storefront-mcp 1.41.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.
- package/README.md +2 -2
- package/README.vi.md +2 -2
- package/dist/api-catalog.generated.json +677 -0
- package/dist/api.js +0 -425
- package/dist/builder/attributes.js +1 -1
- package/dist/builder/catalog.js +1 -1
- package/dist/builder/element-keys.generated.json +136 -4105
- package/dist/builder/element-schema.js +297 -0
- package/dist/builder/page.js +38 -26
- package/dist/changelog.json +14 -14
- package/dist/server.js +3 -1
- package/dist/tools/api-gateway.js +198 -0
- package/dist/tools/appointment.js +5 -49
- package/dist/tools/apps-extra.js +0 -28
- package/dist/tools/apps.js +0 -11
- package/dist/tools/builder-extras.js +3 -1
- package/dist/tools/builder.js +12 -3
- package/dist/tools/cms-files.js +2 -10
- package/dist/tools/families.js +132 -0
- package/dist/tools/marketing.js +0 -45
- package/dist/tools/multilingual.js +0 -16
- package/dist/tools/orders.js +0 -1
- package/dist/tools/pages.js +0 -3
- package/dist/tools/products.js +0 -5
- package/dist/tools/registry.js +53 -26
- package/dist/tools/retired-tools.json +141 -0
- package/dist/tools/reviews.js +0 -5
- package/dist/tools/site-config.js +0 -78
- package/dist/web-guide.js +1 -1
- package/package.json +3 -1
- package/dist/tools/affiliate.js +0 -27
- package/dist/tools/catalog-extras.js +0 -88
- package/dist/tools/media.js +0 -39
- package/dist/tools/sale-channels.js +0 -45
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// api_find / api_get / api_call: the whole builderx_api surface the storefront JWT can reach,
|
|
2
|
+
// from src/api-catalog.generated.json (scripts/gen-api-catalog.mjs reads the Phoenix routers and
|
|
3
|
+
// controllers). The hand-written tools stay the way to do anything they cover: a write to a route
|
|
4
|
+
// one of them owns is refused here and names that tool, since those tools carry the guards
|
|
5
|
+
// (settings merge, page-source validation, native-first, CMS tokens, by_ai…).
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { FAMILY_OF } from "./families.js";
|
|
9
|
+
/** How to call a dedicated tool: family members run as an action. */
|
|
10
|
+
const callName = (t) => (FAMILY_OF[t] ? `${FAMILY_OF[t]}{action:"${t}"}` : t);
|
|
11
|
+
let CATALOG = { meta: {}, ops: [] };
|
|
12
|
+
try {
|
|
13
|
+
CATALOG = JSON.parse(readFileSync(new URL("../api-catalog.generated.json", import.meta.url), "utf8"));
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
/* catalog missing: the tools answer with an empty list */
|
|
17
|
+
}
|
|
18
|
+
export const API_OPS = CATALOG.ops;
|
|
19
|
+
const BY_ID = new Map(API_OPS.map((o) => [o.id, o]));
|
|
20
|
+
/** Irreversible account-level operations: never through the generic gateway. */
|
|
21
|
+
const DENY = {
|
|
22
|
+
"post:/api/v1/dashboard/site/delete": "deleting a site is done by the owner in the WebCake dashboard",
|
|
23
|
+
"post:/api/v1/dashboard/site/:site_id/settings/employee/move_owner_permission": "transferring site ownership is done by the owner in the WebCake dashboard",
|
|
24
|
+
};
|
|
25
|
+
const pathParams = (path) => [...path.matchAll(/:(\w+)/g)].map((m) => m[1]);
|
|
26
|
+
const words = (s) => s.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
27
|
+
/** One line per operation — what api_find returns for a query. */
|
|
28
|
+
export function opLine(o) {
|
|
29
|
+
const keys = o.params ? Object.keys(o.params) : [];
|
|
30
|
+
const shown = keys.slice(0, 6).map((k) => (o.required?.includes(k) ? `${k}*` : k));
|
|
31
|
+
return `${o.id} — ${o.handler}${shown.length ? ` (${shown.join(", ")}${keys.length > 6 ? ", …" : ""})` : ""}${o.tools ? ` ⇒ tool: ${o.tools.slice(0, 3).map(callName).join(", ")}` : ""}`;
|
|
32
|
+
}
|
|
33
|
+
export function searchOps(query, limit = 15, method) {
|
|
34
|
+
const terms = words(query);
|
|
35
|
+
const scored = API_OPS.filter((o) => !method || o.method === method.toUpperCase())
|
|
36
|
+
.map((o) => {
|
|
37
|
+
const segs = words(o.path.replace(/:\w+/g, ""));
|
|
38
|
+
const hw = words(o.handler);
|
|
39
|
+
const pw = Object.keys(o.params || {}).flatMap(words);
|
|
40
|
+
let s = 0;
|
|
41
|
+
for (const t of terms) {
|
|
42
|
+
if (segs.includes(t))
|
|
43
|
+
s += 3;
|
|
44
|
+
else if (segs.some((w) => w.startsWith(t) || t.startsWith(w) && w.length > 3))
|
|
45
|
+
s += 2;
|
|
46
|
+
if (hw.includes(t))
|
|
47
|
+
s += 2;
|
|
48
|
+
if (pw.includes(t))
|
|
49
|
+
s += 1;
|
|
50
|
+
}
|
|
51
|
+
if (s && o.path.includes("/dashboard/site/:site_id/"))
|
|
52
|
+
s += 0.5; // the site-scoped admin API
|
|
53
|
+
return { o, s };
|
|
54
|
+
})
|
|
55
|
+
.filter((x) => x.s > 0)
|
|
56
|
+
.sort((a, b) => b.s - a.s || a.o.path.length - b.o.path.length);
|
|
57
|
+
return scored.slice(0, limit).map((x) => x.o);
|
|
58
|
+
}
|
|
59
|
+
/** The call sheet: everything needed to call one operation correctly. */
|
|
60
|
+
export function describeOp(o) {
|
|
61
|
+
const where = o.method === "GET" ? "query" : "body";
|
|
62
|
+
return {
|
|
63
|
+
id: o.id,
|
|
64
|
+
method: o.method,
|
|
65
|
+
path: o.path,
|
|
66
|
+
handler: o.handler,
|
|
67
|
+
path_params: pathParams(o.path),
|
|
68
|
+
[where]: o.params || "not readable from the controller — send a modified copy of the matching GET",
|
|
69
|
+
...(o.required ? { required: o.required } : {}),
|
|
70
|
+
...(o.perms ? { needs_permission: o.perms } : {}),
|
|
71
|
+
...(o.tools
|
|
72
|
+
? { prefer_tool: o.tools.map(callName), note: o.method === "GET" ? "A dedicated tool covers this route and returns a cleaner result." : "Writes to this route go through the dedicated tool (it carries the guards); api_call refuses them." }
|
|
73
|
+
: {}),
|
|
74
|
+
...(DENY[o.id] ? { refused: DENY[o.id] } : {}),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
// Never hand a secret to the model: values under these keys are replaced in every result
|
|
78
|
+
// (a dedicated tool used to whitelist them; the generic gateway has to do it itself).
|
|
79
|
+
const SECRET_KEY = /secret|passw|token|api_?key|private_?key|access_?key|hash_?key|checksum|signature|credential|webhook_key|qr_data/i;
|
|
80
|
+
/** On a route that hands out credentials (…/token, …/api_key), a bare `key` is the secret too. */
|
|
81
|
+
const SECRET_ROUTE = /token|api_key|secret|credential/i;
|
|
82
|
+
export function redactSecrets(v, secretRoute = false, depth = 0) {
|
|
83
|
+
if (depth > 12 || v === null || typeof v !== "object")
|
|
84
|
+
return v;
|
|
85
|
+
if (Array.isArray(v))
|
|
86
|
+
return v.map((x) => redactSecrets(x, secretRoute, depth + 1));
|
|
87
|
+
const out = {};
|
|
88
|
+
for (const [k, x] of Object.entries(v)) {
|
|
89
|
+
const secret = SECRET_KEY.test(k) || (secretRoute && /^(key|value)$/.test(k));
|
|
90
|
+
out[k] = secret && x !== null && x !== "" && typeof x !== "boolean" && typeof x !== "object" ? "[redacted]" : redactSecrets(x, secretRoute, depth + 1);
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
const LIST_KEYS = ["data", "items", "products", "orders", "customers", "articles", "results", "list", "records", "entries"];
|
|
95
|
+
/** Trim a response for the model: keep `pick` fields per item, cap list length. */
|
|
96
|
+
export function trimResult(res, pick, maxItems = 50) {
|
|
97
|
+
const pickOne = (x) => pick && x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(pick.filter((k) => k in x).map((k) => [k, x[k]])) : x;
|
|
98
|
+
const trimList = (arr) => {
|
|
99
|
+
const items = arr.slice(0, maxItems).map(pickOne);
|
|
100
|
+
return arr.length > maxItems ? { items, total_items: arr.length, truncated: true } : items;
|
|
101
|
+
};
|
|
102
|
+
if (Array.isArray(res))
|
|
103
|
+
return trimList(res);
|
|
104
|
+
if (res && typeof res === "object") {
|
|
105
|
+
for (const k of LIST_KEYS) {
|
|
106
|
+
if (Array.isArray(res[k]))
|
|
107
|
+
return { ...res, [k]: trimList(res[k]) };
|
|
108
|
+
if (res[k] && typeof res[k] === "object")
|
|
109
|
+
for (const k2 of LIST_KEYS)
|
|
110
|
+
if (Array.isArray(res[k][k2]))
|
|
111
|
+
return { ...res, [k]: { ...res[k], [k2]: trimList(res[k][k2]) } };
|
|
112
|
+
}
|
|
113
|
+
return pick ? pickOne(res) : res;
|
|
114
|
+
}
|
|
115
|
+
return res;
|
|
116
|
+
}
|
|
117
|
+
const MAX_CHARS = 30_000;
|
|
118
|
+
export function registerApiGatewayTools(server, api, handle) {
|
|
119
|
+
server.tool("api_find", `Search the FULL WebCake backend API (${API_OPS.length} operations the storefront account can call — far more than the dedicated tools cover). With \`query\`: one line per match \`id — Controller.action (body/query keys, * = required) ⇒ tool: dedicated tool if one exists\`. With \`id\`: the call sheet (path params, body/query keys with their nested fields, required keys, permission needed). Prefer a dedicated tool when one is listed; use api_get / api_call for the rest.`, {
|
|
120
|
+
query: z.string().optional().describe("English keywords from the path/controller, e.g. 'shipping fee', 'product tag', 'customer point'"),
|
|
121
|
+
id: z.string().optional().describe("Exact operation id from a previous search, e.g. 'post:/api/v1/dashboard/site/:site_id/products/create'"),
|
|
122
|
+
method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).optional().describe("Only this HTTP method"),
|
|
123
|
+
limit: z.number().int().min(1).max(40).optional().describe("Max lines (default 15)"),
|
|
124
|
+
}, ({ query, id, method, limit }) => handle(async () => {
|
|
125
|
+
if (id) {
|
|
126
|
+
const o = BY_ID.get(id);
|
|
127
|
+
if (!o)
|
|
128
|
+
throw new Error(`Unknown operation "${id}". Search with api_find({ query }).`);
|
|
129
|
+
return describeOp(o);
|
|
130
|
+
}
|
|
131
|
+
if (!query)
|
|
132
|
+
throw new Error("Pass query (keywords) or id (an operation id).");
|
|
133
|
+
const hits = searchOps(query, limit ?? 15, method);
|
|
134
|
+
return hits.length ? hits.map(opLine) : `No operation matches "${query}". Try other English words from the path (e.g. 'promotion', 'shipping', 'tag').`;
|
|
135
|
+
}));
|
|
136
|
+
const call = async (args, readOnly) => {
|
|
137
|
+
const o = args.id ? BY_ID.get(args.id) : API_OPS.find((x) => x.method === String(args.method || "").toUpperCase() && x.path === args.path);
|
|
138
|
+
if (!o)
|
|
139
|
+
throw new Error(`Unknown operation${args.id ? ` "${args.id}"` : ""}. Find it with api_find({ query }) and pass its id.`);
|
|
140
|
+
if (readOnly && o.method !== "GET")
|
|
141
|
+
throw new Error(`${o.id} is a ${o.method} — run it with api_call.`);
|
|
142
|
+
if (DENY[o.id])
|
|
143
|
+
throw new Error(`Refused: ${DENY[o.id]}.`);
|
|
144
|
+
if (o.method !== "GET" && o.tools)
|
|
145
|
+
throw new Error(`Refused: ${o.id} is written through ${o.tools.map(callName).join(" / ")} — that tool validates and guards this write. Use it instead.`);
|
|
146
|
+
const params = { ...(args.path_params || {}) };
|
|
147
|
+
if (params.site_id == null && pathParams(o.path).includes("site_id")) {
|
|
148
|
+
if (!api.siteId)
|
|
149
|
+
throw new Error("No site selected — call list_my_sites + switch_site, or pass path_params.site_id.");
|
|
150
|
+
params.site_id = api.siteId;
|
|
151
|
+
}
|
|
152
|
+
const missingPath = pathParams(o.path).filter((p) => params[p] == null || params[p] === "");
|
|
153
|
+
if (missingPath.length)
|
|
154
|
+
throw new Error(`Missing path_params: ${missingPath.join(", ")}. Call sheet: api_find({ id: "${o.id}" }).`);
|
|
155
|
+
const path = o.path.replace(/:(\w+)/g, (_, p) => encodeURIComponent(String(params[p])));
|
|
156
|
+
const input = o.method === "GET" ? args.query || {} : args.body || {};
|
|
157
|
+
const missing = (o.required || []).filter((k) => input[k] === undefined);
|
|
158
|
+
if (missing.length)
|
|
159
|
+
throw new Error(`Missing required ${o.method === "GET" ? "query" : "body"} keys: ${missing.join(", ")}. Call sheet: api_find({ id: "${o.id}" }).`);
|
|
160
|
+
const unknown = o.params ? Object.keys(input).filter((k) => !(k in o.params)) : [];
|
|
161
|
+
if (o.method !== "GET" && args.dry_run !== false)
|
|
162
|
+
return {
|
|
163
|
+
dry_run: true,
|
|
164
|
+
would_send: { method: o.method, path, ...(args.query ? { query: args.query } : {}), body: input },
|
|
165
|
+
...(unknown.length ? { unknown_keys: unknown, note: "the action never reads these keys" } : {}),
|
|
166
|
+
next: "Show the user what will change; on their OK call again with dry_run:false.",
|
|
167
|
+
};
|
|
168
|
+
let res;
|
|
169
|
+
try {
|
|
170
|
+
res = await api.request(o.method === "ANY" ? "POST" : o.method, path, o.method === "GET" ? { query: input } : { body: input, query: args.query });
|
|
171
|
+
}
|
|
172
|
+
catch (e) {
|
|
173
|
+
const msg = e?.message || String(e);
|
|
174
|
+
throw new Error(/API 403/.test(msg) && o.perms ? `${msg} — needs site permission ${o.perms.join(" / ")}.` : msg);
|
|
175
|
+
}
|
|
176
|
+
const out = trimResult(redactSecrets(res, SECRET_ROUTE.test(o.path)), args.pick, args.max_items ?? 50);
|
|
177
|
+
const text = JSON.stringify(out);
|
|
178
|
+
return {
|
|
179
|
+
...(unknown.length ? { unknown_keys: unknown } : {}),
|
|
180
|
+
result: text.length > MAX_CHARS ? `${text.slice(0, MAX_CHARS)}… (cut at ${MAX_CHARS} chars — narrow with pick / max_items / query filters)` : out,
|
|
181
|
+
};
|
|
182
|
+
};
|
|
183
|
+
const shared = {
|
|
184
|
+
id: z.string().optional().describe("Operation id from api_find (preferred)"),
|
|
185
|
+
method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "ANY"]).optional().describe("With path, when id is not given"),
|
|
186
|
+
path: z.string().optional().describe("Catalog path with :params, e.g. /api/v1/dashboard/site/:site_id/product_tags/all"),
|
|
187
|
+
path_params: z.record(z.string()).optional().describe("Values for :params in the path; site_id defaults to the current site"),
|
|
188
|
+
query: z.record(z.any()).optional().describe("Query-string values"),
|
|
189
|
+
pick: z.array(z.string()).optional().describe("Keep only these fields on each item of a list result (or on a single object)"),
|
|
190
|
+
max_items: z.number().int().min(1).max(500).optional().describe("Cap list results (default 50)"),
|
|
191
|
+
};
|
|
192
|
+
server.tool("api_get", "Run a READ-ONLY (GET) operation from api_find by id. site_id is filled from the current site. Use pick / max_items to keep the result small. Refuses anything that is not a GET.", shared, (args) => handle(() => call(args, true)));
|
|
193
|
+
server.tool("api_call", "Run any operation from api_find by id (GET, POST, PUT, PATCH, DELETE). Writes default to dry_run:true and return exactly what would be sent — show the user, then repeat with dry_run:false. Refuses writes to routes a dedicated tool owns (it names the tool) and irreversible account operations. Required keys are checked against the call sheet before sending.", {
|
|
194
|
+
...shared,
|
|
195
|
+
body: z.any().optional().describe("JSON body for POST/PUT/PATCH/DELETE (keys from the call sheet)"),
|
|
196
|
+
dry_run: z.boolean().optional().describe("Default true for writes: describe, don't send"),
|
|
197
|
+
}, (args) => handle(() => call(args, false)));
|
|
198
|
+
}
|
|
@@ -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:
|
|
47
|
-
|
|
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 (
|
|
51
|
-
appointment_address_id: z.string().describe("Address/location id (
|
|
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 (
|
|
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
|
}
|
package/dist/tools/apps-extra.js
CHANGED
|
@@ -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
|
}
|
package/dist/tools/apps.js
CHANGED
|
@@ -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
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { withCode } from "../builder/element-schema.js";
|
|
2
3
|
import { resolvePreviewUrl, draftPreviewUrl } from "../config.js";
|
|
3
4
|
import { captureScreenshot, resolveMicrolinkKey, resolveScreenshotProxyBase } from "../persistence/screenshot-client.js";
|
|
4
5
|
import { validatePage, missingBreakpoints } from "../builder/page.js";
|
|
@@ -22,7 +23,8 @@ export async function preflightSite(api) {
|
|
|
22
23
|
// write (missing/duplicate id, native-first volume…) already publishes today, so it only warns.
|
|
23
24
|
const judge = (name, src, v) => {
|
|
24
25
|
const shape = checkShape(src);
|
|
25
|
-
|
|
26
|
+
// validatePage tags shape errors "[SHAPE] …"; compare in that form.
|
|
27
|
+
const crash = shape.errors.filter((e) => !shape.editorOnly.includes(e)).map((e) => withCode("SHAPE", e)); // the live site blanks
|
|
26
28
|
const fatal = (v.errors || []).filter((e) => crash.includes(e));
|
|
27
29
|
const rest = (v.errors || []).filter((e) => !crash.includes(e));
|
|
28
30
|
errors.push(...fatal.slice(0, 10).map((e) => `${name}: ${e}`));
|
package/dist/tools/builder.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { elementSchema, suggestType, valueRules } from "../builder/element-schema.js";
|
|
2
3
|
import { z } from "zod";
|
|
3
4
|
import { BUILD_GUIDE } from "../builder/guide.js";
|
|
4
5
|
import { PAGE_SCHEMA } from "../builder/page-schema.js";
|
|
@@ -173,9 +174,17 @@ export function registerBuilderTools(server, api, handle) {
|
|
|
173
174
|
server.tool("get_build_guide", "Get the BuilderX page authoring guide: page shape, the grid layout model, styling, breakpoints, forms/data, and the build workflow. Read this before building or heavily editing a page.", {}, () => handle(async () => ({ guide: BUILD_GUIDE })));
|
|
174
175
|
server.tool("get_page_schema", "Get the authoritative JSON Schema (Draft 2020-12) for a page source `{ sections: [...] }` — the structural contract for every node (id/type/specials/runtime{style,config}/children/events/bindings) in the CSS-grid model. Use it as the shape to emit; validate_page enforces the semantic rules.", {}, () => handle(async () => PAGE_SCHEMA));
|
|
175
176
|
server.tool("list_elements", "List all BuilderX element/component types you can place on a page, grouped by category with a one-line summary and whether each is a container.", {}, () => handle(async () => listElements()));
|
|
176
|
-
server.tool("get_element", "Get the full detail of an element type: category, container flag, summary, an ATTRIBUTES reference (the meaningful specials/config keys + their purpose
|
|
177
|
+
server.tool("get_element", "Get the full detail of an element type: category, container flag, summary, an ATTRIBUTES reference (the meaningful specials/config keys + their purpose, events, and dataset binding targets), VALUE_RULES (per key: allowed values `one of …` that validate_page enforces, values `seen` on real pages, and non-string value types), PARENTS when it must sit inside a given container, and a live skeleton node (the authoritative default shape) you can copy and edit. Read this before authoring/editing an element so you set the right keys.", {
|
|
177
178
|
type: z.string().describe("Element type, e.g. 'text', 'button', 'grid-product'"),
|
|
178
|
-
}, ({ type }) => handle(async () =>
|
|
179
|
+
}, ({ type }) => handle(async () => {
|
|
180
|
+
const el = getElement(type);
|
|
181
|
+
if (el.error) {
|
|
182
|
+
const guess = suggestType(type);
|
|
183
|
+
return guess ? { ...el, did_you_mean: guess } : el;
|
|
184
|
+
}
|
|
185
|
+
const parents = elementSchema(type)?.parents;
|
|
186
|
+
return { ...el, ...(parents ? { parents } : {}), value_rules: valueRules(type) };
|
|
187
|
+
}));
|
|
179
188
|
server.tool("list_events", "List every interaction EVENT you can attach to a node: the triggers (eventName: click/hover/success/submit/…) and the actions (open_page, scroll_to, toggle, open_popup, add_to_cart, buy_now, phone_call, open_link, …) with the exact extra fields each action needs. Attach via new_element/new_section opts.events (ids are auto-minted, e.g. opts.events=[{ action:'add_to_cart', open_page:'cart' }]).", {}, () => handle(async () => describeEventsCatalog()));
|
|
180
189
|
server.tool("list_bindings", "List every dynamic-data BINDING target: the datasets (product, cart_item, order, order_item, post, category, customer, customer_address, …) and their exact field names ('product::product_price', …), which page type each needs (store/member/blog), and how repeater children (grid-product, cart-items, post-list) bind per-item. Attach via new_element opts.bindings (ids auto-minted, e.g. opts.bindings=[{ target:'product::product_price' }]).", {}, () => handle(async () => describeBindingsCatalog()));
|
|
181
190
|
server.tool("new_element", "Build a single structurally-valid element node from the real builder factory. Returns the node — edit its specials/style, then place it in a section's children.", {
|
|
@@ -207,7 +216,7 @@ Example children: [{ "type":"container", "children":[{"type":"image","opts":{...
|
|
|
207
216
|
containerOpts: container_opts || {},
|
|
208
217
|
})));
|
|
209
218
|
server.tool("new_page_skeleton", "Return an empty but valid page source: { sections: [] }. Add sections built with new_section, then save with build_page.", {}, () => handle(async () => newPageSkeleton()));
|
|
210
|
-
server.tool("validate_page", "Validate a page source ({ sections: [...] }).
|
|
219
|
+
server.tool("validate_page", "Validate a page source ({ sections: [...] }) against every element's schema. Each message reads `[CODE] #id (type) where: problem → fix`. errors block saving (duplicate/missing ids, renderer-crash shapes…); warnings render wrong (UNKNOWN_KEY invented/misspelled key, STYLE_KEY not a CSS property, TYPE_MISMATCH, BAD_VALUE outside the allowed values, BAD_PARENT, OUTSIDE_FORM, FIELD_NAME, EVENT/BINDING problems…). Repeated warnings are collapsed per code; summary.by_code counts all. Always run this before build_page and fix by code.", {
|
|
211
220
|
source: z.any().describe("Page source object or JSON string"),
|
|
212
221
|
}, ({ source }) => handle(async () => {
|
|
213
222
|
const parsed = parseSource(source);
|
package/dist/tools/cms-files.js
CHANGED
|
@@ -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 (
|
|
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.
|
|
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])));
|