@diviops/mcp-server 1.5.37 → 1.5.39

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/dist/index.js CHANGED
@@ -12,7 +12,7 @@ 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 { MissingCapabilityError, proToolGatesSatisfied, } from "./compatibility.js";
15
+ import { capabilityUpgradeHint, MissingCapabilityError, observedVersion, proToolGatesSatisfied, } from "./compatibility.js";
16
16
  import { missingCapabilityEnvelope, } from "./capability-envelope.js";
17
17
  import { ErrorCodes, envelopeMap, recordIdempotent, serializeEnvelope, withCode, wrapResponse, } from "./envelope.js";
18
18
  import { preflightCrossEnvHeaderSync, } from "./cross-env-preflight/header-preflight.js";
@@ -22,8 +22,10 @@ import { createSourcePayloadRef, loadSourcePayloadRef, } from "./cross-env-prefl
22
22
  import { optimizeSchema } from "./schema-optimizer.js";
23
23
  import { schemaModuleRoute } from "./schema-route.js";
24
24
  import { createWpCli } from "./wp-cli.js";
25
+ import { META_INFO_CONFIG, META_PING_CONFIG, requestAbortSignal, } from "./health-tools.js";
26
+ import { CanonicalToolRegistry } from "./canonical-tool-registry.js";
25
27
  import { isolationFailure, scanValueForForeignVarRefs, writerIsolationErrorResult, } from "./validate-attrs.js";
26
- import { readFileSync, readdirSync } from "fs";
28
+ import { readFileSync, readdirSync, realpathSync } from "fs";
27
29
  import { join, dirname } from "path";
28
30
  import { fileURLToPath } from "url";
29
31
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -31,7 +33,9 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
31
33
  const WP_URL = process.env.WP_URL ?? "";
32
34
  const WP_USER = process.env.WP_USER ?? "";
33
35
  const WP_APP_PASSWORD = process.env.WP_APP_PASSWORD ?? "";
34
- if (!WP_URL || !WP_USER || !WP_APP_PASSWORD) {
36
+ function requireCredentials() {
37
+ if (WP_URL && WP_USER && WP_APP_PASSWORD)
38
+ return;
35
39
  const missing = [
36
40
  !WP_URL && "WP_URL",
37
41
  !WP_USER && "WP_USER",
@@ -86,10 +90,7 @@ const SERVER_VERSION = (() => {
86
90
  }
87
91
  })();
88
92
  // ── MCP Server ───────────────────────────────────────────────────────
89
- const server = new McpServer({
90
- name: "diviops-mcp",
91
- version: SERVER_VERSION,
92
- });
93
+ const registry = new CanonicalToolRegistry();
93
94
  let handshakeState = { kind: "pending" };
94
95
  const toolCatalog = [];
95
96
  function recordToolCatalog(entry) {
@@ -310,7 +311,10 @@ function backupCapabilityError(toolName, backup) {
310
311
  }
311
312
  catch (e) {
312
313
  if (e instanceof MissingCapabilityError) {
313
- return missingCapabilityEnvelope(e, toolName, "Update the diviops-agent WP plugin to a version that supports rollback snapshot backup, or omit backup:true from this call.");
314
+ return missingCapabilityEnvelope(e, toolName, {
315
+ serverVersion: SERVER_VERSION,
316
+ hint: capabilityUpgradeHint(e.capability, e.pluginComponent, "Alternatively, omit backup:true from this call."),
317
+ });
314
318
  }
315
319
  throw e;
316
320
  }
@@ -339,14 +343,16 @@ function registerPluginTool(name, config, handler) {
339
343
  }
340
344
  catch (e) {
341
345
  if (e instanceof MissingCapabilityError) {
342
- return missingCapabilityEnvelope(e, name);
346
+ return missingCapabilityEnvelope(e, name, {
347
+ serverVersion: SERVER_VERSION,
348
+ });
343
349
  }
344
350
  throw e;
345
351
  }
346
352
  return handler(args);
347
353
  });
348
354
  recordIdempotent(name, config?._meta);
349
- server.registerTool(name, config, wrapped);
355
+ registry.registerTool(name, config, wrapped);
350
356
  }
