@cloudhal/mcp-server 0.7.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +1,18 @@
1
1
  /**
2
- * RFC-0041 §3, §8: typed custom field values over MCP. `create_entry` and `update_entry` check
3
- * them in `precheck` with the store's own checker (changed keys only, unknown keys, a translation's
4
- * copy of a non-localized value, `requiredToPublish` for review and published, image and `asset:`
5
- * references), so a call that the store would refuse never reaches a person. `update_entry` takes
6
- * `fields` as a merge patch (`null` removes a key), and its approval prompt names each typed change
7
- * readably: labels, option labels, dates in their zone, values quoted and truncated.
2
+ * RFC-0041 §3, §8 and RFC-0045 §6: typed custom field values over MCP. `create_entry` and
3
+ * `update_entry` check them in `precheck` with the store's own write plan, run as a dry run
4
+ * (`NodeWriteOptions.dryRun`): values of changed keys, unknown keys, a translation's copy of a
5
+ * non-localized value, `requiredToPublish` for review and published, image and `asset:`
6
+ * references, and RFC-0045's reference targets (a group of this site in an allowed collection,
7
+ * not the entry's own, `where`), repeater items and the 100-references cap. So a call that the
8
+ * store would refuse never reaches a person. `update_entry` takes `fields` as a merge patch (`null`
9
+ * removes a key); `fieldsStrict` and `clearFields` are read in `entry-fields-input.ts`, the
10
+ * approval prompt's wording is `field-prompts.ts`.
8
11
  */
9
-
10
- import {
11
- checkFieldValues,
12
- checkRequiredToPublish,
13
- convertContext,
14
- fieldDefinitions,
15
- fieldLabel,
16
- normalizeThroughMarkers,
17
- optionLabel,
18
- refuseFieldIssues,
19
- } from "@cloudhal/core-ts/fields";
20
- import { fieldAssetIssues, fieldAssetRefs } from "@cloudhal/core-ts/media";
12
+
13
+
21
14
  import { isReservedKey } from "@cloudhal/core-ts/names";
22
- import { quote, ToolError } from "./common.js";
15
+ import { ToolError, toToolError } from "./common.js";
23
16
 
24
17
 
25
18
 
@@ -52,143 +45,22 @@ export function mergeFields(current , patch )
52
45
  return next;
53
46
  }
54
47
 
55
- const isTranslation = (e ) =>
56
- !!e.translation && e.translation.group !== e.id && e.translation.source?.siteId === undefined;
57
-
58
- /** The same-site original of a translation (as the store reads it). */
59
- async function originalOf(
60
- ctx ,
61
- entry ,
62
- ) {
63
- if (!isTranslation(entry)) return undefined;
64
- const original = await ctx.store.getContentEntry(entry.translation?.group );
65
- return original?.siteId === entry.siteId ? original : undefined;
66
- }
67
-
68
- /** What an entry write would store, for the check. */
69
-
70
-
71
-
72
-
73
-
74
-
75
-
76
-
77
48
  /**
78
- * The store's field checks, run before anyone is asked: throws `invalid_fields`, `unknown_field`,
79
- * `field_not_localized`, `required_field` or `too_large` with every issue at its path.
49
+ * The store's plan-time checks of a write, without writing (`dryRun`): throws what the write
50
+ * would, as tool errors (`invalid_fields`, `unknown_field`, `unknown_entry`, `required_field`,
51
+ * `required_term`, …, every issue at its path), else returns the entry as the store would write
52
+ * it (canonical reference ids, values through the markers). `update` is the stored entry with
53
+ * the call's changes.
80
54
  */
