@velocity-astro/cms-api 0.1.0-beta.1 → 0.1.0-beta.12
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/dist/api.d.ts +3 -0
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +90 -6
- package/dist/api.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +33 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +745 -0
- package/dist/mcp.js.map +1 -0
- package/dist/tokens.d.ts +45 -0
- package/dist/tokens.d.ts.map +1 -0
- package/dist/tokens.js +2 -0
- package/dist/tokens.js.map +1 -0
- package/package.json +2 -2
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,745 @@
|
|
|
1
|
+
import { CmsError, ValidationError, fromStoredData, hasUnpublishedChanges, liveFields, pageAddress, richTextFromMarkdown, toStoredData, } from '@velocity-astro/cms-core';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
/**
|
|
4
|
+
* The Model Context Protocol, spoken over the API (`POST /api/cms/mcp`), so an AI agent such as
|
|
5
|
+
* Claude, ChatGPT or Cursor can work with a site's content: read the content types, write and
|
|
6
|
+
* publish entries, build pages from the template's sections, and, where its token allows, work
|
|
7
|
+
* with forms, contacts and deals.
|
|
8
|
+
*
|
|
9
|
+
* It holds no rules of its own, like every route of the API. Each tool checks the shape of what
|
|
10
|
+
* it was sent and calls the services as the actor that asked, so a token's role and allowances
|
|
11
|
+
* decide what an agent may do, exactly as a person's role does. Values go in and come out by
|
|
12
|
+
* field key; the services keep them by field id. Pages are built only from the blocks the
|
|
13
|
+
* template describes, with their own fields: the agent works on the rails the editor does.
|
|
14
|
+
*
|
|
15
|
+
* The transport is the protocol's "streamable HTTP" in its plain form: one JSON-RPC message (or
|
|
16
|
+
* a list of them) in, the answer as JSON out. Nothing is streamed and no session is kept.
|
|
17
|
+
*/
|
|
18
|
+
/** The versions of the protocol this server speaks, newest first. */
|
|
19
|
+
const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
20
|
+
const SERVER = { name: 'velocity-cms', title: 'Velocity CMS', version: '1' };
|
|
21
|
+
const INSTRUCTIONS = `This is a site's content in Velocity CMS.
|
|
22
|
+
Start with describe_site: it lists the content types, what this token may do, and the forms.
|
|
23
|
+
Values are written by field key. Formatted text (richtext) takes a string, or {"markdown": "..."} for headings, lists, bold, italics and links.
|
|
24
|
+
A page built from sections (a "blocks" field) is built from the blocks its content type lists, each with its own fields: read get_content_type or list_blocks first, then add_section, update_section, move_section, remove_section or set_sections. A look is one of the choices a field offers.
|
|
25
|
+
An idea the blocks cannot show is welcome: a new kind of section is a block in the site's model with a component of the same key in its code, so it is drawn on the theme and editors can change it. design_new_section gives the site's colours, fonts and blocks to design from and the steps to add one; once it is deployed, these tools use it like any other.
|
|
26
|
+
What you write is a draft until it is published. Publishing needs a token that allows it; otherwise tell the person the draft is ready for them to publish in the editor.
|
|
27
|
+
Contacts, deals and what visitors sent are personal data: they are there only when the token allows it, and never belong on a page.`;
|
|
28
|
+
const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
29
|
+
const say = (text, locale) => text?.[locale] ?? Object.values(text ?? {})[0];
|
|
30
|
+
/** Text as a tool takes it: one string (in the default language) or text per language. */
|
|
31
|
+
const words = z.union([z.string(), z.record(z.string(), z.string())]);
|
|
32
|
+
const wordsIn = (value, locale) => (typeof value === 'string' ? { [locale]: value } : value);
|
|
33
|
+
const values = z.record(z.string(), z.unknown());
|
|
34
|
+
const limit = z.number().int().min(1).max(200).default(50);
|
|
35
|
+
const offset = z.number().int().min(0).default(0);
|
|
36
|
+
const entryId = z.string().min(1).describe('The entry\'s id, from list_entries or get_entry.');
|
|
37
|
+
/**
|
|
38
|
+
* Values as an agent writes them, made ready for the services: `{ "markdown": "..." }`, anywhere,
|
|
39
|
+
* becomes formatted text. Nothing else is changed; each field's type checks the rest.
|
|
40
|
+
*/
|
|
41
|
+
function written(value) {
|
|
42
|
+
if (Array.isArray(value))
|
|
43
|
+
return value.map(written);
|
|
44
|
+
if (!isObject(value))
|
|
45
|
+
return value;
|
|
46
|
+
const keys = Object.keys(value);
|
|
47
|
+
if (keys.length === 1 && keys[0] === 'markdown' && typeof value['markdown'] === 'string')
|
|
48
|
+
return richTextFromMarkdown(value['markdown']);
|
|
49
|
+
return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, written(inner)]));
|
|
50
|
+
}
|
|
51
|
+
const isFieldDef = (value) => isObject(value) && typeof value['id'] === 'string' && typeof value['key'] === 'string' && typeof value['type'] === 'string' && isObject(value['label']);
|
|
52
|
+
const isBlockDef = (value) => isObject(value) && typeof value['id'] === 'string' && typeof value['key'] === 'string' && Array.isArray(value['fields']) && value['type'] === undefined;
|
|
53
|
+
/** Fields as an agent needs them: by key, with what each takes and the fields and blocks inside it. Ids are left out. */
|
|
54
|
+
function describeFields(fields, locale) {
|
|
55
|
+
return liveFields(fields).map((field) => {
|
|
56
|
+
const options = describeOptions(field.options, locale);
|
|
57
|
+
return {
|
|
58
|
+
key: field.key,
|
|
59
|
+
type: field.type,
|
|
60
|
+
label: say(field.label, locale),
|
|
61
|
+
...(field.required && { required: true }),
|
|
62
|
+
...(!field.translated && { sharedAcrossLanguages: true }),
|
|
63
|
+
...(field.help && { help: say(field.help, locale) }),
|
|
64
|
+
...(isObject(options) && Object.keys(options).length > 0 && { options }),
|
|
65
|
+
};
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
/** A field's settings, with the fields and blocks inside them described in turn, whatever the field's type. */
|
|
69
|
+
function describeOptions(value, locale) {
|
|
70
|
+
if (Array.isArray(value)) {
|
|
71
|
+
if (value.length > 0 && value.every(isFieldDef))
|
|
72
|
+
return describeFields(value, locale);
|
|
73
|
+
if (value.length > 0 && value.every(isBlockDef))
|
|
74
|
+
return describeBlocks(value, locale);
|
|
75
|
+
return value.map((item) => describeOptions(item, locale));
|
|
76
|
+
}
|
|
77
|
+
if (!isObject(value))
|
|
78
|
+
return value;
|
|
79
|
+
return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, describeOptions(inner, locale)]));
|
|
80
|
+
}
|
|
81
|
+
/** A field's settings as `options`, when it has any worth saying. */
|
|
82
|
+
function describeOptionsOf(field, locale) {
|
|
83
|
+
const options = describeOptions(field.options, locale);
|
|
84
|
+
return isObject(options) && Object.keys(options).length > 0 ? { options } : {};
|
|
85
|
+
}
|
|
86
|
+
/** The blocks a field allows, as a page may be built from them today. A retired block is left out. */
|
|
87
|
+
function describeBlocks(blocks, locale) {
|
|
88
|
+
return blocks
|
|
89
|
+
.filter((block) => block.retiredAt === undefined)
|
|
90
|
+
.map((block) => ({
|
|
91
|
+
key: block.key,
|
|
92
|
+
label: say(block.label, locale),
|
|
93
|
+
...(block.description && { description: say(block.description, locale) }),
|
|
94
|
+
...(block.group && { group: block.group }),
|
|
95
|
+
fields: describeFields(block.fields, locale),
|
|
96
|
+
}));
|
|
97
|
+
}
|
|
98
|
+
/** The name an entry is called by: its type's title field, or the first text field. */
|
|
99
|
+
function titleOf(type, entry) {
|
|
100
|
+
const path = type.titlePath ?? [liveFields(type.fields).find((field) => field.type === 'text')?.id ?? ''];
|
|
101
|
+
let value = entry.data;
|
|
102
|
+
for (const id of path)
|
|
103
|
+
value = isObject(value) ? value[id] : undefined;
|
|
104
|
+
return typeof value === 'string' ? value : undefined;
|
|
105
|
+
}
|
|
106
|
+
function summary(type, entry) {
|
|
107
|
+
return {
|
|
108
|
+
id: entry.id,
|
|
109
|
+
title: titleOf(type, entry) ?? entry.slug,
|
|
110
|
+
slug: entry.slug,
|
|
111
|
+
locale: entry.locale,
|
|
112
|
+
status: entry.status,
|
|
113
|
+
...(hasUnpublishedChanges(entry) && { unpublishedChanges: true }),
|
|
114
|
+
...(entry.publishAt && { publishAt: entry.publishAt }),
|
|
115
|
+
updatedAt: entry.updatedAt,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/** The `blocks` field a section tool works in: the one named, or the type's only one. */
|
|
119
|
+
function sectionsField(type, key) {
|
|
120
|
+
const fields = liveFields(type.fields).filter((field) => field.type === 'blocks');
|
|
121
|
+
const field = key === undefined ? (fields.length === 1 ? fields[0] : undefined) : fields.find((candidate) => candidate.key === key);
|
|
122
|
+
if (field)
|
|
123
|
+
return field;
|
|
124
|
+
const known = fields.map((candidate) => candidate.key).join(', ');
|
|
125
|
+
throw new ValidationError(fields.length === 0
|
|
126
|
+
? `The ${type.key} content type has no sections: it is not built from blocks.`
|
|
127
|
+
: key === undefined
|
|
128
|
+
? `The ${type.key} content type has more than one field of sections. Name one as "field": ${known}.`
|
|
129
|
+
: `The ${type.key} content type has no field of sections called "${key}". Its fields of sections are: ${known}.`, [{ path: ['field'], message: 'No such field of sections.' }]);
|
|
130
|
+
}
|
|
131
|
+
const sectionList = (value) => (Array.isArray(value) ? value : []).filter(isObject).map((section) => ({ ...section, block: String(section['block']), data: isObject(section['data']) ? section['data'] : {} }));
|
|
132
|
+
async function loadEntry(call, id) {
|
|
133
|
+
const entry = await call.cms.content.get(call.actor, id);
|
|
134
|
+
const type = await call.cms.schema.get(entry.typeId);
|
|
135
|
+
return { entry, type, values: fromStoredData(type.fields, entry.data) };
|
|
136
|
+
}
|
|
137
|
+
/** The entry as an agent reads it: its values by key, where its page is, and what to send back to change it. */
|
|
138
|
+
function entryView(type, entry, locale) {
|
|
139
|
+
const page = entry.published ? pageAddress(type, { locale: entry.locale, ...entry.published }, locale) : null;
|
|
140
|
+
return {
|
|
141
|
+
...summary(type, entry),
|
|
142
|
+
type: type.key,
|
|
143
|
+
translationGroup: entry.translationGroup,
|
|
144
|
+
revision: entry.revision,
|
|
145
|
+
...(entry.published && { publishedSlug: entry.published.slug, publishedAt: entry.published.at }),
|
|
146
|
+
...(page !== null && { page }),
|
|
147
|
+
...(entry.publishProblem && { publishProblem: entry.publishProblem }),
|
|
148
|
+
data: fromStoredData(type.fields, entry.data),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/** Saves new values for an entry, with the revision it was read at, and publishes it when asked. */
|
|
152
|
+
async function save(call, entry, type, next, options = {}) {
|
|
153
|
+
const data = toStoredData(type.fields, next, () => globalThis.crypto.randomUUID());
|
|
154
|
+
let saved = await call.cms.content.update(call.actor, entry.id, { data, expectedRevision: entry.revision, ...(options.slug !== undefined && { slug: options.slug }) });
|
|
155
|
+
if (options.publish)
|
|
156
|
+
saved = await call.cms.content.publish(call.actor, saved.id, saved.revision);
|
|
157
|
+
return entryView(type, saved, call.locale);
|
|
158
|
+
}
|
|
159
|
+
/** Changes the sections of one field of an entry, through the same save as every change. */
|
|
160
|
+
async function changeSections(call, input, change) {
|
|
161
|
+
const { entry, type, values: current } = await loadEntry(call, input.id);
|
|
162
|
+
const field = sectionsField(type, input.field);
|
|
163
|
+
const blocks = (field.options.blocks ?? []).filter((block) => block.retiredAt === undefined);
|
|
164
|
+
const sections = change(sectionList(current[field.key]), blocks);
|
|
165
|
+
const view = await save(call, entry, type, { ...current, [field.key]: sections }, { publish: input.publish });
|
|
166
|
+
return { ...view, data: undefined, sections: outline(view.data[field.key]) };
|
|
167
|
+
}
|
|
168
|
+
/** The sections of a page in order, short enough to read: which block, its id and its values. */
|
|
169
|
+
function outline(value) {
|
|
170
|
+
return sectionList(value).map((section, index) => ({ index, id: section.id, block: section.block, ...(section.hidden && { hidden: true }), data: section.data }));
|
|
171
|
+
}
|
|
172
|
+
/** A block the field allows, or a refusal that lists the ones it does. */
|
|
173
|
+
function blockOf(blocks, key) {
|
|
174
|
+
const block = blocks.find((candidate) => candidate.key === key);
|
|
175
|
+
if (block)
|
|
176
|
+
return block;
|
|
177
|
+
throw new ValidationError(`There is no block "${key}" here yet. The blocks this page can be built from are: ${blocks.map((candidate) => candidate.key).join(', ')}. To add a new kind of section, see design_new_section.`, [{ path: ['block'], message: 'No such block.' }]);
|
|
178
|
+
}
|
|
179
|
+
function indexOf(sections, id) {
|
|
180
|
+
const index = sections.findIndex((section) => section.id === id);
|
|
181
|
+
if (index < 0)
|
|
182
|
+
throw new ValidationError(`There is no section "${id}" on this page. get_sections lists them.`, [{ path: ['section'], message: 'No such section.' }]);
|
|
183
|
+
return index;
|
|
184
|
+
}
|
|
185
|
+
/** Leaves out what was not given, which a service reads as "not changed". */
|
|
186
|
+
function given(input) {
|
|
187
|
+
return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined));
|
|
188
|
+
}
|
|
189
|
+
const tool = (definition) => definition;
|
|
190
|
+
const ALL_PERMISSIONS = ['schema:write', 'entry:read', 'entry:write', 'entry:publish', 'entry:delete', 'form:write', 'submission:read', 'submission:manage', 'contact:read', 'contact:manage', 'user:manage', 'plugin:manage', 'settings:manage'];
|
|
191
|
+
const formField = z.object({
|
|
192
|
+
id: z.string().optional().describe('Keep the id a field was read with, so what it holds stays with it.'),
|
|
193
|
+
key: z.string(),
|
|
194
|
+
type: z.string().describe('A kind a visitor can fill in: text, email, phone, number, date, select, boolean, url.'),
|
|
195
|
+
label: words,
|
|
196
|
+
help: words.optional(),
|
|
197
|
+
required: z.boolean().optional(),
|
|
198
|
+
options: values.optional(),
|
|
199
|
+
});
|
|
200
|
+
const fieldsIn = (fields, locale) => fields.map((field) => given({ ...field, label: wordsIn(field.label, locale), help: field.help === undefined ? undefined : wordsIn(field.help, locale) }));
|
|
201
|
+
/** Every tool, in the order a client lists them. */
|
|
202
|
+
export const MCP_TOOLS = [
|
|
203
|
+
tool({
|
|
204
|
+
name: 'describe_site',
|
|
205
|
+
title: 'Describe the site',
|
|
206
|
+
description: 'Start here. The content types (with their address patterns and field keys), the forms, and what this token may do.',
|
|
207
|
+
input: z.object({}),
|
|
208
|
+
readOnly: true,
|
|
209
|
+
run: async (_input, { cms, actor, locale }) => {
|
|
210
|
+
const types = await cms.schema.list();
|
|
211
|
+
const can = ALL_PERMISSIONS.filter((permission) => cms.access.can(actor, permission));
|
|
212
|
+
const forms = can.includes('entry:read') ? await cms.forms.list(actor) : [];
|
|
213
|
+
return {
|
|
214
|
+
defaultLanguage: locale,
|
|
215
|
+
mayDo: can,
|
|
216
|
+
contentTypes: types.map((type) => ({
|
|
217
|
+
key: type.key,
|
|
218
|
+
kind: type.kind,
|
|
219
|
+
label: say(type.label, locale),
|
|
220
|
+
...(type.urlPattern && { urlPattern: type.urlPattern }),
|
|
221
|
+
...(type.inSettings && { inSettings: true }),
|
|
222
|
+
fields: liveFields(type.fields).map((field) => `${field.key} (${field.type})`),
|
|
223
|
+
...(liveFields(type.fields).some((field) => field.type === 'blocks') && { builtFromSections: true }),
|
|
224
|
+
})),
|
|
225
|
+
forms: forms.map((form) => ({ key: form.key, label: say(form.label, locale), open: form.open })),
|
|
226
|
+
};
|
|
227
|
+
},
|
|
228
|
+
}),
|
|
229
|
+
tool({
|
|
230
|
+
name: 'get_content_type',
|
|
231
|
+
title: 'Get a content type',
|
|
232
|
+
description: 'One content type in full: every field by key with its type, whether it is required, its choices and, for a page built from sections, every block it allows with that block\'s fields.',
|
|
233
|
+
input: z.object({ type: z.string().describe('The content type\'s key, such as pages or posts.') }),
|
|
234
|
+
readOnly: true,
|
|
235
|
+
run: async ({ type: key }, { cms, locale }) => {
|
|
236
|
+
const type = await cms.schema.getByKey(key);
|
|
237
|
+
return { key: type.key, kind: type.kind, label: say(type.label, locale), ...(type.urlPattern && { urlPattern: type.urlPattern }), ...(type.localizedUrlPatterns && { localizedUrlPatterns: type.localizedUrlPatterns }), fields: describeFields(type.fields, locale) };
|
|
238
|
+
},
|
|
239
|
+
}),
|
|
240
|
+
tool({
|
|
241
|
+
name: 'list_blocks',
|
|
242
|
+
title: 'List the blocks a page takes',
|
|
243
|
+
description: 'The blocks (kinds of section) a content type\'s pages can be built from today, each with its fields. For an idea none of them can show, see design_new_section.',
|
|
244
|
+
input: z.object({ type: z.string(), field: z.string().optional().describe('The field of sections, when the type has more than one.') }),
|
|
245
|
+
readOnly: true,
|
|
246
|
+
run: async ({ type: key, field }, { cms, locale }) => {
|
|
247
|
+
const type = await cms.schema.getByKey(key);
|
|
248
|
+
const sections = sectionsField(type, field);
|
|
249
|
+
return { type: type.key, field: sections.key, blocks: describeBlocks(sections.options.blocks ?? [], locale) };
|
|
250
|
+
},
|
|
251
|
+
}),
|
|
252
|
+
tool({
|
|
253
|
+
name: 'design_new_section',
|
|
254
|
+
title: 'Design a new kind of section',
|
|
255
|
+
description: 'For an idea no block can show: the site\'s theme (its published colours and fonts), every block it has with its fields and named looks, and the steps to add a new block and its component in the site\'s code.',
|
|
256
|
+
input: z.object({}),
|
|
257
|
+
readOnly: true,
|
|
258
|
+
run: async (_input, { cms, actor, locale }) => {
|
|
259
|
+
const types = await cms.schema.list();
|
|
260
|
+
const theme = [];
|
|
261
|
+
for (const type of types.filter((one) => one.kind === 'single')) {
|
|
262
|
+
const looks = liveFields(type.fields).filter((field) => field.type === 'color' || field.type === 'font');
|
|
263
|
+
if (looks.length === 0)
|
|
264
|
+
continue;
|
|
265
|
+
const [entry] = (await cms.content.find(actor, { typeId: type.id, limit: 1 })).items;
|
|
266
|
+
const published = entry?.published ? fromStoredData(type.fields, entry.published.data) : {};
|
|
267
|
+
theme.push({ type: type.key, fields: looks.map((field) => ({ key: field.key, type: field.type, label: say(field.label, locale), value: published[field.key] ?? null, ...describeOptionsOf(field, locale) })) });
|
|
268
|
+
}
|
|
269
|
+
const blocks = types.flatMap((type) => liveFields(type.fields)
|
|
270
|
+
.filter((field) => Array.isArray(field.options.blocks))
|
|
271
|
+
.map((field) => ({ type: type.key, field: field.key, blocks: describeBlocks(field.options.blocks, locale) })));
|
|
272
|
+
return {
|
|
273
|
+
theme,
|
|
274
|
+
blocks,
|
|
275
|
+
steps: [
|
|
276
|
+
'In the site\'s code, describe the block in the model (usually cms/model.mjs) on the blocks field of the types that should take it: { key, label, description, icon, group, fields }. Keys start with a lowercase letter and are permanent.',
|
|
277
|
+
'Give each look a select field with named choices (and swatches for colours) drawn from the theme above, never a free colour, size or class. Text, pictures, links, lists and forms are fields of their own, so editors can change them.',
|
|
278
|
+
'Write its component, of the same key, in the block map (export const blocks = { ... }): every prop optional, wrapped with sectionMark(section.id, section.data), each field marked with fieldMark(key).',
|
|
279
|
+
'Run the seed, then `npx velocity-cms check`, and build the site. The cms-add-section skill has each step in full.',
|
|
280
|
+
'Once the site is deployed, add_section can place it on any page whose type takes it.',
|
|
281
|
+
],
|
|
282
|
+
};
|
|
283
|
+
},
|
|
284
|
+
}),
|
|
285
|
+
tool({
|
|
286
|
+
name: 'list_entries',
|
|
287
|
+
title: 'List entries',
|
|
288
|
+
description: 'The entries of one content type, most recently changed first: id, title, slug, language and status. Give a slug to find one entry.',
|
|
289
|
+
input: z.object({ type: z.string(), locale: z.string().optional(), slug: z.string().optional(), status: z.enum(['draft', 'scheduled', 'published']).optional(), limit, offset }),
|
|
290
|
+
readOnly: true,
|
|
291
|
+
run: async ({ type: key, ...query }, { cms, actor }) => {
|
|
292
|
+
const type = await cms.schema.getByKey(key);
|
|
293
|
+
const page = await cms.content.find(actor, given({ typeId: type.id, order: 'updated', ...query }));
|
|
294
|
+
return { total: page.total, items: page.items.map((entry) => summary(type, entry)) };
|
|
295
|
+
},
|
|
296
|
+
}),
|
|
297
|
+
tool({
|
|
298
|
+
name: 'get_entry',
|
|
299
|
+
title: 'Get an entry',
|
|
300
|
+
description: 'One entry: its values by field key (the version being worked on), its status, revision and the address of its page.',
|
|
301
|
+
input: z.object({ id: entryId }),
|
|
302
|
+
readOnly: true,
|
|
303
|
+
run: async ({ id }, call) => {
|
|
304
|
+
const { entry, type } = await loadEntry(call, id);
|
|
305
|
+
return entryView(type, entry, call.locale);
|
|
306
|
+
},
|
|
307
|
+
}),
|
|
308
|
+
tool({
|
|
309
|
+
name: 'create_entry',
|
|
310
|
+
title: 'Create an entry',
|
|
311
|
+
description: 'Creates an entry as a draft, with its values by field key. A page built from sections takes a list of {"block": "<key>", "data": {...}} in its sections field. Give translationOf (an entry id) to write the same entry in another language. Set publish to put it on the site, if this token may.',
|
|
312
|
+
input: z.object({
|
|
313
|
+
type: z.string(),
|
|
314
|
+
slug: z.string().describe('The entry\'s name in its address: lowercase words joined by hyphens. A page whose address pattern is /[...slug] may use parts, such as services/roofing; index is the home page.'),
|
|
315
|
+
data: values,
|
|
316
|
+
locale: z.string().optional(),
|
|
317
|
+
translationOf: z.string().optional(),
|
|
318
|
+
publish: z.boolean().optional(),
|
|
319
|
+
}),
|
|
320
|
+
run: async ({ type: key, slug, data, locale, translationOf, publish }, call) => {
|
|
321
|
+
const { cms, actor } = call;
|
|
322
|
+
const type = await cms.schema.getByKey(key);
|
|
323
|
+
const group = translationOf === undefined ? undefined : (await cms.content.get(actor, translationOf)).translationGroup;
|
|
324
|
+
const stored = toStoredData(type.fields, written(data), () => globalThis.crypto.randomUUID());
|
|
325
|
+
let entry = await cms.content.create(actor, { typeId: type.id, locale: locale ?? call.locale, slug, data: stored, ...(group !== undefined && { translationGroup: group }) });
|
|
326
|
+
if (publish)
|
|
327
|
+
entry = await cms.content.publish(actor, entry.id, entry.revision);
|
|
328
|
+
return entryView(type, entry, call.locale);
|
|
329
|
+
},
|
|
330
|
+
}),
|
|
331
|
+
tool({
|
|
332
|
+
name: 'update_entry',
|
|
333
|
+
title: 'Update an entry',
|
|
334
|
+
description: 'Changes an entry\'s values by field key. Each key given replaces that field\'s value (null empties it); fields not named stay as they are. Saved as a draft unless publish is set.',
|
|
335
|
+
input: z.object({ id: entryId, data: values.default({}), slug: z.string().optional(), publish: z.boolean().optional() }),
|
|
336
|
+
run: async ({ id, data, slug, publish }, call) => {
|
|
337
|
+
const { entry, type, values: current } = await loadEntry(call, id);
|
|
338
|
+
return save(call, entry, type, { ...current, ...written(data) }, { slug, publish });
|
|
339
|
+
},
|
|
340
|
+
}),
|
|
341
|
+
tool({
|
|
342
|
+
name: 'publish_entry',
|
|
343
|
+
title: 'Publish an entry',
|
|
344
|
+
description: 'Puts the version being worked on on the site, at once. Needs a token that may publish.',
|
|
345
|
+
input: z.object({ id: entryId }),
|
|
346
|
+
run: async ({ id }, call) => {
|
|
347
|
+
const { entry, type } = await loadEntry(call, id);
|
|
348
|
+
return entryView(type, await call.cms.content.publish(call.actor, id, entry.revision), call.locale);
|
|
349
|
+
},
|
|
350
|
+
}),
|
|
351
|
+
tool({
|
|
352
|
+
name: 'unpublish_entry',
|
|
353
|
+
title: 'Unpublish an entry',
|
|
354
|
+
description: 'Takes an entry off the site. Its content is kept as a draft.',
|
|
355
|
+
input: z.object({ id: entryId }),
|
|
356
|
+
run: async ({ id }, call) => {
|
|
357
|
+
const { type } = await loadEntry(call, id);
|
|
358
|
+
return entryView(type, await call.cms.content.unpublish(call.actor, id), call.locale);
|
|
359
|
+
},
|
|
360
|
+
}),
|
|
361
|
+
tool({
|
|
362
|
+
name: 'schedule_entry',
|
|
363
|
+
title: 'Schedule an entry',
|
|
364
|
+
description: 'Sets a time for the entry to go on the site by itself, as it is then.',
|
|
365
|
+
input: z.object({ id: entryId, at: z.string().describe('When, as an ISO 8601 time with its zone, such as 2026-12-01T09:00:00Z.') }),
|
|
366
|
+
run: async ({ id, at }, call) => {
|
|
367
|
+
const { entry, type } = await loadEntry(call, id);
|
|
368
|
+
return entryView(type, await call.cms.content.schedule(call.actor, id, { at, expectedRevision: entry.revision }), call.locale);
|
|
369
|
+
},
|
|
370
|
+
}),
|
|
371
|
+
tool({
|
|
372
|
+
name: 'duplicate_entry',
|
|
373
|
+
title: 'Duplicate an entry',
|
|
374
|
+
description: 'Makes a draft copy of an entry, with a free slug.',
|
|
375
|
+
input: z.object({ id: entryId }),
|
|
376
|
+
run: async ({ id }, call) => {
|
|
377
|
+
const { type } = await loadEntry(call, id);
|
|
378
|
+
return entryView(type, await call.cms.content.duplicate(call.actor, id), call.locale);
|
|
379
|
+
},
|
|
380
|
+
}),
|
|
381
|
+
tool({
|
|
382
|
+
name: 'trash_entry',
|
|
383
|
+
title: 'Move an entry to the trash',
|
|
384
|
+
description: 'Takes an entry off the site and out of every list. It can be restored from the trash in the editor.',
|
|
385
|
+
input: z.object({ id: entryId }),
|
|
386
|
+
run: async ({ id }, call) => {
|
|
387
|
+
const { type } = await loadEntry(call, id);
|
|
388
|
+
const entry = await call.cms.content.trash(call.actor, id);
|
|
389
|
+
return { ...summary(type, entry), trashed: true };
|
|
390
|
+
},
|
|
391
|
+
}),
|
|
392
|
+
tool({
|
|
393
|
+
name: 'entry_history',
|
|
394
|
+
title: 'List an entry\'s history',
|
|
395
|
+
description: 'Every saved version of an entry, newest first: revision, status and when.',
|
|
396
|
+
input: z.object({ id: entryId }),
|
|
397
|
+
readOnly: true,
|
|
398
|
+
run: async ({ id }, { cms, actor }) => (await cms.content.history(actor, id)).map(({ revision, status, createdAt, actorId }) => ({ revision, status, createdAt, by: actorId })),
|
|
399
|
+
}),
|
|
400
|
+
tool({
|
|
401
|
+
name: 'preview_link',
|
|
402
|
+
title: 'Make a preview link',
|
|
403
|
+
description: 'A link to the entry\'s page showing the saved draft, good for a while, to show a person before it is published.',
|
|
404
|
+
input: z.object({ id: entryId }),
|
|
405
|
+
run: async ({ id }, { cms, actor }) => cms.previews.link(actor, id),
|
|
406
|
+
}),
|
|
407
|
+
tool({
|
|
408
|
+
name: 'get_sections',
|
|
409
|
+
title: 'Get a page\'s sections',
|
|
410
|
+
description: 'The sections of a page in order: index, id, block and values. Section ids are what the other section tools take.',
|
|
411
|
+
input: z.object({ id: entryId, field: z.string().optional() }),
|
|
412
|
+
readOnly: true,
|
|
413
|
+
run: async ({ id, field }, call) => {
|
|
414
|
+
const { type, values: current } = await loadEntry(call, id);
|
|
415
|
+
const sections = sectionsField(type, field);
|
|
416
|
+
return { field: sections.key, sections: outline(current[sections.key]) };
|
|
417
|
+
},
|
|
418
|
+
}),
|
|
419
|
+
tool({
|
|
420
|
+
name: 'add_section',
|
|
421
|
+
title: 'Add a section',
|
|
422
|
+
description: 'Adds a section to a page, from one of the blocks the page allows (list_blocks), with that block\'s values by field key. At the end unless an index or the id of a section to follow is given.',
|
|
423
|
+
input: z.object({ id: entryId, block: z.string(), data: values.default({}), field: z.string().optional(), index: z.number().int().min(0).optional(), after: z.string().optional(), publish: z.boolean().optional() }),
|
|
424
|
+
run: async ({ block, data, index, after, ...input }, call) => changeSections(call, input, (sections, blocks) => {
|
|
425
|
+
const section = { block: blockOf(blocks, block).key, data: written(data) };
|
|
426
|
+
const at = after !== undefined ? indexOf(sections, after) + 1 : Math.min(index ?? sections.length, sections.length);
|
|
427
|
+
return [...sections.slice(0, at), section, ...sections.slice(at)];
|
|
428
|
+
}),
|
|
429
|
+
}),
|
|
430
|
+
tool({
|
|
431
|
+
name: 'update_section',
|
|
432
|
+
title: 'Update a section',
|
|
433
|
+
description: 'Changes the values of one section, by field key. Keys not named stay as they are; null empties one. Its block cannot change: remove it and add another.',
|
|
434
|
+
input: z.object({ id: entryId, section: z.string(), data: values, field: z.string().optional(), publish: z.boolean().optional() }),
|
|
435
|
+
run: async ({ section: sectionId, data, ...input }, call) => changeSections(call, input, (sections) => {
|
|
436
|
+
const at = indexOf(sections, sectionId);
|
|
437
|
+
const section = sections[at];
|
|
438
|
+
return sections.map((one, index) => (index === at ? { ...section, data: { ...section.data, ...written(data) } } : one));
|
|
439
|
+
}),
|
|
440
|
+
}),
|
|
441
|
+
tool({
|
|
442
|
+
name: 'move_section',
|
|
443
|
+
title: 'Move a section',
|
|
444
|
+
description: 'Moves one section to a new place in the page, counted from 0.',
|
|
445
|
+
input: z.object({ id: entryId, section: z.string(), to: z.number().int().min(0), field: z.string().optional(), publish: z.boolean().optional() }),
|
|
446
|
+
run: async ({ section: sectionId, to, ...input }, call) => changeSections(call, input, (sections) => {
|
|
447
|
+
const at = indexOf(sections, sectionId);
|
|
448
|
+
const rest = sections.filter((_, index) => index !== at);
|
|
449
|
+
const place = Math.min(to, rest.length);
|
|
450
|
+
return [...rest.slice(0, place), sections[at], ...rest.slice(place)];
|
|
451
|
+
}),
|
|
452
|
+
}),
|
|
453
|
+
tool({
|
|
454
|
+
name: 'remove_section',
|
|
455
|
+
title: 'Remove a section',
|
|
456
|
+
description: 'Takes one section off a page. The entry\'s history keeps it.',
|
|
457
|
+
input: z.object({ id: entryId, section: z.string(), field: z.string().optional(), publish: z.boolean().optional() }),
|
|
458
|
+
run: async ({ section: sectionId, ...input }, call) => changeSections(call, input, (sections) => {
|
|
459
|
+
const at = indexOf(sections, sectionId);
|
|
460
|
+
return sections.filter((_, index) => index !== at);
|
|
461
|
+
}),
|
|
462
|
+
}),
|
|
463
|
+
tool({
|
|
464
|
+
name: 'set_sections',
|
|
465
|
+
title: 'Lay out a page',
|
|
466
|
+
description: 'Replaces every section of a page at once, in order: a list of {"block": "<key>", "data": {...}}. Keep a section\'s "id" to keep it as it is; leave it out for a new one.',
|
|
467
|
+
input: z.object({ id: entryId, sections: z.array(z.object({ id: z.string().optional(), block: z.string(), data: values.default({}) })), field: z.string().optional(), publish: z.boolean().optional() }),
|
|
468
|
+
run: async ({ sections: wanted, ...input }, call) => changeSections(call, input, (_sections, blocks) => wanted.map((section) => given({ id: section.id, block: blockOf(blocks, section.block).key, data: written(section.data) }))),
|
|
469
|
+
}),
|
|
470
|
+
tool({
|
|
471
|
+
name: 'list_images',
|
|
472
|
+
title: 'List images',
|
|
473
|
+
description: 'The images an image field can hold: the template\'s own and those uploaded. An image field stores the name.',
|
|
474
|
+
input: z.object({}),
|
|
475
|
+
readOnly: true,
|
|
476
|
+
run: async (_input, { cms, actor }) => (await cms.media.images(actor)).map(({ name, url, width, height }) => given({ name, url, width, height })),
|
|
477
|
+
}),
|
|
478
|
+
tool({
|
|
479
|
+
name: 'list_forms',
|
|
480
|
+
title: 'List forms',
|
|
481
|
+
description: 'The site\'s forms with their fields. A section that shows a form stores the form\'s id.',
|
|
482
|
+
input: z.object({}),
|
|
483
|
+
readOnly: true,
|
|
484
|
+
run: async (_input, { cms, actor, locale }) => (await cms.forms.list(actor)).map((form) => ({ id: form.id, key: form.key, label: say(form.label, locale), open: form.open, ...(form.startsDeal && { startsDeal: true }), fields: describeFields(form.fields, locale) })),
|
|
485
|
+
}),
|
|
486
|
+
tool({
|
|
487
|
+
name: 'create_form',
|
|
488
|
+
title: 'Create a form',
|
|
489
|
+
description: 'Makes a form visitors fill in. contact names the keys of the fields that hold the sender\'s name, email and phone, which is what makes a sender a contact in the CRM.',
|
|
490
|
+
input: z.object({
|
|
491
|
+
key: z.string(),
|
|
492
|
+
label: words,
|
|
493
|
+
fields: z.array(formField).max(50),
|
|
494
|
+
submitLabel: words.optional(),
|
|
495
|
+
success: words.optional(),
|
|
496
|
+
notify: z.array(z.string()).optional().describe('Email addresses told of each submission.'),
|
|
497
|
+
contact: z.object({ name: z.string().optional(), email: z.string().optional(), phone: z.string().optional() }).optional(),
|
|
498
|
+
startsDeal: z.boolean().optional(),
|
|
499
|
+
}),
|
|
500
|
+
run: async ({ label, fields, submitLabel, success, ...rest }, { cms, actor, locale }) => {
|
|
501
|
+
const form = given({
|
|
502
|
+
...rest,
|
|
503
|
+
label: wordsIn(label, locale),
|
|
504
|
+
fields: fieldsIn(fields.map(({ id: _id, ...field }) => field), locale),
|
|
505
|
+
submitLabel: submitLabel === undefined ? undefined : wordsIn(submitLabel, locale),
|
|
506
|
+
success: success === undefined ? undefined : wordsIn(success, locale),
|
|
507
|
+
contact: rest.contact === undefined ? undefined : given(rest.contact),
|
|
508
|
+
});
|
|
509
|
+
const made = await cms.forms.create(actor, form);
|
|
510
|
+
return { id: made.id, key: made.key, fields: describeFields(made.fields, locale) };
|
|
511
|
+
},
|
|
512
|
+
}),
|
|
513
|
+
tool({
|
|
514
|
+
name: 'list_submissions',
|
|
515
|
+
title: 'List what a form received',
|
|
516
|
+
description: 'What visitors sent with one form, newest first. Personal data: only for a token allowed it, and never to be put on a page.',
|
|
517
|
+
input: z.object({ form: z.string().describe('The form\'s key.'), status: z.enum(['new', 'handled', 'spam']).optional(), limit, offset }),
|
|
518
|
+
readOnly: true,
|
|
519
|
+
run: async ({ form: key, ...query }, { cms, actor }) => {
|
|
520
|
+
const form = (await cms.forms.list(actor)).find((candidate) => candidate.key === key);
|
|
521
|
+
if (!form)
|
|
522
|
+
throw new ValidationError(`There is no form "${key}".`, [{ path: ['form'], message: 'No such form.' }]);
|
|
523
|
+
return cms.submissions.find(actor, given({ formId: form.id, ...query }));
|
|
524
|
+
},
|
|
525
|
+
}),
|
|
526
|
+
tool({
|
|
527
|
+
name: 'list_contacts',
|
|
528
|
+
title: 'List contacts',
|
|
529
|
+
description: 'The people who wrote to the site or were added, with their stage. Personal data: only for a token allowed it.',
|
|
530
|
+
input: z.object({ search: z.string().max(200).optional(), stage: z.string().optional().describe('A stage id, from get_pipeline.'), limit, offset }),
|
|
531
|
+
readOnly: true,
|
|
532
|
+
run: async (query, { cms, actor }) => cms.contacts.find(actor, given(query)),
|
|
533
|
+
}),
|
|
534
|
+
tool({
|
|
535
|
+
name: 'get_contact',
|
|
536
|
+
title: 'Get a contact',
|
|
537
|
+
description: 'One contact with their timeline: what they sent and what the team noted.',
|
|
538
|
+
input: z.object({ id: z.string() }),
|
|
539
|
+
readOnly: true,
|
|
540
|
+
run: async ({ id }, { cms, actor }) => ({ contact: await cms.contacts.get(actor, id), timeline: await cms.contacts.timeline(actor, id) }),
|
|
541
|
+
}),
|
|
542
|
+
tool({
|
|
543
|
+
name: 'create_contact',
|
|
544
|
+
title: 'Add a contact',
|
|
545
|
+
description: 'Adds a person to the CRM by hand. Someone already here by email is refused.',
|
|
546
|
+
input: z.object({ email: z.string(), name: z.string().optional(), phone: z.string().optional(), data: values.optional().describe('Custom field values, by custom field id.') }),
|
|
547
|
+
run: async (input, { cms, actor }) => cms.contacts.create(actor, given(input)),
|
|
548
|
+
}),
|
|
549
|
+
tool({
|
|
550
|
+
name: 'update_contact',
|
|
551
|
+
title: 'Update a contact',
|
|
552
|
+
description: 'Changes a contact: their stage, who looks after them, the day to follow up, their name or phone.',
|
|
553
|
+
input: z.object({ id: z.string(), stage: z.string().optional(), ownerId: z.string().nullable().optional(), followUpAt: z.string().nullable().optional(), name: z.string().nullable().optional(), phone: z.string().nullable().optional(), data: values.optional() }),
|
|
554
|
+
run: async ({ id, ...changes }, { cms, actor }) => {
|
|
555
|
+
const contact = await cms.contacts.get(actor, id);
|
|
556
|
+
return cms.contacts.update(actor, id, given({ ...changes, expectedRevision: contact.revision }));
|
|
557
|
+
},
|
|
558
|
+
}),
|
|
559
|
+
tool({
|
|
560
|
+
name: 'add_contact_note',
|
|
561
|
+
title: 'Note something on a contact',
|
|
562
|
+
description: 'Adds a note to a contact\'s timeline, as the team does.',
|
|
563
|
+
input: z.object({ id: z.string(), text: z.string() }),
|
|
564
|
+
run: async ({ id, text }, { cms, actor }) => cms.contacts.addNote(actor, id, text),
|
|
565
|
+
}),
|
|
566
|
+
tool({
|
|
567
|
+
name: 'get_pipeline',
|
|
568
|
+
title: 'Get the pipeline',
|
|
569
|
+
description: 'The stages contacts and deals move through (ids, names, kinds, chances), the currency, who new contacts go to and the monthly target.',
|
|
570
|
+
input: z.object({}),
|
|
571
|
+
readOnly: true,
|
|
572
|
+
run: async (_input, { cms, actor }) => cms.pipeline.get(actor),
|
|
573
|
+
}),
|
|
574
|
+
tool({
|
|
575
|
+
name: 'save_pipeline',
|
|
576
|
+
title: 'Set up the pipeline',
|
|
577
|
+
description: 'Sets every stage in order (keep a stage\'s id to keep it; a stage left out is removed and its contacts move to the first), the currency, who new contacts are given to and the monthly target.',
|
|
578
|
+
input: z.object({
|
|
579
|
+
stages: z.array(z.object({ id: z.string().optional(), label: z.string().optional(), kind: z.enum(['open', 'won', 'lost']), chance: z.number().optional() })).max(50),
|
|
580
|
+
currency: z.string().max(10).optional(),
|
|
581
|
+
assignTo: z.array(z.string()).optional().describe('Ids of people on the team, from list_team.'),
|
|
582
|
+
monthlyTarget: z.number().nullable().optional(),
|
|
583
|
+
}),
|
|
584
|
+
run: async ({ stages, ...rest }, { cms, actor }) => {
|
|
585
|
+
const current = await cms.pipeline.get(actor);
|
|
586
|
+
return cms.pipeline.save(actor, given({ ...rest, stages: stages.map((stage) => given(stage)), expectedRevision: current.revision }));
|
|
587
|
+
},
|
|
588
|
+
}),
|
|
589
|
+
tool({
|
|
590
|
+
name: 'list_team',
|
|
591
|
+
title: 'List the team',
|
|
592
|
+
description: 'Who a contact or a deal can be given to: ids, names and roles.',
|
|
593
|
+
input: z.object({}),
|
|
594
|
+
readOnly: true,
|
|
595
|
+
run: async (_input, { cms, actor }) => cms.contacts.owners(actor),
|
|
596
|
+
}),
|
|
597
|
+
tool({
|
|
598
|
+
name: 'get_custom_fields',
|
|
599
|
+
title: 'Get custom fields',
|
|
600
|
+
description: 'The fields the site adds to its contacts and its deals.',
|
|
601
|
+
input: z.object({}),
|
|
602
|
+
readOnly: true,
|
|
603
|
+
run: async (_input, { cms, actor }) => cms.customFields.get(actor),
|
|
604
|
+
}),
|
|
605
|
+
tool({
|
|
606
|
+
name: 'save_custom_fields',
|
|
607
|
+
title: 'Set custom fields',
|
|
608
|
+
description: 'Sets the fields of contacts or of deals, as a whole list. Keep a field\'s id to keep what it holds; a field left out is removed, and its values kept. None can be required.',
|
|
609
|
+
input: z.object({ contact: z.array(formField).max(100).optional(), deal: z.array(formField).max(100).optional() }),
|
|
610
|
+
run: async ({ contact, deal }, { cms, actor, locale }) => {
|
|
611
|
+
const current = await cms.customFields.get(actor);
|
|
612
|
+
return cms.customFields.save(actor, given({ contact: contact && fieldsIn(contact, locale), deal: deal && fieldsIn(deal, locale), expectedRevision: current.revision }));
|
|
613
|
+
},
|
|
614
|
+
}),
|
|
615
|
+
tool({
|
|
616
|
+
name: 'list_deals',
|
|
617
|
+
title: 'List deals',
|
|
618
|
+
description: 'Deals, optionally of one contact or in one stage.',
|
|
619
|
+
input: z.object({ contact: z.string().optional(), stage: z.string().optional(), limit, offset }),
|
|
620
|
+
readOnly: true,
|
|
621
|
+
run: async ({ contact, ...query }, { cms, actor }) => cms.deals.find(actor, given({ ...query, contactId: contact })),
|
|
622
|
+
}),
|
|
623
|
+
tool({
|
|
624
|
+
name: 'create_deal',
|
|
625
|
+
title: 'Create a deal',
|
|
626
|
+
description: 'A deal for a contact: a title, a whole amount of the pipeline\'s currency and a stage. about ties it to an entry (its content type\'s id and its translation group) when that type takes deals.',
|
|
627
|
+
input: z.object({
|
|
628
|
+
contactId: z.string(),
|
|
629
|
+
title: z.string(),
|
|
630
|
+
value: z.number(),
|
|
631
|
+
stage: z.string().optional(),
|
|
632
|
+
ownerId: z.string().optional(),
|
|
633
|
+
closeOn: z.string().optional(),
|
|
634
|
+
about: z.object({ typeId: z.string(), entry: z.string() }).optional(),
|
|
635
|
+
data: values.optional(),
|
|
636
|
+
}),
|
|
637
|
+
run: async (input, { cms, actor }) => cms.deals.create(actor, given(input)),
|
|
638
|
+
}),
|
|
639
|
+
tool({
|
|
640
|
+
name: 'update_deal',
|
|
641
|
+
title: 'Update a deal',
|
|
642
|
+
description: 'Changes a deal: its stage, value, title, owner or close date.',
|
|
643
|
+
input: z.object({ id: z.string(), title: z.string().optional(), value: z.number().optional(), stage: z.string().optional(), ownerId: z.string().nullable().optional(), closeOn: z.string().nullable().optional(), data: values.optional() }),
|
|
644
|
+
run: async ({ id, ...changes }, { cms, actor }) => {
|
|
645
|
+
const deal = await cms.deals.get(actor, id);
|
|
646
|
+
return cms.deals.update(actor, id, given({ ...changes, expectedRevision: deal.revision }));
|
|
647
|
+
},
|
|
648
|
+
}),
|
|
649
|
+
tool({
|
|
650
|
+
name: 'forecast',
|
|
651
|
+
title: 'Forecast deals',
|
|
652
|
+
description: 'What is open, forecast and won, by stage.',
|
|
653
|
+
input: z.object({}),
|
|
654
|
+
readOnly: true,
|
|
655
|
+
run: async (_input, { cms, actor }) => cms.deals.forecast(actor),
|
|
656
|
+
}),
|
|
657
|
+
];
|
|
658
|
+
const RPC_ERRORS = { parse: -32700, invalidRequest: -32600, methodNotFound: -32601, invalidParams: -32602, internal: -32603 };
|
|
659
|
+
/** Answers MCP's JSON-RPC messages for one actor. Faults are the API's to report; a refusal is the tool's answer. */
|
|
660
|
+
export class McpEndpoint {
|
|
661
|
+
#options;
|
|
662
|
+
#tools = new Map(MCP_TOOLS.map((one) => [one.name, one]));
|
|
663
|
+
constructor(options) {
|
|
664
|
+
this.#options = options;
|
|
665
|
+
}
|
|
666
|
+
/** The answer to a message or a list of them, or `null` when nothing needs one (notifications). */
|
|
667
|
+
async handle(actor, body) {
|
|
668
|
+
if (Array.isArray(body)) {
|
|
669
|
+
const answers = (await Promise.all(body.map((message) => this.#one(actor, message)))).filter((answer) => answer !== null);
|
|
670
|
+
return answers.length > 0 ? answers : null;
|
|
671
|
+
}
|
|
672
|
+
return this.#one(actor, body);
|
|
673
|
+
}
|
|
674
|
+
async #one(actor, message) {
|
|
675
|
+
if (!isObject(message) || typeof message['method'] !== 'string') {
|
|
676
|
+
// A response sent to us (we ask nothing of the client) or something that is no message.
|
|
677
|
+
return isObject(message) && ('result' in message || 'error' in message) ? null : failure(null, RPC_ERRORS.invalidRequest, 'This is not a JSON-RPC request.');
|
|
678
|
+
}
|
|
679
|
+
const { id, method, params } = message;
|
|
680
|
+
// A notification (no id) is answered with nothing, whatever it says.
|
|
681
|
+
if (id === undefined)
|
|
682
|
+
return null;
|
|
683
|
+
const answer = (result) => ({ jsonrpc: '2.0', id, result });
|
|
684
|
+
switch (method) {
|
|
685
|
+
case 'initialize': {
|
|
686
|
+
const asked = isObject(params) ? params['protocolVersion'] : undefined;
|
|
687
|
+
const protocolVersion = PROTOCOL_VERSIONS.find((version) => version === asked) ?? PROTOCOL_VERSIONS[0];
|
|
688
|
+
return answer({ protocolVersion, capabilities: { tools: { listChanged: false } }, serverInfo: SERVER, instructions: INSTRUCTIONS });
|
|
689
|
+
}
|
|
690
|
+
case 'ping':
|
|
691
|
+
return answer({});
|
|
692
|
+
case 'tools/list':
|
|
693
|
+
return answer({ tools: [...this.#tools.values()].filter((one) => this.#offered(actor, one)).map(listed) });
|
|
694
|
+
case 'tools/call':
|
|
695
|
+
return answer(await this.#call(actor, params));
|
|
696
|
+
case 'resources/list':
|
|
697
|
+
return answer({ resources: [] });
|
|
698
|
+
case 'resources/templates/list':
|
|
699
|
+
return answer({ resourceTemplates: [] });
|
|
700
|
+
case 'prompts/list':
|
|
701
|
+
return answer({ prompts: [] });
|
|
702
|
+
default:
|
|
703
|
+
return failure(id, RPC_ERRORS.methodNotFound, `This server has no method "${String(method)}".`);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
/** Every tool is listed, except those about personal data for an actor that may not read it. */
|
|
707
|
+
#offered(actor, one) {
|
|
708
|
+
const personal = PERSONAL_TOOLS.has(one.name);
|
|
709
|
+
return !personal || this.#options.cms.access.can(actor, 'contact:read') || this.#options.cms.access.can(actor, 'submission:read');
|
|
710
|
+
}
|
|
711
|
+
async #call(actor, params) {
|
|
712
|
+
const name = isObject(params) ? params['name'] : undefined;
|
|
713
|
+
const one = typeof name === 'string' ? this.#tools.get(name) : undefined;
|
|
714
|
+
if (!one)
|
|
715
|
+
return refusal(`There is no tool "${String(name)}". tools/list names them.`);
|
|
716
|
+
const parsed = one.input.safeParse(isObject(params) && params['arguments'] !== undefined ? params['arguments'] : {});
|
|
717
|
+
if (!parsed.success) {
|
|
718
|
+
const first = parsed.error.issues[0];
|
|
719
|
+
return refusal(`The arguments are not in the shape ${one.name} takes. ${first && first.path.length > 0 ? `"${first.path.join('.')}": ` : ''}${first?.message ?? ''}`.trim());
|
|
720
|
+
}
|
|
721
|
+
try {
|
|
722
|
+
const result = await one.run(parsed.data, { cms: this.#options.cms, actor, locale: this.#options.defaultLocale });
|
|
723
|
+
return { content: [{ type: 'text', text: JSON.stringify(result ?? {}, null, 2) }] };
|
|
724
|
+
}
|
|
725
|
+
catch (error) {
|
|
726
|
+
// A refusal keeps the service's own words, which say what to do. A fault is the API's to report.
|
|
727
|
+
if (!(error instanceof CmsError))
|
|
728
|
+
throw error;
|
|
729
|
+
const issues = error instanceof ValidationError && error.issues.length > 0 ? `\n${error.issues.map((issue) => `- ${issue.path.join('.') || '(entry)'}: ${issue.message}`).join('\n')}` : '';
|
|
730
|
+
return refusal(`${error.message}${issues}`);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
const PERSONAL_TOOLS = new Set(['list_submissions', 'list_contacts', 'get_contact', 'create_contact', 'update_contact', 'add_contact_note', 'get_pipeline', 'save_pipeline', 'list_team', 'get_custom_fields', 'save_custom_fields', 'list_deals', 'create_deal', 'update_deal', 'forecast']);
|
|
735
|
+
function listed(one) {
|
|
736
|
+
const { $schema: _schema, ...inputSchema } = z.toJSONSchema(one.input, { io: 'input' });
|
|
737
|
+
return { name: one.name, title: one.title, description: one.description, inputSchema, annotations: { title: one.title, readOnlyHint: one.readOnly === true, destructiveHint: one.name === 'trash_entry' || one.name === 'remove_section' } };
|
|
738
|
+
}
|
|
739
|
+
function refusal(text) {
|
|
740
|
+
return { content: [{ type: 'text', text }], isError: true };
|
|
741
|
+
}
|
|
742
|
+
function failure(id, code, message) {
|
|
743
|
+
return { jsonrpc: '2.0', id: id ?? null, error: { code, message } };
|
|
744
|
+
}
|
|
745
|
+
//# sourceMappingURL=mcp.js.map
|