351
357
  /**
352
358
  * Server-local tools (no plugin dependency) register via this thin shim
@@ -358,7 +364,7 @@ function registerPluginTool(name, config, handler) {
358
364
  function registerLocalTool(name, config, handler) {
359
365
  recordToolCatalog({ name, kind: "server_local", registered: true });
360
366
  recordIdempotent(name, config?._meta);
361
- server.registerTool(name, config, handler);
367
+ registry.registerTool(name, config, handler);
362
368
  }
363
369
  /**
364
370
  * Register a Pro-coverage-slice tool (ADR-003 / ADR-007).
@@ -411,7 +417,7 @@ function registerProTool(name, config, handler, gates) {
411
417
  return;
412
418
  catalogEntry.registered = true;
413
419
  recordIdempotent(name, config?._meta);
414
- server.registerTool(name, config, handler);
420
+ registry.registerTool(name, config, handler);
415
421
  }
416
422
  /* eslint-enable @typescript-eslint/no-explicit-any */
417
423
  // ── dry_run convention ──────────────────────────────────────────────
@@ -438,7 +444,67 @@ const BACKUP_FIELD = z
438
444
  .optional()
439
445
  .default(false)
440
446
  .describe("When true on supported content writes, capture a rollback snapshot before applying. dry_run + backup only reports the planned snapshot and does not create one.");
447
+ const SEO_FIELD = z.enum(["seo_title", "meta_description"]);
448
+ const SEO_PROVIDER = z.enum(["auto", "tsf"]);
449
+ const SEO_CHANGE = z.discriminatedUnion("action", [
450
+ z.strictObject({
451
+ field: SEO_FIELD,
452
+ action: z.literal("set"),
453
+ value: z.string(),
454
+ }),
455
+ z.strictObject({
456
+ field: SEO_FIELD,
457
+ action: z.literal("clear"),
458
+ }),
459
+ ]);
460
+ const SEO_CHANGES = z
461
+ .array(SEO_CHANGE)
462
+ .min(1)
463
+ .max(2)
464
+ .superRefine((changes, context) => {
465
+ const seen = new Set();
466
+ changes.forEach((change, index) => {
467
+ if (seen.has(change.field)) {
468
+ context.addIssue({
469
+ code: "custom",
470
+ message: `Duplicate operation for semantic field '${change.field}'.`,
471
+ path: [index, "field"],
472
+ });
473
+ }
474
+ seen.add(change.field);
475
+ });
476
+ });
441
477
  // ── Read Tools ───────────────────────────────────────────────────────