81
- export async function checkEntryFields(ctx , check ) {
82
- const { site, stored } = check;
83
- let next = check.next;
84
- const defs = fieldDefinitions(site, next.collection);
85
- // While a field operation runs, a write goes through its marker (as the store normalizes it).
86
- if (defs.some((d) => d.migration)) {
87
- const fields = normalizeThroughMarkers(defs, next.fields, {
88
- convert: convertContext(site),
89
- translation: isTranslation(next),
90
- });
91
- if (fields) next = { ...next, fields };
92
- }
93
- const values = next.fields ?? {};
94
- const previous = stored?.collection === next.collection ? (stored.fields ?? {}) : undefined;
95
- if (defs.length === 0) {
96
- if (!previous || JSON.stringify(previous) !== JSON.stringify(values))
97
- refuseFieldIssues(checkFieldValues([], { values }));
98
- return;
99
- }
100
- const original = await originalOf(ctx, next);
101
- const issues = checkFieldValues(defs, {
102
- values,
103
- previous,
104
- original: original ? { id: original.id, values: original.fields ?? {} } : undefined,
105
- blocks: ctx.store.blocks,
106
- });
107
- // The store's asset check: new references name usable files of the site.
108
- issues.push(
109
- ...(await fieldAssetIssues({
110
- defs,
111
- refs: fieldAssetRefs(defs, values),
112
- kept: stored ? fieldAssetRefs(fieldDefinitions(site, stored.collection), stored.fields) : [],
113
- lookup: (ids) => ctx.store.getAssets(site.id, ids),
114
- skip: new Set(issues.map((i) => i.path.split("/").slice(0, 2).join("/"))),
115
- })),
116
- );
117
- issues.push(...checkRequiredToPublish(site, { ...next, fields: values }, original));
118
- refuseFieldIssues(issues);
119
- }
120
-
121
- /** "5 Nov 2026" (a calendar day: no zone). */
122
- function day(value ) {
123
- const d = new Date(`${value}T00:00:00Z`);
124
- if (Number.isNaN(d.getTime())) return quote(value);
125
- return new Intl.DateTimeFormat("en-GB", {
126
- day: "numeric",
127
- month: "short",
128
- year: "numeric",
129
- timeZone: "UTC",
130
- }).format(d);
131
- }
132
-
133
- /** "5 Nov 2026 19:30 Istanbul" (the wall clock in the value's own zone). */
134
- function instant(value ) {
135
- const v = value ;
136
- if (typeof v?.at !== "string" || typeof v.timeZone !== "string") return quote(JSON.stringify(v));
137
- const at = new Date(v.at);
138
- if (Number.isNaN(at.getTime())) return quote(v.at);
55
+ export async function checkEntryWrite(
56
+ ctx ,
57
+ write ,
58
+ ) {
139
59
  try {
140
- const parts = new Intl.DateTimeFormat("en-GB", {
141
- day: "numeric",
142
- month: "short",
143
- year: "numeric",
144
- hour: "2-digit",
145
- minute: "2-digit",
146
- hourCycle: "h23",
147
- timeZone: v.timeZone,
148
- }).format(at);
149
- const city = (v.timeZone.split("/").pop() ?? v.timeZone).replace(/_/g, " ");
150
- return `${parts.replace(",", "")} ${city}`;
151
- } catch {
152
- return `${quote(v.at)} ${quote(v.timeZone)}`;
153
- }
154
- }
155
-
156
- /** A value as a person reads it in an approval prompt (agent text quoted and truncated). */
157
- export function describeFieldValue(
158
- def ,
159
- value ,
160
- locale ,
161
- ) {
162
- if (!def) return `"${quote(JSON.stringify(value) ?? "")}"`;
163
- switch (def.type) {
164
- case "number":
165
- return typeof value === "number" ? String(value) : `"${quote(String(value))}"`;
166
- case "boolean":
167
- return value === true ? "yes" : "no";
168
- case "date":
169
- return typeof value === "string" ? day(value) : `"${quote(String(value))}"`;
170
- case "datetime":
171
- return instant(value);
172
- case "select": {
173
- const list = Array.isArray(value) ? value : [value];
174
- return list.map((v) => quote(optionLabel(def, String(v), locale, locale))).join(", ");
175
- }
176
- default:
177
- return `"${quote(typeof value === "string" ? value : JSON.stringify(value))}"`;
60
+ if ("update" in write)
61
+ return await ctx.store.updateContentEntry(write.update, { dryRun: true });
62
+ return await ctx.store.createContentEntry(write.create, { dryRun: true });
63
+ } catch (e) {
64
+ throw toToolError(e);
178
65
  }
179
66
  }
180
-
181
- /** "startsAt → 5 Nov 2026 19:30 Istanbul, format → Talk, Workshop, notes removed". */
182
- export function describeFieldPatch(site , collection , patch ) {
183
- const defs = new Map(fieldDefinitions(site, collection).map((d) => [d.key, d]));
184
- const locale = site.defaultLocale;
185
- return Object.entries(patch)
186
- .map(([key, value]) => {
187
- const def = defs.get(key);
188
- const name = def ? `"${quote(fieldLabel(def, locale, locale), 40)}" (${key})` : key;
189
- return value === null
190
- ? `${name} removed`
191
- : `${name} → ${describeFieldValue(def, value, locale)}`;
192
- })
193
- .join(", ");
194
- }
@@ -4,15 +4,25 @@
4
4
  * list values are ready), and `limit`/`cursor` paging: with `orderBy` the store pages, without it
