@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.
@@ -4,6 +4,7 @@
4
4
  * `details.issues`, each at its slash path (`fields/startsAt/at`), so the hint only names the tool.
5
5
  */
6
6
 
7
+ import { FIELD_TYPES } from "@cloudhal/core-ts/fields";
7
8
 
8
9
  const OPERATIONS = "rename_field, change_field_type, set_field_localized or remove_field";
9
10
 
@@ -37,6 +38,28 @@ const HINTS = {
37
38
  "fix the mappings at the paths in details.issues: list_collections shows a preset's paths, which are required and the sources each takes (structuredData.paths); field sources need a field of a fitting type, and required values come from the entry, never a constant",
38
39
  invalid_expiry:
39
40
  "expiry.field must be a date or datetime field of the collection (list_collections → fields)",
41
+ // RFC-0045 (references and repeaters; refused until they are enabled)
42
+ fields_unsupported: `reference and repeater fields are not available on this server yet: give the field one of the types update_collection's fields input takes (${FIELD_TYPES.join(", ")}; text for now), and keep the rest of the change as it is`,
43
+ reference_target_unknown:
44
+ "a reference field's collections must be collections of this site (list_collections)",
45
+ too_many_references:
46
+ "an entry holds at most 100 references across its fields and repeater items; remove some",
47
+ unknown_entry:
48
+ "each reference names the groupId of an entry of this site in one of the field's collections (list_entries); remove or replace the ids at the paths in details.issues",
49
+ reference_target_moved:
50
+ "published entries show this entry through a field that does not allow the new collection: keep it where it is, or ask a person to unpublish or edit those entries first",
51
+ entry_referenced:
52
+ "published entries (details.referrers) show this entry, and it is the last one of its group here: ask a person to unpublish or edit them first; archiving it does not release them",
53
+ translation_shape_mismatch:
54
+ "send that repeater as get_translation_source returns it, translated: by item paths, or as the whole list when it is named in `wholeLists` (the translation already holds its own list); a whole list given beside item paths must have the source's length and order",
55
+ translation_group_in_use:
56
+ "other language versions use this entry as their original: unlink or move them first, then change its translation",
57
+ field_operation_running:
58
+ "a field operation is converting values into references to this collection: wait until it finishes, then try again",
59
+ field_operation_unsupported:
60
+ "field operations on reference and repeater fields are not available on this server yet; edit the entries instead",
61
+ field_key_in_use:
62
+ "entries of the collection already hold a value under that key: pick another key, or convert the existing field with change_field_type",
40
63
  list_field_in_use:
41
64
  "contentList sections on the pages in details.pages still filter or sort by that field: change their where/orderBy first (update_page), then try again",
42
65
  };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * RFC-0041 §8 and RFC-0045 §6: typed field changes as a person reads them in an approval prompt.
