@typeroll/mcp-server 0.45.121 → 0.45.123

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,251 @@
1
+ // Menus: named trees of links a site keeps once and shows in its header,
2
+ // footer and mobile menu. Saved directly (revision checked, no working copy);
3
+ // they reach the live site with the next publication.
4
+ import { z } from 'zod';
5
+ import { ApiError } from '../client.js';
6
+ import { fail, ok, versionParam } from './helpers.js';
7
+ function v(version) {
8
+ return version ? { version } : undefined;
9
+ }
10
+ const MENU_MODEL = 'A menu has an id, a name, optional `locations` and a tree of `items` at most 3 levels deep (top level, submenu, and a third level that makes a wide submenu in columns). ' +
11
+ 'Item types: `page` (page_id; links by page id, so the label and address follow renames and moves, and an unpublished or deleted page drops out with a warning; `label` overrides the title), ' +
12
+ '`url` (href and label; an external address, a path or an #anchor), `children` (page_id; lists that page\'s published child pages automatically: with a label they form a submenu under it, without one they sit in place) ' +
13
+ 'and `heading` (label only, no link; a column title in a wide submenu). Any item may set `description` (a short line in submenus), `icon` and `link_rel`. Items with `children` get a submenu. ' +
14
+ 'Locations: `primary` (header), `footer` and `mobile`, or another short lowercase name; one menu per location per site. ' +
15
+ '`auto_add_pages: true` appends new top-level published pages (other than the home page) to the end automatically. ' +
16
+ 'To show a menu, use a `core/navigation_links` block with data { source: "menu", menu: "location:primary" } (or a menu id) and optionally `submenus`: auto (dropdown in a row, accordion in a column and the mobile drawer), dropdown, accordion, expanded or none. It needs render version 15 (read_site_settings → render.version; raise it with tr-upgrade-rendering).';
17
+ // Nested items have the same shape; they stay untyped here so the schema is
18
+ // not recursive (the server validates the whole tree and reports each path).
19
+ const itemShape = z.object({
20
+ id: z.string().optional().describe('Unique in the menu (lowercase letters, digits, - and _). Omit for a new item to get one.'),
21
+ type: z.enum(['page', 'url', 'children', 'heading']),
22
+ page_id: z.string().optional().describe('page and children items: the page id (not its slug or URL).'),
23
+ href: z.string().optional().describe('url items: the address, path or #anchor.'),
24
+ label: z.string().optional().describe('Required for url and heading; overrides the page title for page items.'),
25
+ description: z.string().optional(),
26
+ icon: z.string().optional(),
27
+ link_rel: z.string().optional().describe('For example "nofollow sponsored".'),
28
+ children: z.array(z.record(z.string(), z.unknown())).optional().describe('Submenu items of the same shape. At most 3 levels in all.'),
29
+ }).passthrough();
30
+ /** A 400 from a menu save carries every problem with its path; show them plainly. */
31
+ function menuFailure(error) {
32
+ if (error instanceof ApiError && error.status === 400) {
33
+ const errors = error.body?.details?.errors;
34
+ if (Array.isArray(errors) && errors.length) {
35
+ return {
36
+ content: [{
37
+ type: 'text',
38
+ text: JSON.stringify({
39
+ error: 'The menu was not saved: it is not valid.',
40
+ status: 400,
41
+ errors,
42
+ hint: 'Fix each path (for example items[1].children[0].href) and send the whole menu again.',
43
+ }, null, 2),
44
+ }],
45
+ isError: true,
46
+ };
47
+ }
48
+ }
49
+ if (error instanceof ApiError && error.status === 409) {
50
+ return {
51
+ content: [{
52
+ type: 'text',
53
+ text: JSON.stringify({
54
+ error: error.message,
55
+ status: 409,
56
+ hint: 'Either someone saved the menu after you read it (read_menu again and reapply your change with the new updated_at), or a location you set is already filled by another menu (remove it there first).',
57
+ }, null, 2),
58
+ }],
59
+ isError: true,
60
+ };
61
+ }
62
+ return fail(error);
63
+ }
64
+ function itemIds(items, out = new Set()) {
65
+ for (const item of items) {
66
+ if (typeof item.id === 'string' && item.id)
67
+ out.add(item.id);
68
+ if (Array.isArray(item.children))
69
+ itemIds(item.children, out);
70
+ }
71
+ return out;
72
+ }
73
+ /** Path of nesting levels to the item with `id`: the item list it sits in and its depth. */
74
+ function findItem(items, id, depth = 1) {
75
+ for (const item of items) {
76
+ if (item.id === id)
77
+ return { item, depth };
78
+ const found = Array.isArray(item.children) ? findItem(item.children, id, depth + 1) : null;
79
+ if (found)
80
+ return found;
81
+ }
82
+ return null;
83
+ }
84
+ function newItemId(item, taken) {
85
+ const source = String(item.label ?? item.page_id ?? item.href ?? item.type ?? 'item');
86
+ const base = source.toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '')
87
+ .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48).replace(/-+$/, '') || 'item';
88
+ let id = /^[a-z0-9]/.test(base) ? base : `item-${base}`;
89
+ for (let n = 2; taken.has(id); n++)
90
+ id = `${base}-${n}`;
91
+ return id;
92
+ }
93
+ const menuBody = (menu) => ({
94
+ name: menu.name,
95
+ ...(menu.locations !== undefined ? { locations: menu.locations } : {}),
96
+ ...(menu.auto_add_pages !== undefined ? { auto_add_pages: menu.auto_add_pages } : {}),
97
+ items: menu.items,
98
+ });
99
+ export const menuTools = [
100
+ {
101
+ name: 'list_menus',
102
+ description: 'List the site\'s menus (WordPress-style menus with locations): each with its id, name, locations, auto_add_pages, items and updated_at. ' +
103
+ 'Check this before building a header or footer: a new site starts with a `primary` menu (location primary, Home, auto_add_pages on) and a `footer` menu. ' + MENU_MODEL,
104
+ inputSchema: { version: versionParam },
105
+ handler: async (args, { client, siteId }) => {
106
+ try {
107
+ return ok(await client.get(siteId, 'menus', v(args.version)));
108
+ }
109
+ catch (error) {
110
+ return fail(error);
111
+ }
112
+ },
113
+ },
114
+ {
115
+ name: 'read_menu',
116
+ description: 'Read one menu with its whole item tree and updated_at. Pass that updated_at as expected_updated_at to update_menu so a save made in between is not overwritten.',
117
+ inputSchema: { menu_id: z.string(), version: versionParam },
118
+ handler: async (args, { client, siteId }) => {
119
+ try {
120
+ return ok(await client.get(siteId, `menus/${encodeURIComponent(args.menu_id)}`, v(args.version)));
121
+ }
122
+ catch (error) {
123
+ return fail(error);
124
+ }
125
+ },
126
+ },
127
+ {
128
+ name: 'update_menu',
129
+ description: 'Create a menu or replace a whole menu (name, locations, auto_add_pages and the full item tree). ' +
130
+ 'To change an existing menu: read_menu, edit the tree, and send it back with expected_updated_at set to the updated_at you read; a save by someone else in between returns 409. Without menu_id, or with a menu_id that does not exist yet, the menu is created. ' +
131
+ 'Every save is validated as a whole and keeps the previous menu as a revision; an invalid menu returns `errors` with the path of each problem (for example items[0].href). ' +
132
+ 'Link pages with type "page" and their page_id (from list_pages), not with url items, so renames follow; use a "children" item for an automatic submenu of a page\'s child pages. ' +
133
+ 'Menus are saved directly (no working copy) and reach the live site with the next publication. To add one item, add_menu_item is simpler. ' + MENU_MODEL,
134
+ inputSchema: {
135
+ menu_id: z.string().optional().describe('The menu to replace or create. Omit to create a menu whose id is derived from the name.'),
136
+ name: z.string().describe('Shown in the portal, e.g. "Main menu".'),
137
+ locations: z.array(z.string()).optional().describe('primary, footer, mobile or another short lowercase name. Omit to keep none; [] clears them.'),
138
+ auto_add_pages: z.boolean().optional().describe('Append new top-level published pages automatically.'),
139
+ items: z.array(itemShape).describe('The whole item tree, at most 3 levels deep and 200 items.'),
140
+ expected_updated_at: z.string().optional().describe('The updated_at from read_menu or list_menus. Required to replace an existing menu.'),
141
+ version: versionParam,
142
+ },
143
+ handler: async (args, { client, siteId }) => {
144
+ const body = menuBody(args);
145
+ try {
146
+ if (args.menu_id && args.expected_updated_at !== undefined) {
147
+ return ok(await client.put(siteId, `menus/${encodeURIComponent(args.menu_id)}`, { ...body, expected_updated_at: args.expected_updated_at }, v(args.version)));
148
+ }
149
+ if (args.menu_id) {
150
+ let exists = true;
151
+ try {
152
+ await client.get(siteId, `menus/${encodeURIComponent(args.menu_id)}`, v(args.version));
153
+ }
154
+ catch (error) {
155
+ if (error instanceof ApiError && error.status === 404)
156
+ exists = false;
157
+ else
158
+ throw error;
159
+ }
160
+ if (exists) {
161
+ return {
162
+ content: [{ type: 'text', text: JSON.stringify({ error: `The menu ${args.menu_id} already exists. Read it with read_menu and pass its updated_at as expected_updated_at to replace it.`, status: 409 }, null, 2) }],
163
+ isError: true,
164
+ };
165
+ }
166
+ }
167
+ return ok(await client.post(siteId, 'menus', { ...(args.menu_id ? { id: args.menu_id } : {}), ...body }, v(args.version)));
168
+ }
169
+ catch (error) {
170
+ return menuFailure(error);
171
+ }
172
+ },
173
+ },
174
+ {
175
+ name: 'add_menu_item',
176
+ description: 'Append one item to a menu, at the top level or under a parent item (parent_item_id), and save it. Reads the menu and saves it with its updated_at, so a concurrent save is refused with 409 rather than lost. ' +
177
+ 'Example: { menu_id: "primary", item: { type: "page", page_id: "about" } } or a submenu entry { menu_id: "primary", parent_item_id: "services", item: { type: "url", href: "https://shop.example.com", label: "Shop" } }. ' +
178
+ 'Use type "page" with a page_id (it follows renames), "children" for the page\'s child pages as an automatic submenu, "url" for other addresses and "heading" for a column title. Menus are at most 3 levels deep. ' +
179
+ 'Returns the saved menu and the new item\'s id. To restructure or remove items, use read_menu and update_menu.',
180
+ inputSchema: {
181
+ menu_id: z.string(),
182
+ item: itemShape,
183
+ parent_item_id: z.string().optional().describe('Put the item in this item\'s submenu (as its last child). Omit for the top level.'),
184
+ position: z.number().int().min(0).optional().describe('Index to insert at among its siblings. Default: at the end.'),
185
+ version: versionParam,
186
+ },
187
+ handler: async (args, { client, siteId }) => {
188
+ try {
189
+ const path = `menus/${encodeURIComponent(args.menu_id)}`;
190
+ const read = await client.get(siteId, path, v(args.version));
191
+ const menu = read?.menu;
192
+ if (!menu || !Array.isArray(menu.items))
193
+ throw new Error(`The menu ${args.menu_id} could not be read`);
194
+ const items = structuredClone(menu.items);
195
+ const item = { ...args.item };
196
+ const taken = itemIds(items);
197
+ if (typeof item.id === 'string' && item.id) {
198
+ if (taken.has(item.id))
199
+ return { content: [{ type: 'text', text: JSON.stringify({ error: `An item with the id ${item.id} is already in the menu. Choose another id or omit it.`, status: 400 }, null, 2) }], isError: true };
200
+ }
201
+ else
202
+ item.id = newItemId(item, taken);
203
+ let siblings = items;
204
+ if (args.parent_item_id) {
205
+ const parent = findItem(items, args.parent_item_id);
206
+ if (!parent)
207
+ return { content: [{ type: 'text', text: JSON.stringify({ error: `No item ${args.parent_item_id} in the menu ${args.menu_id}. read_menu lists the item ids.`, status: 404 }, null, 2) }], isError: true };
208
+ if (parent.depth >= 3)
209
+ return { content: [{ type: 'text', text: JSON.stringify({ error: 'Menus are at most 3 levels deep; the parent is already on the third level.', status: 400 }, null, 2) }], isError: true };
210
+ if (parent.item.type === 'children')
211
+ return { content: [{ type: 'text', text: JSON.stringify({ error: 'A "children" item lists its pages by itself and cannot hold items. Choose another parent.', status: 400 }, null, 2) }], isError: true };
212
+ parent.item.children = Array.isArray(parent.item.children) ? parent.item.children : [];
213
+ siblings = parent.item.children;
214
+ }
215
+ const at = args.position === undefined ? siblings.length : Math.min(args.position, siblings.length);
216
+ siblings.splice(at, 0, item);
217
+ const saved = await client.put(siteId, path, { ...menuBody({ ...menu, items }), expected_updated_at: menu.updated_at ?? '' }, v(args.version));
218
+ return ok({ item_id: item.id, ...saved });
219
+ }
220
+ catch (error) {
221
+ return menuFailure(error);
222
+ }
223
+ },
224
+ },
225
+ {
226
+ name: 'delete_menu',
227
+ description: 'Delete a menu. A navigation block that shows it (by id or by its location) then renders an empty list until another menu fills the location. Check where it is shown first with find_menu_usage. Takes effect at the next publication.',
228
+ inputSchema: { menu_id: z.string(), version: versionParam },
229
+ handler: async (args, { client, siteId }) => {
230
+ try {
231
+ return ok(await client.del(siteId, `menus/${encodeURIComponent(args.menu_id)}`, v(args.version)));
232
+ }
233
+ catch (error) {
234
+ return fail(error);
235
+ }
236
+ },
237
+ },
238
+ {
239
+ name: 'find_menu_usage',
240
+ description: 'Where a menu is shown: the global blocks (header, footer, others), pages and page templates whose core/navigation_links block has source "menu" and names this menu by id or by one of its locations (location:primary), saved or in a draft. Read it before deleting a menu or moving its location.',
241
+ inputSchema: { menu_id: z.string(), version: versionParam },
242
+ handler: async (args, { client, siteId }) => {
243
+ try {
244
+ return ok(await client.get(siteId, `menus/${encodeURIComponent(args.menu_id)}/usage`, v(args.version)));
245
+ }
246
+ catch (error) {
247
+ return fail(error);
248
+ }
249
+ },
250
+ },
251
+ ];
@@ -0,0 +1,66 @@
1
+ // Typeroll packages (.typeroll): export part of a site, or a whole site, as
2
+ // one portable file, and inspect or import a package into a site. Each tool
3
+ // maps onto /api/v1/sites/{siteId}/packages/*.
4
+ import { z } from 'zod';
5
+ import { ok, versionParam, withErrorBoundary } from './helpers.js';
6
+ const v = (version) => (version ? { version } : undefined);
7
+ const ids = z.union([z.literal('all'), z.array(z.string().min(1).max(100)).max(500)]);
8
+ const FORMAT = 'A package belongs to no organization: it carries no organization or site ids, and its media files (and font files the author may pass on) travel inside it, so anyone can import it into their own site, for example a template pack bought from someone else. ' +
9
+ 'Media references in content become `typeroll-media:<id>` tokens and app blocks are named by their app, not the site\'s installation.';
10
+ const STYLES = 'Styles are never mapped to the site\'s "nearest" styles: every style the imported content uses is created on the site. A style is reused only when the site has one with the same id and the same definition; a differing one is created under a new id (hero-2, named "Hero (imported)") and the imported content is rewritten to it. Block types, templates, global blocks, menus and pages that collide get new ids the same way.';
11
+ const DESIGN = 'options.design: "content" (default: the blocks and the styles they use), "styles" (also the package\'s other class styles) or "full" (also the element styles body/h1–h6/link replacing the site\'s, colours, typography, scales, content widths and font roles; requires admin). ' +
12
+ 'Font files in the package are added to the Fonts library only with options.font_licence_confirmed: true, which means the user confirmed the font licence allows use on this site; ask the user, never assume it. options.fonts: false leaves the fonts out. Adobe Fonts, Bunny Fonts and Fontshare kits never transfer: only the family names, with a warning.';
13
+ const source = {
14
+ data_base64: z.string().optional().describe('The .typeroll file, base64-encoded (at most 32 MB). Send this or source_url.'),
15
+ source_url: z.string().optional().describe('An https:// address to download the package from (up to 200 MB), instead of data_base64.'),
16
+ };
17
+ const options = z.object({
18
+ design: z.enum(['content', 'styles', 'full']).optional(),
19
+ fonts: z.boolean().optional().describe('With design "full": import the package\'s font roles and font files (default true).'),
20
+ only: z.array(z.string()).max(5000).optional().describe('Only these entries, e.g. ["block_templates.hero", "menus.main"]; all when absent.'),
21
+ font_licence_confirmed: z.boolean().optional().describe('true: the user confirmed the licence of the package\'s font files allows use on this site.'),
22
+ }).strict();
23
+ const body = (args) => Object.fromEntries(Object.entries(args).filter(([key, value]) => key !== 'version' && value !== undefined));
24
+ export const packageTools = [
25
+ {
26
+ name: 'export_package',
27
+ description: 'Export part of the site, or the whole site, as a Typeroll package (.typeroll) and get a signed download address valid for one hour (download_url, filename, bytes, sha256, expires_at, warnings). ' + FORMAT + ' ' +
28
+ 'selection.kind "collection" holds what you choose: block_templates, page_templates, global_blocks (free global blocks) and block_types as id lists or "all", styles "used" (default) or "all", design (colours, typography, scales, content widths, font roles and element styles), menus, site_fields (definitions) and demo_media (media ids to mark as demo content the buyer replaces). Global blocks, block types and styles the content uses come along by themselves; links to this site\'s pages become plain addresses. ' +
29
+ 'kind "site" holds everything (pages, header and footer, menus, site fields with values, every style and the design) and requires admin. ' +
30
+ 'fonts: { families, redistributable_confirmed: true } adds uploaded font files only when the user confirmed their licence allows passing them on; catalog families need no files. Requires write permission.',
31
+ inputSchema: {
32
+ selection: z.object({
33
+ kind: z.enum(['collection', 'site']),
34
+ block_templates: ids.optional(), page_templates: ids.optional(), global_blocks: ids.optional(), block_types: ids.optional(), menus: ids.optional(),
35
+ styles: z.enum(['used', 'all']).optional(), design: z.boolean().optional(), site_fields: z.boolean().optional(),
36
+ fonts: z.object({ families: z.array(z.string()).max(60), redistributable_confirmed: z.literal(true) }).strict().optional(),
37
+ demo_media: z.array(z.string()).max(2000).optional(),
38
+ }).strict(),
39
+ meta: z.object({
40
+ id: z.string().describe('A slug for the package, e.g. "acme-restaurant-sections".'),
41
+ name: z.string(), version: z.string().describe('e.g. "1.0.0"'),
42
+ description: z.string().optional(),
43
+ author: z.union([z.string(), z.object({ name: z.string(), url: z.string().optional() }).strict()]).optional(),
44
+ licence: z.union([z.string(), z.object({ name: z.string(), url: z.string().optional() }).strict()]).optional(),
45
+ languages: z.array(z.string()).max(20).optional(),
46
+ }).strict(),
47
+ version: versionParam,
48
+ },
49
+ handler: withErrorBoundary(async (args, { client, siteId }) => ok(await client.post(siteId, 'packages/export', body(args), v(args.version)))),
50
+ },
51
+ {
52
+ name: 'inspect_package',
53
+ description: 'Read a Typeroll package and show what importing it into the site would do, without changing anything: the package (name, version, author, licence, counts), its signature (verified with the publisher when a trusted publisher signed it; unsigned or unknown otherwise), the plan (per style, block type, template, global block, menu, page and media file: create, reuse, rename or replace, with the id maps), warnings, errors that would stop the import, and needs (admin, font_licence). ' +
54
+ STYLES + ' ' + DESIGN + ' Run it before import_package and show the user the plan.',
55
+ inputSchema: { ...source, options: options.optional(), version: versionParam },
56
+ handler: withErrorBoundary(async (args, { client, siteId }) => ok(await client.post(siteId, 'packages/inspect', body(args), v(args.version)))),
57
+ },
58
+ {
59
+ name: 'import_package',
60
+ description: 'Import a Typeroll package into the site: media first (into the Media library, reusing files with the same bytes; demo files are marked for replacement before publication), then fonts, block types, design and styles, global blocks, block templates (with where they came from), page templates, menus, site fields and, for a site package, pages. Returns a report of what was created, reused, renamed and replaced. ' +
61
+ STYLES + ' ' + DESIGN + ' ' +
62
+ 'Requires write permission; admin for design "full" or when the import adds fonts or settings pages. The whole plan is checked before anything is written; a write that fails part-way answers package_import_partial with the report of what was written.',
63
+ inputSchema: { ...source, options, version: versionParam },
64
+ handler: withErrorBoundary(async (args, { client, siteId }) => ok(await client.post(siteId, 'packages/import', body(args), v(args.version)))),
65
+ },
66
+ ];
@@ -49,7 +49,7 @@ export const reusableBlockTools = [
49
49
  },