5
5
  * the list keeps its order (last updated first) and is paged here; without `limit` it is unpaged,
6
6
  * as before. Problems are refused as `invalid_query` with their paths (`where/0/value`).
7
+ *
8
+ * RFC-0045 §6: each entry carries its `groupId` (`COALESCE(translation.group, id)`), the value a
9
+ * reference field stores. Reference fields are not list fields until rollout step 8, so `where`
10
+ * cannot filter by them yet (`checkFieldQuery` refuses them).
7
11
  */
8
12
  import type { ContentEntry } from "@cloudhal/core-contracts";
9
13
  import { type EntryQuery } from "@cloudhal/core-ts";
10
14
  import type { JsonSchema, ToolContext } from "./common.js";
11
15
  export declare const ENTRY_QUERY_INPUT: Record<string, JsonSchema>;
16
+ /** A listed entry: the contract's entry plus its translation group id. */
17
+ export declare const ENTRY_LISTED: JsonSchema;
18
+ type Listed = ContentEntry & {
19
+ groupId: string;
20
+ };
12
21
  export interface EntryListAnswer {
13
- entries: ContentEntry[];
22
+ entries: Listed[];
14
23
  total?: number;
15
24
  nextCursor?: string;
16
25
  }
17
26
  /** The entries of `base` matching the call's field query, ordered and paged. */
18
27
  export declare function listEntries(ctx: ToolContext, siteId: string, base: EntryQuery, a: Record<string, unknown>): Promise<EntryListAnswer>;
28
+ export {};
@@ -4,6 +4,10 @@
4
4
  * list values are ready), and `limit`/`cursor` paging: with `orderBy` the store pages, without it
5
5
  * the list keeps its order (last updated first) and is paged here; without `limit` it is unpaged,
6
6
  * as before. Problems are refused as `invalid_query` with their paths (`where/0/value`).
7
+ *
8
+ * RFC-0045 §6: each entry carries its `groupId` (`COALESCE(translation.group, id)`), the value a
9
+ * reference field stores. Reference fields are not list fields until rollout step 8, so `where`
10
+ * cannot filter by them yet (`checkFieldQuery` refuses them).
7
11
  */
8
12
 
9
13
  import { SiteSchema } from "@cloudhal/core-contracts";
@@ -13,7 +17,9 @@ import {
13
17
  InvariantError,
14
18
  queryContentEntries,
15
19
  } from "@cloudhal/core-ts";
20
+ import { memberGroup } from "@cloudhal/core-ts/fields";
16
21
 
22
+ import { ENTRY } from "./content-shared.js";
17
23
 
18
24
  const DEFS = SiteSchema.$defs ;
19
25
 
@@ -66,8 +72,23 @@ function decodeCursor(raw ) {
66
72
  return m ? Number(m[1]) : refuse("cursor", "not a cursor this list returned");
67
73
  }
68
74
 
