Skip to content

Commit eea0efb

Browse files
authored
feat(cms): add updateRichText MCP tool for surgical richText edits (#47)
1 parent 7ce143a commit eea0efb

4 files changed

Lines changed: 425 additions & 0 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/** The MCP tool result shape expected by `@payloadcms/plugin-mcp`. */
2+
export type ToolResult = { content: { type: 'text'; text: string }[] }
3+
4+
/** Wrap a value as an MCP text result containing JSON. */
5+
export const jsonResult = (data: unknown): ToolResult => ({
6+
content: [{ text: JSON.stringify(data), type: 'text' as const }],
7+
})
8+
9+
/** Wrap an error as an MCP text result. */
10+
export const errorResult = (message: string, err?: unknown): ToolResult =>
11+
jsonResult({
12+
error: message,
13+
...(err ? { details: err instanceof Error ? err.message : String(err) } : {}),
14+
})
15+
16+
const GLOBAL_PREFIX = 'globals/'
17+
18+
/** A collection slug, or a global addressed as `globals/<slug>`. */
19+
export const parseTarget = (
20+
target: string,
21+
): { type: 'collection'; slug: string } | { type: 'global'; slug: string } =>
22+
target.startsWith(GLOBAL_PREFIX)
23+
? { slug: target.slice(GLOBAL_PREFIX.length), type: 'global' }
24+
: { slug: target, type: 'collection' }
Lines changed: 356 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
1+
import type { CollectionSlug, GlobalSlug, PayloadRequest, SelectType, TypedLocale } from 'payload'
2+
3+
import { z } from 'zod'
4+
5+
import type { LexicalNode, RichTextLexical } from '@/shared/lexicalTypes'
6+
7+
import { errorResult, jsonResult, parseTarget } from './contentHelpers'
8+
9+
const nodeInputSchema = z
10+
.object({
11+
children: z
12+
.array(z.record(z.string(), z.any()))
13+
.optional()
14+
.describe(
15+
'Raw Lexical inline children (text nodes, links, etc.) for mixed or formatted content. When present, text is ignored.',
16+
),
17+
fields: z
18+
.record(z.string(), z.any())
19+
.optional()
20+
.describe('Block fields including blockType. Used when type is "block".'),
21+
items: z
22+
.array(z.string())
23+
.optional()
24+
.describe('List items as plain strings. Used when type is "ul" or "ol".'),
25+
text: z
26+
.string()
27+
.optional()
28+
.describe('Plain text content. Used for paragraph or heading when no children are provided.'),
29+
type: z
30+
.string()
31+
.describe('"paragraph" | "h1"–"h6" | "ul" | "ol" | "hr" | "block" | any Lexical node type'),
32+
})
33+
.describe(
34+
'Node to write. Use shorthand properties (text, items, fields) for common cases, or pass children for raw Lexical inline nodes.',
35+
)
36+
37+
type NodeInput = z.infer<typeof nodeInputSchema>
38+
39+
const argsSchema = z.object({
40+
collection: z
41+
.string()
42+
.describe('Collection slug or "globals/<slug>" to target a global (e.g. "globals/footer").'),
43+
draft: z.boolean().optional().describe('Save as a draft. Defaults to false.'),
44+
field: z
45+
.string()
46+
.describe(
47+
'RichText field name or dot path. Top-level field, e.g. "content"; or a path into an array/group/tab field, e.g. "infoSections.0.richText". Paths cannot descend into lexical block fields.',
48+
),
49+
id: z
50+
.union([z.string(), z.number()])
51+
.optional()
52+
.describe('Document ID (collections only; omit for globals).'),
53+
index: z
54+
.number()
55+
.int()
56+
.min(0)
57+
.optional()
58+
.describe('0-based index in root.children. Required for insert, replace, delete.'),
59+
locale: z
60+
.string()
61+
.optional()
62+
.describe('Locale code (e.g. "en", "de"). Defaults to the default locale.'),
63+
node: nodeInputSchema.optional().describe('Node to write. Required for append, insert, replace.'),
64+
operation: z
65+
.enum(['read', 'append', 'insert', 'replace', 'delete'])
66+
.describe(
67+
'read: return indexed node summary. append: add node at end. insert: add node before index. replace: swap node at index. delete: remove node at index.',
68+
),
69+
})
70+
71+
function makeTextNode(text: string): LexicalNode {
72+
return {
73+
detail: 0,
74+
format: 0,
75+
mode: 'normal',
76+
style: '',
77+
text,
78+
type: 'text',
79+
version: 1,
80+
} as unknown as LexicalNode
81+
}
82+
83+
function toNode(input: NodeInput): LexicalNode {
84+
const { children, fields, items, text, type } = input
85+
const inlineChildren = children ? (children as LexicalNode[]) : text ? [makeTextNode(text)] : []
86+
87+
if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(type)) {
88+
return {
89+
children: inlineChildren,
90+
direction: 'ltr',
91+
format: '',
92+
indent: 0,
93+
tag: type,
94+
type: 'heading',
95+
version: 1,
96+
} as unknown as LexicalNode
97+
}
98+
99+
if (type === 'ul' || type === 'ol') {
100+
return {
101+
children: (items ?? []).map((item, i) => ({
102+
children: [makeTextNode(item)],
103+
direction: 'ltr' as const,
104+
format: '',
105+
indent: 0,
106+
type: 'listitem',
107+
value: i + 1,
108+
version: 1,
109+
})),
110+
direction: 'ltr',
111+
format: '',
112+
indent: 0,
113+
listType: type === 'ul' ? 'bullet' : 'number',
114+
start: 1,
115+
tag: type,
116+
type: 'list',
117+
version: 1,
118+
} as unknown as LexicalNode
119+
}
120+
121+
if (type === 'hr' || type === 'horizontalrule') {
122+
return {
123+
format: '',
124+
indent: 0,
125+
type: 'horizontalrule',
126+
version: 1,
127+
} as LexicalNode
128+
}
129+
130+
if (type === 'block') {
131+
return {
132+
fields: fields ?? {},
133+
format: '',
134+
indent: 0,
135+
type: 'block',
136+
version: 2,
137+
} as unknown as LexicalNode
138+
}
139+
140+
// paragraph or any other node type
141+
return {
142+
children: inlineChildren,
143+
direction: 'ltr',
144+
format: '',
145+
indent: 0,
146+
textFormat: 0,
147+
textStyle: '',
148+
type,
149+
version: 1,
150+
} as unknown as LexicalNode
151+
}
152+
153+
function collectText(node: LexicalNode): string {
154+
const parts: string[] = []
155+
function walk(n: LexicalNode) {
156+
if (n.text) parts.push(n.text)
157+
n.children?.forEach(walk)
158+
}
159+
walk(node)
160+
return parts.join('')
161+
}
162+
163+
function summarizeNode(node: LexicalNode, index: number): Record<string, unknown> {
164+
const n = node as Record<string, unknown> & LexicalNode
165+
const preview = (max = 80) => {
166+
const t = collectText(node)
167+
return t.length > max ? `${t.slice(0, max)}…` : t
168+
}
169+
170+
switch (node.type) {
171+
case 'heading':
172+
return { index, preview: preview(), tag: node.tag, type: 'heading' }
173+
case 'list':
174+
return {
175+
index,
176+
itemCount: node.children?.length ?? 0,
177+
listType: n.listType,
178+
type: 'list',
179+
}
180+
case 'block':
181+
return {
182+
blockType: (n.fields as Record<string, unknown> | undefined)?.blockType ?? 'unknown',
183+
index,
184+
type: 'block',
185+
}
186+
case 'horizontalrule':
187+
return { index, type: 'horizontalrule' }
188+
default:
189+
return { index, preview: preview(), type: node.type }
190+
}
191+
}
192+
193+
export const updateRichTextTool = {
194+
annotations: {
195+
destructiveHint: false,
196+
idempotentHint: false,
197+
readOnlyHint: false,
198+
title: 'Update rich text',
199+
},
200+
description:
201+
'Read or surgically update a single richText field without rewriting the whole document. The field can be a top-level field ("content") or a dot path into an array/group/tab field ("infoSections.0.richText"). Use read to get an index-annotated node summary, then append / insert / replace / delete to modify individual nodes by index. Returns an updated node summary after each mutation. Access is enforced per request by Payload access control.',
202+
handler: async (args: Record<string, unknown>, req: PayloadRequest) => {
203+
try {
204+
const { collection, draft, field, id, index, locale, node, operation } =
205+
argsSchema.parse(args)
206+
const target = parseTarget(collection)
207+
const draftFlag = draft ?? false
208+
const localeTyped = locale as TypedLocale | undefined
209+
// `field` may be a dot path into a nested field, e.g. "infoSections.0.richText".
210+
// Fetch and write back the top-level field so the nested array/group stays intact.
211+
const fieldPath = field.split('.')
212+
const topField = fieldPath[0]
213+
const selectField = { [topField]: true } as unknown as SelectType
214+
215+
// --- Fetch the document (only the target field) ---
216+
let doc: Record<string, unknown>
217+
218+
if (target.type === 'global') {
219+
doc = (await req.payload.findGlobal({
220+
depth: 0,
221+
draft: draftFlag,
222+
locale: localeTyped,
223+
overrideAccess: false,
224+
req,
225+
select: selectField,
226+
slug: target.slug as GlobalSlug,
227+
})) as unknown as Record<string, unknown>
228+
} else {
229+
if (id === undefined) return errorResult('id is required for collection documents.')
230+
const found = await req.payload.findByID({
231+
collection: target.slug as CollectionSlug,
232+
depth: 0,
233+
disableErrors: true,
234+
draft: draftFlag,
235+
id,
236+
locale: localeTyped,
237+
overrideAccess: false,
238+
req,
239+
select: selectField,
240+
})
241+
if (!found) return errorResult(`No ${target.slug} document with id "${id}".`)
242+
doc = found as unknown as Record<string, unknown>
243+
}
244+
245+
// --- Resolve the (possibly nested) richText field ---
246+
let container: Record<string, unknown> = doc
247+
for (let i = 0; i < fieldPath.length - 1; i++) {
248+
const segment = fieldPath[i]
249+
const next = container[segment]
250+
if (next === null || typeof next !== 'object') {
251+
return errorResult(
252+
`Field path "${field}" could not be resolved: segment "${segment}" is missing or not an object/array.`,
253+
)
254+
}
255+
container = next as Record<string, unknown>
256+
}
257+
const leafField = fieldPath[fieldPath.length - 1]
258+
259+
// --- Extract children ---
260+
const richText = container[leafField] as RichTextLexical | null | undefined
261+
if (!richText?.root || !Array.isArray(richText.root.children)) {
262+
return errorResult(
263+
`Field "${field}" was not found or is not a richText field. Use getEntitySchema to verify field names.`,
264+
)
265+
}
266+
const children = richText.root.children as LexicalNode[]
267+
268+
// --- Read ---
269+
if (operation === 'read') {
270+
return jsonResult({
271+
count: children.length,
272+
nodes: children.map(summarizeNode),
273+
})
274+
}
275+
276+
// --- Validate mutation args ---
277+
if ((operation === 'append' || operation === 'insert' || operation === 'replace') && !node) {
278+
return errorResult(`node is required for ${operation}.`)
279+
}
280+
if (
281+
(operation === 'insert' || operation === 'replace' || operation === 'delete') &&
282+
index === undefined
283+
) {
284+
return errorResult(`index is required for ${operation}.`)
285+
}
286+
287+
// --- Apply mutation ---
288+
let newChildren: LexicalNode[]
289+
290+
if (operation === 'append') {
291+
newChildren = [...children, toNode(node!)]
292+
} else if (operation === 'insert') {
293+
if (index! > children.length)
294+
return errorResult(`index ${index} is out of range (0–${children.length}).`)
295+
newChildren = [...children.slice(0, index), toNode(node!), ...children.slice(index)]
296+
} else if (operation === 'replace') {
297+
if (index! >= children.length)
298+
return errorResult(`index ${index} is out of range (0–${children.length - 1}).`)
299+
newChildren = [...children.slice(0, index), toNode(node!), ...children.slice(index! + 1)]
300+
} else {
301+
// delete
302+
if (index! >= children.length)
303+
return errorResult(`index ${index} is out of range (0–${children.length - 1}).`)
304+
newChildren = [...children.slice(0, index), ...children.slice(index! + 1)]
305+
}
306+
307+
const updatedRichText: RichTextLexical = {
308+
...richText,
309+
root: { ...richText.root, children: newChildren },
310+
}
311+
312+
// Write the mutated richText back into its container. For a nested path this
313+
// mutates the fetched top-level field in place, which is then sent as a whole.
314+
container[leafField] = updatedRichText
315+
316+
// The `restrictMcpToDraft` beforeChange hook already forces MCP API-key writes to
317+
// drafts, so this isn't strictly required — but injecting it keeps the intent
318+
// explicit. Harmlessly stripped on collections without drafts enabled.
319+
const writeData: Record<string, unknown> = { [topField]: doc[topField] }
320+
if (draftFlag) writeData._status = 'draft'
321+
322+
// --- Write back ---
323+
if (target.type === 'global') {
324+
await req.payload.updateGlobal({
325+
data: writeData,
326+
depth: 0,
327+
draft: draftFlag,
328+
locale: localeTyped,
329+
overrideAccess: false,
330+
req,
331+
slug: target.slug as GlobalSlug,
332+
})
333+
} else {
334+
await req.payload.update({
335+
collection: target.slug as CollectionSlug,
336+
data: writeData,
337+
depth: 0,
338+
draft: draftFlag,
339+
id: id!,
340+
locale: localeTyped,
341+
overrideAccess: false,
342+
req,
343+
})
344+
}
345+
346+
return jsonResult({
347+
count: newChildren.length,
348+
nodes: newChildren.map(summarizeNode),
349+
})
350+
} catch (err) {
351+
return errorResult('Failed to update rich text', err)
352+
}
353+
},
354+
name: 'updateRichText',
355+
parameters: argsSchema.shape,
356+
}

0 commit comments

Comments
 (0)