@apex-inc/mcp-server 0.75.0 → 0.79.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.
Files changed (86) hide show
  1. package/README.md +8 -0
  2. package/dist/api-client.d.ts +13 -21
  3. package/dist/api-client.d.ts.map +1 -1
  4. package/dist/api-client.js +203 -61
  5. package/dist/api-client.js.map +1 -1
  6. package/dist/auth.d.ts.map +1 -1
  7. package/dist/auth.js +7 -6
  8. package/dist/auth.js.map +1 -1
  9. package/dist/fetch-timeout.d.ts +23 -0
  10. package/dist/fetch-timeout.d.ts.map +1 -0
  11. package/dist/fetch-timeout.js +78 -0
  12. package/dist/fetch-timeout.js.map +1 -0
  13. package/dist/hosted.d.ts +34 -0
  14. package/dist/hosted.d.ts.map +1 -0
  15. package/dist/hosted.js +74 -0
  16. package/dist/hosted.js.map +1 -0
  17. package/dist/index.js +49 -117
  18. package/dist/index.js.map +1 -1
  19. package/dist/letter-blocks.d.ts.map +1 -1
  20. package/dist/letter-blocks.js +13 -22
  21. package/dist/letter-blocks.js.map +1 -1
  22. package/dist/live-test-files.d.ts +35 -0
  23. package/dist/live-test-files.d.ts.map +1 -0
  24. package/dist/live-test-files.js +114 -0
  25. package/dist/live-test-files.js.map +1 -0
  26. package/dist/live-test-guard.d.ts.map +1 -1
  27. package/dist/live-test-guard.js +7 -1
  28. package/dist/live-test-guard.js.map +1 -1
  29. package/dist/request-context.d.ts +40 -0
  30. package/dist/request-context.d.ts.map +1 -0
  31. package/dist/request-context.js +11 -0
  32. package/dist/request-context.js.map +1 -0
  33. package/dist/server-factory.d.ts +31 -0
  34. package/dist/server-factory.d.ts.map +1 -0
  35. package/dist/server-factory.js +585 -0
  36. package/dist/server-factory.js.map +1 -0
  37. package/dist/setup-catchup-tools.d.ts +4 -0
  38. package/dist/setup-catchup-tools.d.ts.map +1 -1
  39. package/dist/setup-catchup-tools.js +33 -67
  40. package/dist/setup-catchup-tools.js.map +1 -1
  41. package/dist/smoke-tools.d.ts.map +1 -1
  42. package/dist/smoke-tools.js +2 -0
  43. package/dist/smoke-tools.js.map +1 -1
  44. package/dist/tool-catalog.d.ts +2 -0
  45. package/dist/tool-catalog.d.ts.map +1 -1
  46. package/dist/tool-catalog.js +6 -1
  47. package/dist/tool-catalog.js.map +1 -1
  48. package/dist/tool-groups.d.ts.map +1 -1
  49. package/dist/tool-groups.js +12 -0
  50. package/dist/tool-groups.js.map +1 -1
  51. package/dist/tool-mode.d.ts +48 -0
  52. package/dist/tool-mode.d.ts.map +1 -0
  53. package/dist/tool-mode.js +189 -0
  54. package/dist/tool-mode.js.map +1 -0
  55. package/dist/tool-shared.d.ts +9 -1
  56. package/dist/tool-shared.d.ts.map +1 -1
  57. package/dist/tool-shared.js +52 -6
  58. package/dist/tool-shared.js.map +1 -1
  59. package/dist/tools/adoption.d.ts.map +1 -1
  60. package/dist/tools/adoption.js +2 -1
  61. package/dist/tools/adoption.js.map +1 -1
  62. package/dist/tools/apex-campaigns.d.ts +394 -0
  63. package/dist/tools/apex-campaigns.d.ts.map +1 -1
  64. package/dist/tools/apex-campaigns.js +256 -1
  65. package/dist/tools/apex-campaigns.js.map +1 -1
  66. package/dist/tools/context.d.ts +2 -2
  67. package/dist/tools/experiments.d.ts +69 -1
  68. package/dist/tools/experiments.d.ts.map +1 -1
  69. package/dist/tools/experiments.js +140 -76
  70. package/dist/tools/experiments.js.map +1 -1
  71. package/dist/tools/letters.d.ts +214 -48
  72. package/dist/tools/letters.d.ts.map +1 -1
  73. package/dist/tools/letters.js +240 -44
  74. package/dist/tools/letters.js.map +1 -1
  75. package/dist/tools/measurement.d.ts +70 -28
  76. package/dist/tools/measurement.d.ts.map +1 -1
  77. package/dist/tools/measurement.js +165 -27
  78. package/dist/tools/measurement.js.map +1 -1
  79. package/dist/tools.d.ts +774 -76
  80. package/dist/tools.d.ts.map +1 -1
  81. package/package.json +11 -1
  82. package/skills/apex-growth-intelligence/SKILL.md +4 -0
  83. package/skills/apex-growth-tracking/SKILL.md +1 -1
  84. package/skills/apex-integration-cookbook/SKILL.md +23 -3
  85. package/skills/apex-setup/SKILL.md +2 -1
  86. package/skills/apex-spec/SKILL.md +6 -1
