@cloudhal/mcp-server 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,7 +21,7 @@ import { createCloudhalMcpHandler } from "@cloudhal/mcp-server/http"; // fet
21
21
  ## Tool reference
22
22
 
23
23
  <!-- tools:start (generated by scripts/mcp-tools-doc.ts; do not edit) -->
24
- **105 tools**, in the order the server lists them.
24
+ **109 tools**, in the order the server lists them.
25
25
 
26
26
  | Tool | Scopes | Kind | Approval | What it does |
27
27
  |---|---|---|---|---|
@@ -39,7 +39,7 @@ import { createCloudhalMcpHandler } from "@cloudhal/mcp-server/http"; // fet
39
39
  | `list_entries` | `content:read` | read | — | Content entries, newest first. |
40
40
  | `get_entry` | `content:read` | read | — | One content entry with its body and current revision. |
41
41
  | `create_entry` | `content:write` | write | by the key's mode | 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`;… |
42
- | `update_entry` | `content:write` | write | by the key's mode | Update title, summary, body, slug, status (draft → review → published) or terms (`terms`: add, remove or set categories and tags by id, slug or name) of an entry. |
42
+ | `update_entry` | `content:write` | write | by the key's mode | 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`… |
43
43
  | `add_correction` | `content:write` | write | by the key's mode | Append a correction, clarification or update notice to an article (RFC-0019 §2) when a published story changed in substance. |
44
44
  | `delete_entry` | `content:write` | write (destructive) | by the key's mode | Delete a content entry. |