478
+ registerPluginTool("diviops_seo_provider_list", {
479
+ description: "List the Free/core semantic SEO provider adapters and their installed, active, version, compatibility, field, and capability evidence. The first MVP reports only The SEO Framework and never loads an inactive provider. This is discovery only: it returns no post payload and provides no provider installation or activation path. Returns the standardized envelope.",
480
+ inputSchema: {},
481
+ annotations: { idempotentHint: true },
482
+ _meta: { idempotent: "true" },
483
+ }, async () => {
484
+ const result = await wp.requestEnveloped("/seo/provider/list");
485
+ return {
486
+ content: [
487
+ { type: "text", text: serializeEnvelope(result, "diviops_seo_provider_list") },
488
+ ],
489
+ };
490
+ });
491
+ registerPluginTool("diviops_seo_metadata_get", {
492
+ description: "Read explicit and effective semantic SEO metadata for one provider-supported post. Free/core and explicit-metadata-only: caller-visible fields are fixed to seo_title and meta_description; no raw metadata keys or provider maps are accepted or returned. Requires edit_post before stored payload exposure. Returns exact explicit presence/value, effective provider output, deterministic checksum, provider lifecycle/capability evidence, canonical WordPress identity evidence, and cache status. Error codes include not_found, forbidden, seo.provider_absent, seo.provider_incompatible, seo.provider_unsupported, and seo.post_type_unsupported. Returns the standardized envelope.",
493
+ inputSchema: {
494
+ post_id: z.number().int().positive().describe("WordPress post/page ID to inspect. Requires edit_post on this exact target."),
495
+ provider: SEO_PROVIDER.optional().default("auto").describe("Provider selector. auto resolves only the active supported TSF adapter in V1."),
496
+ },
497
+ annotations: { idempotentHint: true },
498
+ _meta: { idempotent: "true" },
499
+ }, async ({ post_id, provider }) => {
500
+ const params = new URLSearchParams({ provider: provider ?? "auto" }).toString();
501
+ const result = await wp.requestEnveloped(`/seo/metadata/${post_id}?${params}`);
502
+ return {
503
+ content: [
504
+ { type: "text", text: serializeEnvelope(result, "diviops_seo_metadata_get") },
505
+ ],
506
+ };
507
+ });
442
508
  registerPluginTool("diviops_page_list", {
443
509
  description: "List pages/posts in the WordPress site. Returns title, ID, URL, status, and whether each page uses Divi builder. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }.",
444
510
  inputSchema: {
@@ -743,7 +809,10 @@ registerPluginTool("diviops_schema_get_module", {
743
809
  if (handshakeState.kind === "ok" &&
744
810
  !handshakeState.capabilities["schema_get_module_dump_all"]) {
745
811
  const err = new MissingCapabilityError("schema_get_module_dump_all", handshakeState.pluginVersion);
746
- return missingCapabilityEnvelope(err, "diviops_schema_get_module", "Update the diviops-agent WP plugin to a version that exposes the dump-all surface, or use mode:'single'.");
812
+ return missingCapabilityEnvelope(err, "diviops_schema_get_module", {
813
+ serverVersion: SERVER_VERSION,
814
+ hint: capabilityUpgradeHint(err.capability, err.pluginComponent, "Alternatively, use mode:'single'."),
815
+ });
747
816
  }
748
817
  const result = await wp.requestEnveloped("/schema/module/dump-all");
749
818
  return {
@@ -1125,6 +1194,39 @@ registerPluginTool("diviops_meta_find_icon", {
1125
1194
  };
1126
1195
  });
1127
1196
  // ── Write Tools ──────────────────────────────────────────────────────
1197
+ registerPluginTool("diviops_seo_metadata_update", {
1198
+ description: "Update explicit TSF SEO metadata on one provider-supported post through the Free/core semantic contract. Explicit metadata only: changes is a strict one-or-two-item discriminated list for seo_title and meta_description; set requires a plain-text value and clear forbids one. Unknown properties, duplicate fields, HTML/markup, control or invalid UTF-8 bytes, serialized/non-scalar values, secret-like values, and unresolved Divi/global/provider/dynamic tokens are refused before mutation. Requires edit_post and expected_checksum; drift refuses before mutation with no force path. Uses TSF's public sanitize/write/clear lifecycle, exact stored readback, request-local rollback on error/mismatch, and reports before/after checksums, readback, lifecycle, cache, rollback, no-op, and write evidence. Effective output must be verified by a follow-up diviops_seo_metadata_get. No persistent snapshot, canonical override, robots, social, schema, redirect, bulk, cross-site, or automatic Divi extraction path exists." +
1199
+ DRY_RUN_DESC_SUFFIX,
1200
+ inputSchema: {
1201
+ post_id: z.number().int().positive().describe("WordPress post/page ID to update. Requires edit_post on this exact target."),
1202
+ provider: SEO_PROVIDER.optional().default("auto").describe("Provider selector. Use auto or tsf."),
1203
+ expected_checksum: z
1204
+ .string()
1205
+ .regex(/^sha256:[a-f0-9]{64}$/)
1206
+ .describe("Exact checksum returned by diviops_seo_metadata_get. Required; there is no force path."),
1207
+ changes: SEO_CHANGES.describe("Strict semantic set/clear operations. Each field may appear at most once."),
1208
+ dry_run: DRY_RUN_FIELD,
1209
+ },
1210
+ annotations: { idempotentHint: false },
1211
+ _meta: { idempotent: "conditional" },
1212
+ }, async ({ post_id, provider, expected_checksum, changes, dry_run }) => {
1213
+ const body = {
1214
+ provider: provider ?? "auto",
1215
+ expected_checksum,
1216
+ changes,
1217
+ };
1218
+ if (dry_run)
1219
+ body.dry_run = true;
1220
+ const result = await wp.requestEnveloped(`/seo/metadata/${post_id}`, {
1221
+ method: "POST",
1222
+ body,
1223
+ });
1224
+ return {
1225
+ content: [
1226
+ { type: "text", text: serializeEnvelope(result, "diviops_seo_metadata_update") },
1227
+ ],
1228
+ };
1229
+ });
1128
1230
  registerPluginTool("diviops_page_update_content", {
1129
1231
  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. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; missing page_id returns 'not_found', edit-permission failures return 'forbidden' (HTTP 403), non-string content returns 'invalid_input' with `error.data = { field, received_type }`." +
1130
1232
  DRY_RUN_DESC_SUFFIX,
@@ -1240,7 +1342,10 @@ registerPluginTool("diviops_render_preview", {
1240
1342
  }
1241
1343
  catch (e) {
1242
1344
  if (e instanceof MissingCapabilityError) {
1243
- return missingCapabilityEnvelope(e, "diviops_render_preview", "Update the diviops-agent WP plugin to a version that supports page_id rendering, or provide inline content instead.");
1345
+ return missingCapabilityEnvelope(e, "diviops_render_preview", {
1346
+ serverVersion: SERVER_VERSION,
1347
+ hint: capabilityUpgradeHint(e.capability, e.pluginComponent, "Alternatively, provide inline content instead."),
1348
+ });
1244
1349
  }
1245
1350
  throw e;
1246
1351
  }
@@ -1277,7 +1382,10 @@ registerPluginTool("diviops_validate_blocks", {
1277
1382
  }
1278
1383
  catch (e) {
1279
1384
  if (e instanceof MissingCapabilityError) {
1280
- return missingCapabilityEnvelope(e, "diviops_validate_blocks", "Update the diviops-agent WP plugin to a version that supports page_id validation, or provide inline content instead.");
1385
+ return missingCapabilityEnvelope(e, "diviops_validate_blocks", {
1386
+ serverVersion: SERVER_VERSION,
1387
+ hint: capabilityUpgradeHint(e.capability, e.pluginComponent, "Alternatively, provide inline content instead."),
1388
+ });
1281
1389
  }
1282
1390
  throw e;
1283
1391
  }
@@ -3383,12 +3491,12 @@ registerLocalTool("diviops_scf_field_group_get", {
3383
3491
  });
3384
3492
  // ── Connection ──────────────────────────────────────────────────────
3385
3493
  registerLocalTool("diviops_meta_ping", {
3386
- description: "Test the connection to the WordPress site and verify the Divi MCP plugin is active. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; success payload is { connected: true, message: \"Connected to Divi <version>\" } and connection failure surfaces as { ok: false, error: { code: 'wp_error', message } } with the underlying transport message preserved.",
3387
- annotations: { idempotentHint: true },
3494
+ ...META_PING_CONFIG,
3388
3495
  _meta: { idempotent: "true" },
3389
- }, async () => {
3496
+ }, async (_args, context) => {
3497
+ const signal = requestAbortSignal(_args, context);
3390
3498
  const response = await wrapResponse(async () => {
3391
- const ping = await wp.testConnection();
3499
+ const ping = await wp.testConnection(signal);
3392
3500
  if (!ping.ok) {
3393
3501
  withCode(ErrorCodes.WP_ERROR, ping.message);
3394
3502
  }
@@ -3401,8 +3509,7 @@ registerLocalTool("diviops_meta_ping", {
3401
3509
  };
3402
3510
  });
3403
3511
  registerLocalTool("diviops_meta_info", {
3404
- description: "Returns DiviOps MCP server identity, server_version, license type, numeric tool_count, registered tool catalog summary, active plugin version summary, WP-CLI allowlist, and plugin handshake/slice state including Pro and FluentCart target readiness. Use as the S0 preflight before dogfooding or product work. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }.",
3405
- annotations: { idempotentHint: true },
3512
+ ...META_INFO_CONFIG,
3406
3513
  _meta: { idempotent: "true" },
3407
3514
  }, async () => {
3408
3515
  const response = await wrapResponse(async () => buildMetaInfo());
@@ -3413,7 +3520,7 @@ registerLocalTool("diviops_meta_info", {
3413
3520
  };
3414
3521
  });
3415
3522
  // ── Resources ────────────────────────────────────────────────────────
3416
- server.registerResource("divi-block-format-guide", "divi://block-format-guide", {}, async () => ({
3523
+ registry.registerResource("divi-block-format-guide", "divi://block-format-guide", {}, async () => ({
3417
3524
  contents: [
3418
3525
  {
3419
3526
  uri: "divi://block-format-guide",
@@ -4845,8 +4952,11 @@ function registerProTools() {
4845
4952
  if (global_update_file !== undefined &&
4846
4953
  handshakeState.kind === "ok" &&
4847
4954
  !handshakeState.capabilities["fluentcart_license_update_file_set"]) {
4848
- const err = new MissingCapabilityError("fluentcart_license_update_file_set", handshakeState.pluginVersion);
4849
- return missingCapabilityEnvelope(err, "diviops_fc_license_settings_update", "Update the diviops-agent-pro WP plugin to a version that supports authoring the global_update_file pointer, or omit global_update_file from this call.");
4955
+ const err = new MissingCapabilityError("fluentcart_license_update_file_set", handshakeState.proVersion, "pro");
4956
+ return missingCapabilityEnvelope(err, "diviops_fc_license_settings_update", {
4957
+ serverVersion: SERVER_VERSION,
4958
+ hint: capabilityUpgradeHint(err.capability, err.pluginComponent, "Alternatively, omit global_update_file from this call."),
4959
+ });
4850
4960
  }
4851
4961
  const body = {};
4852
4962
  if (enabled !== undefined)
@@ -5041,9 +5151,9 @@ function registerProTools() {
5041
5151
  // ── V3.1 — order/license/activation read + guarded mark-paid ───────
5042
5152
  //
5043
5153
  // FluentCart commerce-artifact readback surface plus a single
5044
- // mutating tool: a guarded offline mark-paid that mirrors FCP's
5045
- // OrderController::markAsPaid. Lifts the local checkout/license
5046
- // smoke off of eval-file PHP probes.
5154
+ // mutating tool: a guarded offline mark-paid that uses FluentCart 1.6's
5155
+ // canonical charge + StatusHelper synchronization contract. Lifts the local
5156
+ // checkout/license smoke off of eval-file PHP probes.
5047
5157
  // diviops_fc_order_list — POST /diviops/v1/pro/fluentcart/orders
5048
5158
  registerProTool("diviops_fc_order_list", {
5049
5159
  description: "List FluentCart orders for commerce dogfooding / smoke baselines (Pro tier; V3.1; requires FluentCart installed + activated). Returns a paginated summary with order identity (id, status, payment_status), gateway info (payment_method + payment_method_title, mode), totals (currency, total_amount, total_paid), fulfillment_type, type (payment/subscription), customer (customer_id + customer_email), item_count, license_count, and timestamps (created_at, updated_at, completed_at). Filterable by status, payment_status, payment_method, product_id, customer_email, and mode (test/live). Read-only. Returns the standardized envelope { ok, data?, error: { code, message, hint? } }; the success payload is { orders: OrderSummary[], pagination: { page, per_page, total, total_pages }, filters: { ... } }. Error codes: invalid_input (HTTP 400) when status/payment_status/mode is out of range; fluentcart.module_inactive (HTTP 412); fluentcart.query_failed (HTTP 500). Use this alongside diviops_fc_order_get / diviops_fc_license_list to verify a smoke run without raw SQL probes.",
@@ -5163,7 +5273,7 @@ function registerProTools() {
5163
5273
  }, { target: "fluentcart", capabilityKey: "fluentcart_order_get" });
5164
5274
  // diviops_fc_order_mark_paid — POST /diviops/v1/pro/fluentcart/orders/{id}/mark-paid
5165
5275
  registerProTool("diviops_fc_order_mark_paid", {
5166
- description: "Guarded local/offline mark-paid for a FluentCart order (Pro tier; V3.1; requires FluentCart installed + activated). Mirrors the canonical `FluentCart\\App\\Http\\Controllers\\OrderController::markAsPaid` sequence — updates the pending offline transaction, flips payment_status to 'paid' (unless partially_refunded), flips order status to 'processing' (and 'completed' for digital fulfillment), then dispatches `OrderPaid` (which fires the `fluent_cart/order_paid` WordPress action, the listener `LicenseGenerationHandler::maybeGenerateLicensesOnPurchaseSuccess` hangs off of) plus `OrderStatusUpdated`. Does NOT directly insert license rows — license generation is a side effect of the dispatched event, exactly like the FCP admin path. Refuses non-offline gateways (anything other than `payment_method='offline_payment'`) with `fluentcart.unsupported_payment_method` (HTTP 422) — this slice is for local/test/COD smokes only. Refuses canceled orders with `fluentcart.order_canceled` (HTTP 422). Already-paid orders are repeat-safe: returns `ok:true` with `data.already_paid: true` (no second event fires). **dry_run defaults to TRUE** for safety; apply requires `dry_run:false` PLUS `confirm_order_id` + `confirm_payment_method` + `confirm_due_amount` matching current state. Dry-run payload: { dry_run:true, plan: { summary, changes[] (payment_status, status, total_paid, transaction), warnings[] }, events: ['fluent_cart/order_paid', 'fluent_cart/order_status_updated'], order_id, licenses_before }. Apply payload: { order: OrderSummary (post-mutation), transaction: TransactionSummary, events_fired: string[], licenses_before, licenses_after, licenses_created, license_ids: number[], licenses: LicenseRedactedSummary[] (no full keys). Error codes: invalid_input (400) when id/confirmation fields are wrong; not_found (404); fluentcart.order_canceled (422); fluentcart.unsupported_payment_method (422); fluentcart.module_inactive (412); fluentcart.command_failed (500). Idempotency: repeat-safe via already_paid sentinel." +
5276
+ description: "Guarded local/offline mark-paid for a FluentCart order (Pro tier; V3.1; exact audited FluentCart 1.6.0 contract). DiviOps serializes apply on the FluentCart order row, creates or updates one canonical succeeded `transaction_type=charge` transaction, then delegates the atomic paid transition and every derived cart/event/subscription/license/fulfillment effect to `FluentCart\\App\\Helpers\\StatusHelper::syncOrderStatuses`; it never dispatches vendor events or mutates subscriptions/licenses directly. Initial payment/subscription orders use FluentCart's `order_paid` and initial-activation family; renewal invoices use `renewal_paid` and store-managed subscription advancement without replaying new-order effects. Exact Free/installed-Pro version, transaction-lock, and StatusHelper shapes are checked before querying or mutation; older, newer, mixed, and unsupported shapes fail closed with component evidence. Refuses real gateways, canceled orders, missing subscription context, non-manual/system subscription collection, and conflicting legacy/duplicate transaction candidates. Already-paid and concurrent retries are no-ops after locked readback, while interrupted retries reuse the single matching succeeded charge before synchronization. **dry_run defaults to TRUE**; apply requires `dry_run:false` plus matching `confirm_order_id`, `confirm_payment_method`, and `confirm_due_amount`. Dry-run returns the transaction action plus canonical sync effect scope. Apply returns exact order/charge readback, initial-vs-renewal transition evidence, redacted license readback, and subscription before/after summaries. Exceptions after transaction mutation starts return `fluentcart.mutation_uncertain` with best-effort readback and explicitly require manual inspection instead of a blind retry. Error codes include invalid_input (400), not_found (404), fluentcart.unsupported_version (412), fluentcart.order_canceled / fluentcart.unsupported_payment_method / fluentcart.unsupported_order_shape / fluentcart.missing_subscription_context / fluentcart.unsupported_subscription_shape (422), fluentcart.transaction_conflict / fluentcart.concurrent_state_changed (409), fluentcart.readback_failed / fluentcart.mutation_uncertain (500), fluentcart.module_inactive (412), and fluentcart.command_failed (500). Idempotency is conditional and retry-safe only when the response says so." +
5167
5277
  " Pass dry_run: false plus the confirm_* fields to apply.",
5168
5278
  inputSchema: {
5169
5279
  id: z
@@ -5444,8 +5554,26 @@ function registerProTools() {
5444
5554
  };
5445
5555
  }, { target: "fluentcart", capabilityKey: "fluentcart_gateway_get" });
5446
5556
  }
5557
+ let productionRegistryFinalized = false;
5558
+ /**
5559
+ * Complete the canonical registry after the connected site's handshake has
5560
+ * settled. Production startup and the credential-free dual-era compatibility
5561
+ * fixture deliberately share this seam so the v2 proof materializes the real
5562
+ * Free/Pro-gated catalog instead of maintaining a second set of definitions.
5563
+ */
5564
+ export function finalizeProductionRegistryForHandshake(state) {
5565
+ if (productionRegistryFinalized) {
5566
+ throw new Error("Production MCP registry has already been finalized");
5567
+ }
5568
+ handshakeState = state;
5569
+ registerCrossEnvEvidenceTools();
5570
+ registerProTools();
5571
+ productionRegistryFinalized = true;
5572
+ return registry;
5573
+ }
5447
5574
  // ── Start ────────────────────────────────────────────────────────────
5448
5575
  async function main() {
5576
+ requireCredentials();
5449
5577
  // Capability handshake — populate the per-tool gate map (#486)
5450
5578
  // and the ADR-003 / ADR-007 Pro-extension surface (target presence,
5451
5579
  // module activation). On Free-only sites the Pro fields are
@@ -5455,7 +5583,7 @@ async function main() {
5455
5583
  handshakeState = {
5456
5584
  kind: "ok",
5457
5585
  capabilities: hs.capabilities,
5458
- pluginVersion: hs.plugin_version,
5586
+ pluginVersion: observedVersion(hs.plugin_version),
5459
5587
  proVersion: hs.pro_version,
5460
5588
  proActive: hs.pro_active === true,
5461
5589
  availableTargets: hs.available_targets ?? {},
@@ -5469,9 +5597,9 @@ async function main() {
5469
5597
  const proInfo = handshakeState.proActive
5470
5598
  ? `Pro active (${hs.pro_version ?? "version unknown"})`
5471
5599
  : "Pro inactive";
5472
- console.error(`Handshake OK: plugin ${hs.plugin_version}, ${diviInfo}, ${proInfo}, ${capCount} capabilities`);
5600
+ console.error(`Handshake OK: plugin ${hs.plugin_version ?? "version unknown"}, ${diviInfo}, ${proInfo}, ${capCount} capabilities`);
5473
5601
  if (capCount === 0) {
5474
- console.error("Warning: plugin returned an empty capability map. Plugin-touching tools will fail with an upgrade hint. Update diviops-agent to ≥1.2.0.");
5602
+ console.error("Warning: plugin returned an empty capability map. Plugin-touching tools will refuse with capability-based upgrade guidance; install a compatible Free plugin component and reconnect the MCP session.");
5475
5603
  }
5476
5604
  }
5477
5605
  catch (error) {
@@ -5493,18 +5621,32 @@ async function main() {
5493
5621
  // The cross-env evidence schema is additive-capability aware: older Free
5494
5622
  // plugins retain the existing header-only enum, while current plugins prove
5495
5623
  // footer support through cross_env_footer_layout_evidence.
5496
- registerCrossEnvEvidenceTools();
5497
- // Pro coverage-slice registration must run AFTER the handshake so the
5498
- // gates (`pro_active`, `available_targets`, `active_modules`,
5499
- // capability map) reflect the connected site's actual state. On Free
5500
- // sites — or when the handshake failed — registerProTool's internal
5501
- // gates short-circuit so no Pro tools register.
5502
- registerProTools();
5624
+ // Cross-env evidence and Pro coverage-slice registration must run AFTER
5625
+ // the handshake so capability and tier gates reflect the connected site.
5626
+ const finalizedRegistry = finalizeProductionRegistryForHandshake(handshakeState);
5627
+ const server = new McpServer({
5628
+ name: "diviops-mcp",
5629
+ version: SERVER_VERSION,
5630
+ });
5631
+ finalizedRegistry.install(server);
5503
5632
  const transport = new StdioServerTransport();
5504
5633
  await server.connect(transport);
5505
5634
  console.error("Divi MCP Server running on stdio");
5506
5635
  }
5507
- main().catch((error) => {
5508
- console.error("Fatal error:", error);
5509
- process.exit(1);
5510
- });
5636
+ function isDirectEntryPoint() {
5637
+ const entryPoint = process.argv[1];
5638
+ if (!entryPoint)
5639
+ return false;
5640
+ try {
5641
+ return realpathSync(entryPoint) === fileURLToPath(import.meta.url);
5642
+ }
5643
+ catch {
5644
+ return false;
5645
+ }
5646
+ }
5647
+ if (isDirectEntryPoint()) {
5648
+ main().catch((error) => {
5649
+ console.error("Fatal error:", error);
5650
+ process.exit(1);
5651
+ });
5652
+ }
@@ -8,13 +8,13 @@
8
8
  *
9
9
  * Before any network call the CLI rejects foreign CSS aliases in attrs, then
10
10
  * verifies the plugin handshake reports `storage_multipath_probe_v1` (the
11
- * storage-path capability contract, shipped in plugin 1.4.9).
11
+ * storage-path capability contract).
12
12
  *
13
13
  * `--dry-run` never reaches this module: it requires no credentials, no
14
14
  * handshake, and no network.
15
15
  */
16
16
  import { WPClient } from "../wp-client.js";
17
- import type { HandshakeResult } from "../compatibility.js";
17
+ import { type HandshakeResult } from "../compatibility.js";
18
18
  import type { DiviopsResponse } from "../envelope.js";
19
19
  import { type ForeignVarRef } from "../validate-attrs.js";
20
20
  import type { ButtonPresetEntry } from "./button-emitter.js";
@@ -39,8 +39,10 @@ export declare class CredentialsMissingError extends Error {
39
39
  }
40
40
  export declare class CapabilityMissingError extends Error {
41
41
  readonly capability: string;
42
- readonly pluginVersion: string;
43
- constructor(capability: string, pluginVersion: string);
42
+ readonly pluginVersion: string | null | undefined;
43
+ readonly serverVersion: string | null | undefined;
44
+ readonly tool: string;
45
+ constructor(capability: string, pluginVersion: string | null | undefined, serverVersion: string | null | undefined, tool?: string);
44
46
  }
45
47
  export declare class PresetIsolationError extends Error {
46
48
  readonly refs: ForeignVarRef[];
@@ -8,12 +8,13 @@
8
8
  *
9
9
  * Before any network call the CLI rejects foreign CSS aliases in attrs, then
10
10
  * verifies the plugin handshake reports `storage_multipath_probe_v1` (the
11
- * storage-path capability contract, shipped in plugin 1.4.9).
11
+ * storage-path capability contract).
12
12
  *
13
13
  * `--dry-run` never reaches this module: it requires no credentials, no
14
14
  * handshake, and no network.
15
15
  */
16
16
  import { WPClient } from "../wp-client.js";
17
+ import { capabilityMissingMessage, capabilityUpgradeHint, observedVersion, } from "../compatibility.js";
17
18
  import { formatIsolationError, scanAttrsForForeignVarRefs, } from "../validate-attrs.js";
18
19
  import { buildPresetCreateBody } from "./button-emitter.js";
19
20
  import { buildHeadingFontPresetCreateBody } from "./heading-font-emitter.js";
@@ -34,13 +35,27 @@ export class CredentialsMissingError extends Error {
34
35
  export class CapabilityMissingError extends Error {
35
36
  capability;
36
37
  pluginVersion;
37
- constructor(capability, pluginVersion) {
38
- super(`The active diviops-agent plugin (version ${pluginVersion}) does not report ` +
39
- `the "${capability}" capability required for storage-routed preset writes. ` +
40
- `Upgrade diviops-agent to a version that ships the "${capability}" capability ` +
41
- `(plugin 1.4.9 or later).`);
38
+ serverVersion;
39
+ tool;
40
+ constructor(capability, pluginVersion, serverVersion, tool = "diviops-preset --apply") {
41
+ const cleanPluginVersion = observedVersion(pluginVersion);
42
+ const cleanServerVersion = observedVersion(serverVersion);
43
+ const pluginEvidence = cleanPluginVersion
44
+ ? ` observed_free_plugin_version=${cleanPluginVersion};`
45
+ : "";
46
+ const serverEvidence = cleanServerVersion
47
+ ? ` mcp_server_version=${cleanServerVersion};`
48
+ : "";
49
+ super(capabilityMissingMessage(capability, pluginVersion) +
50
+ " " +
51
+ capabilityUpgradeHint(capability) +
52
+ ` Diagnostics: tool=${tool}; capability=${capability};` +
53
+ pluginEvidence +
54
+ serverEvidence);
42
55
  this.capability = capability;
43
56
  this.pluginVersion = pluginVersion;
57
+ this.serverVersion = serverVersion;
58
+ this.tool = tool;
44
59
  this.name = "CapabilityMissingError";
45
60
  }
46
61
  }
@@ -90,7 +105,7 @@ export function buildClientFromEnv(env = process.env) {
90
105
  export async function assertStorageCapability(client, serverVersion) {
91
106
  const hs = await client.handshake(serverVersion);
92
107
  if (!hs.capabilities || hs.capabilities[STORAGE_CAPABILITY] !== true) {
93
- throw new CapabilityMissingError(STORAGE_CAPABILITY, hs.plugin_version ?? "unknown");
108
+ throw new CapabilityMissingError(STORAGE_CAPABILITY, hs.plugin_version, serverVersion);
94
109
  }
95
110
  return hs;
96
111
  }
@@ -0,0 +1,40 @@
1
+ import type { HandshakeResult } from "./compatibility.js";
2
+ export declare const TARGET_EVIDENCE_SCHEMA_VERSION = 1;
3
+ export type LauncherProfileIdentity = {
4
+ profile_id: string;
5
+ profile_revision: number;
6
+ profile_label: string;
7
+ endpoint: string;
8
+ credential_ref: string;
9
+ };
10
+ export type TargetEvidence = {
11
+ schema_version: 1;
12
+ profile_id: string;
13
+ profile_revision: number;
14
+ profile_label: string;
15
+ endpoint: string;
16
+ credential_ref: string;
17
+ authenticated_user: {
18
+ id: number;
19
+ login: string;
20
+ };
21
+ observed_site_url: string;
22
+ plugin_version: string | null;
23
+ divi: {
24
+ active: boolean;
25
+ version: string | null;
26
+ };
27
+ capabilities: Record<string, boolean>;
28
+ capability_digest: string;
29
+ target_evidence_hash: string;
30
+ observed_at: string;
31
+ drift_state: "healthy";
32
+ };
33
+ export type TargetIdentityForHash = Omit<TargetEvidence, "profile_label" | "target_evidence_hash" | "observed_at" | "drift_state">;
34
+ export declare function canonicalJson(value: unknown): string;
35
+ export declare function normalizeWordPressEndpoint(raw: string): string;
36
+ export declare function canonicalCapabilities(value: unknown): Record<string, boolean>;
37
+ export declare function targetIdentityForHash(evidence: TargetEvidence): TargetIdentityForHash;
38
+ export declare function targetEvidenceHash(evidence: TargetEvidence): string;
39
+ export declare function createTargetEvidence(profile: LauncherProfileIdentity, handshake: HandshakeResult, observedAt?: Date): TargetEvidence;
40
+ export declare function targetDriftAxes(approved: TargetEvidence, current: TargetEvidence): string[];