@@ -1,16 +1,16 @@
1
1
  import { z } from "zod";
2
- import { existsSync, readFileSync } from "node:fs";
3
- import { join } from "node:path";
4
2
  import { apiGet, apiPost, apiPatch, apiDelete, getActiveWorkspace, } from "../api-client.js";
3
+ import { LONG_REQUEST_TIMEOUT_MS } from "../fetch-timeout.js";
4
+ import { resolveLiveCheckFiles } from "../live-test-files.js";
5
5
  import { resolveExperimentHypothesis } from "../experiment-copy.js";
6
6
  import { activationLiveLine, shouldRefuseActivationWiring } from "../activation-wiring.js";
7
7
  import { parseFrontDoorRefusal, renderFrontDoorRefusal } from "../belief-front-door.js";
8
8
  import { apexBaseUrl } from "../base-url.js";
9
9
  import { fetchLiveTestHits, formatLiveTestStop, isFileStop, isObjectStop, } from "../live-test-guard.js";
10
10
  import { hasConflictAdvisory, renderConflictAdvisory, } from "../conflict-advisory.js";
11
- import { APEX, controlPctOf, daysRunningOf, experimentTimingLabel, predictionLines, findVariant, missingScreenshotLines, formatArmLine, titleCaseEvent, assertTargetUrlForActiveWorkspace, errMsg, resolveCreateSurface, } from "../tool-shared.js";
12
- const STARTING_CONFIDENCE_HELP = "Leave unset. A new claim with no tests starts at 50% (untested) and moves only when a test concludes. Set it only when you can name the evidence (a past test or measured data), and say what it is.";
13
- const NEW_BECAUSE_HELP = "Only after Apex returned related beliefs and the user said this is a different claim: one sentence on how it differs. Kept on the record.";
11
+ import { appUrl, APEX, controlPctOf, daysRunningOf, experimentTimingLabel, predictionLines, findVariant, missingScreenshotLines, formatArmLine, titleCaseEvent, assertTargetUrlForActiveWorkspace, errMsg, resolveCreateSurface, } from "../tool-shared.js";
12
+ const STARTING_CONFIDENCE_HELP = "Omit unless backed by prior test/data (untested claims start at 50%).";
13
+ const NEW_BECAUSE_HELP = "One sentence on how this differs from related beliefs (only after Apex returned matches).";
14
14
  const NETWORK_WORD = {
15
15
  meta: "Meta",
16
16
  google: "Google",
@@ -45,7 +45,7 @@ const KEY_EVENT_GOAL_PARAM = {
45
45
  primaryMetricKeyEventId: z
46
46
  .string()
47
47
  .optional()
48
- .describe("Judge the experiment on a key event (id from list_key_events) instead of one event. The test counts every event the key event counts, with its conditions, pinned to the key event's version when the test starts, so editing the key event later never moves a running test. Prefer this when a key event already covers the outcome. Pass this OR primary_metric_event, never both. A key event that counts customers leaving is refused."),
48
+ .describe("Key event id (from list_key_events) to judge the test on; pass this OR primary_metric_event, never both."),
49
49
  };
50
50
  /** The key event a goal names, read from the active workspace, or why it can't be read. */
51
51
  async function readKeyEventGoal(id) {
@@ -79,11 +79,11 @@ const FORM_GOAL_PARAMS = {
79
79
  primaryMetricFormPage: z
80
80
  .string()
81
81
  .optional()
82
- .describe("With primary_metric_event 'form_submit': count only forms sent on this page (a path like '/wholesale', or a URL), the same rule key events use. Omit to count forms on every page."),
82
+ .describe("With primary_metric_event='form_submit': count only forms on this path/URL."),
83
83
  primaryMetricFormId: z
84
84
  .string()
85
85
  .optional()
86
- .describe("With primary_metric_event 'form_submit': count only the form with this id (the form's HTML id, e.g. 'wholesale-apply'). A submission that doesn't say which form it was still counts. Omit to count every form."),
86
+ .describe("With primary_metric_event='form_submit': count only this HTML form id."),
87
87
  };
88
88
  /** The page-and-form narrowing for a form goal, or why it was refused. */
89
89
  function formGoalOf(args) {
@@ -434,49 +434,49 @@ export const experimentTools = {
434
434
  },
435
435
  },
436
436
  create_experiment: {
437
- description: `${APEX} — Create an experiment record. Returns a structured recipe for the AI agent to implement. The agent makes the actual code changes using useApexVariant hook — Apex never generates code. Always call with preview=true first so the user sees a summary.`,
437
+ description: `${APEX} — Create an experiment draft and implementation recipe (useApexVariant). Call with preview=true first.`,
438
438
  schema: z.object({
439
439
  name: z.string().describe("Experiment name"),
440
- targetUrl: z.string().optional().describe("URL of the page to test on the ACTIVE workspace (include #anchor for section targeting). Must be a host registered on this workspace (via set_workspace_environments in production_hosts or beta_hosts, or already sending events) — pre-launch domains with 0 events are allowed for drafting once registered. Never guess a brand domain or a sibling workspace's site. Required for web and mobile; not used for surface 'paid_channel'."),
441
- controlContent: z.string().optional().describe("The current content that the control shows. Required for web and mobile; not used for surface 'paid_channel'."),
442
- variantContent: z.string().optional().describe("The new content for the variant. Required for web and mobile; not used for surface 'paid_channel'."),
443
- targetComponent: z.string().optional().describe("Component or file path where the change should be made"),
444
- targetAnchor: z.string().optional().describe("Section anchor/ID on the page (e.g. 'pricing', 'hero')"),
445
- trafficSplit: z.number().min(1).max(99).optional().describe("Percentage of traffic to control (default 50)"),
446
- beliefId: z.string().optional().describe("ID of the assumption this tests"),
447
- hypothesisId: z.string().optional().describe("ID of the expected outcome"),
448
- predictionId: z.string().optional().describe("ID of the expected impact"),
449
- beliefStatement: z.string().optional().describe("If you don't have a beliefId, pass the assumption statement and Apex will create the belief (and a hypothesis) and link them to this experiment."),
450
- beliefConfidence: z.number().min(0).max(100).optional().describe(`For a belief created from beliefStatement. ${STARTING_CONFIDENCE_HELP}`),
451
- newBecause: z.string().optional().describe(`With beliefStatement. ${NEW_BECAUSE_HELP}`),
452
- hypothesisStatement: z.string().optional().describe("Optional hypothesis statement to record alongside a belief created from beliefStatement."),
453
- primaryMetricEvent: z.string().optional().describe("Event the experiment optimizes: a standard Apex event (e.g. 'checkout_completed') or any event this workspace receives or defined with define_event (e.g. 'demo_booked'). Checked against this workspace; a name it has never seen is refused with the closest matches. Prefer an OUTCOME event (purchase/signup) over a proxy (email_open) — use list_metrics to see which are DETECTED with volume."),
454
- primaryMetricType: z.enum(["rate", "count", "revenue", "duration"]).optional().describe("How the goal is measured. 'rate' (default) = did it happen. 'revenue'/'duration' = a continuous value summed per subject (set primaryMetricValueProperty). Use 'revenue' for Stripe/purchase-value goals."),
455
- primaryMetricValueProperty: z.string().optional().describe("For revenue/duration goals: the event property to sum, e.g. 'value'. Defaults to 'value'."),
440
+ targetUrl: z.string().optional().describe("Registered host URL on the active workspace (include #anchor if needed). Required for web/mobile."),
441
+ controlContent: z.string().optional().describe("Current control content (required for web/mobile)."),
442
+ variantContent: z.string().optional().describe("New variant content (required for web/mobile)."),
443
+ targetComponent: z.string().optional().describe("Target component or file path"),
444
+ targetAnchor: z.string().optional().describe("Section anchor/ID (e.g. 'pricing', 'hero')"),
445
+ trafficSplit: z.number().min(1).max(99).optional().describe("Control traffic % (default 50)"),
446
+ beliefId: z.string().optional().describe("Existing assumption id"),
447
+ hypothesisId: z.string().optional().describe("Existing hypothesis id"),
448
+ predictionId: z.string().optional().describe("Existing prediction id"),
449
+ beliefStatement: z.string().optional().describe("Create and link a new belief + hypothesis if no beliefId"),
450
+ beliefConfidence: z.number().min(0).max(100).optional().describe(`With beliefStatement: ${STARTING_CONFIDENCE_HELP}`),
451
+ newBecause: z.string().optional().describe(`With beliefStatement: ${NEW_BECAUSE_HELP}`),
452
+ hypothesisStatement: z.string().optional().describe("Optional hypothesis alongside beliefStatement"),
453
+ primaryMetricEvent: z.string().optional().describe("Goal event (standard or workspace event from list_metrics). Prefer outcome over proxy."),
454
+ primaryMetricType: z.enum(["rate", "count", "revenue", "duration"]).optional().describe("Goal type: rate (default), count, revenue, or duration."),
455
+ primaryMetricValueProperty: z.string().optional().describe("Property to sum for revenue/duration goals (default 'value')."),
456
456
  ...KEY_EVENT_GOAL_PARAM,
457
457
  ...FORM_GOAL_PARAMS,
458
- guardrailEvent: z.string().optional().describe("Canonical protective event for an EXTRA guardrail that must not regress (e.g. 'purchase_refunded', 'app_uninstall', 'js_error'). Apex already auto-protects revenue/refunds/errors by default — only pass this to add a test-specific harm signal. Use list_metrics({role:'guardrail'}) to see what's firing. Choose one ORTHOGONAL to the primary goal."),
459
- guardrailType: z.enum(["rate", "revenue", "duration"]).optional().describe("How the guardrail is measured. 'rate' (default) = how often the harm event fires. 'revenue' = sum a value (e.g. refund $)."),
460
- guardrailThreshold: z.number().optional().describe("Harm margin for the guardrail, RELATIVE (0.25 = flag a >25% rise). Defaults to 0.25."),
461
- predictionMagnitude: z.string().optional().describe("Your committed prediction of the effect, e.g. '10% lift'. Recorded with 'agent' provenance and used for calibration. Required before the experiment can be ACTIVATED."),
462
- surface: z.enum(["web", "mobile", "paid_channel"]).optional().describe("The PROPERTY the experiment runs in (not the SDK used): 'web' for a website, 'mobile' for a native / Capacitor / React-Native app, 'paid_channel' for an Ad holdout (Apex holds a share of known people back from the workspace's ads on one network and measures the installs the ads actually caused — pass paid_channel too). OPTIONAL for web/mobile — when omitted it is auto-detected from repo signals (capacitor.config.* / @apex-inc/capacitor-plugin → mobile) and the workspace's registered data sources; pass it explicitly only to override or when both web and mobile sources exist. Sets the dashboard data-source label (Website vs Mobile app vs Ads)."),
458
+ guardrailEvent: z.string().optional().describe("Optional extra protective event (Apex already auto-protects revenue/refunds/errors)."),
459
+ guardrailType: z.enum(["rate", "revenue", "duration"]).optional().describe("Guardrail type: rate (default), revenue, or duration."),
460
+ guardrailThreshold: z.number().optional().describe("Relative harm threshold (default 0.25 = +25%)."),
461
+ predictionMagnitude: z.string().optional().describe("Expected lift (e.g. '10% lift'). Required before activation."),
462
+ surface: z.enum(["web", "mobile", "paid_channel"]).optional().describe("Property: 'web', 'mobile', or 'paid_channel' (Ad holdout). Auto-detected when omitted."),
463
463
  paid_channel: z
464
464
  .object({
465
- network: z.enum(["meta", "google", "tiktok", "linkedin"]).describe("Ad network the ad sets run on. Ad holdouts run on Meta and Google; Apex refuses a network that is not switched on (surface_not_enabled), so offer no other. Apex attaches the do-not-show list itself on Meta; on Google the owner adds it as a campaign exclusion (Google: campaign ids)."),
466
- ad_account_id: z.string().optional().describe("The connected ad account the ad sets belong to. Omit to use the account the workspace connected for this network."),
467
- ad_set_ids: z.array(z.string()).min(1).describe("Ad set ids to hold people back from (max 20). Frozen at create; changing them is a new holdout."),
468
- holdout_percent: z.number().min(0.05).max(0.5).describe("Share of the known population held back, 0.05–0.5 (0.2 = one in five)."),
469
- attach_mode: z.enum(["apex", "manual"]).optional().describe("'apex' = Apex puts the list on the ad sets and checks daily (Meta). 'manual' = the owner adds the audience as an exclusion by hand (Google); Apex checks daily and counts nothing until it is on. Defaults to 'apex' on Meta, 'manual' on Google."),
470
- washout_days: z.number().int().min(0).max(30).optional().describe("Days after the list lands before installs count, so pre-list ad exposure washes out. Default 3."),
471
- population_segment_id: z.string().optional().describe("Optional Segment id narrowing who can be drawn."),
465
+ network: z.enum(["meta", "google", "tiktok", "linkedin"]).describe("Ad network (Meta or Google)."),
466
+ ad_account_id: z.string().optional().describe("Ad account id (omit for connected default)."),
467
+ ad_set_ids: z.array(z.string()).min(1).describe("Ad set / Google campaign ids (max 20, frozen at create)."),
468
+ holdout_percent: z.number().min(0.05).max(0.5).describe("Held-back share, 0.05-0.5 (e.g. 0.2)."),
469
+ attach_mode: z.enum(["apex", "manual"]).optional().describe("'apex' (Meta default) or 'manual' (Google default)."),
470
+ washout_days: z.number().int().min(0).max(30).optional().describe("Washout days before counting (default 3)."),
471
+ population_segment_id: z.string().optional().describe("Optional Segment id narrowing population."),
472
472
  })
473
473
  .optional()
474
- .describe("Ad holdout settings. Required when surface is 'paid_channel'; rejected otherwise. The primary metric is always app installs, so primaryMetricEvent is not needed."),
475
- dataSourceId: z.string().optional().describe("Optional explicit Data Source (property) id this experiment runs in, e.g. 'ds_website' or 'ds_ios'. Usually inferred from surface; pass it to bind to a specific registered source. Tenant-validated server-side."),
476
- randomizationUnit: z.enum(["device", "visitor", "person", "account", "org"]).optional().describe("What to bucket on. Default 'visitor' (per-device). Use 'person' to give one stitched user the same variant across their devices, or 'account'/'org' for B2B account-level tests where everyone in an account should see the same variant."),
477
- minSamplePerArm: z.number().int().min(30).optional().describe("Minimum exposed subjects PER ARM before a winner can be claimed (the sample gate). Defaults to 50. Raise it to demand more evidence (detect a smaller lift); lower it (floor 30) for low-traffic properties that would otherwise stall. The real winner-gate is still the 95% probability-to-be-best — this only sets the traffic floor. Pre-registration: frozen once the experiment is running."),
478
- runtimeDays: z.number().int().min(1).max(365).optional().describe("How long to run the experiment, in days (the decision window). Apex force-concludes at this point — decisive winner if reached, else inconclusive. Defaults to 14. Set e.g. 28 to run for four weeks. This is the max runtime, not a minimum: a decisive winner can conclude sooner. Pre-registration: frozen once the experiment is running (fork to change it)."),
479
- preview: z.boolean().optional().describe("If true, returns a preview without creating. Default: true."),
474
+ .describe("Ad holdout config (required for surface='paid_channel')."),
475
+ dataSourceId: z.string().optional().describe("Optional Data Source id (usually inferred from surface)."),
476
+ randomizationUnit: z.enum(["device", "visitor", "person", "account", "org"]).optional().describe("Bucketing unit (default 'visitor')."),
477
+ minSamplePerArm: z.number().int().min(30).optional().describe("Min exposed subjects per arm (default 50, floor 30; frozen at launch)."),
478
+ runtimeDays: z.number().int().min(1).max(365).optional().describe("Max runtime in days (default 14; frozen at launch)."),
479
+ preview: z.boolean().optional().describe("Preview without creating (default true)."),
480
480
  }),
481
481
  handler: async (args) => {
482
482
  // Mobile Measurement P3a — an Ad holdout is not a code change. No page,
@@ -1040,7 +1040,9 @@ export const experimentTools = {
1040
1040
  }),
1041
1041
  handler: async ({ experimentId }) => {
1042
1042
  try {
1043
- const res = await apiPost(`/api/experiments/${encodeURIComponent(experimentId)}/recapture`, {});
1043
+ const res = await apiPost(`/api/experiments/${encodeURIComponent(experimentId)}/recapture`, {}, {
1044
+ timeoutMs: LONG_REQUEST_TIMEOUT_MS,
1045
+ });
1044
1046
  const { captured, errors, identical, message } = res.data;
1045
1047
  const lines = [
1046
1048
  `${APEX} Re-captured ${captured} screenshot${captured === 1 ? "" : "s"} for ${experimentId}.`,
@@ -1668,15 +1670,20 @@ export const experimentTools = {
1668
1670
  },
1669
1671
  },
1670
1672
  list_beliefs: {
1671
- description: `${APEX} — List the workspace's beliefs (the assumptions experiments test). Shows confidence, validation state, and AI-generated provenance so you can LINK an existing belief instead of minting a duplicate.`,
1673
+ description: `${APEX} — List the workspace's beliefs (the assumptions experiments test). Shows confidence, validation state, and AI-generated provenance so you can LINK an existing belief instead of minting a duplicate. Pass include_archived: true to include archived beliefs.`,
1672
1674
  schema: z.object({
1673
1675
  query: z
1674
1676
  .string()
1675
1677
  .optional()
1676
1678
  .describe("Filter beliefs by a keyword in the statement"),
1679
+ includeArchived: z
1680
+ .boolean()
1681
+ .optional()
1682
+ .describe("Include archived beliefs (default false)."),
1677
1683
  }),
1678
- handler: async ({ query }) => {
1679
- const beliefs = await apiGet("/api/beliefs");
1684
+ handler: async ({ query, includeArchived }) => {
1685
+ const path = includeArchived ? "/api/beliefs?includeArchived=true" : "/api/beliefs";
1686
+ const beliefs = await apiGet(path);
1680
1687
  const q = query?.toLowerCase().trim();
1681
1688
  const filtered = q
1682
1689
  ? beliefs.filter((b) => b.statement.toLowerCase().includes(q))
@@ -1696,6 +1703,7 @@ export const experimentTools = {
1696
1703
  .map((b) => {
1697
1704
  const tags = [
1698
1705
  `${Math.round(b.confidence * 100)}% confidence`,
1706
+ b.archivedAt ? "archived" : null,
1699
1707
  b.validationState === "unvalidated" ? "unvalidated" : null,
1700
1708
  b.generatedFromExperimentId ? "AI-generated" : null,
1701
1709
  ]
@@ -1713,7 +1721,7 @@ export const experimentTools = {
1713
1721
  `${"═".repeat(40)}`,
1714
1722
  lines,
1715
1723
  ``,
1716
- `Link one to a new experiment with its id, or generate a fresh belief from your hypothesis.`,
1724
+ `Link one to a new experiment with its id, edit wording with update_belief, or retire an obsolete claim with archive_belief.`,
1717
1725
  `If two of these state the same claim, merge them (merge_beliefs) so their evidence adds up in one place.`,
1718
1726
  ].join("\n"),
1719
1727
  },
@@ -1721,6 +1729,65 @@ export const experimentTools = {
1721
1729
  };
1722
1730
  },
1723
1731
  },
1732
+ update_belief: {
1733
+ description: `${APEX} — Edit a belief's statement in place (for example during a rebrand or to clarify wording). Preserves the belief's id, confidence, evidence, and linked experiments. Workspace admin.`,
1734
+ schema: z.object({
1735
+ beliefId: z.string().min(1).describe("The belief id to edit (from list_beliefs)."),
1736
+ statement: z.string().trim().min(1).max(2000).describe("The updated belief statement."),
1737
+ }),
1738
+ handler: async ({ beliefId, statement }) => {
1739
+ try {
1740
+ const res = await apiPatch(`/api/beliefs/${encodeURIComponent(beliefId)}`, { statement: statement.trim() });
1741
+ const updated = res.data;
1742
+ return {
1743
+ content: [
1744
+ {
1745
+ type: "text",
1746
+ text: [
1747
+ `${APEX} Belief updated (${updated?.id ?? beliefId})`,
1748
+ ` Statement: "${updated?.statement ?? statement.trim()}"`,
1749
+ ` Open Beliefs: ${appUrl("/dashboard/beliefs")}`,
1750
+ ].join("\n"),
1751
+ },
1752
+ ],
1753
+ };
1754
+ }
1755
+ catch (err) {
1756
+ return textError(`Could not update belief: ${errMsg(err)}`);
1757
+ }
1758
+ },
1759
+ },
1760
+ archive_belief: {
1761
+ description: `${APEX} — Archive (or restore) a belief so retired claims leave active lists and duplicate checks while keeping past experiment history intact. Refuses if an active experiment is currently testing this belief. Pass archived: false to restore an archived belief. Workspace admin.`,
1762
+ schema: z.object({
1763
+ beliefId: z.string().min(1).describe("The belief id to archive or restore (from list_beliefs)."),
1764
+ archived: z
1765
+ .boolean()
1766
+ .optional()
1767
+ .describe("true (default) to archive; false to restore an archived belief."),
1768
+ }),
1769
+ handler: async ({ beliefId, archived = true }) => {
1770
+ try {
1771
+ const res = await apiPatch(`/api/beliefs/${encodeURIComponent(beliefId)}`, { archived });
1772
+ const updated = res.data;
1773
+ return {
1774
+ content: [
1775
+ {
1776
+ type: "text",
1777
+ text: [
1778
+ `${APEX} Belief ${archived ? "archived" : "restored"} (${updated?.id ?? beliefId})`,
1779
+ ` Statement: "${updated?.statement ?? beliefId}"`,
1780
+ ` Open Beliefs: ${appUrl("/dashboard/beliefs")}`,
1781
+ ].join("\n"),
1782
+ },
1783
+ ],
1784
+ };
1785
+ }
1786
+ catch (err) {
1787
+ return textError(`Could not ${archived ? "archive" : "restore"} belief: ${errMsg(err)}`);
1788
+ }
1789
+ },
1790
+ },
1724
1791
  merge_beliefs: {
1725
1792
  description: `${APEX} — Merge a duplicate belief into the one that survives. Use when two beliefs state the same claim, so their evidence is split and neither confidence tells the truth. Moves the duplicate's evidence, hypotheses, predictions, outcomes, decision-log entries, child beliefs and linked tests onto the survivor, writes a decision-log entry naming what moved, and keeps the duplicate as a redirect (old ids still resolve; lists hide it). Not reversible from the tools. Show the user both statements and get their go-ahead before calling.`,
1726
1793
  schema: z.object({
@@ -2051,22 +2118,23 @@ export const experimentTools = {
2051
2118
  },
2052
2119
  },
2053
2120
  update_experiment: {
2054
- description: `${APEX} — Edit an EXISTING experiment. Editability is gated by lifecycle: a DRAFT (with no exposures yet) is fully editable; once it has data or is running, the pre-registration (hypothesis, metric, guardrails) and bucketing (surface, variants) freeze and edits return a clear "experiment_locked" reason. After freeze, fork_experiment instead. Use this to fix a mislabeled surface or correct a draft before launch.`,
2121
+ description: `${APEX} — Edit an existing experiment. Drafts are editable; running experiments freeze pre-registration and bucketing (use fork_experiment instead).`,
2055
2122
  schema: z.object({
2056
- experimentId: z.string().describe("The experiment id to edit."),
2057
- name: z.string().optional().describe("Rename (cosmetic; editable anytime)."),
2058
- surface: z.enum(["web", "mobile", "paid_channel"]).optional().describe("Correct the surface — editable only on a draft with 0 exposures (web↔mobile). 'paid_channel' is accepted only when the draft already carries its Ad holdout block."),
2059
- hypothesis: z.string().optional().describe("Edit the hypothesis — draft only (pre-registration)."),
2060
- targetUrl: z.string().optional().describe("Retarget a DRAFT to a URL on the ACTIVE workspace. Same host rules as create_experiment."),
2061
- predictionId: z.string().optional().describe("Attach a minted prediction id (from log_prediction) to this draft. Also stamps the prediction onto the experiment's hypothesis when that link is missing. Required before activation."),
2062
- primaryMetricEvent: z.string().optional().describe("Change the primary metric's event — draft only. Same check as create_experiment: a standard Apex event, or any event this workspace receives or defined."),
2123
+ experimentId: z.string().describe("Experiment id"),
2124
+ name: z.string().optional().describe("Rename (editable anytime)"),
2125
+ surface: z.enum(["web", "mobile", "paid_channel"]).optional().describe("Surface (draft with 0 exposures only)"),
2126
+ hypothesis: z.string().optional().describe("Hypothesis (draft only)"),
2127
+ beliefId: z.string().min(1).optional().describe("Re-link to another belief id (draft only)"),
2128
+ targetUrl: z.string().optional().describe("Retarget draft to a registered workspace URL"),
2129
+ predictionId: z.string().optional().describe("Attach a prediction id from log_prediction (required before activation)"),
2130
+ primaryMetricEvent: z.string().optional().describe("Primary goal event (draft only)"),
2063
2131
  primaryMetricType: z.enum(["rate", "count", "revenue", "duration"]).optional(),
2064
2132
  ...KEY_EVENT_GOAL_PARAM,
2065
2133
  ...FORM_GOAL_PARAMS,
2066
- guardrailEvent: z.string().optional().describe("Replace the guardrail with this canonical protective event — draft only."),
2067
- minSamplePerArm: z.number().int().min(30).optional().describe("Set the minimum exposed subjects PER ARM before a winner can be claimed (the sample gate; floor 30). Draft only — it's part of the pre-registration and freezes at launch (a running experiment returns experiment_locked; fork to change it)."),
2068
- runtimeDays: z.number().int().min(1).max(365).optional().describe("Set how long to run the experiment, in days (the decision window Apex force-concludes at). Draft only — part of the pre-registration; freezes at launch (fork to change it)."),
2069
- allocation: z.enum(["even", "adaptive"]).optional().describe("Journey message tests (surface journey_arm) only, draft only. 'even' keeps every version on an equal share for the whole test (the default, cleanest read on the difference). 'adaptive' starts even, then once every version has reached the minimum per version, sends more people to the version that is ahead. Ask the owner which they want; do not pick for them."),
2134
+ guardrailEvent: z.string().optional().describe("Extra protective guardrail event (draft only)"),
2135
+ minSamplePerArm: z.number().int().min(30).optional().describe("Min exposed subjects per arm (floor 30; draft only)"),
2136
+ runtimeDays: z.number().int().min(1).max(365).optional().describe("Max runtime in days (draft only)"),
2137
+ allocation: z.enum(["even", "adaptive"]).optional().describe("Journey message test split (draft only): 'even' (default) or 'adaptive'. Ask the owner before changing."),
2070
2138
  }),
2071
2139
  handler: async (args) => {
2072
2140
  if (args.targetUrl) {
@@ -2104,6 +2172,8 @@ export const experimentTools = {
2104
2172
  body.surface = args.surface;
2105
2173
  if (args.hypothesis !== undefined)
2106
2174
  body.hypothesis = args.hypothesis;
2175
+ if (args.beliefId !== undefined)
2176
+ body.beliefId = args.beliefId.trim();
2107
2177
  if (args.targetUrl !== undefined)
2108
2178
  body.targetUrl = args.targetUrl;
2109
2179
  if (args.predictionId !== undefined)
@@ -2263,13 +2333,17 @@ export const experimentTools = {
2263
2333
  file_paths: z
2264
2334
  .array(z.string())
2265
2335
  .optional()
2266
- .describe("Repo-relative paths you are about to edit or commit. Full file is read locally when content is omitted."),
2336
+ .describe("Repo-relative or absolute paths you are about to edit or commit. When editing inside a git worktree or another checkout, pass file_contents (preferred), absolute paths, or repo_root so Apex reads the right copy."),
2267
2337
  file_contents: z
2268
2338
  .array(z.object({
2269
2339
  path: z.string(),
2270
2340
  content: z.string().describe("Full file at HEAD, not the diff hunk."),
2271
2341
  }))
2272
2342
  .optional(),
2343
+ repo_root: z
2344
+ .string()
2345
+ .optional()
2346
+ .describe("Absolute path to the repo or git worktree root you are editing. Resolves relative file_paths against this folder instead of the MCP process directory."),
2273
2347
  urls: z
2274
2348
  .array(z.string())
2275
2349
  .optional()
@@ -2289,21 +2363,11 @@ export const experimentTools = {
2289
2363
  }),
2290
2364
  handler: async (args) => {
2291
2365
  try {
2292
- const byPath = new Map();
2293
- for (const row of args.file_contents ?? []) {
2294
- if (row?.path)
2295
- byPath.set(row.path, { path: row.path, content: row.content });
2296
- }
2297
- for (const raw of args.file_paths ?? []) {
2298
- if (!raw || byPath.has(raw))
2299
- continue;
2300
- const abs = raw.startsWith("/") ? raw : join(process.cwd(), raw);
2301
- byPath.set(raw, {
2302
- path: raw,
2303
- content: existsSync(abs) ? readFileSync(abs, "utf8") : undefined,
2304
- });
2305
- }
2306
- const files = [...byPath.values()];
2366
+ const files = resolveLiveCheckFiles({
2367
+ filePaths: args.file_paths,
2368
+ fileContents: args.file_contents,
2369
+ repoRoot: args.repo_root,
2370
+ });
2307
2371
  const hits = await fetchLiveTestHits({
2308
2372
  files,
2309
2373
  urls: args.urls,