45
45
  | `list_translations` | `content:read` | read | — | Every language version of a page or entry (its translation group): locale, status, method (original, human, machine, machine-reviewed), whether it is stale (its source changed sin… |
@@ -79,7 +79,11 @@ import { createCloudhalMcpHandler } from "@cloudhal/mcp-server/http"; // fet
79
79
  | `delete_redirect` | `site:write` | write (destructive) | always a person | Delete a redirect; its old path then answers 404 unless something serves it. |
80
80
  | `list_collections` | `content:read` | read | — | The site's collections (RFC-0040): declared ones, ones that already have entries, and posts. |
81
81
  | `create_collection` | `site:write` | write | always a person | Declare a new collection (RFC-0040), e.g. events, team or jobs, with its names in the site's default locale (labels), an optional icon, permalink (/&lt;prefix>/{slug}, default /&lt;key>… |
82
- | `update_collection` | `site:write` | write | always a person | Change a collection's names (merged per locale), icon, feed, sitemap or default sort (RFC-0040). |
82
+ | `update_collection` | `site:write` | write | always a person | Change a collection's names (merged per locale), icon, feed, sitemap, default sort (RFC-0040) or its typed custom fields (`fields`, the whole list; RFC-0041). |
83
+ | `rename_field` | `site:write`, `content:write` | write | always a person | Rename a typed custom field's key (RFC-0041 §6): every entry's value moves from `from` to `to`; nothing is converted. |
84
+ | `change_field_type` | `site:write`, `content:write` | write (destructive) | always a person | Change a typed custom field's type, or a select's multiple (RFC-0041 §6), converting every value by a closed table (text↔richText, text↔number, text↔select, text↔url, date↔datetim… |
85
+ | `set_field_localized` | `site:write`, `content:write` | write | always a person | Make a typed custom field localized (each language version has its own value; translations fall back to the original's) or shared (only the original holds it; translations' own co… |
86
+ | `remove_field` | `site:write`, `content:write` | write (destructive) | always a person | Remove a typed custom field (RFC-0041 §6): its value is deleted from every entry, then its definition. |
83
87
  | `set_collection_permalink` | `site:write` | write | always a person | Move where a collection's entries live (RFC-0038): permalink "/blog/{slug}" puts collection "posts" at /blog/&lt;slug>; null goes back to the default /&lt;collection>/{slug}. |
84
88
  | `list_menus` | `site:read` | read | — | The site's navigation menus (primary = header, footer, sidebar, custom keys) with id, rev, maxDepth, item count and how many items are hidden on the site. |
85
89
  | `get_menu` | `site:read` | read | — | One menu: the stored tree (send its rev back when writing) and, per item for a locale, whether the site shows it (`state`), why not (`reason`: missing, unpublished, other-locale,… |
@@ -0,0 +1,22 @@
1
+ /**
2
+ * RFC-0041 §8 for the collection tools: `list_collections` shows each collection's field
3
+ * definitions and the JSON Schema of its values (in the caller's locale), and `update_collection`
4
+ * takes the whole `fields` list for free edits (§6). Changes that could lose values are refused by
5
+ * the store's guard (`field_change_needs_operation`) and go through the operation tools instead.
6
+ */
7
+ import type { CollectionSettings, FieldDefinition, Site } from "@cloudhal/core-contracts";
8
+ import { type JsonSchema } from "./common.js";
9
+ /** `update_collection`'s `fields`: the contract's definitions, minus the operation marker. */
10
+ export declare const FIELD_DEFINITIONS_INPUT: JsonSchema;
11
+ /**
12
+ * The settings with `fields` replaced by the agent's list. A running operation's marker stays on
13
+ * its field (agents never write it), so editing labels meanwhile is not read as touching it.
14
+ */
15
+ export declare function withFields(current: CollectionSettings, next: CollectionSettings, fields: FieldDefinition[]): CollectionSettings;
16
+ /** One line for the approval prompt: which fields are added, changed, removed or reordered. */
17
+ export declare function describeFieldEdits(before: readonly FieldDefinition[], after: readonly FieldDefinition[], locale: string): string | undefined;
18
+ /** What `list_collections` adds per collection that has definitions. */
19
+ export declare function fieldsView(site: Site, key: string, locale: string): {
20
+ fields: FieldDefinition[];
21
+ fieldsSchema: JsonSchema;
22
+ } | Record<string, never>;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * RFC-0041 §8 for the collection tools: `list_collections` shows each collection's field
3
+ * definitions and the JSON Schema of its values (in the caller's locale), and `update_collection`
4
+ * takes the whole `fields` list for free edits (§6). Changes that could lose values are refused by
5
+ * the store's guard (`field_change_needs_operation`) and go through the operation tools instead.
6
+ */
7
+
8
+ import { SiteSchema } from "@cloudhal/core-contracts";
9
+ import { fieldLabel, fieldsJsonSchema } from "@cloudhal/core-ts/fields";
10
+ import { quote } from "./common.js";
11
+
12
+ const DEFS = SiteSchema.$defs ;
13
+ const VARIANTS = (DEFS.FieldDefinition ).oneOf ;
14
+
15
+ /** A definition variant without `migration`: only field operations write the marker. */
16
+ function withoutMarker(variant ) {
17
+ const { migration: _m, ...properties } = variant.properties ;
18
+ return { ...variant, properties };
19
+ }
20
+
21
+ /** `update_collection`'s `fields`: the contract's definitions, minus the operation marker. */
22
+ export const FIELD_DEFINITIONS_INPUT = {
23
+ type: "array",
24
+ maxItems: 30,
25
+ description:
26
+ "The collection's typed custom fields, the whole list in form order ([] removes them all). Free edits only: add fields, reorder, change labels and help, add select options or change their labels, toggle multiline, searchable or requiredToPublish, change maxLength/minimum/maximum. Renaming a key, changing a type, localized or multiple, and dropping a key or option still in use need rename_field, change_field_type, set_field_localized or remove_field.",
27
+ items: { $ref: "#/$defs/FieldDefinition" },
28
+ $defs: {
29
+ FieldDefinition: {
30
+ ...DEFS.FieldDefinition,
31
+ oneOf: VARIANTS.map(withoutMarker),
32
+ },
33
+ FieldKey: DEFS.FieldKey,
34
+ FieldLabel: DEFS.FieldLabel,
35
+ FieldLabels: DEFS.FieldLabels,
36
+ FieldOption: DEFS.FieldOption,
37
+ Slug: DEFS.Slug,
38
+ Locale: DEFS.Locale,
39
+ },
40
+ };
41
+
42
+ /**
43
+ * The settings with `fields` replaced by the agent's list. A running operation's marker stays on
44
+ * its field (agents never write it), so editing labels meanwhile is not read as touching it.
45
+ */
46
+ export function withFields(
47
+ current ,
48
+ next ,
49
+ fields ,
50
+ ) {
51
+ const markers = new Map((current.fields ?? []).map((d) => [d.key, d.migration]));
52
+ const { fields: _old, ...rest } = next;
53
+ if (fields.length === 0) return rest;
54
+ return {
55
+ ...rest,
56
+ fields: fields.map((d) => {
57
+ const { migration: _m, ...def } = d;
58
+ const marker = markers.get(d.key);
59
+ return (marker ? { ...def, migration: marker } : def) ;
60
+ }) ,
61
+ };
62
+ }
63
+
64
+ /** JSON with sorted keys: stored definitions may list properties in another order. */
65
+ function canonical(value ) {
66
+ return JSON.stringify(value, (_k, v ) =>
67
+ v && typeof v === "object" && !Array.isArray(v)
68
+ ? Object.fromEntries(Object.entries(v).sort(([x], [y]) => x.localeCompare(y)))
69
+ : v,
70
+ );
71
+ }
72
+
73
+ /** One line for the approval prompt: which fields are added, changed, removed or reordered. */
74
+ export function describeFieldEdits(
75
+ before ,
76
+ after ,
77
+ locale ,
78
+ ) {
79
+ const old = new Map(before.map((d) => [d.key, d]));
80
+ const now = new Map(after.map((d) => [d.key, d]));
81
+ const name = (d ) => `"${quote(fieldLabel(d, locale, locale), 40)}" (${d.key})`;
82
+ const parts = [];
83
+ for (const d of after) {
84
+ const was = old.get(d.key);
85
+ if (!was) parts.push(`add ${name(d)}, ${d.type}${d.localized ? ", localized" : ""}`);
86
+ else if (canonical(was) !== canonical(d)) parts.push(`change ${name(d)}`);
87
+ }
88
+ for (const d of before) if (!now.has(d.key)) parts.push(`remove ${name(d)}`);
89
+ const kept = (list , other ) =>
90
+ list.filter((d) => other.has(d.key)).map((d) => d.key);
91
+ if (kept(before, now).join() !== kept(after, old).join()) parts.push("reorder");
92
+ return parts.length ? ` fields: ${parts.join("; ")}` : undefined;
93
+ }
94
+
95
+ /** What `list_collections` adds per collection that has definitions. */
96
+ export function fieldsView(
97
+ site ,
98
+ key ,
99
+ locale ,
100
+ ) {
101
+ const fields = site.collections?.[key]?.fields;
102
+ if (!fields?.length) return {};
103
+ return {
104
+ fields,
105
+ fieldsSchema: fieldsJsonSchema(fields, locale, site.defaultLocale) ,
106
+ };
107
+ }
@@ -4,7 +4,7 @@
4
4
  * settings in every mode (a new collection widens what agents may write). `requireRegistered` is
5
5
  * the precheck of every tool that creates an entry: no entries in a collection nobody approved.
6
6
  */
7
-
7
+
8
8
  import {
9
9
 
10
10
  collectionSettings,
@@ -12,6 +12,12 @@ import {
12
12
  MAX_COLLECTIONS,
13
13
  } from "@cloudhal/core-ts/collections";
14
14
  import { collectionPermalink } from "@cloudhal/core-ts/permalinks";
15
+ import {
16
+ describeFieldEdits,
17
+ FIELD_DEFINITIONS_INPUT,
18
+ fieldsView,
19
+ withFields,
20
+ } from "./collection-fields.js";
15
21
  import {
16
22
  autoSnapshot,
17
23
  id,
@@ -92,6 +98,7 @@ function settingsOf(a , current )
92
98
  for (const k of ["icon", "feed", "sitemap", "sort"] )
93
99
  if (a[k] !== undefined) (next )[k] = a[k];
94
100
  if (typeof a.permalink === "string") next.permalink = a.permalink;
101
+ if (Array.isArray(a.fields)) return withFields(current, next, a.fields );
95
102
  return next;
96
103
  }
97
104
 
@@ -167,6 +174,12 @@ function describe(p , mode ) {
167
174
  ];
168
175
  const other = Object.keys(p.settings.labels ?? {}).filter((l) => l !== p.site.defaultLocale);
169
176
  if (other.length) lines.push(` also named in: ${other.join(", ")}`);
177
+ const fields = describeFieldEdits(
178
+ p.existing?.settings?.fields ?? [],
179
+ p.settings.fields ?? [],
180
+ p.site.defaultLocale,
181
+ );
182
+ if (fields) lines.push(fields);
170
183
  return `${head}\n${lines.join("\n")}`;
171
184
  }
172
185
 
@@ -178,6 +191,8 @@ const COLLECTION_OUT = obj(
178
191
  counts: { type: "object" },
179
192
  permalink: { type: "string" },
180
193
  taxonomies: { type: "array", items: { type: "string" } },
194
+ fields: { type: "array", items: { type: "object" } },
195
+ fieldsSchema: { type: "object" },
181
196
  },
182
197
  ["key", "declared", "settings", "counts", "permalink", "taxonomies"],
183
198
  );
@@ -186,8 +201,11 @@ const listCollectionsTool = {
186
201
  name: "list_collections",
187
202
  title: "List collections",
188
203
  description:
189
- "The site's collections (RFC-0040): declared ones, ones that already have entries, and posts. Each with its names per locale, icon, entry counts by status, its permalink template, feed/sitemap/sort settings (defaults filled in) and the taxonomies that apply. Entries may only be created in these collections; call create_collection for a new one.",
190
- inputSchema: obj({ siteId: id }, ["siteId"]),
204
+ "The site's collections (RFC-0040): declared ones, ones that already have entries, and posts. Each with its names per locale, icon, entry counts by status, its permalink template, feed/sitemap/sort settings (defaults filled in) and the taxonomies that apply. A collection with typed custom fields (RFC-0041) also has `fields` (the definitions) and `fieldsSchema`, the JSON Schema of an entry's `fields` with labels and help in `locale` (default: the site's default locale): read it before create_entry or update_entry with fields. Entries may only be created in these collections; call create_collection for a new one.",
205
+ inputSchema: obj(
206
+ { siteId: id, locale: str("BCP 47 locale of field labels and help; default the site's") },
207
+ ["siteId"],
208
+ ),
191
209
  outputSchema: obj({ collections: { type: "array", items: COLLECTION_OUT } }, ["collections"]),
192
210
  annotations: {
193
211
  readOnlyHint: true,
@@ -202,9 +220,11 @@ const listCollectionsTool = {
202
220
  ctx.store.listCollections(site.id),
203
221
  ctx.store.listTaxonomies(site.id),
204
222
  ]);
223
+ const locale = (a.locale ) ?? site.defaultLocale;
205
224
  return {
206
225
  collections: registry.map((c) => ({
207
226
  ...c,
227
+ ...fieldsView(site, c.key, locale),
208
228
  settings: collectionSettings(site, c.key),
209
229
  permalink: collectionPermalink(site, c.key),
210
230
  taxonomies: taxonomies
@@ -223,7 +243,7 @@ function writeTool(mode ) {
223
243
  description:
224
244
  mode === "create"
225
245
  ? "Declare a new collection (RFC-0040), e.g. events, team or jobs, with its names in the site's default locale (labels), an optional icon, permalink (/<prefix>/{slug}, default /<key>/{slug}), feed, sitemap and default sort. Its address may not overlap a page, archive, another collection, /search or a locale prefix. A person who may change site settings approves it in every mode; dryRun: true checks without asking. Then create_entry with this collection. Declaring a collection that already has entries names it."
226
- : "Change a collection's names (merged per locale), icon, feed, sitemap or default sort (RFC-0040). The permalink changes only through set_collection_permalink (it moves URLs). A person who may change site settings approves it; dryRun: true checks without asking.",
246
+ : "Change a collection's names (merged per locale), icon, feed, sitemap, default sort (RFC-0040) or its typed custom fields (`fields`, the whole list; RFC-0041). Field edits that keep every stored value are free here; renaming a key, changing a type, localization or multiple, and dropping a key or option still in use are refused (field_change_needs_operation) and go through rename_field, change_field_type, set_field_localized or remove_field. The permalink changes only through set_collection_permalink (it moves URLs). A person who may change site settings approves it; dryRun: true checks without asking.",
227
247
  inputSchema: obj(
228
248
  {
229
249
  siteId: id,
@@ -232,6 +252,7 @@ function writeTool(mode ) {
232
252
  maxLength: 64,
233
253
  }),
234
254
  ...SETTINGS_INPUT,
255
+ ...(mode === "update" ? { fields: FIELD_DEFINITIONS_INPUT } : {}),
235
256
  ...(mode === "create"
236
257
  ? {
237
258
  permalink: str("Template, e.g. /etkinlik/{slug}; default /<key>/{slug}", {
@@ -31,6 +31,7 @@ import {
31
31
 
32
32
  import { ScheduleConflictError, ScheduleError } from "@cloudhal/schedules";
33
33
 
34
+ import { fieldHint } from "./field-hints.js";
34
35
 
35
36
  import { ScheduleRequestError, } from "./schedules.js";
36
37
 
@@ -374,6 +375,8 @@ export async function autoSnapshot(
374
375
 
375
376
  /** What to do next, per invariant (RFC-0002 §3). */
376
377
  function invariantHint(e ) {
378
+ const field = fieldHint(e.code, e.details);
379
+ if (field) return field;
377
380
  const key = typeof e.details.taxonomy === "string" ? e.details.taxonomy : undefined;
378
381
  switch (e.code) {
379
382
  case "required_term":
@@ -0,0 +1,35 @@
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.
8
+ */
9
+ import type { ContentEntry, FieldDefinition, Site } from "@cloudhal/core-contracts";
10
+ import { type JsonSchema, type ToolContext } from "./common.js";
11
+ type Values = Record<string, unknown>;
12
+ /** `create_entry`'s `fields`: a static schema cannot vary by site, so it points to list_collections. */
13
+ export declare const FIELDS_INPUT: JsonSchema;
14
+ /** `update_entry`'s `fields`: a merge patch. */
15
+ export declare const FIELDS_PATCH: JsonSchema;
16
+ /** The stored `fields` with `patch` applied: `null` removes a key. */
17
+ export declare function mergeFields(current: Values | undefined, patch: Values): Values;
18
+ /** What an entry write would store, for the check. */
19
+ export interface FieldsCheck {
20
+ site: Site;
21
+ /** The entry as it would be written (its `fields` after the patch). */
22
+ next: Pick<ContentEntry, "id" | "siteId" | "collection" | "fields" | "status" | "translation">;
23
+ /** The stored entry (absent for a new one). */
24
+ stored?: Pick<ContentEntry, "collection" | "fields"> | undefined;
25
+ }
26
+ /**
27
+ * The store's field checks, run before anyone is asked: throws `invalid_fields`, `unknown_field`,
28
+ * `field_not_localized`, `required_field` or `too_large` with every issue at its path.
29
+ */
30
+ export declare function checkEntryFields(ctx: ToolContext, check: FieldsCheck): Promise<void>;
31
+ /** A value as a person reads it in an approval prompt (agent text quoted and truncated). */
32
+ export declare function describeFieldValue(def: FieldDefinition | undefined, value: unknown, locale: string): string;
33
+ /** "startsAt → 5 Nov 2026 19:30 Istanbul, format → Talk, Workshop, notes removed". */
34
+ export declare function describeFieldPatch(site: Site, collection: string, patch: Values): string;
35
+ export {};
@@ -0,0 +1,233 @@
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.
8
+ */
9
+
10
+ import {
11
+ ASSET_ID_PATTERN,
12
+ checkFieldValues,
13
+ checkRequiredToPublish,
14
+ convertContext,
15
+
16
+ fieldDefinitions,
17
+ fieldLabel,
18
+ normalizeThroughMarkers,
19
+ optionLabel,
20
+ refuseFieldIssues,
21
+ } from "@cloudhal/core-ts/fields";
22
+ import { markdownAssetIds } from "@cloudhal/core-ts/media";
23
+ import { quote, } from "./common.js";
24
+
25
+
26
+
27
+ /** `create_entry`'s `fields`: a static schema cannot vary by site, so it points to list_collections. */
28
+ export const FIELDS_INPUT = {
29
+ type: "object",
30
+ description:
31
+ "Typed custom fields of the collection: read its fieldsSchema from list_collections first (keys, types, allowed values, limits). A collection without field definitions takes any JSON here.",
32
+ };
33
+
34
+ /** `update_entry`'s `fields`: a merge patch. */
35
+ export const FIELDS_PATCH = {
36
+ type: "object",
37
+ description:
38
+ "Typed custom fields to change, as a merge patch: given keys are set, null removes a key, others stay. The collection's fieldsSchema (list_collections) lists the keys and allowed values.",
39
+ };
40
+
41
+ /** The stored `fields` with `patch` applied: `null` removes a key. */
42
+ export function mergeFields(current , patch ) {
43
+ const next = { ...(current ?? {}) };
44
+ for (const [key, value] of Object.entries(patch)) {
45
+ if (value === null) delete next[key];
46
+ else next[key] = value;
47
+ }
48
+ return next;
49
+ }
50
+
51
+ const isTranslation = (e ) =>
52
+ !!e.translation && e.translation.group !== e.id && e.translation.source?.siteId === undefined;
53
+
54
+ /** The same-site original of a translation (as the store reads it). */
55
+ async function originalOf(
56
+ ctx ,
57
+ entry ,
58
+ ) {
59
+ if (!isTranslation(entry)) return undefined;
60
+ const original = await ctx.store.getContentEntry(entry.translation?.group );
61
+ return original?.siteId === entry.siteId ? original : undefined;
62
+ }
63
+
64
+ const ASSET_ID = new RegExp(ASSET_ID_PATTERN);
65
+
66
+ /** `fields.<key>` → asset ids an image or rich-text value refers to. */
67
+ function assetRefs(defs , values ) {
68
+ const out = new Set ();
69
+ for (const def of defs) {
70
+ const value = values?.[def.key];
71
+ if (typeof value !== "string") continue;
72
+ if (def.type === "image" && ASSET_ID.test(value)) out.add(`${def.key}\n${value}`);
73
+ else if (def.type === "richText" && value.includes("asset:"))
74
+ for (const id of markdownAssetIds(value)) out.add(`${def.key}\n${id}`);
75
+ }
76
+ return out;
77
+ }
78
+
79
+ function assetProblem(asset , def , siteId ) {
80
+ if (!asset || asset.siteId !== siteId) return "is not a file of this site";
81
+ if (def.type === "image" && asset.kind !== "image")
82
+ return `is a ${asset.kind} file, not an image`;
83
+ if (asset.status === "retired") return "was retired and cannot be newly used";
84
+ return undefined;
85
+ }
86
+
87
+ /** New references (not held by the stored entry under the same key) name usable files of the site. */
88
+ async function assetIssues(
89
+ ctx ,
90
+ check
91
+
92
+
93
+
94
+
95
+ ,
96
+ ) {
97
+ const held = assetRefs(check.defs, check.stored);
98
+ const byKey = new Map(check.defs.map((d) => [d.key, d]));
99
+ const out = [];
100
+ for (const ref of assetRefs(check.defs, check.values)) {
101
+ if (held.has(ref)) continue;
102
+ const [key = "", assetId = ""] = ref.split("\n");
103
+ const problem = assetProblem(
104
+ await ctx.store.getAsset(assetId),
105
+ byKey.get(key) ,
106
+ check.siteId,
107
+ );
108
+ if (problem)
109
+ out.push({ path: `fields/${key}`, code: "invalid_value", message: `${assetId} ${problem}` });
110
+ }
111
+ return out;
112
+ }
113
+
114
+ /** What an entry write would store, for the check. */
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+ /**
124
+ * The store's field checks, run before anyone is asked: throws `invalid_fields`, `unknown_field`,
125
+ * `field_not_localized`, `required_field` or `too_large` with every issue at its path.
126
+ */
127
+ export async function checkEntryFields(ctx , check ) {
128
+ const { site, stored } = check;
129
+ let next = check.next;
130
+ const defs = fieldDefinitions(site, next.collection);
131
+ // While a field operation runs, a write goes through its marker (as the store normalizes it).
132
+ if (defs.some((d) => d.migration)) {
133
+ const fields = normalizeThroughMarkers(defs, next.fields, {
134
+ convert: convertContext(site),
135
+ translation: isTranslation(next),
136
+ });
137
+ if (fields) next = { ...next, fields };
138
+ }
139
+ const values = next.fields ?? {};
140
+ const previous = stored?.collection === next.collection ? (stored.fields ?? {}) : undefined;
141
+ if (defs.length === 0) {
142
+ if (!previous || JSON.stringify(previous) !== JSON.stringify(values))
143
+ refuseFieldIssues(checkFieldValues([], { values }));
144
+ return;
145
+ }
146
+ const original = await originalOf(ctx, next);
147
+ const issues = checkFieldValues(defs, {
148
+ values,
149
+ previous,
150
+ original: original ? { id: original.id, values: original.fields ?? {} } : undefined,
151
+ blocks: ctx.store.blocks,
152
+ });
153
+ const invalid = new Set(issues.map((i) => i.path.split("/").slice(0, 2).join("/")));
154
+ const assets = await assetIssues(ctx, { siteId: site.id, defs, values, stored: previous });
155
+ issues.push(...assets.filter((i) => !invalid.has(i.path)));
156
+ issues.push(...checkRequiredToPublish(site, { ...next, fields: values }, original));
157
+ refuseFieldIssues(issues);
158
+ }
159
+
160
+ /** "5 Nov 2026" (a calendar day: no zone). */
161
+ function day(value ) {
162
+ const d = new Date(`${value}T00:00:00Z`);
163
+ if (Number.isNaN(d.getTime())) return quote(value);
164
+ return new Intl.DateTimeFormat("en-GB", {
165
+ day: "numeric",
166
+ month: "short",
167
+ year: "numeric",
168
+ timeZone: "UTC",
169
+ }).format(d);
170
+ }
171
+
172
+ /** "5 Nov 2026 19:30 Istanbul" (the wall clock in the value's own zone). */
173
+ function instant(value ) {
174
+ const v = value ;
175
+ if (typeof v?.at !== "string" || typeof v.timeZone !== "string") return quote(JSON.stringify(v));
176
+ const at = new Date(v.at);
177
+ if (Number.isNaN(at.getTime())) return quote(v.at);
178
+ try {
179
+ const parts = new Intl.DateTimeFormat("en-GB", {
180
+ day: "numeric",
181
+ month: "short",
182
+ year: "numeric",
183
+ hour: "2-digit",
184
+ minute: "2-digit",
185
+ hourCycle: "h23",
186
+ timeZone: v.timeZone,
187
+ }).format(at);
188
+ const city = (v.timeZone.split("/").pop() ?? v.timeZone).replace(/_/g, " ");
189
+ return `${parts.replace(",", "")} ${city}`;
190
+ } catch {
191
+ return `${quote(v.at)} ${quote(v.timeZone)}`;
192
+ }
193
+ }
194
+
195
+ /** A value as a person reads it in an approval prompt (agent text quoted and truncated). */
196
+ export function describeFieldValue(
197
+ def ,
198
+ value ,
199
+ locale ,
200
+ ) {
201
+ if (!def) return `"${quote(JSON.stringify(value) ?? "")}"`;
202
+ switch (def.type) {
203
+ case "number":
204
+ return typeof value === "number" ? String(value) : `"${quote(String(value))}"`;
205
+ case "boolean":
206
+ return value === true ? "yes" : "no";
207
+ case "date":
208
+ return typeof value === "string" ? day(value) : `"${quote(String(value))}"`;
209
+ case "datetime":
210
+ return instant(value);
211
+ case "select": {
212
+ const list = Array.isArray(value) ? value : [value];
213
+ return list.map((v) => quote(optionLabel(def, String(v), locale, locale))).join(", ");
214
+ }
215
+ default:
216
+ return `"${quote(typeof value === "string" ? value : JSON.stringify(value))}"`;
217
+ }
218
+ }
219
+
220
+ /** "startsAt → 5 Nov 2026 19:30 Istanbul, format → Talk, Workshop, notes removed". */
221
+ export function describeFieldPatch(site , collection , patch ) {
222
+ const defs = new Map(fieldDefinitions(site, collection).map((d) => [d.key, d]));
223
+ const locale = site.defaultLocale;
224
+ return Object.entries(patch)
225
+ .map(([key, value]) => {
226
+ const def = defs.get(key);
227
+ const name = def ? `"${quote(fieldLabel(def, locale, locale), 40)}" (${key})` : key;
228
+ return value === null
229
+ ? `${name} removed`
230
+ : `${name} → ${describeFieldValue(def, value, locale)}`;
231
+ })
232
+ .join(", ");
233
+ }
@@ -26,6 +26,13 @@ import {
26
26
  unknownBlocks,
27
27
  unknownBlocksOf,
28
28
  } from "./content-shared.js";
29
+ import {
30
+ checkEntryFields,
31
+ describeFieldPatch,
32
+ FIELDS_INPUT,
33
+ FIELDS_PATCH,
34
+ mergeFields,
35
+ } from "./entry-fields.js";
29
36
  import { entryTerms, reportDeltas } from "./entry-terms.js";
30
37
  import { menuHint, menuItemsHiddenBy } from "./menu-tools.js";
31
38
  import { assignmentDeltas, describeDeltas, TAGS_INPUT, TERMS_INPUT, termLookup } from "./terms.js";
@@ -110,7 +117,7 @@ const createEntryTool = {
110
117
  name: "create_entry",
111
118
  title: "Create article",
112
119
  description:
113
- "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). Snapshots afterwards.",
120
+ "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.",
114
121
  inputSchema: obj(
115
122
  {
116
123
  siteId: id,
@@ -125,7 +132,7 @@ const createEntryTool = {
125
132
  terms: TERMS_INPUT,
126
133
  tags: TAGS_INPUT,
127
134
  coverImage: COVER_INPUT,
128
- fields: { type: "object", description: "Collection-specific fields" },
135
+ fields: FIELDS_INPUT,
129
136
  },
130
137
  ["siteId", "slug", "title", "body"],
131
138
  ),
@@ -141,9 +148,24 @@ const createEntryTool = {
141
148
  },
142
149
  scopes: ["content:write"],
143
150
  own: "entry",
144
- // RFC-0040 §5: only collections of the registry (a new one goes through create_collection).
145
- precheck: (a, ctx) =>
146
- requireRegistered(ctx, a.siteId , (a.collection ) ?? "posts"),
151
+ // RFC-0040 §5: only collections of the registry (a new one goes through create_collection);
152
+ // RFC-0041 §8: field values are checked before anyone is asked.
153
+ precheck: async (a, ctx) => {
154
+ const collection = (a.collection ) ?? "posts";
155
+ await requireRegistered(ctx, a.siteId , collection);
156
+ const site = await ctx.store.getSite(a.siteId );
157
+ if (!site) return;
158
+ await checkEntryFields(ctx, {
159
+ site,
160
+ next: {
161
+ id: "",
162
+ siteId: site.id,
163
+ collection,
164
+ status: "draft",
165
+ fields: (a.fields ) ?? {},
166
+ },
167
+ });
168
+ },
147
169
  handler: async (a, ctx) => {
148
170
  const site = await requireSite(ctx, a.siteId );
149
171
  await entryLimitCheck(ctx, "create", undefined, {
@@ -189,7 +211,7 @@ const updateEntryTool = {
189
211
  name: "update_entry",
190
212
  title: "Update article",
191
213
  description:
192
- "Update title, summary, body, slug, status (draft → review → published) or terms (`terms`: add, remove or set categories and tags by id, slug or name) of an entry. Review and published articles need a primary term in every required taxonomy. Requires the current `rev`. Changing a published article's slug leaves a redirect. Snapshots afterwards.",
214
+ "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.",
193
215
  inputSchema: obj(
194
216
  {
195
217
  siteId: id,
@@ -207,6 +229,7 @@ const updateEntryTool = {
207
229
  description: "Cover image; null removes it",
208
230
  },
209
231
  status: { type: "string", enum: ["draft", "review", "published", "archived"] },
232
+ fields: FIELDS_PATCH,
210
233
  },
211
234
  ["siteId", "entryId", "rev"],
212
235
  ),
@@ -219,15 +242,18 @@ const updateEntryTool = {
219
242
  },
220
243
  scopes: ["content:write"],
221
244
  own: "entry",
222
- // Own-limited callers (Authors, Contributors and their agents) only touch their own articles.
245
+ // Own-limited callers (Authors, Contributors and their agents) only touch their own articles;
246
+ // field values (RFC-0041 §8) are checked before anyone is asked.
223
247
  precheck: async (a, ctx) => {
224
- if (!ctx.limit) return;
225
248
  const entry = await ctx.store.getContentEntry(a.entryId );
226
249
  if (!entry || entry.siteId !== a.siteId) return;
227
- await entryLimitCheck(ctx, "update", entry, {
228
- author: entry.author,
229
- status: (a.status ) ?? entry.status,
230
- });
250
+ const status = (a.status ) ?? entry.status;
251
+ if (ctx.limit) await entryLimitCheck(ctx, "update", entry, { author: entry.author, status });
252
+ if (a.fields === undefined && status === entry.status) return;
253
+ const site = await ctx.store.getSite(entry.siteId);
254
+ if (!site) return;
255
+ const fields = mergeFields(entry.fields, (a.fields ) ?? {});
256
+ await checkEntryFields(ctx, { site, next: { ...entry, status, fields }, stored: entry });
231
257
  },
232
258
  approvalPrompt: async (a, ctx) => {
233
259
  const entry = await ctx.store.getContentEntry(a.entryId );
@@ -247,6 +273,10 @@ const updateEntryTool = {
247
273
  : "cover image"
248
274
  : "",
249
275
  ].filter(Boolean);
276
+ if (a.fields && site && Object.keys(a.fields).length)
277
+ changes.push(
278
+ `fields: ${describeFieldPatch(site, entry.collection, a.fields )}`,
279
+ );
250
280
  if (a.terms || a.tags) {
251
281
  try {
252
282
  const { terms } = await entryTerms(ctx, site , entry, a);
@@ -295,6 +325,9 @@ const updateEntryTool = {
295
325
  ...(a.title ? { title: a.title } : {}),
296
326
  ...(a.summary !== undefined ? { summary: a.summary } : {}),
297
327
  ...(a.body !== undefined ? { body: { ...entry.body, value: a.body } } : {}),
328
+ ...(a.fields !== undefined
329
+ ? { fields: mergeFields(entry.fields, a.fields ) }
330
+ : {}),
298
331
  ...(a.slug ? { slug: a.slug } : {}),
299
332
  tags,
300
333
  ...(terms ? { terms } : {}),
@@ -0,0 +1,7 @@
1
+ /**
2
+ * RFC-0041: what an agent does next after a typed-field refusal. Every refusal keeps its issues in
3
+ * `details.issues`, each at its slash path (`fields/startsAt/at`), so the hint only names the tool.
4
+ */
5
+ import type { InvariantCode } from "@cloudhal/core-ts";
6
+ /** The next step for a field refusal; undefined for codes that are not about fields. */
7
+ export declare function fieldHint(code: InvariantCode, details: Readonly<Record<string, unknown>>): string | undefined;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * RFC-0041: what an agent does next after a typed-field refusal. Every refusal keeps its issues in
3
+ * `details.issues`, each at its slash path (`fields/startsAt/at`), so the hint only names the tool.
4
+ */
5
+
6
+
7
+ const OPERATIONS = "rename_field, change_field_type, set_field_localized or remove_field";
8
+
9
+ const HINTS = {
10
+ invalid_fields:
11
+ "fix the values at the paths in details.issues; list_collections shows the collection's fieldsSchema (types, allowed values, limits)",
12
+ unknown_field:
13
+ "use one of the collection's field keys (list_collections → fieldsSchema); a new field is added with update_collection, which a person approves",
14
+ field_not_localized:
15
+ "that field is shared by every language version: set it on the original entry named in the message, and leave it out of the translation",
16
+ required_field:
17
+ "give the fields named in details.issues a value (update_entry with fields), or keep the entry a draft",
18
+ field_key_reserved:
19
+ "pick another key: built-in entry properties (title, slug, body, …) cannot be field keys",
20
+ field_key_duplicate: "every field key appears once per collection",
21
+ field_option_duplicate: "every option value appears once per select field",
22
+ field_bounds: "a number field's minimum must not be above its maximum",
23
+ too_many_fields:
24
+ "a collection has at most 30 fields, a site 200 and a select 50 options; remove some first",
25
+ field_change_needs_operation: `that change could lose or reinterpret stored values: use ${OPERATIONS} (each shows a dry run and waits for a person; try dryRun: true first)`,
26
+ operation_in_progress:
27
+ "a person can continue or revert it in Studio, or call the same operation tool again with that operationId (it needs a new approval)",
28
+ field_values_unconvertible:
29
+ 'details.report.samples shows the values; change them first (update_entry), or call again with onInvalid: "clear" to drop them (the person approving sees how many)',
30
+ field_operation_incomplete:
31
+ "call the operation tool again with its operationId to finish it (a new approval), or ask a person to continue it in Studio",
32
+ };
33
+
34
+ /** The next step for a field refusal; undefined for codes that are not about fields. */
35
+ export function fieldHint(code , details ) {
36
+ if (code === "too_large" && Array.isArray(details.issues))
37
+ return "field values are at most 256 KB per entry and collection settings 256 KB per site; shorten or drop values";
38
+ return HINTS[code];
39
+ }
@@ -0,0 +1,6 @@
1
+ import { type FieldOperation, type FieldOperationReport } from "@cloudhal/core-ts";
2
+ import { type ToolDefinition } from "./common.js";
3
+ /** The approval prompt, built from the dry run (RFC-0041 §6 step 1). */
4
+ export declare function describeOperation(op: FieldOperation, report: FieldOperationReport, locale: string): string;
5
+ /** rename_field … remove_field, after the collection tools. */
6
+ export declare function fieldTools(): ToolDefinition[];
@@ -0,0 +1,360 @@
1
+ /**
2
+ * RFC-0041 §6, §8: the four field operations for agents — `rename_field`, `change_field_type`,
3
+ * `set_field_localized` and `remove_field`. Each needs `site:write` and `content:write` (it
4
+ * rewrites entries), always waits for a person who may change site settings (`person`-classed, so
5
+ * `bypass` waits too), and shows that person the dry run: entries touched, values moved, converted
6
+ * or cleared, samples before and after. `precheck` runs the same dry run, so a call that would
7
+ * clear values without `onInvalid: "clear"` never reaches anyone.
8
+ *
9
+ * An operation that hits its budget answers `done: false` with its `operationId`. A person
10
+ * continues it in Studio, or the agent calls the same tool again with that `operationId`, which
11
+ * needs a new approval (ADR-0043 open question 9: approvals stay single use).
12
+ */
13
+
14
+ import { SiteSchema } from "@cloudhal/core-contracts";
15
+ import {
16
+ continueFieldOperation,
17
+
18
+
19
+
20
+
21
+ fieldOperationStatus,
22
+ InvariantError,
23
+ runFieldOperation,
24
+ } from "@cloudhal/core-ts";
25
+ import { FIELD_TYPES, fieldLabel } from "@cloudhal/core-ts/fields";
26
+ import {
27
+ id,
28
+
29
+ obj,
30
+ quote,
31
+ requireSite,
32
+ SLUG_PATTERN,
33
+ str,
34
+
35
+
36
+ ToolError,
37
+ toToolError,
38
+ } from "./common.js";
39
+
40
+ const DEFS = SiteSchema.$defs ;
41
+ const KEY = DEFS.FieldKey ;
42
+
43
+ const COMMON = {
44
+ siteId: id,
45
+ collection: str("Collection key (list_collections)", { pattern: SLUG_PATTERN, maxLength: 64 }),
46
+ operationId: str(
47
+ "Continue the unfinished operation this tool answered with done: false (repeat the same call with it; a person approves again)",
48
+ { pattern: id.pattern },
49
+ ),
50
+ dryRun: {
51
+ type: "boolean",
52
+ description: "Only report what would change, without asking anyone or changing anything",
53
+ },
54
+ } ;
55
+
56
+ const COUNTS = obj({
57
+ touched: { type: "integer" },
58
+ moved: { type: "integer" },
59
+ converted: { type: "integer" },
60
+ cleared: { type: "integer" },
61
+ removed: { type: "integer" },
62
+ unconvertible: { type: "integer" },
63
+ unchanged: { type: "integer" },
64
+ entries: { type: "integer" },
65
+ });
66
+
67
+ const OUTPUT = obj(
68
+ {
69
+ prompt: { type: "string" },
70
+ dryRun: { type: "boolean" },
71
+ done: { type: "boolean" },
72
+ operationId: { type: "string" },
73
+ report: { ...COUNTS, additionalProperties: true },
74
+ rewritten: { type: "integer" },
75
+ skipped: { type: "array", items: { type: "object" } },
76
+ status: { type: "object" },
77
+ hint: { type: "string" },
78
+ },
79
+ ["prompt", "dryRun", "done"],
80
+ );
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+ /** What the operation does, for the prompt's first line. */
93
+ function headline(op , report , locale ) {
94
+ const def = report.definition.before;
95
+ const field = `"${quote(fieldLabel(def, locale, locale), 40)}" (${def.key}) of ${op.collection}`;
96
+ switch (op.op) {
97
+ case "rename_field":
98
+ return `Rename the field ${field} to ${op.to}?`;
99
+ case "change_field_type":
100
+ return `Change the field ${field} from ${def.type} to ${op.type}${op.multiple ? " (multiple)" : ""}?`;
101
+ case "set_field_localized":
102
+ return op.localized
103
+ ? `Make the field ${field} localized (each language version gets its own value)?`
104
+ : `Make the field ${field} shared by all language versions (translations' own copies are deleted)?`;
105
+ case "remove_field":
106
+ return `Remove the field ${field} and its values from every entry?`;
107
+ }
108
+ }
109
+
110
+ const sample = (v ) =>
111
+ v === undefined ? "nothing" : `"${quote(typeof v === "string" ? v : JSON.stringify(v), 40)}"`;
112
+
113
+ /** The approval prompt, built from the dry run (RFC-0041 §6 step 1). */
114
+ export function describeOperation(
115
+ op ,
116
+ report ,
117
+ locale ,
118
+ ) {
119
+ const counts = [
120
+ `${report.touched} of ${report.entries} entries change`,
121
+ report.moved ? `${report.moved} values moved` : "",
122
+ report.converted ? `${report.converted} converted` : "",
123
+ report.cleared ? `${report.cleared} cleared` : "",
124
+ report.removed ? `${report.removed} removed` : "",
125
+ report.unconvertible ? `${report.unconvertible} cannot be converted` : "",
126
+ report.unchanged ? `${report.unchanged} unchanged` : "",
127
+ ].filter(Boolean);
128
+ const lines = [headline(op, report, locale), ` ${counts.join(", ")}.`];
129
+ for (const s of report.samples.slice(0, 3))
130
+ lines.push(` ${s.entryId} (${s.locale}): ${sample(s.before)} → ${sample(s.after)}`);
131
+ if (op.op === "rename_field" || op.op === "change_field_type")
132
+ lines.push(
133
+ ` Theme code reading entry.fields.${report.key} directly stops working; themes using entryFields keep working.`,
134
+ );
135
+ lines.push(
136
+ " Snapshots are taken before and after, and it can be reverted. Only the draft changes: the live site keeps the old field until the next publish.",
137
+ );
138
+ return lines.join("\n");
139
+ }
140
+
141
+ async function locale(ctx , siteId ) {
142
+ return (await requireSite(ctx, siteId)).defaultLocale;
143
+ }
144
+
145
+ /** The unfinished operation `operationId` names, checked against this call. */
146
+ async function continued(ctx , siteId , op , opId ) {
147
+ let status ;
148
+ try {
149
+ status = await fieldOperationStatus(ctx.store, siteId, opId);
150
+ } catch (e) {
151
+ throw toToolError(e);
152
+ }
153
+ if (status.operation.op !== op.op || status.operation.collection !== op.collection)
154
+ throw new ToolError(
155
+ "invalid",
156
+ `${opId} is a ${status.operation.op} on ${status.operation.collection}; call that tool with it`,
157
+ );
158
+ return status;
159
+ }
160
+
161
+ async function dryRun(ctx , siteId , op ) {
162
+ try {
163
+ return (
164
+ await runFieldOperation(ctx.store, siteId, op, { actor: ctx.principal.actor, dryRun: true })
165
+ ).report;
166
+ } catch (e) {
167
+ throw toToolError(e);
168
+ }
169
+ }
170
+
171
+ /** The precheck: the dry run's refusal, or an operation id that is not this call's. */
172
+ async function precheck(spec , a , ctx ) {
173
+ const siteId = a.siteId ;
174
+ const site = await requireSite(ctx, siteId);
175
+ const op = spec.operation(a.collection , a);
176
+ if (typeof a.operationId === "string") {
177
+ await continued(ctx, siteId, op, a.operationId);
178
+ return;
179
+ }
180
+ // Another operation still rewriting the collection is the refusal that says what to do.
181
+ const running = site.collections?.[op.collection]?.fields?.find((d) => d.migration)?.migration;
182
+ if (running)
183
+ throw toToolError(
184
+ new InvariantError(
185
+ "operation_in_progress",
186
+ `field operation ${running.id} is still rewriting ${op.collection}`,
187
+ { operationId: running.id, collection: op.collection },
188
+ ),
189
+ );
190
+ const report = await dryRun(ctx, siteId, op);
191
+ if (report.refusal)
192
+ throw toToolError(new InvariantError(report.refusal.code, report.refusal.message, { report }));
193
+ }
194
+
195
+ async function prompt(spec , a , ctx ) {
196
+ const siteId = a.siteId ;
197
+ const op = spec.operation(a.collection , a);
198
+ if (typeof a.operationId === "string") {
199
+ const status = await continued(ctx, siteId, op, a.operationId);
200
+ return `Continue the field operation ${status.operationId} (${op.op} on ${op.collection}, started earlier)? ${status.pending} entries are still to rewrite.`;
201
+ }
202
+ return describeOperation(op, await dryRun(ctx, siteId, op), await locale(ctx, siteId));
203
+ }
204
+
205
+ function answer(r , promptText ) {
206
+ return {
207
+ prompt: promptText,
208
+ dryRun: r.dryRun,
209
+ done: r.done,
210
+ ...(r.operationId ? { operationId: r.operationId } : {}),
211
+ report: r.report,
212
+ rewritten: r.rewritten,
213
+ skipped: r.skipped,
214
+ ...(!r.dryRun && !r.done
215
+ ? {
216
+ hint: `The operation stopped at its budget. A person can continue it in Studio, or call ${r.report.op} again with operationId "${r.operationId}" (it needs a new approval).`,
217
+ }
218
+ : {}),
219
+ };
220
+ }
221
+
222
+ async function handle(spec , a , ctx ) {
223
+ const siteId = a.siteId ;
224
+ const op = spec.operation(a.collection , a);
225
+ const options = { actor: ctx.principal.actor, ...(ctx.now ? { now: ctx.now } : {}) };
226
+ try {
227
+ if (typeof a.operationId === "string") {
228
+ const status = await continued(ctx, siteId, op, a.operationId);
229
+ // A dry run of a continuation only says where the operation stands.
230
+ if (a.dryRun === true)
231
+ return {
232
+ prompt: await prompt(spec, a, ctx),
233
+ dryRun: true,
234
+ done: status.state !== "running",
235
+ operationId: status.operationId,
236
+ status,
237
+ };
238
+ const r = await continueFieldOperation(ctx.store, siteId, status.operationId, options);
239
+ return answer(r, describeOperation(op, r.report, await locale(ctx, siteId)));
240
+ }
241
+ const r = await runFieldOperation(ctx.store, siteId, op, {
242
+ ...options,
243
+ dryRun: a.dryRun === true,
244
+ });
245
+ return answer(r, describeOperation(op, r.report, await locale(ctx, siteId)));
246
+ } catch (e) {
247
+ throw toToolError(e);
248
+ }
249
+ }
250
+
251
+ function operationTool(spec ) {
252
+ return {
253
+ name: spec.name,
254
+ title: spec.title,
255
+ description: `${spec.description} Needs a person who may change site settings in every mode; the approval shows the dry run (entries touched, values changed, samples). dryRun: true reports without asking. Snapshots before and after; revertible; only the draft changes until the next publish. A run that stops at its budget answers done: false with an operationId: call again with it (a new approval) or let a person continue it in Studio.`,
256
+ inputSchema: obj({ ...COMMON, ...spec.input }, ["siteId", "collection", ...spec.required]),
257
+ outputSchema: OUTPUT,
258
+ annotations: {
259
+ readOnlyHint: false,
260
+ destructiveHint: spec.destructive,
261
+ idempotentHint: false,
262
+ openWorldHint: false,
263
+ },
264
+ scopes: ["site:write", "content:write"],
265
+ approverScopes: ["site:settings"],
266
+ requiresApproval: true,
267
+ classify: (a) => (a.dryRun === true ? "read" : "person"),
268
+ precheck: (a, ctx) => precheck(spec, a, ctx),
269
+ approvalPrompt: (a, ctx) => prompt(spec, a, ctx),
270
+ handler: (a, ctx) => handle(spec, a, ctx),
271
+ };
272
+ }
273
+
274
+ const SPECS = [
275
+ {
276
+ name: "rename_field",
277
+ title: "Rename field",
278
+ description:
279
+ "Rename a typed custom field's key (RFC-0041 §6): every entry's value moves from `from` to `to`; nothing is converted.",
280
+ input: {
281
+ from: { ...KEY, description: "The field's current key" },
282
+ to: { ...KEY, description: "The new key" },
283
+ },
284
+ required: ["from", "to"],
285
+ destructive: false,
286
+ operation: (collection, a) => ({
287
+ op: "rename_field",
288
+ collection,
289
+ from: a.from ,
290
+ to: a.to ,
291
+ }),
292
+ },
293
+ {
294
+ name: "change_field_type",
295
+ title: "Change field type",
296
+ description:
297
+ "Change a typed custom field's type, or a select's multiple (RFC-0041 §6), converting every value by a closed table (text↔richText, text↔number, text↔select, text↔url, date↔datetime, single↔multiple select). Values that cannot be converted refuse the call unless onInvalid is \"clear\".",
298
+ input: {
299
+ key: { ...KEY, description: "The field's key" },
300
+ type: str("The new type", { enum: [...FIELD_TYPES] }),
301
+ options: {
302
+ type: "array",
303
+ description:
304
+ "A new select's options (default: the field's own when it already is a select)",
305
+ minItems: 1,
306
+ maxItems: 50,
307
+ items: { $ref: "#/$defs/FieldOption" },
308
+ $defs: { FieldOption: DEFS.FieldOption, Slug: DEFS.Slug, Locale: DEFS.Locale },
309
+ },
310
+ multiple: { type: "boolean", description: "For a select: the value is a list of options" },
311
+ onInvalid: str("Drop values that cannot be converted (the person approving sees how many)", {
312
+ enum: ["clear"],
313
+ }),
314
+ },
315
+ required: ["key", "type"],
316
+ destructive: true,
317
+ operation: (collection, a) => ({
318
+ op: "change_field_type",
319
+ collection,
320
+ key: a.key ,
321
+ type: a.type ,
322
+ ...(a.options ? { options: a.options } : {}),
323
+ ...(typeof a.multiple === "boolean" ? { multiple: a.multiple } : {}),
324
+ ...(a.onInvalid === "clear" ? { onInvalid: "clear" } : {}),
325
+ }),
326
+ },
327
+ {
328
+ name: "set_field_localized",
329
+ title: "Set field localization",
330
+ description:
331
+ "Make a typed custom field localized (each language version has its own value; translations fall back to the original's) or shared (only the original holds it; translations' own copies are deleted) (RFC-0041 §5, §6).",
332
+ input: {
333
+ key: { ...KEY, description: "The field's key" },
334
+ localized: { type: "boolean", description: "true: per language version; false: shared" },
335
+ },
336
+ required: ["key", "localized"],
337
+ destructive: false,
338
+ operation: (collection, a) => ({
339
+ op: "set_field_localized",
340
+ collection,
341
+ key: a.key ,
342
+ localized: a.localized ,
343
+ }),
344
+ },
345
+ {
346
+ name: "remove_field",
347
+ title: "Remove field",
348
+ description:
349
+ "Remove a typed custom field (RFC-0041 §6): its value is deleted from every entry, then its definition.",
350
+ input: { key: { ...KEY, description: "The field's key" } },
351
+ required: ["key"],
352
+ destructive: true,
353
+ operation: (collection, a) => ({ op: "remove_field", collection, key: a.key }),
354
+ },
355
+ ];
356
+
357
+ /** rename_field … remove_field, after the collection tools. */
358
+ export function fieldTools() {
359
+ return SPECS.map(operationTool);
360
+ }
@@ -11,6 +11,8 @@ Categories and tags: before you file an article, call list_taxonomies (which tax
11
11
 
12
12
  Collections: entries live in collections (posts, and others such as events or team). Call list_collections before create_entry and write only into those; a new kind of content needs create_collection first (a person approves it, so try dryRun: true and explain why), and update_collection renames one.
13
13
 
14
+ Typed fields: a collection may define custom fields (list_collections → \`fields\` and \`fieldsSchema\`, e.g. an event's date or a job's salary). Read its fieldsSchema before create_entry or update_entry and send values that fit it (update_entry's \`fields\` is a merge patch: null removes a key); invalid values are refused with their paths. A field marked "set on the original only" is shared by every language version: never set it on a translation. update_collection adds fields and edits labels, help and options; renaming a key, changing a type or localization, or removing a field that holds values go through rename_field, change_field_type, set_field_localized or remove_field. They always wait for a person who sees the dry run, so call them with dryRun: true first and explain the counts.
15
+
14
16
  Entry URLs: an entry lives at its collection's permalink (get_site → \`collections\`; /<collection>/{slug} by default). set_collection_permalink moves a whole collection (e.g. posts to /blog/{slug}) and leaves a 301 from the old URLs; it always waits for a person, so call it with dryRun: true first and show them the URLs that move.
15
17
 
16
18
  Corrections: when a published article changes in substance, say so with add_correction (correction, clarification or update) instead of editing silently. Notices that are live cannot be removed or reworded by you, and publishing a new one always waits for a person.
package/dist/src/tools.js CHANGED
@@ -37,6 +37,7 @@ import { ToolError, toToolError } from ".
37
37
  import { designTools } from "./design-tools.js";
38
38
  import { elevationTools } from "./elevation-tools.js";
39
39
  import { entryTools } from "./entry-tools.js";
40
+ import { fieldTools } from "./field-tools.js";
40
41
  import { menuTools } from "./menu-tools.js";
41
42
  import { pageRemovalTools, siteAndPageTools } from "./page-tools.js";
42
43
  import { permalinkTools } from "./permalink-tools.js";
@@ -89,6 +90,8 @@ export function defineTools() {
89
90
  ...taxonomyTools(),
90
91
  // RFC-0040 §5: the collection registry; new collections are a person's decision.
91
92
  ...collectionTools(),
93
+ // RFC-0041 §8: field operations rewrite entries; always a person's decision.
94
+ ...fieldTools(),
92
95
  // RFC-0038 §5: where a collection's entries live (always a person's decision).
93
96
  ...permalinkTools(),
94
97
  ...menuTools(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudhal/mcp-server",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Cloudhal MCP server: semantic site tools (pages, articles, snapshots, preview, publish) governed by the policy engine",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://cloudhal.dev",
@@ -56,15 +56,15 @@
56
56
  "README.md"
57
57
  ],
58
58
  "dependencies": {
59
- "@cloudhal/analytics": "0.4.0",
60
- "@cloudhal/agent-runtime": "0.4.0",
61
- "@cloudhal/astro-renderer": "0.4.0",
62
- "@cloudhal/comments": "0.4.0",
63
- "@cloudhal/core-contracts": "0.4.0",
64
- "@cloudhal/core-ts": "0.4.0",
65
- "@cloudhal/storage": "0.4.0",
59
+ "@cloudhal/analytics": "0.5.0",
60
+ "@cloudhal/agent-runtime": "0.5.0",
61
+ "@cloudhal/astro-renderer": "0.5.0",
62
+ "@cloudhal/comments": "0.5.0",
63
+ "@cloudhal/core-contracts": "0.5.0",
64
+ "@cloudhal/core-ts": "0.5.0",
65
+ "@cloudhal/storage": "0.5.0",
66
66
  "@modelcontextprotocol/server": "2.3.1",
67
- "@cloudhal/schedules": "0.4.0"
67
+ "@cloudhal/schedules": "0.5.0"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@cloudflare/workers-types": "^5.20261007.1",