50
50
  {
51
51
  name: 'save_block_template',
52
- description: 'Save a block template: a section starter that editors and agents insert as an independent copy. Pass `from: { page_id, block_id }` to save a block from a page (its draft), or `blocks`. Prefer templates that use named styles (style_id, part_styles) over one-off values, so copies stay consistent. Templates belong to the site, not a branch.',
52
+ description: 'Save a block template: a section starter that editors and agents insert as an independent copy. Pass `from: { page_id, block_id }` to save a block from a page (its draft), or `blocks`. Prefer templates that use named styles (style_id, part_styles) over one-off values, so copies stay consistent. The answer\'s design_findings lists hard-coded colours and font families (not blocking) with the palette or font role to use instead; `replacement` gives the exact field change when one role matches, which update_block_template applies by sending the changed blocks. Templates belong to the site, not a branch.',
53
53
  inputSchema: {
54
54
  name: z.string(),
55
55
  description: z.string().optional().describe('When to use it.'),
@@ -61,7 +61,7 @@ export const reusableBlockTools = [
61
61
  },
62
62
  {
63
63
  name: 'update_block_template',
64
- description: 'Rename a block template, change its description, or replace its blocks. Pages that already inserted it do not change.',
64
+ description: 'Rename a block template, change its description, or replace its blocks. Pages that already inserted it do not change. Answers with design_findings, as save_block_template.',
65
65
  inputSchema: {
66
66
  template_id: z.string(),
67
67
  name: z.string().optional(),
@@ -13,7 +13,7 @@ function v(version) {
13
13
  export const settingsTools = [
14
14
  {
15
15
  name: 'lint_design_tokens',
16
- description: 'Read-only design audit of saved Pages, partials, page templates, custom block types, styles and custom CSS in the selected Version. Lists hardcoded colours, typography and spacing with exact paths and token suggestions. exact_replacements is a dry-run plan for unambiguous direct block hex matches; never apply ambiguous roles or CSS automatically. css_findings lists custom CSS that works against the theme (heavy !important use, fonts not in the theme, theme fonts loaded twice, a first-section background image set in CSS, rules on platform block classes), each with the Style, token or block setting that replaces it. Does not block launch. Unsaved working copies are excluded.',
16
+ description: 'Read-only design audit of saved Pages, partials, page templates, block templates, custom block types, styles and custom CSS in the selected Version. Lists hardcoded colours, typography and spacing with exact paths and token suggestions. exact_replacements is a dry-run plan for unambiguous direct block hex matches; never apply ambiguous roles or CSS automatically. css_findings lists custom CSS that works against the theme (heavy !important use, fonts not in the theme, theme fonts loaded twice, a first-section background image set in CSS, rules on platform block classes), each with the Style, token or block setting that replaces it. Does not block launch. Unsaved working copies are excluded.',
17
17
  inputSchema: { version: versionParam },
18
18
  handler: withErrorBoundary(async (args, { client, siteId }) => ok(await client.get(siteId, 'design-token-audit', v(args.version)))),
19
19
  },
@@ -67,6 +67,7 @@ export const settingsTools = [
67
67
  robots_txt: z.string().optional(),
68
68
  ai_crawler_policy: z.enum(['allow_all', 'no_training', 'block_all']).nullable().optional().describe('AI crawler preference, written as Cloudflare-compatible Content Signals in robots.txt and the Content-Signal response header. `allow_all` (default, writes nothing); `no_training` (search=yes, ai-input=yes, ai-train=no, and Disallow groups for training-only crawlers such as GPTBot, ClaudeBot and Google-Extended); `block_all` (also disallows AI search and user agents such as OAI-SearchBot, ChatGPT-User and PerplexityBot). Googlebot, Bingbot and Applebot are never blocked. An explicit group for an agent in robots_txt wins. A Cloudflare zone AI bot policy is enforced at the edge and can override this; `null` resets to the default.'),
69
69
  header_behavior: z.enum(['static', 'sticky', 'reveal_on_scroll_up']).nullable().optional().describe('Site header while scrolling. `static` (default, writes nothing) scrolls with the page; `sticky` stays at the top; `reveal_on_scroll_up` hides while scrolling down and returns as a compact header on the first scroll up, with the navigation menu toggle at every width. The compact state carries `data-header-compact` for site CSS. null clears.'),
70
+ time_zone: z.string().max(64).nullable().optional().describe('IANA time zone that decides which day and hour it is at the business, for "today", "open now" and dated snippets; times typed into opening hours are never converted. Every site has one: new sites get the usual zone for their language (sv → Europe/Stockholm, nb → Europe/Oslo, da → Europe/Copenhagen, fi → Europe/Helsinki, en-GB → Europe/London; otherwise Europe/Stockholm). Set it when the business is elsewhere. null resets it to the zone of its language.'),
70
71
  date_format: z.string().max(40).nullable().optional().describe('How page and card dates read (render version 14), in the page language: `medium` (default, "12 okt. 2026"), `long` ("12 oktober 2026"), `numeric` (the language\'s numeric order) or `iso` ("2026-10-12"); or a pattern of YYYY, MMMM, MMM, MM, M, DD and D such as "D MMMM YYYY". A Page date block with its own format keeps it. null restores the default.'),
71
72
  motion: z.enum(['full', 'reduced']).nullable().optional().describe('Motion for every visitor (render version 14). `full` (default) plays what each block asks for: entrance animations, carousel autoplay, background videos, moving logo rows and scroll films. `reduced` turns all of them off for everyone; blocks show their still image or content. Visitors whose device asks for reduced motion always get the reduced version. null resets to full.'),
72
73
  content_widths: z.object({ narrow: z.number().int().min(480).max(1200).optional(), normal: z.number().int().min(720).max(1600).optional(), wide: z.number().int().min(960).max(2400).optional() }).strict().nullable().optional().describe('The shared content widths in px (render version 14): defaults narrow 672, normal 1040, wide 1280. Sections, containers, heroes, feature rows and calls to action use them, so blocks of the same width line up. Keep narrow ≤ normal ≤ wide; null restores the defaults.'),
@@ -151,6 +152,17 @@ export const settingsTools = [
151
152
  }).optional(),
152
153
  }).optional().describe('Banner wording for this language. Without text or labels the banner uses the built-in wording in this language; scripts and enabled stay site-wide.'),
153
154
  })).nullable().optional().describe('One site, several languages: each section is a language whose pages (Page.language) live under home_path. Pages in a section get its home link in breadcrumbs, a 404 page at <home_path>404.html, and its tagline, fallback description and banner wording. Pages in the site language keep the top-level settings. Replaces the whole list; null or [] clears it. Use template/show_if on page.language in the header and footer for per-language menus.'),
155
+ handover: z.object({
156
+ lock_structure: z.boolean().optional().describe('Lock the structure for people without design rights (editors, clients with a shared site): they change text and images but cannot add, remove, move, duplicate or retype blocks, apply a page template or create or delete pages; those writes answer 403 structure_locked. Administrators and builders are never locked.'),
157
+ start_page: z.string().max(128).optional().describe('Page id the start view links to first; must be a page of the site.'),
158
+ checklist: z.array(z.object({
159
+ id: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),
160
+ label: z.string().min(1).max(200),
161
+ done: z.boolean().optional(),
162
+ href: z.string().max(501).optional().describe('A portal path starting with /, e.g. /app/sites/<siteId>/media.'),
163
+ }).strict()).max(40).optional(),
164
+ handed_over_at: z.string().optional().describe('ISO date when the site was handed over; absent while it is being built.'),
165
+ }).strict().nullable().optional().describe('Handing the site over to its editors: a checklist, the start page and an optional structure lock. Replaces the whole object (not merged); null removes it. Needs design rights (an administrator or builder).'),
154
166
  },
