@diviops/mcp-server 1.5.53 → 1.5.55

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
@@ -8,7 +8,61 @@ The Node.js MCP server inside the DiviOps harness. It gives Claude Code, Codex,
8
8
  Claude Code <-> MCP Server (stdio) <-> WordPress REST API <-> DiviOps Agent plugin
9
9
  ```
10
10
 
11
- ## 1.5.53 candidate release note
11
+ ## 1.5.55 candidate release note
12
+
13
+ With Free 1.5.27, preset deletion supports real dry-run previews and guarded
14
+ `preset_ids` exact-set apply through `preset_delete_exact_v1`. Review the preview
15
+ and pass its registry checksum on apply; bounded reference checks run again.
16
+ Defaults, references and incomplete evidence refuse even with force. Legacy
17
+ single-ID deletion retains its default-only guard, without reference checks.
18
+ MCP refuses new safety parameters on old or capability-unverified handlers.
19
+ These checks are point-in-time, not a transaction or automatic rollback.
20
+
21
+ Native Code content strings may contain literal pseudo-escapes; shared validation
22
+ and write serialization checks still require valid JSON and block delimiters.
23
+ Free 1.5.27 also fixes uncached reads/readback of valid empty page content.
24
+
25
+ `diviops_page_update_content` can retain a successful reviewed dry-run using
26
+ `retain_content:true`; apply with `content_ref` instead of resending `content`,
27
+ keeping the same target, expected checksum and backup intent. References are
28
+ memory-only, MCP-process-local and one-use, expire five minutes from reservation,
29
+ and are limited to eight candidates, 2 MiB each and 8 MiB total. They are consumed
30
+ before apply checks/dispatch, even on failed or uncertain apply: inspect the
31
+ target and review a new dry-run instead of automatically retrying. Existing write
32
+ checks still run. Retention is not approval, a backup, cross-client isolation or
33
+ a reduction in content sent from MCP to WordPress. Direct-content calls remain.
34
+
35
+ Public builder companion 1.4.8 carries exact-ID deletion and retained-content
36
+ guidance, stable native FAQ wrapper sizing, and source-qualified Divi 5.13.1
37
+ generated guidance. Dependencies and compatibility floors are unchanged.
38
+ This is source preparation only: local source evidence does not qualify these
39
+ packages or establish that staging has the fixes. Package validation, runtime
40
+ adoption and publication require separate authorization.
41
+
42
+ ## Previous 1.5.54 candidate release note
43
+
44
+ Adds optional `bounded:true` to `diviops_page_get` for UTF-8-safe raw content
45
+ chunks of at most 4096 bytes, with a full-page checksum and byte-offset
46
+ continuation. Start at offset zero, then pass each `next_offset` and the initial
47
+ `expected_checksum` until `complete:true`. Content drift refuses continuation;
48
+ discard collected chunks and restart. Free 1.5.26 supplies the precise
49
+ `page_get_bounded_utf8_v1` capability; unsupported older plugins are refused
50
+ before any page fetch, without an unbounded fallback. Reconnect after supported
51
+ plugin updates to refresh the capability handshake.
52
+
53
+ Default reads, authentication, permissions, writes, dependencies and global
54
+ compatibility floors are unchanged. Each chunk request still reads and hashes
55
+ the full upstream content. Bounded responses are not memory-bounded streaming,
56
+ a snapshot service or a universal client-delivery guarantee. This is source
57
+ candidate preparation, not new-package qualification or publication.
58
+
59
+ Independent public builder companion 1.4.7 carries three pending references:
60
+ targeted inspection and checksum-bound continuation in `tools.md`, a native CTA
61
+ preset-ownership example in `presets.md`, and opt-in native image-reveal guidance
62
+ in `design-effects.md`. The image-reveal runtime is already delivered separately
63
+ in Design Library 1.0.0-beta.24; this preparation does not re-release Design.
64
+
65
+ ## Previous 1.5.53 candidate release note
12
66
 
13
67
  The only MCP change is an inspector tool-description clarification: direct variable
14
68
  references and partial coverage are now explicit. No new tools or input-schema,
@@ -505,6 +559,8 @@ Every write tool accepts `dry_run: boolean` (default `false`). When `true`, the
505
559
 
506
560
  `meta_wp_cli` and `scf_import` do not accept `dry_run` (raw passthrough / upstream gap respectively). `scf_sync` passes `dry_run` through to upstream `wp scf json sync --dry-run`, so its preview is the upstream plain-text summary rather than a plugin-built `data.plan`. For bulk preview-then-commit flows (preset reassign, preset cleanup), see [safety-patterns.md](../docs/safety-patterns.md).
507
561
 
562
+ Preset deletion requires `preset_delete_exact_v1` for real dry-run or guarded `preset_ids` (1-200 exact IDs). Preview returns a registry checksum; exact-set apply requires it and rechecks defaults/references across all post content, postmeta and canonical preset definitions. Incomplete evidence refuses, and force cannot bypass exact-set checks. Legacy `preset_id` remains default-guard-only, with its existing force override. MCP never forwards new safety parameters to old or capability-unverified handlers, which could otherwise ignore `dry_run` and delete. See [coverage, limits and nontransactional semantics](../docs/safety-patterns.md#exact-set-preset-deletion).
563
+
508
564
  Selected guarded post-content write tools also accept `backup: true`. In apply
509
565
  mode the Free plugin stores an option-backed rollback snapshot before writing
510
566
  and returns `data.backup` evidence with the snapshot id and status. With
@@ -0,0 +1,9 @@
1
+ export declare const BOUNDED_PAGE_CAPABILITY = "page_get_bounded_utf8_v1";
2
+ export declare const BOUNDED_PAGE_TEXT_LIMIT: number;
3
+ export declare function boundedPageError(code: string, message: string): string;
4
+ /** Validate only this optional wire contract; never forward upstream diagnostics. */
5
+ export declare function serializeBoundedPageRead(result: unknown, request: {
6
+ page_id: number;
7
+ offset: number;
8
+ expected_checksum?: string;
9
+ }): string;
@@ -0,0 +1,67 @@
1
+ import { createHash } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { serializeEnvelope } from "./envelope.js";
4
+ export const BOUNDED_PAGE_CAPABILITY = "page_get_bounded_utf8_v1";
5
+ export const BOUNDED_PAGE_TEXT_LIMIT = 32 * 1024;
6
+ const TOOL = "diviops_page_get";
7
+ const checksum = z.string().regex(/^sha256:[a-f0-9]{64}$/);
8
+ const byteCount = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
9
+ const chunkEnvelope = z.object({
10
+ ok: z.literal(true),
11
+ data: z.object({
12
+ id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
13
+ encoding: z.literal("utf-8"),
14
+ content_raw: z.string().max(4096),
15
+ content_checksum: checksum,
16
+ total_bytes: byteCount,
17
+ offset: byteCount,
18
+ chunk_bytes: byteCount.max(4096),
19
+ next_offset: byteCount.nullable(),
20
+ complete: z.boolean(),
21
+ }).strict(),
22
+ }).strict();
23
+ export function boundedPageError(code, message) {
24
+ return serializeEnvelope({ ok: false, error: { code, message } }, TOOL);
25
+ }
26
+ const errors = {
27
+ not_found: "Page not found.",
28
+ forbidden: "Page read permission denied.",
29
+ invalid_input: "Invalid bounded read parameters; use the returned byte offset and checksum.",
30
+ "page.content_drift": "Page content changed; discard prior chunks and restart at offset zero.",
31
+ "page.invalid_encoding": "Page content is not valid UTF-8; no bytes were returned.",
32
+ };
33
+ /** Validate only this optional wire contract; never forward upstream diagnostics. */
34
+ export function serializeBoundedPageRead(result, request) {
35
+ const invalid = () => boundedPageError("page.invalid_bounded_response", "Plugin returned an invalid or oversized bounded page response; no content was forwarded.");
36
+ if (typeof result === "object" && result !== null && "ok" in result && result.ok === false) {
37
+ const error = "error" in result ? result.error : null;
38
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : null;
39
+ if (typeof code === "string" && Object.hasOwn(errors, code))
40
+ return boundedPageError(code, errors[code]);
41
+ return boundedPageError("page.bounded_read_failed", "Bounded page read failed; no upstream payload was forwarded.");
42
+ }
43
+ const parsed = chunkEnvelope.safeParse(result);
44
+ if (!parsed.success)
45
+ return invalid();
46
+ const data = parsed.data.data;
47
+ const bytes = Buffer.from(data.content_raw, "utf8");
48
+ const end = data.offset + data.chunk_bytes;
49
+ if (data.id !== request.page_id || data.offset !== request.offset
50
+ || bytes.toString("utf8") !== data.content_raw
51
+ || bytes.length !== data.chunk_bytes || !Number.isSafeInteger(end) || end > data.total_bytes
52
+ || data.complete !== (end === data.total_bytes)
53
+ || data.next_offset !== (data.complete ? null : end)
54
+ || (!data.complete && data.chunk_bytes < 4093)
55
+ || (request.offset > 0 && request.expected_checksum === undefined)
56
+ || (request.expected_checksum !== undefined && data.content_checksum !== request.expected_checksum))
57
+ return invalid();
58
+ if (data.offset === 0 && data.complete
59
+ && data.content_checksum !== `sha256:${createHash("sha256").update(bytes).digest("hex")}`)
60
+ return invalid();
61
+ const text = serializeEnvelope(parsed.data, TOOL);
62
+ // Also measure the surrounding text block, including its second JSON escaping layer.
63
+ if (Buffer.byteLength(text, "utf8") > BOUNDED_PAGE_TEXT_LIMIT
64
+ || Buffer.byteLength(JSON.stringify({ content: [{ type: "text", text }] }), "utf8") > BOUNDED_PAGE_TEXT_LIMIT)
65
+ return invalid();
66
+ return text;
67
+ }
package/dist/index.js CHANGED
@@ -12,7 +12,9 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12
12
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
13
  import { z } from "zod";
14
14
  import { WPClient } from "./wp-client.js";
15
+ import { BOUNDED_PAGE_CAPABILITY, boundedPageError, serializeBoundedPageRead } from "./bounded-page-read.js";
15
16
  import { requestAuthoringWrite } from "./authoring-shape-integration.js";
17
+ import { PageContentCandidates, PAGE_CANDIDATE_LIMITS, candidateError } from "./page-content-candidates.js";
16
18
  import { capabilityUpgradeHint, MissingCapabilityError, observedVersion, proToolGatesSatisfied, } from "./compatibility.js";
17
19
  import { missingCapabilityEnvelope, } from "./capability-envelope.js";
18
20
  import { ErrorCodes, envelopeMap, recordIdempotent, serializeEnvelope, withCode, wrapResponse, } from "./envelope.js";
@@ -55,6 +57,7 @@ const wp = new WPClient({
55
57
  applicationPassword: WP_APP_PASSWORD,
56
58
  });
57
59
  const authoringWrite = (endpoint, method, body, operation, dryRun) => requestAuthoringWrite(wp, { endpoint, method, body, operation, dryRun });
60
+ const pageContentCandidates = new PageContentCandidates();
58
61
  // WP-CLI (optional — Local by Flywheel via WP_PATH, or custom wrapper via WP_CLI_CMD)
59
62
  const WP_PATH = process.env.WP_PATH ?? "";
60
63
  const WP_CLI_CMD = process.env.WP_CLI_CMD?.trim() ?? "";
@@ -566,13 +569,39 @@ registerPluginTool("diviops_page_list", {
566
569
  };
567
570
  });
568
571
  registerPluginTool("diviops_page_get", {
569
- description: "Get detailed info about a specific page including its raw Divi block content and content_checksum (`sha256:` over the exact post_content bytes) for stale-write protection. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; missing page_id returns ok:false with code 'not_found' and a hint pointing to diviops_page_list.",
572
+ description: "Get detailed info about a specific page including its raw Divi block content and content_checksum (`sha256:` over the exact post_content bytes) for stale-write protection. Default response is unchanged and unbounded. Optional bounded:true requires page_get_bounded_utf8_v1 and returns only raw UTF-8 content chunks (at most 4096 bytes), id, encoding, full-page content_checksum, total_bytes, offset, chunk_bytes, next_offset (null at completion), and complete. MCP text is limited to 32 KiB including escaping/metadata. Start at offset:0; continue with next_offset and the initial expected_checksum until complete:true. Drift refuses even same-length edits; discard chunks and restart. No parser reconstruction, fallback, or snapshot storage. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; missing page_id returns ok:false with code 'not_found' and a hint pointing to diviops_page_list in legacy mode.",
570
573
  inputSchema: {
571
574
  page_id: z.number().describe("WordPress post/page ID"),
575
+ bounded: z.boolean().optional().describe("Opt into checksum-bound UTF-8 chunks; omitted/false preserves the legacy response."),
576
+ offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional().describe("Byte offset for bounded mode; defaults to zero. Use the returned next_offset."),
577
+ expected_checksum: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional().describe("Required for nonzero bounded offsets; the exact initial full-page content_checksum."),
572
578
  },
573
579
  annotations: { idempotentHint: true },
574
580
  _meta: { idempotent: "true" },
575
- }, async ({ page_id }) => {
581
+ }, async ({ page_id, bounded, offset, expected_checksum }) => {
582
+ if (bounded || offset !== undefined || expected_checksum !== undefined) {
583
+ const reply = (text) => ({ content: [{ type: "text", text }] });
584
+ if (!bounded || !Number.isSafeInteger(page_id) || page_id <= 0 || ((offset ?? 0) > 0 && expected_checksum === undefined)) {
585
+ return reply(boundedPageError("invalid_input", "Use bounded:true, a positive integer page_id, and expected_checksum for every nonzero offset."));
586
+ }
587
+ // Unlike the legacy gate, unavailable handshake evidence must not dispatch a page read.
588
+ if (handshakeState.kind !== "ok" || handshakeState.capabilities[BOUNDED_PAGE_CAPABILITY] !== true) {
589
+ return reply(boundedPageError("capability_missing", "Bounded page read capability page_get_bounded_utf8_v1 is absent or unavailable. Install a compatible plugin and reconnect; no page was fetched."));
590
+ }
591
+ try {
592
+ const result = await wp.requestEnveloped(`/page/get/${page_id}`, {
593
+ params: {
594
+ bounded: "true",
595
+ offset: String(offset ?? 0),
596
+ ...(expected_checksum === undefined ? {} : { expected_checksum }),
597
+ },
598
+ });
599
+ return reply(serializeBoundedPageRead(result, { page_id, offset: offset ?? 0, expected_checksum }));
600
+ }
601
+ catch {
602
+ return reply(boundedPageError("page.bounded_read_failed", "Bounded page read failed; no upstream payload was forwarded."));
603
+ }
604
+ }
576
605
  const result = await wp.requestEnveloped(`/page/get/${page_id}`);
577
606
  return {
578
607
  content: [
@@ -1257,13 +1286,16 @@ registerPluginTool("diviops_seo_metadata_update", {
1257
1286
  };
1258
1287
  });
1259
1288
  registerPluginTool("diviops_page_update_content", {
1260
- description: "Update the content of a page with Divi block markup. The content should be valid WordPress block markup using divi/* blocks. IMPORTANT: This overwrites the entire page content. Pass expected_checksum from diviops_page_get to refuse stale writes; omission preserves the legacy unconditional-write contract. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; missing page_id returns 'not_found', edit-permission failures return 'forbidden' (HTTP 403), stale content returns 'page.content_drift' (HTTP 409), and non-string content returns 'invalid_input' with `error.data = { field, received_type }`." +
1289
+ description: "Update the content of a page with Divi block markup. The content should be valid WordPress block markup using divi/* blocks. IMPORTANT: This overwrites the entire page content. Pass expected_checksum from diviops_page_get to refuse stale writes; omission preserves the legacy unconditional-write contract. Optionally set retain_content:true with dry_run:true and expected_checksum to retain a successful candidate in this process for 5 minutes (2 MiB each, 8 references / 8 MiB total). Returns data.content_ref, content_checksum, expires_at alongside the dry-run plan. Apply using content_ref instead of content, repeating the same page_id, expected_checksum and backup intent. References are process-local and single-use, consumed before writer dispatch even on failure; never automatically retry. Restart/expiry requires a new dry-run. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; missing page_id returns 'not_found', edit-permission failures return 'forbidden' (HTTP 403), stale content returns 'page.content_drift' (HTTP 409), and non-string content returns 'invalid_input' with `error.data = { field, received_type }`." +
1261
1290
  DRY_RUN_DESC_SUFFIX,
1262
1291
  inputSchema: {
1263
1292
  page_id: z.number().describe("WordPress post/page ID to update"),
1264
1293
  content: z
1265
1294
  .string()
1295
+ .optional()
1266
1296
  .describe("Full page content in WordPress block markup format (<!-- wp:divi/section -->...<!-- /wp:divi/section -->)"),
1297
+ content_ref: z.string().optional().describe("Single-use reference from a successful retained dry-run; apply only, mutually exclusive with content."),
1298
+ retain_content: z.boolean().optional().describe("Retain content only on an explicitly confirmed successful dry-run. Requires expected_checksum. content_checksum hashes exact submitted UTF-8 bytes, not normalized persisted bytes. Capacity and the 5-minute TTL begin before the upstream request. MCP-process-local, not isolated per client session."),
1267
1299
  expected_checksum: z
1268
1300
  .string()
1269
1301
  .regex(/^sha256:[a-f0-9]{64}$/)
@@ -1274,7 +1306,24 @@ registerPluginTool("diviops_page_update_content", {
1274
1306
  },
1275
1307
  annotations: { idempotentHint: false },
1276
1308
  _meta: { idempotent: "conditional" },
1277
- }, async ({ page_id, content, expected_checksum, dry_run, backup }) => {
1309
+ }, async ({ page_id, content, content_ref, retain_content, expected_checksum, dry_run, backup }) => {
1310
+ const reply = (result) => ({ content: [{ type: "text", text: serializeEnvelope(result, "diviops_page_update_content") }] });
1311
+ if ((content === undefined) === (content_ref === undefined) ||
1312
+ (retain_content === true && (dry_run !== true || content === undefined)) ||
1313
+ (content_ref !== undefined && (dry_run === true || retain_content === true)) ||
1314
+ ((retain_content === true || content_ref !== undefined) && (expected_checksum === undefined || !Number.isSafeInteger(page_id) || page_id <= 0))) {
1315
+ return reply(candidateError("invalid_input", "Provide exactly one of content or content_ref. Retention requires content, dry_run:true, a positive page_id and expected_checksum; reference apply requires the same page, checksum and backup intent."));
1316
+ }
1317
+ if (retain_content && Buffer.byteLength(content, "utf8") > PAGE_CANDIDATE_LIMITS.candidateBytes) {
1318
+ return reply(candidateError("page.content_ref_capacity", "Retained candidate exceeds the 2 MiB limit."));
1319
+ }
1320
+ const binding = { site: WP_URL, page_id, expected_checksum: expected_checksum, backup: backup === true };
1321
+ if (content_ref !== undefined) {
1322
+ const resolved = pageContentCandidates.consume(content_ref, binding);
1323
+ if (!resolved.ok)
1324
+ return reply(resolved);
1325
+ content = resolved.data;
1326
+ }
1278
1327
  const backupGate = backupCapabilityError("diviops_page_update_content", backup);
1279
1328
  if (backupGate)
1280
1329
  return backupGate;
@@ -1291,12 +1340,27 @@ registerPluginTool("diviops_page_update_content", {
1291
1340
  body.dry_run = true;
1292
1341
  if (backup)
1293
1342
  body.backup = true;
1294
- const result = await authoringWrite(`/page/update-content/${page_id}`, "POST", body, "page_update_content", dry_run === true);
1295
- return {
1296
- content: [
1297
- { type: "text", text: serializeEnvelope(result, "diviops_page_update_content") },
1298
- ],
1299
- };
1343
+ const reservation = retain_content ? pageContentCandidates.reserve(binding, content) : undefined;
1344
+ if (reservation && !reservation.ok)
1345
+ return reply(reservation);
1346
+ try {
1347
+ const result = await authoringWrite(`/page/update-content/${page_id}`, "POST", body, "page_update_content", dry_run === true);
1348
+ if (reservation?.ok && result.ok) {
1349
+ const data = result.data;
1350
+ if (!data || typeof data !== "object" || !("dry_run" in data) || data.dry_run !== true) {
1351
+ return reply(candidateError("page.content_ref_unconfirmed", "Writer did not confirm a successful dry-run; no candidate retained."));
1352
+ }
1353
+ if (!pageContentCandidates.confirm(reservation.data.content_ref)) {
1354
+ return reply(candidateError("page.content_ref_invalid", "Candidate expired during dry-run; run a new retained dry-run."));
1355
+ }
1356
+ return reply({ ok: true, data: { ...data, ...reservation.data } });
1357
+ }
1358
+ return reply(result);
1359
+ }
1360
+ finally {
1361
+ if (reservation?.ok)
1362
+ pageContentCandidates.cancel(reservation.data.content_ref);
1363
+ }
1300
1364
  });
1301
1365
  registerPluginTool("diviops_page_update_meta", {
1302
1366
  description: "Update page/post metadata fields without touching post_content. Supports title, slug, parent, and menu_order; use diviops_page_update_status for status changes. Slug input must already be in sanitized WordPress post_name form. When a published post's slug changes, preserve_old_slug defaults to true and records the previous slug in _wp_old_slug so WordPress old-slug redirects can work. Returns readback fields after apply. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; missing page_id or invalid parent returns 'not_found', edit-permission failures return 'forbidden' (HTTP 403), invalid/empty slug or malformed field values return 'invalid_input' with `error.data` documenting the field and sanitized slug where relevant." +
@@ -1397,7 +1461,7 @@ registerPluginTool("diviops_render_preview", {
1397
1461
  };
1398
1462
  });
1399
1463
  registerPluginTool("diviops_validate_blocks", {
1400
- description: "Validate Divi block markup before saving. Accepts EITHER inline `content` (string of block markup) OR `page_id` (loads `post_content` from the DB, requires edit_post capability on the page — useful for regression checks on shipped pages without round-tripping the markup blob). Provide exactly one. Checks structure (malformed comments, unknown blocks, missing builderVersion), required attributes (layout display on containers), and known pitfalls (button padding path, icon.enable, gradient enabled/positions). Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; success payload is { valid: bool, total_blocks: number, errors: Finding[], warnings: Finding[] } where each Finding is { block, index, code, message, path? }. Note: shape errors detected in the markup surface as success-branch `data.errors[]` entries (NOT `validation_failed` envelopes) — the findings array is the payload, not an error. The envelope's error branch fires only for tool-level failures (`invalid_input` for neither/both supplied or invalid page_id; `forbidden` for missing edit_post; `not_found` for unknown page_id; `divi_error` for an exception in the walker).",
1464
+ description: "Validate Divi block markup before saving. Accepts EITHER inline `content` (string of block markup) OR `page_id` (loads `post_content` from the DB, requires edit_post capability on the page — useful for regression checks on shipped pages without round-tripping the markup blob). Provide exactly one. Checks shared write serialization and marker integrity (literal pseudo-escapes are allowed in native Code content strings), structure (malformed comments, unknown blocks, missing builderVersion), required attributes (layout display on containers), and known pitfalls (button padding path, icon.enable, gradient enabled/positions). Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; success payload is { valid: bool, total_blocks: number, errors: Finding[], warnings: Finding[] } where each Finding is { block, index, code, message, path? }. Serialization failures return valid:false with invalid_serialization findings and total_blocks:0 because the tree was not walked. Note: shape errors detected in the markup surface as success-branch `data.errors[]` entries (NOT `validation_failed` envelopes) — the findings array is the payload, not an error. The envelope's error branch fires only for tool-level failures (`invalid_input` for neither/both supplied or invalid page_id; `forbidden` for missing edit_post; `not_found` for unknown page_id; `divi_error` for an exception in the walker).",
1401
1465
  inputSchema: {
1402
1466
  content: z
1403
1467
  .string()
@@ -2200,20 +2264,35 @@ registerPluginTool("diviops_preset_update", {
2200
2264
  };
2201
2265
  });
2202
2266
  registerPluginTool("diviops_preset_delete", {
2203
- description: "Delete a specific preset by ID. Use diviops_preset_audit first to verify the preset is unreferenced before deleting. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; missing preset_id returns code 'not_found' with a hint to diviops_preset_audit. Refuses with code 'conflict' (HTTP 409) and `error.data = { preset_id, type, module, name, reason: 'is_default' }` if the target is the registered default for its module/group bucket — clear the pointer first via diviops_preset_set_default with unset=true, or pass force=true to delete and clear the pointer in one write. The `reason` discriminator field leaves room for future conflict reasons (referenced_in_chain, etc.) without reshaping.",
2267
+ description: "Delete presets by exact ID. Legacy preset_id mode checks only the bucket default, NOT references; force=true deletes a default and clears its pointer. Additive preset_ids mode accepts 1-200 unique IDs, refuses defaults, references, unknown/ambiguous IDs, stale registry and incomplete evidence; force cannot bypass these checks. Preview with dry_run:true returns an exact plan and registry_checksum; apply requires expected_registry_checksum and rescans references. Scans all post_content (including revisions/Theme Builder), postmeta, canonical preset definitions/default pointers; conservative matches refuse. Evidence limits: 10000 rows per table, 64 MiB post evidence, nesting 64; unsupported/malformed evidence refuses. Only selected records are removed, in one registry write. No content edits, normalization, transactional guarantee or automatic rollback. Keep other writers idle. Real dry_run in either mode and all exact-set calls require preset_delete_exact_v1; older/unknown plugin capability refuses before dispatch. Returns the standardized envelope; exact-set conflicts carry error.data.reason. Legacy missing IDs return not_found.",
2204
2268
  inputSchema: {
2205
- preset_id: z.string().describe("Preset ID to delete"),
2269
+ preset_id: z.string().min(1).optional().describe("Legacy single ID; mutually exclusive with preset_ids. No reference safeguard."),
2270
+ preset_ids: z.array(z.string().regex(/^[A-Za-z0-9_-]{1,128}$/)).min(1).max(200).optional().describe("Exact guarded selection, never name/duplicate heuristics."),
2271
+ dry_run: z.boolean().optional().describe("True previews with zero writes; false/omitted applies. Capability-gated in both modes."),
2272
+ expected_registry_checksum: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional().describe("Exact preview registry_checksum, required for preset_ids apply only."),
2206
2273
  force: z
2207
2274
  .boolean()
2208
2275
  .optional()
2209
- .describe("When true, deletes the preset even if it is the registered default and clears the default pointer in the same write. Default false (refuse-by-default)."),
2276
+ .describe("Legacy preset_id only: delete a default and clear its pointer. Ignored in exact-set mode; never bypasses its safeguards."),
2210
2277
  },
2211
2278
  annotations: { idempotentHint: true },
2212
2279
  _meta: { idempotent: "true" },
2213
- }, async ({ preset_id, force }) => {
2214
- const body = { preset_id };
2280
+ }, async ({ preset_id, preset_ids, force, dry_run, expected_registry_checksum }) => {
2281
+ const exact = preset_ids !== undefined;
2282
+ if ((preset_id !== undefined) === exact || (exact && (new Set(preset_ids).size !== preset_ids.length || (!dry_run && expected_registry_checksum === undefined))) || (!exact && expected_registry_checksum !== undefined)) {
2283
+ return { content: [{ type: "text", text: serializeEnvelope({ ok: false, error: { code: "invalid_input", message: "Supply preset_id OR 1-200 unique preset_ids; exact-set apply requires expected_registry_checksum from preview." } }, "diviops_preset_delete") }] };
2284
+ }
2285
+ // Never let an old handler silently ignore preview/exact-set parameters and delete.
2286
+ if ((exact || dry_run !== undefined || expected_registry_checksum !== undefined) && (handshakeState.kind !== "ok" || handshakeState.capabilities.preset_delete_exact_v1 !== true)) {
2287
+ return missingCapabilityEnvelope(new MissingCapabilityError("preset_delete_exact_v1", handshakeState.kind === "ok" ? handshakeState.pluginVersion : undefined), "diviops_preset_delete", { serverVersion: SERVER_VERSION });
2288
+ }
2289
+ const body = exact ? { preset_ids } : { preset_id };
2215
2290
  if (force !== undefined)
2216
2291
  body.force = force;
2292
+ if (dry_run !== undefined)
2293
+ body.dry_run = dry_run;
2294
+ if (expected_registry_checksum !== undefined)
2295
+ body.expected_registry_checksum = expected_registry_checksum;
2217
2296
  const result = await wp.requestEnveloped("/preset/delete", {
2218
2297
  method: "POST",
2219
2298
  body,
@@ -2687,7 +2766,7 @@ registerPluginTool("diviops_tb_layout_update", {
2687
2766
  };
2688
2767
  });
2689
2768
  registerPluginTool("diviops_tb_layout_block_insert", {
2690
- description: "Insert one or more serialized Divi blocks into an existing Theme Builder layout without replacing the whole layout. Target a unique parent with `parent_selector` (for example `divi/group[adminLabel=\"Legal Col\"]`, or `divi/group` only when it is unique) or an explicit zero-based `parent_path` from the parsed block tree such as `0.1.2`. `position=append|prepend` inserts as children of the target block; `position=before|after` inserts beside the target within its parent. Ambiguous selectors return ok:false with code 'invalid_input'; missing targets return 'not_found'. The route parses and validates the inserted blocks, rejects malformed pseudo-escapes such as bare `u003c`, validates the final serialized layout before saving, and returns a no-op when the exact requested block sequence already exists at the insertion point." +
2769
+ description: "Insert one or more serialized Divi blocks into an existing Theme Builder layout without replacing the whole layout. Target a unique parent with `parent_selector` (for example `divi/group[adminLabel=\"Legal Col\"]`, or `divi/group` only when it is unique) or an explicit zero-based `parent_path` from the parsed block tree such as `0.1.2`. `position=append|prepend` inserts as children of the target block; `position=before|after` inserts beside the target within its parent. Ambiguous selectors return ok:false with code 'invalid_input'; missing targets return 'not_found'. The route parses and validates the inserted blocks, rejects malformed serialization (literal pseudo-escapes such as bare `u003c` are allowed in native Code content strings), validates the final serialized layout before saving, and returns a no-op when the exact requested block sequence already exists at the insertion point." +
2691
2770
  DRY_RUN_DESC_SUFFIX,
2692
2771
  inputSchema: {
2693
2772
  layout_id: z.number().int().describe("Theme Builder layout post ID to mutate"),
@@ -0,0 +1,34 @@
1
+ import type { DiviopsResponse } from "./envelope.js";
2
+ export declare const PAGE_CANDIDATE_LIMITS: Readonly<{
3
+ ttlMs: 300000;
4
+ count: 8;
5
+ candidateBytes: number;
6
+ totalBytes: number;
7
+ }>;
8
+ type Binding = {
9
+ site: string;
10
+ page_id: number;
11
+ expected_checksum: string;
12
+ backup: boolean;
13
+ };
14
+ export declare const candidateError: (code: string, message: string) => DiviopsResponse<never>;
15
+ /** Memory-only, process-local, single-use references. No payload is written to disk. */
16
+ export declare class PageContentCandidates {
17
+ private readonly now;
18
+ private entries;
19
+ private bytes;
20
+ private timer?;
21
+ constructor(now?: () => number);
22
+ private prune;
23
+ private remove;
24
+ private schedule;
25
+ reserve(binding: Binding, content: string): DiviopsResponse<{
26
+ content_ref: string;
27
+ content_checksum: string;
28
+ expires_at: string;
29
+ }>;
30
+ confirm(ref: string): boolean;
31
+ cancel(ref: string): void;
32
+ consume(ref: string, binding: Binding): DiviopsResponse<string>;
33
+ }
34
+ export {};
@@ -0,0 +1,74 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ export const PAGE_CANDIDATE_LIMITS = Object.freeze({ ttlMs: 300_000, count: 8, candidateBytes: 2 * 1024 * 1024, totalBytes: 8 * 1024 * 1024 });
3
+ export const candidateError = (code, message) => ({ ok: false, error: { code, message } });
4
+ const checksum = (content) => `sha256:${createHash("sha256").update(content, "utf8").digest("hex")}`;
5
+ /** Memory-only, process-local, single-use references. No payload is written to disk. */
6
+ export class PageContentCandidates {
7
+ now;
8
+ entries = new Map();
9
+ bytes = 0;
10
+ timer;
11
+ constructor(now = Date.now) {
12
+ this.now = now;
13
+ }
14
+ prune() {
15
+ for (const [ref, entry] of this.entries) {
16
+ if (entry.expires <= this.now())
17
+ this.remove(ref, entry);
18
+ }
19
+ }
20
+ remove(ref, entry) {
21
+ this.entries.delete(ref);
22
+ this.bytes -= entry.bytes;
23
+ }
24
+ schedule() {
25
+ if (this.timer)
26
+ clearTimeout(this.timer);
27
+ this.timer = undefined;
28
+ if (!this.entries.size)
29
+ return;
30
+ const expires = Math.min(...Array.from(this.entries.values(), e => e.expires));
31
+ this.timer = setTimeout(() => { this.prune(); this.schedule(); }, Math.max(1, expires - this.now()));
32
+ this.timer.unref();
33
+ }
34
+ reserve(binding, content) {
35
+ this.prune();
36
+ const bytes = Buffer.byteLength(content, "utf8");
37
+ if (bytes > PAGE_CANDIDATE_LIMITS.candidateBytes || this.entries.size >= PAGE_CANDIDATE_LIMITS.count || this.bytes + bytes > PAGE_CANDIDATE_LIMITS.totalBytes) {
38
+ return candidateError("page.content_ref_capacity", "Candidate retention capacity exceeded; resend content after capacity becomes available.");
39
+ }
40
+ const ref = `pcr_${randomBytes(32).toString("hex")}`;
41
+ const entry = { ...binding, content, content_checksum: checksum(content), bytes, expires: this.now() + PAGE_CANDIDATE_LIMITS.ttlMs, ready: false };
42
+ this.entries.set(ref, entry);
43
+ this.bytes += bytes;
44
+ this.schedule();
45
+ return { ok: true, data: { content_ref: ref, content_checksum: entry.content_checksum, expires_at: new Date(entry.expires).toISOString() } };
46
+ }
47
+ confirm(ref) {
48
+ this.prune();
49
+ const entry = this.entries.get(ref);
50
+ if (!entry)
51
+ return false;
52
+ entry.ready = true;
53
+ return true;
54
+ }
55
+ cancel(ref) {
56
+ const entry = this.entries.get(ref);
57
+ if (entry && !entry.ready)
58
+ this.remove(ref, entry);
59
+ this.schedule();
60
+ }
61
+ consume(ref, binding) {
62
+ this.prune();
63
+ const entry = this.entries.get(ref);
64
+ if (!entry || !entry.ready)
65
+ return candidateError("page.content_ref_invalid", "Unknown, expired, or consumed content_ref. Run a new retained dry-run.");
66
+ if (entry.site !== binding.site || entry.page_id !== binding.page_id || entry.expected_checksum !== binding.expected_checksum || entry.backup !== binding.backup || checksum(entry.content) !== entry.content_checksum) {
67
+ return candidateError("page.content_ref_mismatch", "content_ref does not match the site, page, reviewed checksum, or backup intent.");
68
+ }
69
+ // Synchronous removal precedes every asynchronous writer dispatch, including failures.
70
+ this.remove(ref, entry);
71
+ this.schedule();
72
+ return { ok: true, data: entry.content };
73
+ }
74
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diviops/mcp-server",
3
- "version": "1.5.53",
3
+ "version": "1.5.55",
4
4
  "description": "MCP server exposing Divi 5 Visual Builder as tools for Claude",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",