75
+ /** A listed entry: the contract's entry plus its translation group id. */
76
+ export const ENTRY_LISTED = {
77
+ ...ENTRY,
78
+ properties: {
79
+ ...(ENTRY.properties ),
80
+ groupId: {
81
+ type: "string",
82
+ description:
83
+ "The entry's translation group id: what a reference field stores to point at it (RFC-0045)",
84
+ },
85
+ },
86
+ };
87
+
88
+
89
+
69
90
 
70
-
91
+
71
92
 
72
93
 
73
94
 
@@ -103,7 +124,8 @@ export async function listEntries(
103
124
  ...(paged ? { limit, offset } : {}),
104
125
  now: (ctx.now?.() ?? new Date()).getTime(),
105
126
  });
106
- const ordered = orderBy ? result.entries : result.entries.sort(byUpdated);
127
+ const sorted = orderBy ? result.entries : result.entries.sort(byUpdated);
128
+ const ordered = sorted.map((e) => ({ ...e, groupId: memberGroup(e) }));
107
129
  if (limit === undefined) return { entries: ordered };
108
130
  const page = paged ? ordered : ordered.slice(offset, offset + limit);
109
131
  const total = paged ? result.total : ordered.length;
@@ -1,7 +1,8 @@
1
1
  /** Article (content entry) tools: list, read, create, update, correct and delete. */
2
2
 
3
3
 
4
-
4
+
5
+ import { fieldDefinitions } from "@cloudhal/core-ts/fields";
5
6
  import { requireRegistered } from "./collection-tools.js";
6
7
  import {
7
8
  autoSnapshot,
@@ -13,6 +14,7 @@ import {
13
14
  requireSite,
14
15
  SLUG_PATTERN,
15
16
  str,
17
+
16
18
 
17
19
  ToolError,
18
20
  } from "./common.js";
@@ -26,18 +28,93 @@ import {
26
28
  unknownBlocks,
27
29
  unknownBlocksOf,
28
30
  } from "./content-shared.js";
31
+ import { checkEntryWrite, FIELDS_INPUT, FIELDS_PATCH, mergeFields } from "./entry-fields.js";
29
32
  import {
30
- checkEntryFields,
31
- describeFieldPatch,
32
- FIELDS_INPUT,
33
- FIELDS_PATCH,
34
- mergeFields,
35
- } from "./entry-fields.js";
36
- import { ENTRY_QUERY_INPUT, listEntries } from "./entry-list.js";
33
+ CLEAR_FIELDS_INPUT,
34
+ DROPPED_ITEMS_OUTPUT,
35
+ FIELDS_STRICT_INPUT,
36
+
37
+ fieldsInputOf,
38
+ } from "./entry-fields-input.js";
39
+ import { ENTRY_LISTED, ENTRY_QUERY_INPUT, listEntries } from "./entry-list.js";
37
40
  import { entryTerms, reportDeltas } from "./entry-terms.js";
41
+ import { describeFieldPatch } from "./field-prompts.js";
38
42
  import { menuHint, menuItemsHiddenBy } from "./menu-tools.js";
43
+ import { listReferencesTool } from "./reference-tools.js";
39
44
  import { assignmentDeltas, describeDeltas, TAGS_INPUT, TERMS_INPUT, termLookup } from "./terms.js";
40
45
 