155
167
  handler: withErrorBoundary(async (args, { client, siteId }) => {
156
168
  const { version, ...body } = args;
@@ -0,0 +1,138 @@
1
+ // Site fields: settings pages a builder defines and the client fills in, like
2
+ // WordPress options pages. One document per version with the definitions
3
+ // (`groups`) and the values; saved directly (revision checked, no working
4
+ // copy) and live with the next publication.
5
+ import { z } from 'zod';
6
+ import { ApiError } from '../client.js';
7
+ import { fail, ok, versionParam } from './helpers.js';
8
+ function v(version) {
9
+ return version ? { version } : undefined;
10
+ }
11
+ const OPENING_HOURS_SHAPE = JSON.stringify({
12
+ name: 'opening_hours', label: 'Opening hours', type: 'object', presentation: 'opening_hours',
13
+ fields: [
14
+ { name: 'days', label: 'Week', type: 'array', min_items: 7, max_items: 7, item_label: 'day', fields: [
15
+ { name: 'day', label: 'Day', type: 'select', options: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] },
16
+ { name: 'closed', label: 'Closed', type: 'boolean' },
17
+ { name: 'opens', label: 'Opens', type: 'text', placeholder: '09:00' },
18
+ { name: 'closes', label: 'Closes', type: 'text', placeholder: '09:00' },
19
+ ] },
20
+ { name: 'exceptions', label: 'Exceptions', type: 'array', max_items: 60, item_label: 'date', fields: [
21
+ { name: 'date', label: 'Date', type: 'date', required: true },
22
+ { name: 'closed', label: 'Closed', type: 'boolean' },
23
+ { name: 'opens', label: 'Opens', type: 'text' },
24
+ { name: 'closes', label: 'Closes', type: 'text' },
25
+ { name: 'note', label: 'Note', type: 'text' },
26
+ ] },
27
+ ],
28
+ });
29
+ const SITE_FIELDS_MODEL = 'Site fields are settings pages for the client: a builder defines groups of typed fields once, and the client (an editor) fills in the values without touching pages or design. ' +
30
+ 'A group is { id, label, description?, access: "editor" | "admin", fields }. access "editor" (the default) lets anyone who edits content change the values; "admin" only site administrators. Definitions are always site admin. ' +
31
+ 'Fields use the content type field model: { name, type, label, required?, help?, placeholder?, default? } with type text, textarea, richtext, boolean (a checkbox, e.g. show_booking), number (min, max), select or multiselect (options), date (2026-11-07), datetime, image, url, email, page_ref, ' +
32
+ 'array (a list: fields, item_label, min_items, max_items) or object (a group of fields). Lists and groups nest at most 3 levels. Field names are lowercase_with_underscores and unique across the whole site. ' +
33
+ 'Opening hours: an object field with presentation "opening_hours" and exactly this shape (a 7-day week plus dated exceptions such as holidays): ' + OPENING_HOURS_SHAPE + ' ' +
34
+ 'Its value: { days: [{ day: "monday", opens: "09:00", closes: "17:00" }, …, { day: "sunday", closed: true }], exceptions: [{ date: "2026-12-24", closed: true, note: "Christmas Eve" }] }. ' +
35
+ 'Using values on the site: `{{site.fields.name}}` (and `{{#each site.fields.list}}…{{/each}}`) in page templates and block text; the `core/site_field` block shows one value with data { field: "name", format } where format is text, date, number, list, opening_hours_today, opening_hours_week, next_opening or open_now; ' +
36
+ 'and the `core/show_if` block shows its children only when its condition holds, e.g. { condition: "site.fields.show_booking" } around a booking calendar. Values reach the live site with the next publication, ' +
37
+ 'except for a top-level field defined with `live: true` (any type, but no list inside a list; opening hours qualify): its value is also published as a live file when saved, and the `core/site_field` block then shows the newest value without a publication (see list_snippets).';
38
+ /** A refused save carries every problem with its path; show them plainly. */
39
+ function siteFieldsFailure(error, what) {
40
+ if (error instanceof ApiError && error.status === 400) {
41
+ const errors = error.body?.errors;
42
+ if (Array.isArray(errors) && errors.length) {
43
+ return {
44
+ content: [{
45
+ type: 'text',
46
+ text: JSON.stringify({
47
+ error: `The site field ${what} were not saved: they are not valid.`,
48
+ status: 400,
49
+ errors,
50
+ hint: what === 'definitions'
51
+ ? 'Fix each path (for example groups[0].fields[2].options) and send all groups again.'
52
+ : 'Fix each path (for example opening_hours.days[0].opens) and send those values again. read_site_fields shows the field definitions.',
53
+ }, null, 2),
54
+ }],
55
+ isError: true,
56
+ };
57
+ }
58
+ }
59
+ if (error instanceof ApiError && error.status === 409) {
60
+ return {
61
+ content: [{
62
+ type: 'text',
63
+ text: JSON.stringify({
64
+ error: error.message,
65
+ status: 409,
66
+ hint: 'Someone saved the site fields after you read them. read_site_fields again and reapply your change with the new updated_at.',
67
+ }, null, 2),
68
+ }],
69
+ isError: true,
70
+ };
71
+ }
72
+ return fail(error);
73
+ }
74
+ const expectedParam = z.string().nullable().optional()
75
+ .describe('The updated_at from read_site_fields ("" or null when it was null: nothing saved yet). A save made in between is refused with 409.');
76
+ export const siteFieldTools = [
77
+ {
78
+ name: 'read_site_fields',
79
+ description: 'Read the site fields: the settings pages (groups with their field definitions), the saved values, updated_at and editable_groups (the groups whose values you may change with your permission). ' +
80
+ 'Read this before define_site_fields or update_site_fields and pass its updated_at as expected_updated_at. ' + SITE_FIELDS_MODEL,
81
+ inputSchema: { version: versionParam },
82
+ handler: async (args, { client, siteId }) => {
83
+ try {
84
+ return ok(await client.get(siteId, 'site-fields', v(args.version)));
85
+ }
86
+ catch (error) {
87
+ return fail(error);
88
+ }
89
+ },
90
+ },
91
+ {
92
+ name: 'define_site_fields',
93
+ description: 'Replace the site\'s settings pages (all groups and their field definitions). Needs admin permission on the site. ' +
94
+ 'Send every group, including the ones you keep: a group or field left out is removed, and so is its value. Renaming a field is a removal plus an addition, so its value is lost; values that no longer fit a changed field type are dropped too (listed in dropped_values). ' +
95
+ 'Example: groups [{ id: "booking", label: "Booking", fields: [{ name: "show_booking", type: "boolean", label: "Show the booking calendar" }, { name: "delivery_days", type: "number", label: "Delivery days right now", min: 0 }] }, { id: "visit", label: "Visit us", fields: [{ name: "visiting_address", type: "textarea", label: "Visiting address", required: true }, <opening hours field> ] }]. ' +
96
+ 'Every save keeps the previous document as a revision; invalid definitions return `errors` with the path of each problem. Then fill in values with update_site_fields. ' + SITE_FIELDS_MODEL,
97
+ inputSchema: {
98
+ groups: z.array(z.object({
99
+ id: z.string().describe('Lowercase letters, digits, - and _.'),
100
+ label: z.string().describe('The settings page title the client sees.'),
101
+ description: z.string().optional(),
102
+ access: z.enum(['editor', 'admin']).optional().describe('Who may change the values. Default editor.'),
103
+ fields: z.array(z.record(z.string(), z.unknown())).describe('Field definitions: { name, type, label, ... }.'),
104
+ }).passthrough()).describe('Every settings page of the site, at most 20 with 200 fields in all.'),
105
+ expected_updated_at: expectedParam,
106
+ version: versionParam,
107
+ },
108
+ handler: async (args, { client, siteId }) => {
109
+ try {
110
+ return ok(await client.put(siteId, 'site-fields', { groups: args.groups, expected_updated_at: args.expected_updated_at }, v(args.version)));
111
+ }
112
+ catch (error) {
113
+ return siteFieldsFailure(error, 'definitions');
114
+ }
115
+ },
116
+ },
117
+ {
118
+ name: 'update_site_fields',
119
+ description: 'Change site field values: send only the fields to change, by name; others keep their values, and null removes one. ' +
120
+ 'Example: { values: { show_booking: false, delivery_days: 3, opening_hours: { days: [...7 days], exceptions: [{ date: "2026-12-24", closed: true }] } } }. ' +
121
+ 'An object or list value is replaced as a whole. Values in groups with access "admin" need admin permission; the rest need write. ' +
122
+ 'Saved directly (not a draft), with the previous values kept as a revision; live at the next publication. Invalid values return `errors` with their paths. ' +
123
+ 'For the field model and how values show on the site, see read_site_fields.',
124
+ inputSchema: {
125
+ values: z.record(z.string(), z.unknown()).describe('Field name → new value; null removes the value.'),
126
+ expected_updated_at: expectedParam,
127
+ version: versionParam,
128
+ },
129
+ handler: async (args, { client, siteId }) => {
130
+ try {
131
+ return ok(await client.patch(siteId, 'site-fields', { values: args.values, expected_updated_at: args.expected_updated_at }, v(args.version)));
132
+ }
133
+ catch (error) {
134
+ return siteFieldsFailure(error, 'values');
135
+ }
136
+ },
137
+ },
138
+ ];
@@ -2,7 +2,7 @@
2
2
  // (archive / restore). Each maps to a v1 route with the same permission
3
3
  // check as the corresponding portal action.
4
4
  import { z } from 'zod';
5
- import { ok, withErrorBoundary } from './helpers.js';
5
+ import { fail, ok, withErrorBoundary } from './helpers.js';
6
6
  /** Optional fields every site-creating tool accepts (POST /api/v1/sites and the create-and-* routes). */
7
7
  export const newSiteFields = {
8
8
  id: z.string().optional().describe('Optional site id: 3-48 lowercase letters, digits and "-" (e.g. "acme-studio"). Used exactly; 409 site_id_taken when the organization has it. Default: the kebab-case name.'),
@@ -35,7 +35,11 @@ export const siteTools = [
35
35
  },
36
36
  {
37
37
  name: 'create_site',
38
- description: "Create + bootstrap a NEW site in your org. Seeds default settings, a published Home page, and a published header/footer that link only to it, so it renders and can be published immediately. Requires an ORG-scoped key (a site-scoped key is bound to one existing site and can't mint new ones; you'll get a 403). Accepts exactly `name`, optional `id`, `domain` and `language`; any other field is refused. Without `id` the site id is the kebab-case `name` (with a random suffix when taken); with `id` that exact id is used, or 409 site_id_taken. `language` is the site's BCP 47 content language (e.g. \"nl-BE\"; default \"en\"), saved at creation so <html lang> is right from the first build. Pass `domain` to kick off the \"point your DNS\" flow (never written as a live domain). Returns the new site's id, language + urls — use that id as `site_id`/`TYPEROLL_SITE_ID` for follow-up calls. After creating, run list_skills → read_skill tr-new-site to bootstrap the design.",
38
+ description: "Create + bootstrap a NEW site in your org. Blank (default): seeds default settings, a published Home page, and a published header/footer that link only to it, so it renders and can be published immediately. Requires an ORG-scoped key (a site-scoped key is bound to one existing site and can't mint new ones; you'll get a 403). Without `id` the site id is the kebab-case `name` (with a random suffix when taken); with `id` that exact id is used, or 409 site_id_taken. `language` is the site's BCP 47 content language (e.g. \"nl-BE\"; default: the template's language, else \"en\"), saved at creation so <html lang> is right from the first build. Pass `domain` to kick off the \"point your DNS\" flow (never written as a live domain). " +
39
+ 'START FROM A TEMPLATE with at most one of: `from_site_id` (another site of YOUR organization, optionally `from_site_version`; sites shared in from other organizations are refused with 404), `from_collection_entry` (a `package` entry of the organization collection, see list_collection_entries), `from_package_base64` or `from_package_url` (a whole-site .typeroll package; a package belongs to no organization, so a bought one works). ' +
40
+ 'Copied: pages (block and HTML pages and records of every content type), header, footer and global blocks, menus, styles (created with their ids, never mapped to "nearest" ones), block types, block and page templates, site fields with values, content types, forms (without their actions) and snippets, and media into the new site\'s own library (demo images stay marked for replacement; readiness lists them). Never copied: domains, publishing and hosting settings, API keys, shares, app installations (listed in warnings: install them on the new site), form actions and credentials, integrations, custom/tracking scripts, robots.txt, noindex switches, redirects, deploy history and revisions. A home page, header, footer and the primary/footer menus are created only where the template has none (started_from.defaults). ' +
41
+ '`design`: "full" (default for a new site: element styles, colours, typography, scales, content widths and font roles), "styles" or "content" (the default look). Font files in the template are added only with `font_licence_confirmed: true` (ask the user whether the font licence allows use on the new site; never assume it), or left out with `fonts: false`; otherwise 400 font_licence_required. A package with an invalid signature is refused (package_signature_invalid); one that is not a whole site answers package_not_a_site. If the import fails the half-created site is removed again (site_create_failed, details.site_removed). ' +
42
+ 'Returns the new site\'s id, language + urls, and with a template `started_from` { kind, source, report, defaults, warnings } — show the warnings to the user. Use the id as `site_id`/`TYPEROLL_SITE_ID` for follow-up calls. After creating a blank site, run list_skills → read_skill tr-new-site to bootstrap the design.',
39
43
  noSite: true,
40
44
  inputSchema: {
41
45
  name: z.string().min(1).describe('Display name. Slugified into the site id unless `id` is given.'),
@@ -44,9 +48,29 @@ export const siteTools = [
44
48
  .string()
45
49
  .optional()
46
50
  .describe('Optional real hostname e.g. "example.com". Starts DNS setup; not set live until DNS verifies.'),
51
+ from_site_id: z.string().optional().describe('Start as a copy of this site of your organization. REST body: `from: { site_id }`.'),
52
+ from_site_version: z.string().optional().describe('With from_site_id: copy this version (branch) of the site instead of main. REST body: `from.version`.'),
53
+ from_collection_entry: z.string().optional().describe('Start from this `package` entry of the organization collection. REST body: `from: { collection_entry }`.'),
54
+ from_package_base64: z.string().optional().describe('Start from a whole-site .typeroll package, base64-encoded (at most 32 MB). REST body: `from: { package: { data_base64 } }`.'),
55
+ from_package_url: z.string().optional().describe('Start from a whole-site .typeroll package downloaded from this https:// address (up to 200 MB). REST body: `from: { package: { source_url } }`.'),
56
+ design: z.enum(['full', 'styles', 'content']).optional().describe('With a template: how much of its look to take (default "full"). REST body: `options.design`.'),
57
+ fonts: z.boolean().optional().describe('With a template and design "full": take its font roles and font files (default true). REST body: `options.fonts`.'),
58
+ font_licence_confirmed: z.boolean().optional().describe('true: the user confirmed the licence of the template\'s font files allows use on the new site. REST body: `options.font_licence_confirmed`.'),
47
59
  },
48
60
  handler: withErrorBoundary(async (args, { client }) => {
49
- const res = await client.rootPost('sites', definedFields(args));
61
+ const { from_site_id, from_site_version, from_collection_entry, from_package_base64, from_package_url, design, fonts, font_licence_confirmed, ...site } = args;
62
+ const sources = [from_site_id, from_collection_entry, from_package_base64, from_package_url].filter(value => value !== undefined);
63
+ if (sources.length > 1)
64
+ return fail(new Error('Pass at most one of from_site_id, from_collection_entry, from_package_base64 and from_package_url.'));
65
+ const options = definedFields({ design, fonts, font_licence_confirmed });
66
+ if (!sources.length && (from_site_version !== undefined || Object.keys(options).length)) {
67
+ return fail(new Error('from_site_version, design, fonts and font_licence_confirmed apply only when starting from a template (from_site_id, from_collection_entry or from_package_*).'));
68
+ }
69
+ const from = from_site_id !== undefined ? { site_id: from_site_id, ...(from_site_version !== undefined ? { version: from_site_version } : {}) }
70
+ : from_collection_entry !== undefined ? { collection_entry: from_collection_entry }
71
+ : from_package_base64 !== undefined ? { package: { data_base64: from_package_base64 } }
72
+ : from_package_url !== undefined ? { package: { source_url: from_package_url } } : undefined;
73
+ const res = await client.rootPost('sites', { ...definedFields(site), ...(from ? { from } : {}), ...(from && Object.keys(options).length ? { options } : {}) });
50
74
  return ok(res);
51
75
  }),
52
76
  },