3
+ * Labels, option labels, dates in their zone; references by their target's title, id and
4
+ * collection (`venue → "Main hall" (entry_…, Places)`); repeaters by item counts and the items
5
+ * added or removed (`speakers: 2 items → 3 items (added "Ada Lovelace", Speaker)`). Every agent or
6
+ * content text is quoted and truncated (`quote()`), so it cannot pose as the prompt's own words.
7
+ */
8
+ import type { ContentEntry, FieldDefinition, Site } from "@cloudhal/core-contracts";
9
+ import { type ToolContext } from "./common.js";
10
+ type Values = Record<string, unknown>;
11
+ /** How a prompt names a translation group: its member's title and its collection's name. */
12
+ export interface Targets {
13
+ /** `"Main hall" (entry_…, Places)`, or the id alone when the site has no member. */
14
+ name(groupId: string): string;
15
+ }
16
+ /** Reads the members of every group id in `values` once, for the prompt. */
17
+ export declare function loadTargets(ctx: ToolContext, site: Site, input: {
18
+ collection: string;
19
+ locale: string;
20
+ values: readonly Values[];
21
+ }): Promise<Targets>;
22
+ /** A value as a person reads it in an approval prompt (agent text quoted and truncated). */
23
+ export declare function describeFieldValue(def: FieldDefinition | undefined, value: unknown, locale: string, targets?: Targets): string;
24
+ /**
25
+ * "startsAt → 5 Nov 2026 19:30 Istanbul, venue → "Main hall" (entry_…, Places), speakers: 2
26
+ * items → 3 items (added "Ada Lovelace", Speaker), notes removed" for an update of `entry`.
27
+ * `planned` is the store's dry run of the write: its values are described where it has them, so
28
+ * the person sees what is stored (a translation's id as its group, items through the markers),
29
+ * not what the agent typed.
30
+ */
31
+ export declare function describeFieldPatch(ctx: ToolContext, site: Site, entry: ContentEntry, change: {
32
+ patch: Values;
33
+ planned?: Values | undefined;
34
+ }): Promise<string>;
35
+ export {};
@@ -0,0 +1,299 @@
1
+ /**
2
+ * RFC-0041 §8 and RFC-0045 §6: typed field changes as a person reads them in an approval prompt.
3
+ * Labels, option labels, dates in their zone; references by their target's title, id and
4
+ * collection (`venue → "Main hall" (entry_…, Places)`); repeaters by item counts and the items
5
+ * added or removed (`speakers: 2 items → 3 items (added "Ada Lovelace", Speaker)`). Every agent or
6
+ * content text is quoted and truncated (`quote()`), so it cannot pose as the prompt's own words.
7
+ */
8
+
9
+
10
+
11
+
12
+
13
+
14
+ import { canonicalJson, getGroupMembers, normalizeEntryFields } from "@cloudhal/core-ts";
15
+ import {
16
+ fieldDefinitions,
17
+ fieldLabel,
18
+ optionLabel,
19
+ referenceValues,
20
+ renamedFrom,
21
+ } from "@cloudhal/core-ts/fields";
22
+ import { quote, } from "./common.js";
23
+
24
+
25
+
26
+ /** "5 Nov 2026" (a calendar day: no zone). */
27
+ function day(value ) {
28
+ const d = new Date(`${value}T00:00:00Z`);
29
+ if (Number.isNaN(d.getTime())) return quote(value);
30
+ return new Intl.DateTimeFormat("en-GB", {
31
+ day: "numeric",
32
+ month: "short",
33
+ year: "numeric",
34
+ timeZone: "UTC",
35
+ }).format(d);
36
+ }
37
+
38
+ /** "5 Nov 2026 19:30 Istanbul" (the wall clock in the value's own zone). */
39
+ function instant(value ) {
40
+ const v = value ;
41
+ if (typeof v?.at !== "string" || typeof v.timeZone !== "string") return quote(JSON.stringify(v));
42
+ const at = new Date(v.at);
43
+ if (Number.isNaN(at.getTime())) return quote(v.at);
44
+ try {
45
+ const parts = new Intl.DateTimeFormat("en-GB", {
46
+ day: "numeric",
47
+ month: "short",
48
+ year: "numeric",
49
+ hour: "2-digit",
50
+ minute: "2-digit",
51
+ hourCycle: "h23",
52
+ timeZone: v.timeZone,
53
+ }).format(at);
54
+ const city = (v.timeZone.split("/").pop() ?? v.timeZone).replace(/_/g, " ");
55
+ return `${parts.replace(",", "")} ${city}`;
56
+ } catch {
57
+ return `${quote(v.at)} ${quote(v.timeZone)}`;
58
+ }
59
+ }
60
+
61
+ /** How a prompt names a translation group: its member's title and its collection's name. */
62
+
63
+  
64
+
65
+
66
+
67
+ const NO_TARGETS = { name: (id) => quote(id) };
68
+
69
+ /** Reads the members of every group id in `values` once, for the prompt. */
70
+ export async function loadTargets(
71
+ ctx ,
72
+ site ,
73
+ input ,
74
+ ) {
75
+ const defs = fieldDefinitions(site, input.collection);
76
+ const ids = new Set ();
77
+ for (const values of input.values)
78
+ for (const def of defs) for (const id of referenceValues(def, values[def.key])) ids.add(id);
79
+ if (ids.size === 0) return NO_TARGETS;
80
+ const members = await getGroupMembers(ctx.store.sql, site.id, [...ids]);
81
+ const plural = (c ) => site.collections?.[c]?.labels?.[site.defaultLocale]?.plural ?? c;
82
+ return {
83
+ name: (id) => {
84
+ const list = members.get(id) ?? [];
85
+ const m =
86
+ list.find((e) => e.locale === input.locale) ??
87
+ list.find((e) => e.locale === site.defaultLocale) ??
88
+ list[0];
89
+ return m
90
+ ? `"${quote(m.title, 40)}" (${quote(id)}, ${quote(plural(m.collection), 40)})`
91
+ : `${quote(id)} (no entry in this site)`;
92
+ },
93
+ };
94
+ }
95
+
96
+ /** A list of up to three names, then how many more. */
97
+ function some(names ) {
98
+ const shown = names.slice(0, 3).join(", ");
99
+ return names.length > 3 ? `${shown} and ${names.length - 3} more` : shown;
100
+ }
101
+
102
+ /** A scalar or reference value of a field or sub-field. */
103
+ function describeScalar(
104
+ def ,
105
+ value ,
106
+ locale ,
107
+ targets ,
108
+ ) {
109
+ switch (def.type) {
110
+ case "number":
111
+ return typeof value === "number" ? String(value) : `"${quote(String(value))}"`;
112
+ case "boolean":
113
+ return value === true ? "yes" : "no";
114
+ case "date":
115
+ return typeof value === "string" ? day(value) : `"${quote(String(value))}"`;
116
+ case "datetime":
117
+ return instant(value);
118
+ case "select": {
119
+ const list = Array.isArray(value) ? value : [value];
120
+ const asField = def ;
121
+ return list.map((v) => quote(optionLabel(asField, String(v), locale, locale))).join(", ");
122
+ }
123
+ case "reference": {
124
+ const list = Array.isArray(value) ? value : [value];
125
+ return some(list.map((v) => (typeof v === "string" ? targets.name(v) : quote(String(v)))));
126
+ }
127
+ default:
128
+ return `"${quote(typeof value === "string" ? value : JSON.stringify(value))}"`;
129
+ }
130
+ }
131
+
132
+ /** The sub-field that names an item: `itemLabel`, else the first text, select or reference. */
133
+ function labelSub(def ) {
134
+ const named = ["text", "select", "reference"];
135
+ return (
136
+ def.fields.find((s) => s.key === def.itemLabel) ??
137
+ def.fields.find((s) => named.includes(s.type))
138
+ );
139
+ }
140
+
141
+ /** An item as `"Ada Lovelace", Speaker`: its label sub-value, then its other selects' labels. */
142
+ function describeItem(
143
+ def ,
144
+ item ,
145
+ locale ,
146
+ targets ,
147
+ ) {
148
+ if (!item || typeof item !== "object") return `"${quote(JSON.stringify(item) ?? "")}"`;
149
+ const values = item ;
150
+ const label = labelSub(def);
151
+ const parts = [];
152
+ if (label && Object.hasOwn(values, label.key))
153
+ parts.push(describeScalar(label, values[label.key], locale, targets));
154
+ for (const sub of def.fields)
155
+ if (sub.type === "select" && sub !== label && Object.hasOwn(values, sub.key))
156
+ parts.push(describeScalar(sub, values[sub.key], locale, targets));
157
+ return parts.length > 0 ? parts.join(", ") : "an item";
158
+ }
159
+
160
+
161
+
162
+
163
+
164
+
165
+ /**
166
+ * Items of `next` not in `before`, and the other way round (as multisets, compared as canonical
167
+ * JSON, so key order never counts), with their indices. An added and a removed item at the same
168
+ * index are one changed item. `reordered`: the items both lists hold are in another order.
169
+ */
170
+ function itemChanges(before , next ) {
171
+ const left = before.map((item, index) => ({ index, item, key: canonicalJson(item) }));
172
+ const added = [];
173
+ const matched = [];
174
+ next.forEach((item, index) => {
175
+ const key = canonicalJson(item);
176
+ const at = left.findIndex((l) => l.key === key);
177
+ if (at === -1) added.push({ index, item });
178
+ else matched.push(...left.splice(at, 1).map((l) => l.index));
179
+ });
180
+ const removedAt = new Map(left.map((l) => [l.index, l.item]));
181
+ const changed = added
182
+ .filter((a) => removedAt.has(a.index))
183
+ .map((a) => ({ index: a.index, before: removedAt.get(a.index), after: a.item }));
184
+ const pairs = new Set(changed.map((c) => c.index));
185
+ return {
186
+ added: added.filter((a) => !pairs.has(a.index)).map((a) => a.item),
187
+ removed: left.filter((l) => !pairs.has(l.index)).map((l) => l.item),
188
+ changed,
189
+ reordered: matched.some((v, i) => i > 0 && v < (matched[i - 1] )),
190
+ };
191
+ }
192
+
193
+ /** `changed item 2: person → "Grace Hopper" (entry_…, People), talk removed`. */
194
+ function describeChangedItem(
195
+ def ,
196
+ change ,
197
+ words ,
198
+ ) {
199
+ const was = (change.before && typeof change.before === "object" ? change.before : {}) ;
200
+ const now = (change.after && typeof change.after === "object" ? change.after : {}) ;
201
+ const parts = [];
202
+ for (const sub of def.fields) {
203
+ const had = Object.hasOwn(was, sub.key);
204
+ const has = Object.hasOwn(now, sub.key);
205
+ if (has && (!had || canonicalJson(was[sub.key]) !== canonicalJson(now[sub.key])))
206
+ parts.push(`${sub.key} → ${describeScalar(sub, now[sub.key], words.locale, words.targets)}`);
207
+ else if (had && !has) parts.push(`${sub.key} removed`);
208
+ }
209
+ return `changed item ${change.index + 1}: ${parts.join(", ") || "its values"}`;
210
+ }
211
+
212
+ const items = (n ) => `${n} ${n === 1 ? "item" : "items"}`;
213
+
214
+ /** `2 items → 3 items (added "Ada Lovelace", Speaker; changed item 1: role → Host)`. */
215
+ function describeRepeater(
216
+ def ,
217
+ change ,
218
+ words ,
219
+ ) {
220
+ const { locale, targets } = words;
221
+ const was = Array.isArray(change.before) ? change.before : [];
222
+ const now = Array.isArray(change.value) ? change.value : [];
223
+ const { added, removed, changed, reordered } = itemChanges(was, now);
224
+ const notes = [
225
+ added.length ? `added ${some(added.map((i) => describeItem(def, i, locale, targets)))}` : "",
226
+ removed.length
227
+ ? `removed ${some(removed.map((i) => describeItem(def, i, locale, targets)))}`
228
+ : "",
229
+ ...changed.slice(0, 3).map((c) => describeChangedItem(def, c, words)),
230
+ changed.length > 3 ? `${changed.length - 3} more items changed` : "",
231
+ ].filter(Boolean);
232
+ if (reordered) notes.push("reordered");
233
+ return `${items(was.length)} → ${items(now.length)}${notes.length ? ` (${notes.join("; ")})` : ""}`;
234
+ }
235
+
236
+ /** A value as a person reads it in an approval prompt (agent text quoted and truncated). */
237
+ export function describeFieldValue(
238
+ def ,
239
+ value ,
240
+ locale ,
241
+ targets = NO_TARGETS,
242
+ ) {
243
+ if (!def) return `"${quote(JSON.stringify(value) ?? "")}"`;
244
+ if (def.type === "repeater")
245
+ return describeRepeater(def, { before: undefined, value }, { locale, targets });
246
+ return describeScalar(def, value, locale, targets);
247
+ }
248
+
249
+ /**
250
+ * "startsAt → 5 Nov 2026 19:30 Istanbul, venue → "Main hall" (entry_…, Places), speakers: 2
251
+ * items → 3 items (added "Ada Lovelace", Speaker), notes removed" for an update of `entry`.
252
+ * `planned` is the store's dry run of the write: its values are described where it has them, so
253
+ * the person sees what is stored (a translation's id as its group, items through the markers),
254
+ * not what the agent typed.
255
+ */
256
+ export async function describeFieldPatch(
257
+ ctx ,
258
+ site ,
259
+ entry ,
260
+ change ,
261
+ ) {
262
+ const { patch, planned } = change;
263
+ const list = fieldDefinitions(site, entry.collection);
264
+ const defs = new Map(list.map((d) => [d.key, d]));
265
+ // A running rename's old key, removed together with its new one, is not named twice.
266
+ const twin = new Set(
267
+ list.flatMap((d) => {
268
+ const from = renamedFrom(d);
269
+ return from !== undefined && Object.hasOwn(patch, d.key) ? [from] : [];
270
+ }),
271
+ );
272
+ const locale = site.defaultLocale;
273
+ // The stored values through the field-operation markers, by the store's own reading (an edition
274
+ // member is not a translation there), so a running operation does not read as items changing.
275
+ const stored = normalizeEntryFields(site, entry).fields ?? {};
276
+ // What the store would write wins, also over a `null` it would not apply.
277
+ const shown = (key , value ) =>
278
+ planned && Object.hasOwn(planned, key) ? planned[key] : value;
279
+ const values = Object.fromEntries(Object.entries(patch).map(([k, v]) => [k, shown(k, v)]));
280
+ const targets = await loadTargets(ctx, site, {
281
+ collection: entry.collection,
282
+ locale: entry.locale,
283
+ values: [values, stored],
284
+ });
285
+ return Object.entries(values)
286
+ .filter(([key]) => !twin.has(key) || defs.has(key))
287
+ .map(([key, value]) => {
288
+ const def = defs.get(key);
289
+ const name = def ? `"${quote(fieldLabel(def, locale, locale), 40)}" (${key})` : key;
290
+ if (value === null) return `${name} removed`;
291
+ if (def?.type === "repeater") {
292
+ const from = renamedFrom(def);
293
+ const before = Object.hasOwn(stored, key) ? stored[key] : from && stored[from];
294
+ return `${name}: ${describeRepeater(def, { before, value }, { locale, targets })}`;
295
+ }
296
+ return `${name} → ${describeFieldValue(def, value, locale, targets)}`;
297
+ })
298
+ .join(", ");
299
+ }
@@ -1,6 +1,7 @@
1
1
  import { type FieldOperation, type FieldOperationReport } from "@cloudhal/core-ts";
2
+ import type { FieldTypeOptions } from "./collection-fields.js";
2
3
  import { type ToolDefinition } from "./common.js";
3
4
  /** The approval prompt, built from the dry run (RFC-0041 §6 step 1). */
4
5
  export declare function describeOperation(op: FieldOperation, report: FieldOperationReport, locale: string): string;
5
6
  /** rename_field … remove_field, after the collection tools. */
6
- export declare function fieldTools(): ToolDefinition[];
7
+ export declare function fieldTools(options?: FieldTypeOptions): ToolDefinition[];