46
+ /** The call's typed field values (`fields`, `fieldsStrict`, `clearFields`) for `collection`. */
47
+ const fieldsOf = (
48
+ a ,
49
+ site ,
50
+ collection ,
51
+ stored ,
52
+ ) =>
53
+ fieldsInputOf(
54
+ a,
55
+ fieldDefinitions(site, collection),
56
+ stored?.collection === collection ? stored.fields : undefined,
57
+ stored ? "update" : "create",
58
+ );
59
+
60
+ const dropped = (input ) =>
61
+ input.droppedItems.length ? { droppedItems: input.droppedItems } : {};
62
+
63
+ /** `create_entry`'s new draft entry from its arguments (precheck and write). */
64
+ async function newEntry(
65
+ ctx ,
66
+ at ,
67
+ ) {
68
+ const { a, site, fields } = at;
69
+ const { terms, tags } = await entryTerms(ctx, site, undefined, a);
70
+ return {
71
+ siteId: site.id,
72
+ collection: (a.collection ) ?? "posts",
73
+ slug: a.slug ,
74
+ locale: (a.locale ) ?? site.defaultLocale,
75
+ status: "draft",
76
+ title: a.title ,
77
+ ...(a.summary ? { summary: a.summary } : {}),
78
+ body: { format: "markdown", value: a.body },
79
+ fields,
80
+ tags,
81
+ ...(terms ? { terms } : {}),
82
+ ...(a.coverImage ? { coverImage: coverImage(a.coverImage) } : {}),
83
+ author: ctx.principal.actor,
84
+ };
85
+ }
86
+
87
+ /** `update_entry`'s next entry: the stored one with the call's changes (precheck, prompt, write). */
88
+ async function updatedEntry(
89
+ ctx ,
90
+ at ,
91
+ ) {
92
+ const { a, site, entry, input } = at;
93
+ const { terms, tags } = await entryTerms(ctx, site, entry, a);
94
+ const { terms: _old, coverImage: oldCover, ...rest } = entry;
95
+ const cover =
96
+ a.coverImage === undefined
97
+ ? oldCover
98
+ : a.coverImage === null
99
+ ? undefined
100
+ : coverImage(a.coverImage);
101
+ return {
102
+ ...rest,
103
+ ...(cover ? { coverImage: cover } : {}),
104
+ ...(a.title ? { title: a.title } : {}),
105
+ ...(a.summary !== undefined ? { summary: a.summary } : {}),
106
+ ...(a.body !== undefined ? { body: { ...entry.body, value: a.body } } : {}),
107
+ ...(input.patch !== undefined ? { fields: mergeFields(entry.fields, input.patch) } : {}),
108
+ ...(a.slug ? { slug: a.slug } : {}),
109
+ tags,
110
+ ...(terms ? { terms } : {}),
111
+ ...(a.status ? { status: a.status } : {}),
112
+ ...(a.status === "published" && !entry.publishedAt
113
+ ? { publishedAt: new Date().toISOString() }
114
+ : {}),
115
+ };
116
+ }
117
+
41
118
  const listEntriesTool = {
42
119
  name: "list_entries",
43
120
  title: "List articles",
@@ -67,7 +144,7 @@ const listEntriesTool = {
67
144
  ),
68
145
  outputSchema: obj(
69
146
  {
70
- entries: { type: "array", items: ENTRY },
147
+ entries: { type: "array", items: ENTRY_LISTED },
71
148
  total: { type: "integer" },
72
149
  nextCursor: { type: "string" },
73
150
  },
@@ -124,7 +201,7 @@ const createEntryTool = {
124
201
  name: "create_entry",
125
202
  title: "Create article",
126
203
  description:
127
- "Create a draft content entry (markdown body) in an existing collection (list_collections; a new one needs create_collection first), optionally filed under existing terms (`terms`; see list_taxonomies and list_terms). Typed custom fields go in `fields`, following the collection's fieldsSchema from list_collections; invalid values are refused with their paths. Snapshots afterwards.",
204
+ "Create a draft content entry (markdown body) in an existing collection (list_collections; a new one needs create_collection first), optionally filed under existing terms (`terms`; see list_taxonomies and list_terms). Typed custom fields go in `fields`, following the collection's fieldsSchema from list_collections, or for strict structured output in `fieldsStrict` (its fieldsSchemaStrict: null means no value); invalid values, and reference fields naming entries outside their collections, are refused with their paths. Snapshots afterwards.",
128
205
  inputSchema: obj(
129
206
  {
130
207
  siteId: id,
@@ -140,13 +217,20 @@ const createEntryTool = {
140
217
  tags: TAGS_INPUT,
141
218
  coverImage: COVER_INPUT,
142
219
  fields: FIELDS_INPUT,
220
+ fieldsStrict: FIELDS_STRICT_INPUT,
143
221
  },
144
222
  ["siteId", "slug", "title", "body"],
145
223
  ),
146
- outputSchema: obj({ entry: ENTRY, snapshot: SNAPSHOT, hint: { type: "string" }, unknownBlocks }, [
147
- "entry",
148
- "snapshot",
149
- ]),
224
+ outputSchema: obj(
225
+ {
226
+ entry: ENTRY,
227
+ snapshot: SNAPSHOT,
228
+ hint: { type: "string" },
229
+ unknownBlocks,
230
+ droppedItems: DROPPED_ITEMS_OUTPUT,
231
+ },
232
+ ["entry", "snapshot"],
233
+ ),
150
234
  annotations: {
151
235
  readOnlyHint: false,
152
236
  destructiveHint: false,
@@ -162,15 +246,9 @@ const createEntryTool = {
162
246
  await requireRegistered(ctx, a.siteId , collection);
163
247
  const site = await ctx.store.getSite(a.siteId );
164
248
  if (!site) return;
165
- await checkEntryFields(ctx, {
166
- site,
167
- next: {
168
- id: "",
169
- siteId: site.id,
170
- collection,
171
- status: "draft",
172
- fields: (a.fields ) ?? {},
173
- },
249
+ const input = fieldsOf(a, site, collection);
250
+ await checkEntryWrite(ctx, {
251
+ create: await newEntry(ctx, { a, site, fields: input.patch ?? {} }),
174
252
  });
175
253
  },
176
254
  handler: async (a, ctx) => {
@@ -179,26 +257,11 @@ const createEntryTool = {
179
257
  author: ctx.principal.actor,
180
258
  status: "draft",
181
259
  });
182
- const { terms, tags } = await entryTerms(ctx, site, undefined, a);
260
+ const collection = (a.collection ) ?? "posts";
261
+ const input = fieldsOf(a, site, collection);
262
+ const draft = await newEntry(ctx, { a, site, fields: input.patch ?? {} });
183
263
  try {
184
- const entry = await ctx.store.createContentEntry(
185
- {
186
- siteId: site.id,
187
- collection: (a.collection ) ?? "posts",
188
- slug: a.slug ,
189
- locale: (a.locale ) ?? site.defaultLocale,
190
- status: "draft",
191
- title: a.title ,
192
- ...(a.summary ? { summary: a.summary } : {}),
193
- body: { format: "markdown", value: a.body },
194
- fields: (a.fields ) ?? {},
195
- tags,
196
- ...(terms ? { terms } : {}),
197
- ...(a.coverImage ? { coverImage: coverImage(a.coverImage) } : {}),
198
- author: ctx.principal.actor,
199
- },
200
- { writer: mcpWriter(ctx) },
201
- );
264
+ const entry = await ctx.store.createContentEntry(draft, { writer: mcpWriter(ctx) });
202
265
  await reportDeltas(ctx, undefined, entry);
203
266
  const snapshot = await autoSnapshot(ctx, site.id, "create_entry");
204
267
  const hint = await menuHint(ctx, site.id, { kind: "contentEntry", id: entry.id });
@@ -206,6 +269,7 @@ const createEntryTool = {
206
269
  entry,
207
270
  snapshot,
208
271
  ...(hint ? { hint } : {}),
272
+ ...dropped(input),
209
273
  ...unknownBlocksOf(ctx, { markdown: entryMarkdown(entry) }),
210
274
  };
211
275
  } catch (e) {
@@ -218,7 +282,7 @@ const updateEntryTool = {
218
282
  name: "update_entry",
219
283
  title: "Update article",
220
284
  description:
221
- "Update title, summary, body, slug, status (draft → review → published), terms (`terms`: add, remove or set categories and tags by id, slug or name) or typed custom fields (`fields`, a merge patch: null removes a key; see the collection's fieldsSchema in list_collections) of an entry. Review and published articles need a primary term in every required taxonomy and every field marked needed to publish. Requires the current `rev`. Changing a published article's slug leaves a redirect. Snapshots afterwards.",
285
+ "Update title, summary, body, slug, status (draft → review → published), terms (`terms`: add, remove or set categories and tags by id, slug or name) or typed custom fields of an entry: `fields`, a merge patch (null removes a key; see the collection's fieldsSchema in list_collections), or for strict structured output `fieldsStrict` (its fieldsSchemaStrict: null leaves a value as it is), and `clearFields` to remove keys. A given reference or repeater value replaces the whole value. Review and published articles need a primary term in every required taxonomy and every field marked needed to publish. Requires the current `rev`. Changing a published article's slug leaves a redirect. Snapshots afterwards.",
222
286
  inputSchema: obj(
223
287
  {
224
288
  siteId: id,
@@ -237,10 +301,15 @@ const updateEntryTool = {
237
301
  },
238
302
  status: { type: "string", enum: ["draft", "review", "published", "archived"] },
239
303
  fields: FIELDS_PATCH,
304
+ fieldsStrict: FIELDS_STRICT_INPUT,
305
+ clearFields: CLEAR_FIELDS_INPUT,
240
306
  },
241
307
  ["siteId", "entryId", "rev"],
242
308
  ),
243
- outputSchema: obj({ entry: ENTRY, snapshot: SNAPSHOT, unknownBlocks }, ["entry", "snapshot"]),
309
+ outputSchema: obj(
310
+ { entry: ENTRY, snapshot: SNAPSHOT, unknownBlocks, droppedItems: DROPPED_ITEMS_OUTPUT },
311
+ ["entry", "snapshot"],
312
+ ),
244
313
  annotations: {
245
314
  readOnlyHint: false,
246
315
  destructiveHint: false,
@@ -256,11 +325,11 @@ const updateEntryTool = {
256
325
  if (!entry || entry.siteId !== a.siteId) return;
257
326
  const status = (a.status ) ?? entry.status;
258
327
  if (ctx.limit) await entryLimitCheck(ctx, "update", entry, { author: entry.author, status });
259
- if (a.fields === undefined && status === entry.status) return;
260
328
  const site = await ctx.store.getSite(entry.siteId);
261
329
  if (!site) return;
262
- const fields = mergeFields(entry.fields, (a.fields ) ?? {});
263
- await checkEntryFields(ctx, { site, next: { ...entry, status, fields }, stored: entry });
330
+ // The store's own plan of exactly this write (values, references, terms, holds), dry.
331
+ const input = fieldsOf(a, site, entry.collection, entry);
332
+ await checkEntryWrite(ctx, { update: await updatedEntry(ctx, { a, site, entry, input }) });
264
333
  },
265
334
  approvalPrompt: async (a, ctx) => {
266
335
  const entry = await ctx.store.getContentEntry(a.entryId );
@@ -280,10 +349,17 @@ const updateEntryTool = {
280
349
  : "cover image"
281
350
  : "",
282
351
  ].filter(Boolean);
283
- if (a.fields && site && Object.keys(a.fields).length)
352
+ const input = site ? fieldsOf(a, site, entry.collection, entry) : undefined;
353
+ const patch = input?.patch;
354
+ if (site && input && patch && Object.keys(patch).length) {
355
+ // What the store would write (canonical ids), as the precheck planned it.
356
+ const planned = await checkEntryWrite(ctx, {
357
+ update: await updatedEntry(ctx, { a, site, entry, input }),
358
+ }).catch(() => undefined);
284
359
  changes.push(
285
- `fields: ${describeFieldPatch(site, entry.collection, a.fields )}`,
360
+ `fields: ${await describeFieldPatch(ctx, site, entry, { patch, planned: planned?.fields })}`,
286
361
  );
362
+ }
287
363
  if (a.terms || a.tags) {
288
364
  try {
289
365
  const { terms } = await entryTerms(ctx, site , entry, a);
@@ -318,31 +394,8 @@ const updateEntryTool = {
318
394
  author: entry.author,
319
395
  status: (a.status ) ?? entry.status,
320
396
  });
321
- const { terms, tags } = await entryTerms(ctx, site, entry, a);
322
- const { terms: _old, coverImage: oldCover, ...rest } = entry;
323
- const cover =
324
- a.coverImage === undefined
325
- ? oldCover
326
- : a.coverImage === null
327
- ? undefined
328
- : coverImage(a.coverImage);
329
- const next = {
330
- ...rest,
331
- ...(cover ? { coverImage: cover } : {}),
332
- ...(a.title ? { title: a.title } : {}),
333
- ...(a.summary !== undefined ? { summary: a.summary } : {}),
334
- ...(a.body !== undefined ? { body: { ...entry.body, value: a.body } } : {}),
335
- ...(a.fields !== undefined
336
- ? { fields: mergeFields(entry.fields, a.fields ) }
337
- : {}),
338
- ...(a.slug ? { slug: a.slug } : {}),
339
- tags,
340
- ...(terms ? { terms } : {}),
341
- ...(a.status ? { status: a.status } : {}),
342
- ...(a.status === "published" && !entry.publishedAt
343
- ? { publishedAt: new Date().toISOString() }
344
- : {}),
345
- };
397
+ const input = fieldsOf(a, site, entry.collection, entry);
398
+ const next = await updatedEntry(ctx, { a, site, entry, input });
346
399
  try {
347
400
  const saved = await ctx.store.updateContentEntry(next, { writer: mcpWriter(ctx) });
348
401
  await reportDeltas(ctx, entry, saved);
@@ -350,6 +403,7 @@ const updateEntryTool = {
350
403
  return {
351
404
  entry: saved,
352
405
  snapshot,
406
+ ...dropped(input),
353
407
  ...unknownBlocksOf(ctx, { markdown: entryMarkdown(saved) }),
354
408
  };
355
409
  } catch (e) {
@@ -432,7 +486,8 @@ const addCorrectionTool = {
432
486
  const deleteEntryTool = {
433
487
  name: "delete_entry",
434
488
  title: "Delete article",
435
- description: "Delete a content entry. Destructive: requires approval. Snapshots afterwards.",
489
+ description:
490
+ "Delete a content entry. Destructive: requires approval. Refused (entry_referenced, with the referrers in details) while published entries show it through a reference field and it is the last entry of its translation group in the site; list_references shows them. Snapshots afterwards.",
436
491
  inputSchema: obj({ siteId: id, entryId: id, rev: { type: "integer", minimum: 0 } }, [
437
492
  "siteId",
438
493
  "entryId",
@@ -447,10 +502,17 @@ const deleteEntryTool = {
447
502
  },
448
503
  scopes: ["content:write"],
449
504
  own: "entry",
505
+ // RFC-0045 §6: a delete that would strand a published reference is refused before anyone is
506
+ // asked, by the store's own plan (`dryRun`).
450
507
  precheck: async (a, ctx) => {
451
- if (!ctx.limit) return;
452
508
  const entry = await ctx.store.getContentEntry(a.entryId );
453
- if (entry && entry.siteId === a.siteId) await entryLimitCheck(ctx, "delete", entry);
509
+ if (!entry || entry.siteId !== a.siteId) return;
510
+ if (ctx.limit) await entryLimitCheck(ctx, "delete", entry);
511
+ try {
512
+ await ctx.store.deleteContentEntry(entry, { dryRun: true });
513
+ } catch (e) {
514
+ mapError(e);
515
+ }
454
516
  },
455
517
  approvalPrompt: async (a, ctx) => {
456
518
  const entry = await ctx.store.getContentEntry(a.entryId );
@@ -478,6 +540,8 @@ export function entryTools() {
478
540
  return [
479
541
  listEntriesTool,
480
542
  getEntryTool,
543
+ // RFC-0045 §6: an entry's references, both directions.
544
+ listReferencesTool,
481
545
  createEntryTool,
482
546
  updateEntryTool,
483
547
  addCorrectionTool,