@sentientui/mcp 0.19.0 → 0.20.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.
@@ -21,9 +21,10 @@ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21
21
 
22
22
  // src/api-client.ts
23
23
  var ApiError = class extends Error {
24
- constructor(status, message) {
24
+ constructor(status, message, detail) {
25
25
  super(message);
26
26
  this.status = status;
27
+ this.detail = detail;
27
28
  this.name = "ApiError";
28
29
  }
29
30
  };
@@ -40,8 +41,14 @@ var ApiClient = class {
40
41
  async post(path, body) {
41
42
  return this.request("POST", path, body);
42
43
  }
44
+ async patch(path, body) {
45
+ return this.request("PATCH", path, body);
46
+ }
47
+ async delete(path, body) {
48
+ return this.request("DELETE", path, body);
49
+ }
43
50
  async request(method, path, body, isRetry = false) {
44
- var _a, _b;
51
+ var _a, _b, _c;
45
52
  const res = await fetch(`${this.baseUrl}/v1/mgmt${path}`, {
46
53
  method,
47
54
  headers: __spreadValues({
@@ -58,7 +65,9 @@ var ApiClient = class {
58
65
  return this.request(method, path, body, true);
59
66
  }
60
67
  }
61
- throw new ApiError(res.status, String((_b = (_a = errBody.error) != null ? _a : errBody.message) != null ? _b : res.statusText));
68
+ const code = String((_b = (_a = errBody.error) != null ? _a : errBody.message) != null ? _b : res.statusText);
69
+ const human = (_c = errBody.message) != null ? _c : errBody.reason;
70
+ throw new ApiError(res.status, code, typeof human === "string" && human !== code ? human : void 0);
62
71
  }
63
72
  };
64
73
 
@@ -403,7 +412,7 @@ function localDate(iso, timeZone) {
403
412
  }
404
413
  function apiErrorGuidance(err, extra) {
405
414
  if (extra && Object.prototype.hasOwnProperty.call(extra, err.message)) {
406
- return extra[err.message];
415
+ return extra[err.message] + detailSuffix(err);
407
416
  }
408
417
  switch (err.message) {
409
418
  case "insufficient_scope":
@@ -412,6 +421,15 @@ function apiErrorGuidance(err, extra) {
412
421
  return "Demo mode is read-only. Create a SentientUI account and sign in (or use a project server key) to make changes.";
413
422
  case "insufficient_role":
414
423
  return "Your account role does not permit this action \u2014 it needs the account owner or an admin.";
424
+ // The mgmt write routes answer a viewer with `role_required` (and origins
425
+ // with `not_authorized`), not `insufficient_role` — so every role refusal
426
+ // fell through to the generic 403 "check your key has access" advice and
427
+ // sent the agent re-authenticating for a permission it already had wrong.
428
+ case "role_required":
429
+ case "not_authorized":
430
+ return `Your role on this project cannot make this change \u2014 it needs an editor or admin.${detailSuffix(err)}`;
431
+ case "ai_unavailable":
432
+ return "AI generation is unavailable on the SentientUI server right now (no model is configured). Nothing was queued \u2014 retry later.";
415
433
  default:
416
434
  break;
417
435
  }
@@ -443,10 +461,25 @@ function apiErrorGuidance(err, extra) {
443
461
  return `This feature requires a higher plan (${err.message}). Upgrade your SentientUI plan, then try again.`;
444
462
  }
445
463
  if (err.status === 403) {
446
- return `Access denied (${err.message}). Check that your key or login has access to this project.`;
464
+ return `Access denied (${err.message}). Check that your key or login has access to this project.${detailSuffix(err)}`;
465
+ }
466
+ if (err.status === 404) {
467
+ return `Not found (${err.message}). The project, component, variant, goal or cell does not exist, or this credential cannot see it (an sk_ server key sees only its own project). Re-read the ids with list_projects, list_components, list_goals or get_cell_matrix and retry with an exact id.` + detailSuffix(err);
468
+ }
469
+ if (err.status === 400) {
470
+ return `The API rejected the arguments (${err.message}).${detailSuffix(err)} Correct the input and retry \u2014 repeating the same call will fail the same way.`;
471
+ }
472
+ if (err.status === 409) {
473
+ return `Conflict (${err.message}): the target's current state does not allow this.${detailSuffix(err)} Read its current state first, then retry the step that makes this valid.`;
474
+ }
475
+ if (err.status === 502 || err.status === 503 || err.status === 504) {
476
+ return `SentientUI is temporarily unavailable (${err.status} ${err.message}). Nothing changed \u2014 wait a moment and retry.`;
447
477
  }
448
478
  return null;
449
479
  }
480
+ function detailSuffix(err) {
481
+ return err.detail ? ` Server says: ${untrusted(err.detail, 300)}` : "";
482
+ }
450
483
  async function settled(p) {
451
484
  try {
452
485
  return { ok: true, value: await p };
@@ -559,6 +592,37 @@ function registerProjectTools(server, client) {
559
592
  };
560
593
  }, CREATE_PROJECT_GUIDANCE)
561
594
  );
595
+ server.registerTool(
596
+ "add_origin",
597
+ {
598
+ title: "Add allowed origin",
599
+ description: "Allow-list a site origin (scheme + host, e.g. https://www.example.com) so the SDK's events from it are accepted. Idempotent: an origin already on the list is left as is. Removing an origin is dashboard-only. Needs an editor/admin login or the project's sk_ server key. Confirm the exact origin with the user first \u2014 an allowed origin can send events into this project.",
600
+ inputSchema: {
601
+ projectId: projectIdSchema,
602
+ origin: z2.string().min(1).max(500).describe("The site origin, e.g. https://www.example.com (a pasted page URL is reduced to its origin)")
603
+ },
604
+ outputSchema: {
605
+ origins: z2.array(z2.string()).describe("The full allow-list after the change")
606
+ },
607
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
608
+ },
609
+ withApiErrorGuidance(async ({ projectId, origin }) => {
610
+ var _a;
611
+ const id = encodeURIComponent(projectId);
612
+ const res = await client.post(`/projects/${id}/origins`, { origin });
613
+ const origins = (_a = res.origins) != null ? _a : [];
614
+ return {
615
+ content: [{
616
+ type: "text",
617
+ text: `Allowed origins: ${origins.map((o) => untrusted(o)).join(", ") || "(none)"}. Events from these origins are accepted (other API instances pick the change up within ~30 seconds, when their key cache expires).`
618
+ }],
619
+ structuredContent: { origins }
620
+ };
621
+ }, {
622
+ invalid_origin: "That is not a usable origin. Pass a scheme and host, e.g. https://www.example.com.",
623
+ origin_required: "An origin is required, e.g. https://www.example.com."
624
+ })
625
+ );
562
626
  server.registerTool(
563
627
  "list_projects",
564
628
  {
@@ -603,13 +667,16 @@ function registerProjectTools(server, client) {
603
667
  "get_project_stats",
604
668
  {
605
669
  title: "Project health stats",
606
- description: "Get health stats for a project: event volume, session count, agent calls, and status.",
670
+ description: "Get ingestion health for a project: status, events and sessions in the last 24 hours, the time of the last event, and the all-time count of calls to the SentientUI agent API (/v1/agent) \u2014 NOT MCP tool calls.",
607
671
  inputSchema: { projectId: projectIdSchema },
608
672
  outputSchema: {
609
673
  status: z2.string().describe("Overall project health status"),
610
674
  events24h: z2.number().describe("Events in the last 24 hours"),
611
675
  sessions24h: z2.number().describe("Sessions in the last 24 hours"),
612
- agentCalls: z2.number().describe("Total agent (MCP/API) calls"),
676
+ // Was "Total agent (MCP/API) calls" — but the count comes from
677
+ // agent_events, which only the /v1/agent endpoint writes. MCP tool calls
678
+ // are never in it, so an agent read its own activity as missing.
679
+ agentCalls: z2.number().describe("All-time calls to the /v1/agent agent API (not MCP tool calls)"),
613
680
  lastEventAt: z2.string().nullable().describe("ISO timestamp of the last event, or null")
614
681
  },
615
682
  annotations: {
@@ -626,7 +693,7 @@ function registerProjectTools(server, client) {
626
693
  `Status: ${stats.status}`,
627
694
  `Events (24h): ${stats.events24h}`,
628
695
  `Sessions (24h): ${stats.sessions24h}`,
629
- `Agent calls (total): ${stats.agentCalls}`,
696
+ `Agent API calls (/v1/agent, all-time): ${stats.agentCalls}`,
630
697
  `Last event: ${(_a = stats.lastEventAt) != null ? _a : "never"}`
631
698
  ].join("\n");
632
699
  return {
@@ -1107,7 +1174,10 @@ function registerPersonaTools(server, client) {
1107
1174
  "get_persona_breakdown",
1108
1175
  {
1109
1176
  title: "Persona breakdown",
1110
- description: "Get the distribution of visitor persona clusters with session counts and reliability scores." + UNTRUSTED_FIELDS_NOTE,
1177
+ // Takes no range/from/to on purpose: the API computes it over every
1178
+ // retained session and has no window. Saying so stops an agent from
1179
+ // reading it beside a 7d get_variant_performance as the same period.
1180
+ description: "Get the distribution of visitor persona clusters with session counts and reliability scores, over ALL retained human sessions (not windowed \u2014 this has no range input, unlike the conversion tools)." + UNTRUSTED_FIELDS_NOTE,
1111
1181
  inputSchema: { projectId: projectIdSchema },
1112
1182
  _meta: uiMeta("persona-breakdown"),
1113
1183
  outputSchema: {
@@ -1168,8 +1238,13 @@ function registerGoalTools(server, client) {
1168
1238
  server.registerTool(
1169
1239
  "get_goal_funnel",
1170
1240
  {
1171
- title: "Goal funnel",
1172
- description: "Get goal hit counts and unique-session conversion rates for a window (default: last 30 calendar days), plus a per-variant breakdown. NOTE: the per-variant completionRate values are ALL-TIME (bounded only by plan retention), NOT windowed \u2014 a variant completion rate needs the full assignment history as its denominator, so it does not change when you narrow `range`, and retired components keep appearing in it. Only hits/uniqueSessions/conversionRate/revenue respect the window. This is a flat per-goal list \u2014 for multi-step funnel drop-off, use get_funnel_report." + UNTRUSTED_FIELDS_NOTE,
1241
+ // Named get_goal_funnel for compatibility (renaming a published tool
1242
+ // breaks every saved prompt and host allow-list), but it is NOT a funnel:
1243
+ // agents asked it for step drop-off and reported per-goal rates as funnel
1244
+ // stages. The title and the first words of the description now say what
1245
+ // it is, and point to the real funnel tool.
1246
+ title: "Goal conversions (per goal \u2014 not a step funnel)",
1247
+ description: "Per-goal conversion summary \u2014 NOT a step funnel (for step-by-step drop-off use list_funnels + get_funnel_report). Gets goal hit counts and unique-session conversion rates for a window (default: last 30 calendar days), plus a per-variant breakdown. NOTE: the per-variant completionRate values are ALL-TIME (bounded only by plan retention), NOT windowed \u2014 a variant completion rate needs the full assignment history as its denominator, so it does not change when you narrow `range`, and retired components keep appearing in it. Only hits/uniqueSessions/conversionRate/revenue respect the window. Per-variant rates are descriptive, not joined to the evidence verdicts \u2014 for whether an arm is ahead, use get_variant_performance." + UNTRUSTED_FIELDS_NOTE,
1173
1248
  inputSchema: __spreadValues({ projectId: projectIdSchema }, rangeInputSchema("30d")),
1174
1249
  _meta: uiMeta("goal-funnel"),
1175
1250
  outputSchema: {
@@ -1559,7 +1634,9 @@ function registerLayoutTools(server, client) {
1559
1634
  "get_layout_stats",
1560
1635
  {
1561
1636
  title: "Layout stats",
1562
- description: "Get per-persona section layout rankings and bandit reward weights." + UNTRUSTED_FIELDS_NOTE,
1637
+ // No window by design: these are the bandit's cumulative pulls and reward,
1638
+ // the state serving reads — not a report over a period.
1639
+ description: "Get per-persona section layout rankings with bandit pulls and average reward \u2014 the cumulative learning state serving uses (not windowed; there is no range input). avgReward is a reward signal, not a conversion rate." + UNTRUSTED_FIELDS_NOTE,
1563
1640
  inputSchema: { projectId: projectIdSchema },
1564
1641
  _meta: uiMeta("layout-stats"),
1565
1642
  outputSchema: {
@@ -1611,7 +1688,7 @@ function registerVariantWriteTools(server, client) {
1611
1688
  "create_variant",
1612
1689
  {
1613
1690
  title: "Create managed variant",
1614
- description: "Create a NO-CODE managed text variant for a component (content stored in SentientUI, rendered by <AdaptiveText>). Use this ONLY for text-only variants the user wants without a code change. For variants that will live in the codebase (full components \u2014 copy, markup, styling), use get_variant_brief and write the variant in code instead; those auto-register on deploy and do not need create_variant. Requires a paid plan (server keys are Starter+; anonymous demo tokens are read-only).",
1691
+ description: "Create a NO-CODE managed text variant for a component (content stored in SentientUI, rendered by <AdaptiveText>). Use this ONLY for text-only variants the user wants without a code change. For variants that will live in the codebase (full components \u2014 copy, markup, styling), use get_variant_brief and write the variant in code instead; those auto-register on deploy and do not need create_variant. Works on every plan with an editor/admin login or the project's sk_ server key (anonymous demo tokens are read-only). The variant is created as a DRAFT \u2014 it serves no traffic until activated with update_variant (status 'active'). Confirm the text with the user before calling.",
1615
1692
  inputSchema: {
1616
1693
  projectId: projectIdSchema,
1617
1694
  componentId: z10.string().min(1).max(200).describe("The component ID to add a variant to"),
@@ -1645,7 +1722,7 @@ function registerVariantWriteTools(server, client) {
1645
1722
  return {
1646
1723
  content: [{
1647
1724
  type: "text",
1648
- text: `Managed text variant created: ${result.variantId} ("${result.displayName}") for component ${componentId}${contentNote}. It is in draft state \u2014 activate it from the dashboard. Reminder: this is a no-code managed variant; for code-native variants, edit the code instead (see get_variant_brief).`
1725
+ text: `Managed text variant created: ${result.variantId} ("${result.displayName}") for component ${componentId}${contentNote}. It is a draft and serves no traffic yet \u2014 after the user confirms, activate it with update_variant (status 'active'), or delete it with delete_variant_draft. Reminder: this is a no-code managed variant; for code-native variants, edit the code instead (see get_variant_brief).`
1649
1726
  }],
1650
1727
  structuredContent: {
1651
1728
  variantId: result.variantId,
@@ -1661,20 +1738,24 @@ function registerVariantWriteTools(server, client) {
1661
1738
  "pause_variant",
1662
1739
  {
1663
1740
  title: "Pause variant",
1664
- description: "Pause a variant, stopping traffic from being assigned to it.",
1741
+ description: "Pause a variant: no new traffic is assigned to it until it is resumed. This changes what live visitors see, so CONFIRM with the user before calling. Undo with resume_variant.",
1665
1742
  inputSchema: {
1666
1743
  projectId: projectIdSchema,
1667
- componentId: z10.string().describe("The component ID"),
1668
- variantId: z10.string().describe("The variant ID to pause")
1744
+ componentId: z10.string().min(1).max(200).describe("The component ID"),
1745
+ variantId: z10.string().min(1).max(200).describe("The variant ID to pause")
1669
1746
  },
1670
1747
  outputSchema: {
1671
1748
  variantId: z10.string(),
1672
1749
  componentId: z10.string(),
1673
1750
  paused: z10.literal(true).describe("The variant is now paused")
1674
1751
  },
1752
+ // destructiveHint was false, so hosts that gate destructive tools behind a
1753
+ // confirmation ran this without asking — yet it pulls a live arm out of
1754
+ // serving for every visitor. It is reversible (resume_variant), but the
1755
+ // hint is about the change to the environment, not about undo.
1675
1756
  annotations: {
1676
1757
  readOnlyHint: false,
1677
- destructiveHint: false,
1758
+ destructiveHint: true,
1678
1759
  idempotentHint: true,
1679
1760
  openWorldHint: false
1680
1761
  }
@@ -1685,17 +1766,194 @@ function registerVariantWriteTools(server, client) {
1685
1766
  return {
1686
1767
  content: [{
1687
1768
  type: "text",
1688
- text: `Variant ${variantId} in component ${componentId} has been paused. No new traffic will be assigned to it.`
1769
+ text: `Variant ${untrusted(variantId)} in component ${untrusted(componentId)} is paused. No new traffic will be assigned to it. Undo with resume_variant.`
1689
1770
  }],
1690
1771
  structuredContent: { variantId, componentId, paused: true }
1691
1772
  };
1692
1773
  })
1693
1774
  );
1775
+ server.registerTool(
1776
+ "resume_variant",
1777
+ {
1778
+ title: "Resume variant",
1779
+ description: "Resume a paused variant so it is assigned traffic again \u2014 works for a manual pause (pause_variant) and for a guardrail auto-pause (see list_guardrail_events). Resuming a guardrail-paused arm puts a variant the guardrail judged harmful back in front of visitors, so CONFIRM with the user first.",
1780
+ inputSchema: {
1781
+ projectId: projectIdSchema,
1782
+ componentId: z10.string().min(1).max(200).describe("The component ID"),
1783
+ variantId: z10.string().min(1).max(200).describe("The paused variant ID to resume")
1784
+ },
1785
+ outputSchema: {
1786
+ variantId: z10.string(),
1787
+ componentId: z10.string(),
1788
+ paused: z10.literal(false).describe("The variant is no longer paused")
1789
+ },
1790
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
1791
+ },
1792
+ withApiErrorGuidance(async ({ projectId, componentId, variantId }) => {
1793
+ const id = encodeURIComponent(projectId);
1794
+ await client.post(`/projects/${id}/guardrails/${encodeURIComponent(componentId)}/unpause`, {
1795
+ variantIds: [variantId]
1796
+ });
1797
+ return {
1798
+ content: [{
1799
+ type: "text",
1800
+ text: `Variant ${untrusted(variantId)} in component ${untrusted(componentId)} is resumed and will be assigned traffic again.`
1801
+ }],
1802
+ structuredContent: { variantId, componentId, paused: false }
1803
+ };
1804
+ })
1805
+ );
1806
+ server.registerTool(
1807
+ "update_variant",
1808
+ {
1809
+ title: "Update managed variant",
1810
+ description: "Edit a NO-CODE managed variant (one created with create_variant or in the dashboard): its display name, its text, or its status \u2014 'active' starts serving it to visitors, 'draft' takes it back out of rotation. Code-native variants cannot be edited here (change the code). Overwriting text or activating changes what live visitors see, so CONFIRM with the user first. Omit a field to leave it unchanged.",
1811
+ inputSchema: {
1812
+ projectId: projectIdSchema,
1813
+ componentId: z10.string().min(1).max(200).describe("The component ID"),
1814
+ variantId: z10.string().min(1).max(200).describe("The managed variant ID (dm_\u2026)"),
1815
+ displayName: z10.string().min(1).max(200).optional().describe("New display name"),
1816
+ content: z10.string().max(1e4).optional().describe("New text content (replaces the old text)"),
1817
+ status: z10.enum(["draft", "active"]).optional().describe("'active' serves it; 'draft' stops serving it")
1818
+ },
1819
+ outputSchema: {
1820
+ variantId: z10.string(),
1821
+ componentId: z10.string(),
1822
+ changed: z10.array(z10.string()).describe("Fields that were sent for update"),
1823
+ status: z10.enum(["draft", "active"]).nullable().describe("The new status, or null when unchanged")
1824
+ },
1825
+ // Destructive: the previous text is overwritten, not versioned.
1826
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }
1827
+ },
1828
+ withApiErrorGuidance(async ({ projectId, componentId, variantId, displayName, content, status }) => {
1829
+ const changed = [
1830
+ ...displayName !== void 0 ? ["displayName"] : [],
1831
+ ...content !== void 0 ? ["content"] : [],
1832
+ ...status !== void 0 ? ["status"] : []
1833
+ ];
1834
+ if (changed.length === 0) {
1835
+ return {
1836
+ content: [{ type: "text", text: "Nothing to update \u2014 pass displayName, content and/or status." }],
1837
+ isError: true
1838
+ };
1839
+ }
1840
+ const id = encodeURIComponent(projectId);
1841
+ await client.patch(`/projects/${id}/variants`, { componentId, variantId, displayName, content, status });
1842
+ const statusNote = status === "active" ? " It is now ACTIVE and will be assigned traffic." : status === "draft" ? " It is now a draft and no longer serves traffic." : "";
1843
+ return {
1844
+ content: [{
1845
+ type: "text",
1846
+ text: `Managed variant ${untrusted(variantId)} in component ${untrusted(componentId)} updated (${changed.join(", ")}).${statusNote}`
1847
+ }],
1848
+ structuredContent: { variantId, componentId, changed, status: status != null ? status : null }
1849
+ };
1850
+ }, {
1851
+ // PATCH matches managed variants only, so a code-native id answers a
1852
+ // bare not_found that read as "that variant does not exist".
1853
+ not_found: "No MANAGED variant with that id exists in this component. Code-native variants (declared in <Adaptive variants>) are edited in the code, not here \u2014 check ids with list_components (a wrong projectId answers the same way)."
1854
+ })
1855
+ );
1856
+ server.registerTool(
1857
+ "delete_variant_draft",
1858
+ {
1859
+ title: "Delete draft variant",
1860
+ description: "Permanently delete a managed variant that is still a DRAFT (never activated). Active variants cannot be deleted \u2014 pause or retire them instead. CONFIRM with the user first: this cannot be undone.",
1861
+ inputSchema: {
1862
+ projectId: projectIdSchema,
1863
+ componentId: z10.string().min(1).max(200).describe("The component ID"),
1864
+ variantId: z10.string().min(1).max(200).describe("The draft managed variant ID (dm_\u2026)")
1865
+ },
1866
+ outputSchema: {
1867
+ variantId: z10.string(),
1868
+ componentId: z10.string(),
1869
+ deleted: z10.literal(true)
1870
+ },
1871
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
1872
+ },
1873
+ withApiErrorGuidance(async ({ projectId, componentId, variantId }) => {
1874
+ const id = encodeURIComponent(projectId);
1875
+ await client.delete(`/projects/${id}/variants`, { componentId, variantId });
1876
+ return {
1877
+ content: [{
1878
+ type: "text",
1879
+ text: `Draft variant ${untrusted(variantId)} in component ${untrusted(componentId)} was deleted.`
1880
+ }],
1881
+ structuredContent: { variantId, componentId, deleted: true }
1882
+ };
1883
+ }, {
1884
+ // The API's DELETE matches managed drafts only, so an active or
1885
+ // code-native variant answers a bare not_found — say why.
1886
+ not_found: "No managed DRAFT variant with that id exists in this component. Active and code-native variants cannot be deleted \u2014 use pause_variant or retire_variant instead (check ids with list_components; a wrong projectId answers the same way)."
1887
+ })
1888
+ );
1889
+ server.registerTool(
1890
+ "retire_variant",
1891
+ {
1892
+ title: "Retire variant",
1893
+ description: "Retire (archive) an ACTIVE variant: it stops serving and moves to the archived list. Works for code-native variants that were removed from the code and linger. A promoted (pinned) variant must be unpromoted in the dashboard first. CONFIRM with the user first; undo with restore_variant.",
1894
+ inputSchema: {
1895
+ projectId: projectIdSchema,
1896
+ componentId: z10.string().min(1).max(200).describe("The component ID"),
1897
+ variantId: z10.string().min(1).max(200).describe("The active variant ID to retire")
1898
+ },
1899
+ outputSchema: {
1900
+ variantId: z10.string(),
1901
+ componentId: z10.string(),
1902
+ status: z10.literal("retired")
1903
+ },
1904
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }
1905
+ },
1906
+ withApiErrorGuidance(async ({ projectId, componentId, variantId }) => {
1907
+ const id = encodeURIComponent(projectId);
1908
+ await client.post(`/projects/${id}/variants/retire`, { componentId, variantId });
1909
+ return {
1910
+ content: [{
1911
+ type: "text",
1912
+ text: `Variant ${untrusted(variantId)} in component ${untrusted(componentId)} is retired and no longer serves. Undo with restore_variant.`
1913
+ }],
1914
+ structuredContent: { variantId, componentId, status: "retired" }
1915
+ };
1916
+ }, {
1917
+ variant_promoted: "This variant is promoted (pinned as the winner), so it cannot be retired. Unpromote it in the dashboard first, then retry.",
1918
+ not_found: "No ACTIVE variant with that id exists in this component (it may already be retired, or still a draft), or the projectId is wrong. Check ids with list_components."
1919
+ })
1920
+ );
1921
+ server.registerTool(
1922
+ "restore_variant",
1923
+ {
1924
+ title: "Restore variant",
1925
+ description: "Bring a RETIRED variant back to active so it serves again. For a managed draft that was never activated use update_variant (status 'active') instead. Restoring does not clear a pause \u2014 use resume_variant for that. CONFIRM with the user first.",
1926
+ inputSchema: {
1927
+ projectId: projectIdSchema,
1928
+ componentId: z10.string().min(1).max(200).describe("The component ID"),
1929
+ variantId: z10.string().min(1).max(200).describe("The retired variant ID to restore")
1930
+ },
1931
+ outputSchema: {
1932
+ variantId: z10.string(),
1933
+ componentId: z10.string(),
1934
+ status: z10.literal("active")
1935
+ },
1936
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
1937
+ },
1938
+ withApiErrorGuidance(async ({ projectId, componentId, variantId }) => {
1939
+ const id = encodeURIComponent(projectId);
1940
+ await client.post(`/projects/${id}/variants/restore`, { componentId, variantId });
1941
+ return {
1942
+ content: [{
1943
+ type: "text",
1944
+ text: `Variant ${untrusted(variantId)} in component ${untrusted(componentId)} is active again. If it was also paused, call resume_variant.`
1945
+ }],
1946
+ structuredContent: { variantId, componentId, status: "active" }
1947
+ };
1948
+ })
1949
+ );
1694
1950
  server.registerTool(
1695
1951
  "refresh_insights",
1696
1952
  {
1697
1953
  title: "Refresh insights",
1698
- description: "Trigger fresh AI insight generation for a project. Returns immediately; use get_insights in ~15 seconds to see results.",
1954
+ // The plan and role gates were undocumented, so agents on Free called it
1955
+ // and got a bare 403 they could not explain to the user.
1956
+ description: "Trigger fresh AI insight generation for a project (a paid model call). Needs the Starter plan or higher and an editor/admin role (anonymous demo tokens are read-only); advisor recommendations additionally need Growth or higher. Returns immediately; call get_insights in ~15 seconds to see results.",
1699
1957
  inputSchema: { projectId: projectIdSchema },
1700
1958
  outputSchema: {
1701
1959
  projectId: z10.string(),
@@ -1747,11 +2005,21 @@ var BEST_PRACTICE_PRIORS = {
1747
2005
  "Make the CTA specific and benefit-led.",
1748
2006
  "Add a single strong proof point; remove competing distractions."
1749
2007
  ],
1750
- marketplace: [
1751
- "Reduce choice overload: guide the visitor to a clear next step.",
1752
- "Surface trust and liquidity signals (ratings, counts, recency).",
1753
- "Make the primary action on each listing obvious.",
1754
- "Reassure on safety/guarantees near the point of decision."
2008
+ // Keys must be the project context types the API accepts (projects.ts
2009
+ // VALID_CONTEXT_TYPES: saas | ecommerce | marketing | landing | internal).
2010
+ // A `marketplace` key sat here that no project could ever have, while
2011
+ // marketing and internal projects silently fell through to the generic list.
2012
+ marketing: [
2013
+ 'Make the page answer "what is this and why should I care" in the first screen.',
2014
+ "Give each section one job and one next step; cut competing CTAs.",
2015
+ "Put the strongest proof (named customers, a hard number) near the primary CTA.",
2016
+ "Match the copy to where the visitor came from (campaign, search intent)."
2017
+ ],
2018
+ internal: [
2019
+ "Optimize for task completion, not persuasion: make the next step obvious.",
2020
+ "Reduce steps and fields; prefill what the system already knows.",
2021
+ "Use plain, specific labels over marketing copy.",
2022
+ "Make errors and empty states say exactly what to do next."
1755
2023
  ]
1756
2024
  };
1757
2025
  var GENERIC_PRIORS = [
@@ -2282,12 +2550,12 @@ function registerAgentTrafficTools(server, client) {
2282
2550
  "get_agent_traffic",
2283
2551
  {
2284
2552
  title: "Agent traffic",
2285
- description: "Which AI agents and crawlers are reading this site: totals by type (passive crawlers, agentic browsers, agent API calls), engine breakdown, and the paths they fetch most. Defaults to the last 30 days; pass from/to for a custom period (agent logs are retained 30 days on Free/Starter, 90 on Growth+). Agent traffic is tracked separately and never counted in conversion rate." + UNTRUSTED_FIELDS_NOTE,
2286
- inputSchema: {
2287
- projectId: projectIdSchema,
2288
- from: z14.string().optional().describe("Period start (ISO 8601 date or timestamp). Defaults to 30 days ago."),
2289
- to: z14.string().optional().describe("Period end (ISO 8601 date or timestamp). Defaults to now.")
2290
- },
2553
+ description: "Which AI agents and crawlers are reading this site: totals by type (passive crawlers, agentic browsers, agent API calls), engine breakdown, and the paths they fetch most. Defaults to the last 30 calendar days; pass range (7d/30d/90d/all) or from/to (YYYY-MM-DD) like every other windowed tool (agent logs are retained 30 days on Free/Starter, 90 on Growth+). Agent traffic is tracked separately and never counted in conversion rate." + UNTRUSTED_FIELDS_NOTE,
2554
+ // This tool alone took ad-hoc ISO from/to with no range token and echoed
2555
+ // no window, while every other windowed tool used rangeInputSchema — so
2556
+ // agents passed range:'7d' here, it was silently dropped, and 30 days of
2557
+ // traffic was reported as a week. The endpoint uses the shared resolver.
2558
+ inputSchema: __spreadValues({ projectId: projectIdSchema }, rangeInputSchema("30d")),
2291
2559
  outputSchema: {
2292
2560
  totals: z14.object({ crawler: z14.number(), api: z14.number(), browser: z14.number() }),
2293
2561
  engines: z14.array(
@@ -2301,20 +2569,18 @@ function registerAgentTrafficTools(server, client) {
2301
2569
  })
2302
2570
  ),
2303
2571
  intents: z14.object({ user: z14.number(), search: z14.number(), training: z14.number(), other: z14.number() }).describe("Crawler fetches by purpose: user = an assistant answering a real person live"),
2304
- topPaths: z14.array(z14.object({ path: z14.string(), count: z14.number(), engines: z14.number() }))
2572
+ topPaths: z14.array(z14.object({ path: z14.string(), count: z14.number(), engines: z14.number() })),
2573
+ window: windowOutputSchema
2305
2574
  },
2306
2575
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
2307
2576
  },
2308
- withApiErrorGuidance(async ({ projectId, from, to }) => {
2577
+ withApiErrorGuidance(async ({ projectId, range, from, to }) => {
2309
2578
  const id = encodeURIComponent(projectId);
2310
- const qs = new URLSearchParams();
2311
- if (from) qs.set("from", from);
2312
- if (to) qs.set("to", to);
2313
- const query = qs.toString();
2314
2579
  const s = await client.get(
2315
- `/projects/${id}/agent-activity/summary${query ? `?${query}` : ""}`
2580
+ `/projects/${id}/agent-activity/summary${rangeQuery({ range, from, to })}`
2316
2581
  );
2317
- const structuredContent = { totals: s.totals, engines: s.engines, intents: s.intents, topPaths: s.topPaths };
2582
+ const structuredContent = { totals: s.totals, engines: s.engines, intents: s.intents, topPaths: s.topPaths, window: s.window };
2583
+ const win = windowLine(s.window);
2318
2584
  const total = s.totals.crawler + s.totals.api + s.totals.browser;
2319
2585
  if (total === 0) {
2320
2586
  return {
@@ -2326,6 +2592,7 @@ function registerAgentTrafficTools(server, client) {
2326
2592
  };
2327
2593
  }
2328
2594
  const lines = [
2595
+ ...win ? [win] : [],
2329
2596
  `Agent traffic: ${s.totals.crawler} crawler fetches, ${s.totals.api} agent API calls, ${s.totals.browser} agentic browser sessions.`,
2330
2597
  `Live user fetches: ${s.intents.user} \xB7 Search index: ${s.intents.search} \xB7 Training: ${s.intents.training}${s.intents.other ? ` \xB7 Other: ${s.intents.other}` : ""} (a "live user fetch" = an AI assistant reading your site to answer a real person).`,
2331
2598
  "",
@@ -2416,7 +2683,7 @@ var personaOutput = z15.object({
2416
2683
  var cellOutput = z15.object({
2417
2684
  slotId: z15.string(),
2418
2685
  persona: z15.string(),
2419
- status: z15.string().describe("pending | generating | live | error | rejected"),
2686
+ status: z15.string().describe("pending | generating | review (waiting for approval) | live | error | rejected"),
2420
2687
  requestedBy: z15.string(),
2421
2688
  armId: z15.string().nullable(),
2422
2689
  rationale: z15.string().nullable(),
@@ -2456,6 +2723,10 @@ function registerCellTools(server, client) {
2456
2723
  personas: z15.array(personaOutput),
2457
2724
  cells: z15.array(cellOutput),
2458
2725
  autoFill: z15.boolean(),
2726
+ // The API has always sent this; without it in the schema zod stripped
2727
+ // it, and generate_cell had no way to know a version would wait for a
2728
+ // human instead of publishing.
2729
+ reviewMode: z15.boolean().optional().describe("True when generated versions wait for approval (review_cell) instead of publishing automatically"),
2459
2730
  // Nullable: a project with no persona set at all reports null, not a
2460
2731
  // string. That is the NORMAL state since the default vocabulary was
2461
2732
  // emptied, so a non-nullable schema failed output validation on most
@@ -2472,7 +2743,7 @@ function registerCellTools(server, client) {
2472
2743
  const byCell = new Map(data.cells.map((c) => [`${c.slotId}::${c.persona}`, c]));
2473
2744
  const lines = [
2474
2745
  `Slots: ${data.slots.map((s) => `${untrusted(s.displayName)}${s.live === false ? " [draft]" : ""}`).join(", ") || "(none published)"}`,
2475
- `Auto-fill on first miss: ${data.autoFill ? "ON" : "off"} \xB7 persona source: ${(_a = data.personaSource) != null ? _a : 'none (one "everyone" row)'}`
2746
+ `Auto-fill on first miss: ${data.autoFill ? "ON" : "off"} \xB7 review before publishing: ${data.reviewMode ? "ON (approve with review_cell)" : "off"} \xB7 persona source: ${(_a = data.personaSource) != null ? _a : 'none (one "everyone" row)'}`
2476
2747
  ];
2477
2748
  for (const p of data.personas) {
2478
2749
  const states = data.slots.map((s) => {
@@ -2557,7 +2828,12 @@ function registerCellTools(server, client) {
2557
2828
  "generate_cell",
2558
2829
  {
2559
2830
  title: "Generate a cell version",
2560
- description: "Queue AI generation of a version for one (persona, slot) cell. The worker writes it asynchronously (usually under a minute), brand-locked, and it goes live as a named option the optimizer explores. Also works to regenerate or retry a failed cell. Requires a paid plan (anonymous demo tokens are read-only).",
2831
+ // The old copy promised "goes live, usually under a minute" — but with
2832
+ // review mode on the worker parks the version for a human (status
2833
+ // 'review') and nothing serves until someone approves it, and the queue
2834
+ // can defer a cell (retry backoff, the plan's monthly generation cap). An
2835
+ // agent relayed "it's live" for versions no visitor would ever see.
2836
+ description: "Queue AI generation of a version for one (persona, slot) cell; the worker writes it asynchronously, brand-locked. If the project has review mode on, the finished version WAITS for approval (list_cell_reviews / review_cell) and serves nobody until approved; otherwise it publishes automatically as a named option the optimizer explores. Also regenerates or retries a failed cell. Generation volume is capped per plan (Free included). Check get_cell_matrix for progress. Confirm with the user before calling \u2014 each generation is a model call against the plan quota.",
2561
2837
  inputSchema: {
2562
2838
  projectId: projectIdSchema,
2563
2839
  slotId: z15.string().min(1).max(128).describe("The slot id (a matrix column)"),
@@ -2566,28 +2842,130 @@ function registerCellTools(server, client) {
2566
2842
  outputSchema: {
2567
2843
  slotId: z15.string(),
2568
2844
  persona: z15.string(),
2569
- status: z15.literal("pending").describe("Queued \u2014 check get_cell_matrix for progress")
2845
+ status: z15.literal("pending").describe("Queued \u2014 check get_cell_matrix for progress"),
2846
+ reviewMode: z15.boolean().nullable().describe("True: the version will wait for review_cell approval. False: it publishes automatically. Null: could not be read.")
2570
2847
  },
2571
2848
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
2572
2849
  },
2573
2850
  withApiErrorGuidance(async ({ projectId, slotId, persona }) => {
2574
2851
  const id = encodeURIComponent(projectId);
2575
2852
  await client.post(`/projects/${id}/cells/generate`, { slotId, persona });
2853
+ const matrix = await settled(client.get(`/projects/${id}/cells`));
2854
+ const reviewMode = matrix.ok && typeof matrix.value.reviewMode === "boolean" ? matrix.value.reviewMode : null;
2855
+ const next = reviewMode === true ? "Review mode is ON: when it is written it will WAIT for approval and serve nobody until then \u2014 list it with list_cell_reviews and approve or reject it with review_cell (after the user decides)." : reviewMode === false ? "Review mode is off: once written it publishes automatically and the optimizer starts exploring it." : 'Could not read whether review mode is on \u2014 check get_cell_matrix: status "review" means it is waiting for approval (review_cell), "live" means it is serving.';
2576
2856
  return {
2577
2857
  content: [
2578
2858
  {
2579
2859
  type: "text",
2580
- text: `Writing a version of ${untrusted(slotId, 64)} for ${untrusted(persona, 64)} \u2014 it usually goes live in under a minute. Check get_cell_matrix (status flips pending \u2192 live) or get_cell_detail for the story once it lands.`
2860
+ text: `Queued a version of ${untrusted(slotId, 64)} for ${untrusted(persona, 64)}. It is written asynchronously (the queue may defer it \u2014 retries back off, and the plan caps generations). ${next} Track it with get_cell_matrix or get_cell_detail.`
2581
2861
  }
2582
2862
  ],
2583
- structuredContent: { slotId, persona, status: "pending" }
2863
+ structuredContent: { slotId, persona, status: "pending", reviewMode }
2864
+ };
2865
+ })
2866
+ );
2867
+ server.registerTool(
2868
+ "list_cell_reviews",
2869
+ {
2870
+ title: "Versions waiting for review",
2871
+ description: "Generated versions waiting for approval (review mode): which slot and visitor type, the proposed text or layout, and why it was written. Approve or reject each with review_cell after the user decides." + UNTRUSTED_FIELDS_NOTE,
2872
+ inputSchema: { projectId: projectIdSchema },
2873
+ outputSchema: {
2874
+ reviews: z15.array(
2875
+ z15.object({
2876
+ slotId: z15.string(),
2877
+ slotName: z15.string(),
2878
+ persona: z15.string(),
2879
+ personaDisplay: z15.string(),
2880
+ content: z15.string().nullable().describe("Proposed text, when the version is text (null for a block/layout version)"),
2881
+ rationale: z15.string().nullable(),
2882
+ refinedFrom: z15.string().nullable().describe("Live version this one would replace; that version keeps serving until approval"),
2883
+ updatedAt: z15.string()
2884
+ })
2885
+ )
2886
+ },
2887
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
2888
+ },
2889
+ withApiErrorGuidance(async ({ projectId }) => {
2890
+ var _a;
2891
+ const id = encodeURIComponent(projectId);
2892
+ const data = await client.get(`/projects/${id}/cell-reviews`);
2893
+ const reviews = ((_a = data.reviews) != null ? _a : []).map((r) => {
2894
+ var _a2, _b, _c;
2895
+ return {
2896
+ slotId: r.slotId,
2897
+ slotName: r.slotName,
2898
+ persona: r.persona,
2899
+ personaDisplay: r.personaDisplay,
2900
+ content: typeof ((_a2 = r.pendingArm) == null ? void 0 : _a2.content) === "string" ? r.pendingArm.content : null,
2901
+ rationale: (_b = r.rationale) != null ? _b : null,
2902
+ refinedFrom: (_c = r.refinedFrom) != null ? _c : null,
2903
+ updatedAt: String(r.updatedAt)
2904
+ };
2905
+ });
2906
+ if (reviews.length === 0) {
2907
+ return {
2908
+ content: [{ type: "text", text: "No generated versions are waiting for review." }],
2909
+ structuredContent: { reviews }
2910
+ };
2911
+ }
2912
+ const lines = reviews.map(
2913
+ (r) => [
2914
+ `- ${untrusted(r.slotName, 60)} (slotId ${untrusted(r.slotId, 64)}) for ${untrusted(r.personaDisplay, 60)} (persona ${untrusted(r.persona, 64)})`,
2915
+ r.content !== null ? ` Proposed text: ${untrusted(r.content, 300)}` : " Proposed: a designed block/layout (preview it in the dashboard)",
2916
+ r.rationale ? ` Why: ${untrusted(r.rationale, 300)}` : null,
2917
+ r.refinedFrom ? ` Would replace ${untrusted(r.refinedFrom, 64)}, which keeps serving until approval.` : null
2918
+ ].filter((l) => l !== null).join("\n")
2919
+ );
2920
+ lines.push("", "Approve or reject each with review_cell (slotId + persona) once the user has decided.");
2921
+ return { content: [{ type: "text", text: lines.join("\n") }], structuredContent: { reviews } };
2922
+ })
2923
+ );
2924
+ server.registerTool(
2925
+ "review_cell",
2926
+ {
2927
+ title: "Approve or reject a generated version",
2928
+ description: "Approve or reject ONE generated version waiting for review (see list_cell_reviews). 'approve' publishes it to live visitors of that type; 'reject' discards it (a rejected refinement leaves the current live version in place). This is the human decision review mode exists for \u2014 only call it with the user's explicit go-ahead.",
2929
+ inputSchema: {
2930
+ projectId: projectIdSchema,
2931
+ slotId: z15.string().min(1).max(128).describe("The slot id of the version under review"),
2932
+ persona: z15.string().min(1).max(64).describe("The persona key of the version under review"),
2933
+ action: z15.enum(["approve", "reject"]),
2934
+ feedback: z15.string().max(2e3).optional().describe("Optional reviewer note, stored with a rejection")
2935
+ },
2936
+ outputSchema: {
2937
+ slotId: z15.string(),
2938
+ persona: z15.string(),
2939
+ action: z15.enum(["approve", "reject"]),
2940
+ status: z15.string().describe("live (approved, or a rejected refinement whose incumbent keeps serving) | rejected"),
2941
+ armId: z15.string().nullable().describe("The published option id, on approval")
2942
+ },
2943
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
2944
+ },
2945
+ withApiErrorGuidance(async ({ projectId, slotId, persona, action, feedback }) => {
2946
+ var _a, _b;
2947
+ const id = encodeURIComponent(projectId);
2948
+ const res = await client.post(`/projects/${id}/cells/review`, {
2949
+ slotId,
2950
+ persona,
2951
+ action,
2952
+ feedback
2953
+ });
2954
+ const status = (_a = res.status) != null ? _a : action === "approve" ? "live" : "rejected";
2955
+ const text = action === "approve" ? `Approved: the version for ${untrusted(persona, 64)} in ${untrusted(slotId, 64)} is now live${res.armId ? ` as option ${untrusted(res.armId, 64)}` : ""}.` : status === "live" ? `Rejected: the proposed refinement for ${untrusted(persona, 64)} in ${untrusted(slotId, 64)} was discarded; the current live version keeps serving.` : `Rejected: the version for ${untrusted(persona, 64)} in ${untrusted(slotId, 64)} was discarded; that visitor type keeps seeing the original.`;
2956
+ return {
2957
+ content: [{ type: "text", text }],
2958
+ structuredContent: { slotId, persona, action, status, armId: (_b = res.armId) != null ? _b : null }
2584
2959
  };
2960
+ }, {
2961
+ not_found: "No version is waiting for review in that cell (it may already have been approved or rejected). Check list_cell_reviews.",
2962
+ publish_failed: "Approval could not publish this version (the slot may be full of options, or its configuration changed). It stays in review \u2014 check the reason in get_cell_detail or the dashboard, then retry."
2585
2963
  })
2586
2964
  );
2587
2965
  }
2588
2966
 
2589
2967
  // src/server.ts
2590
- var PKG_VERSION = true ? "0.19.0" : "0.0.0-dev";
2968
+ var PKG_VERSION = true ? "0.20.0" : "0.0.0-dev";
2591
2969
  function createMcpServer(client) {
2592
2970
  const server = new McpServer(
2593
2971
  {