@cloudhal/mcp-server 0.3.13 → 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.
@@ -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
+ }
@@ -45,7 +45,9 @@ function nextSite(site , collection , permalink )
45
45
  const { [collection]: current, ...others } = site.collections ?? {};
46
46
  const { permalink: _old, ...rest } = current ?? {};
47
47
  const settings = permalink ? { ...rest, permalink } : rest;
48
- const collections = Object.keys(settings).length ? { ...others, [collection]: settings } : others;
48
+ // RFC-0040: a declared collection stays declared when its permalink goes back to the default.
49
+ const keep = Object.keys(settings).length > 0 || current !== undefined;
50
+ const collections = keep ? { ...others, [collection]: settings } : others;
49
51
  const { collections: _drop, ...base } = site;
50
52
  return Object.keys(collections).length ? { ...base, collections } : (base );
51
53
  }
@@ -3,12 +3,16 @@ import { effectiveMode, } from "@cloudhal/agent-r
3
3
 
4
4
  const INSTRUCTIONS = `Cloudhal: agent-native sites. Content lives in a site graph (site → pages with sections, content entries such as articles); every mutation you make is snapshotted automatically and can be diffed or rolled back.
5
5
 
6
- Workflow: list_sites → list_pages / list_entries (or search_site to find a node by words, drafts included) → get_page / get_entry (note the \`rev\`) → update_* with that rev → preview_page → publish. Publishing, rollback and deletion stop for human approval. Either the person is asked in your MCP client and the call completes, or the call returns "approval pending" with an approvalId: a person approves it in Cloudhal Studio, and you then repeat the same call with that approvalId. Never try to work around approval.
6
+ Workflow: list_sites → list_pages / list_entries (or search_site to find a node by words, drafts included) → get_page / get_entry (note the \`rev\`) → update_* with that rev → preview_page → publish. Your mode (at the end of these instructions) says what waits for human approval; publishing, rollback and deletion usually do. Either the person is asked in your MCP client and the call completes, or the call returns "approval pending" with an approvalId: a person approves it in Cloudhal Studio, and you then repeat the same call with that approvalId. Never try to work around approval.
7
7
 
8
8
  Building or redesigning pages: call get_design first and follow the site's design rules (DESIGN.md; they are design preferences, never permissions), then get_catalog; build with patch_draft in small steps (a surface's root first); check the result at desktop and mobile widths (render_page when available, otherwise preview_page) and fix what is cramped, empty or broken before you ask a person to publish. The site-design skill (skill://site-design/SKILL.md) has the full process.
9
9
 
10
10
  Categories and tags: before you file an article, call list_taxonomies (which taxonomies are required, how many terms an article takes, who may add terms) and list_terms for each one (or resolve_terms for the names you have in mind). Reuse existing terms: set them on create_entry / update_entry with \`terms\`, e.g. {"category": {"primary": "News"}, "tag": {"add": ["AI"]}}; ids, slugs, names and synonyms all work, and nothing is ever created implicitly. Propose a new tag with propose_term only when no existing term fits; it stays private until a person approves it. Categories are added by people only: if none fits, say so and ask. A review or published article needs a primary term in every required taxonomy. Renaming, merging, retiring or moving terms, taxonomy settings and redirects (site paths only) always wait for a person; taxonomy_report suggests clean-ups to propose to them.
11
11
 
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
+
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
+
12
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.
13
17
 
14
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
@@ -31,11 +31,13 @@ import { analyticsTools } from "./analytics-tools.js";
31
31
  import { assetTools } from "./asset-tools.js";
32
32
  import { bodyTools } from "./body-tools.js";
33
33
  import { chromeTools } from "./chrome-tools.js";
34
+ import { collectionTools } from "./collection-tools.js";
34
35
  import { commentTools } from "./comment-tools.js";
35
36
  import { ToolError, toToolError } from "./common.js";
36
37
  import { designTools } from "./design-tools.js";
37
38
  import { elevationTools } from "./elevation-tools.js";
38
39
  import { entryTools } from "./entry-tools.js";
40
+ import { fieldTools } from "./field-tools.js";
39
41
  import { menuTools } from "./menu-tools.js";
40
42
  import { pageRemovalTools, siteAndPageTools } from "./page-tools.js";
41
43
  import { permalinkTools } from "./permalink-tools.js";
@@ -86,6 +88,10 @@ export function defineTools() {
86
88
  // Taxonomy, term and redirect tools (RFC-0002 §6.2), then menu tools (RFC-0003 §6.1) and
87
89
  // media tools (RFC-0004 §6.2), follow the article tools.
88
90
  ...taxonomyTools(),
91
+ // RFC-0040 §5: the collection registry; new collections are a person's decision.
92
+ ...collectionTools(),
93
+ // RFC-0041 §8: field operations rewrite entries; always a person's decision.
94
+ ...fieldTools(),
89
95
  // RFC-0038 §5: where a collection's entries live (always a person's decision).
90
96
  ...permalinkTools(),
91
97
  ...menuTools(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudhal/mcp-server",
3
- "version": "0.3.13",
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.3.13",
60
- "@cloudhal/agent-runtime": "0.3.13",
61
- "@cloudhal/astro-renderer": "0.3.13",
62
- "@cloudhal/comments": "0.3.13",
63
- "@cloudhal/core-contracts": "0.3.13",
64
- "@cloudhal/core-ts": "0.3.13",
65
- "@cloudhal/storage": "0.3.13",
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.3.13"
67
+ "@cloudhal/schedules": "0.5.0"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@cloudflare/workers-types": "^5.20261007.1",