@apex-inc/mcp-server 0.65.0 → 0.68.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 (48) hide show
  1. package/dist/api-client.d.ts +2 -0
  2. package/dist/api-client.d.ts.map +1 -1
  3. package/dist/api-client.js +11 -0
  4. package/dist/api-client.js.map +1 -1
  5. package/dist/letter-blocks.d.ts +15 -3
  6. package/dist/letter-blocks.d.ts.map +1 -1
  7. package/dist/letter-blocks.js +28 -1
  8. package/dist/letter-blocks.js.map +1 -1
  9. package/dist/setup-catchup-tools.d.ts +130 -4
  10. package/dist/setup-catchup-tools.d.ts.map +1 -1
  11. package/dist/setup-catchup-tools.js +205 -14
  12. package/dist/setup-catchup-tools.js.map +1 -1
  13. package/dist/tool-groups.d.ts.map +1 -1
  14. package/dist/tool-groups.js +8 -1
  15. package/dist/tool-groups.js.map +1 -1
  16. package/dist/tool-shared.d.ts +10 -2
  17. package/dist/tool-shared.d.ts.map +1 -1
  18. package/dist/tool-shared.js +36 -2
  19. package/dist/tool-shared.js.map +1 -1
  20. package/dist/tools/ad-platforms.d.ts +24 -16
  21. package/dist/tools/ad-platforms.d.ts.map +1 -1
  22. package/dist/tools/ad-platforms.js +54 -11
  23. package/dist/tools/ad-platforms.js.map +1 -1
  24. package/dist/tools/apex-campaigns.d.ts +2 -2
  25. package/dist/tools/context.d.ts +48 -8
  26. package/dist/tools/context.d.ts.map +1 -1
  27. package/dist/tools/context.js +114 -35
  28. package/dist/tools/context.js.map +1 -1
  29. package/dist/tools/experiments.d.ts.map +1 -1
  30. package/dist/tools/experiments.js +31 -14
  31. package/dist/tools/experiments.js.map +1 -1
  32. package/dist/tools/letters.d.ts +115 -26
  33. package/dist/tools/letters.d.ts.map +1 -1
  34. package/dist/tools/letters.js +243 -24
  35. package/dist/tools/letters.js.map +1 -1
  36. package/dist/tools/measurement.d.ts +150 -7
  37. package/dist/tools/measurement.d.ts.map +1 -1
  38. package/dist/tools/measurement.js +270 -34
  39. package/dist/tools/measurement.js.map +1 -1
  40. package/dist/tools/partners.d.ts +27 -4
  41. package/dist/tools/partners.d.ts.map +1 -1
  42. package/dist/tools/partners.js +74 -6
  43. package/dist/tools/partners.js.map +1 -1
  44. package/dist/tools.d.ts +503 -67
  45. package/dist/tools.d.ts.map +1 -1
  46. package/package.json +1 -1
  47. package/skills/apex-communications/SKILL.md +4 -3
  48. package/skills/apex-integration-cookbook/SKILL.md +25 -0
@@ -1,8 +1,8 @@
1
1
  import { z } from "zod";
2
- import { apiGet, apiPost, apiPatch, apiPut, apiDelete, postServerEvents, SERVER_KEY_NEEDED_MESSAGE, getActiveWorkspace, } from "../api-client.js";
2
+ import { apiGet, apiPost, apiPatch, apiPut, postServerEvents, SERVER_KEY_NEEDED_MESSAGE, } from "../api-client.js";
3
3
  import { getPersonLabel, lowerPerson } from "../person-label.js";
4
4
  import { MCP_SERVER_VERSION } from "../version.js";
5
- import { APEX, appUrl, errMsg, MCP_AGENT_VISITOR_ID, windowQuery, } from "../tool-shared.js";
5
+ import { APEX, appUrl, errMsg, MCP_AGENT_VISITOR_ID, resolveActiveWorkspace, windowQuery, } from "../tool-shared.js";
6
6
  function text(t, isError = false) {
7
7
  return { content: [{ type: "text", text: t }], ...(isError ? { isError: true } : {}) };
8
8
  }
@@ -21,6 +21,10 @@ const keyEventSourceSchema = z.object({
21
21
  selector: z.string().optional().describe('For form_submit: one form, as "#id". Omit for any form.'),
22
22
  target_url: z.string().optional().describe("For form_submit: the page the form is on. Omit for any page."),
23
23
  where: z.array(keyEventConditionSchema).max(10).optional().describe("Conditions on the event's data, all must hold."),
24
+ revenue_stream: z
25
+ .enum(["dedupe_with_billing", "additive"])
26
+ .optional()
27
+ .describe('Only on Revenue key events (purchase/subscribe): "dedupe_with_billing" (default, billing stays primary) or "additive" (separate money stream not in Stripe/Shopify/QuickBooks, e.g. offline deals).'),
24
28
  });
25
29
  const keyEventCategorySchema = z
26
30
  .enum([
@@ -41,13 +45,26 @@ const keyEventCategorySchema = z
41
45
  "other",
42
46
  ])
43
47
  .describe("What kind of step it is; sets its place in the funnel.");
48
+ async function revenueOverlapNoteFor(category) {
49
+ if (category !== "purchase" && category !== "subscribe")
50
+ return null;
51
+ try {
52
+ const res = await apiGet("/api/revenue/sources");
53
+ return res.data?.overlapWarning ?? null;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
44
59
  function keyEventLine(k, i) {
45
60
  const tags = [
46
- k.isCurrentGoal ? "main goal" : null,
61
+ k.archivedAt ? `archived ${k.archivedAt.slice(0, 10)}` : null,
62
+ k.isCurrentGoal && !k.archivedAt ? "main goal" : null,
47
63
  k.entityScope === "account" ? "counts companies" : null,
48
64
  k.definitionVersion > 1 ? `v${k.definitionVersion}` : null,
49
65
  ].filter(Boolean);
50
- return ` ${i + 1}. ${k.name} [${k.id}]${tags.length ? ` (${tags.join(", ")})` : ""}: ${k.counts}`;
66
+ const head = ` ${i + 1}. ${k.name} [${k.id}]${tags.length ? ` (${tags.join(", ")})` : ""}: ${k.counts}`;
67
+ return k.nameWarning ? `${head}\n ⚠ ${k.nameWarning}` : head;
51
68
  }
52
69
  const KEY_EVENT_USE_KIND = {
53
70
  journey: "Adaptive Journey",
@@ -78,11 +95,13 @@ function keyEventSuggestionLines(s, nameOf) {
78
95
  const ids = s.keyEventIds ?? [];
79
96
  const what = s.kind === "merge_key_events"
80
97
  ? `Merge ${ids.slice(1).map(named).join(", ")} into ${ids[0] ? named(ids[0]) : s.name}: they count the same thing`
81
- : s.kind === "extend_key_event"
82
- ? `Add ${s.events.join(", ")} to ${ids[0] ? named(ids[0]) : s.name}`
83
- : s.events.length > 1
84
- ? `Make "${s.name}" a key event, reached by ${s.events.join(", ")}`
85
- : `Make "${s.name}" a key event, reached by ${s.events[0]}`;
98
+ : s.kind === "restore_key_event"
99
+ ? `Bring back archived key event "${s.name}"${ids[0] ? ` [${ids[0]}]` : ""}: ${s.events.join(", ")} arrived again`
100
+ : s.kind === "extend_key_event"
101
+ ? `Add ${s.events.join(", ")} to ${ids[0] ? named(ids[0]) : s.name}`
102
+ : s.events.length > 1
103
+ ? `Make "${s.name}" a key event, reached by ${s.events.join(", ")}`
104
+ : `Make "${s.name}" a key event, reached by ${s.events[0]}`;
86
105
  return [
87
106
  ` ${what}`,
88
107
  ` suggestion_id ${s.id}. ${sureWords(s.confidence)} (${Math.round(s.confidence * 100)}%).`,
@@ -283,7 +302,8 @@ export const measurementTools = {
283
302
  const q = days && days !== "all" ? `?days=${days}` : "?days=all";
284
303
  const res = await apiGet(`/api/growth/reality${q}`);
285
304
  const goals = res.data?.goals ?? [];
286
- if (goals.length === 0) {
305
+ const unmeasured = res.data?.unmeasuredKeyEvents ?? [];
306
+ if (goals.length === 0 && unmeasured.length === 0) {
287
307
  return {
288
308
  content: [
289
309
  {
@@ -295,8 +315,14 @@ export const measurementTools = {
295
315
  }
296
316
  const pctFmt = (v) => v == null ? "—" : `${v > 0 ? "+" : ""}${(v * 100).toFixed(1)}%`;
297
317
  const lines = goals.map((g) => {
318
+ const totalConversions = (g.counts?.exposedConversions ?? 0) + (g.counts?.holdoutConversions ?? 0);
319
+ if (totalConversions === 0) {
320
+ const evLabel = g.eventName ? `${g.eventName} ` : "";
321
+ const totalSubjects = (g.counts?.exposedSubjects ?? 0) + (g.counts?.holdoutSubjects ?? 0);
322
+ return ` • ${g.goalName}: NO EVENTS YET (0 ${evLabel}conversions across ${totalSubjects.toLocaleString()} holdout-tracked people since ${g.collectingSince || "—"} — check get_wiring_status or list_data_sources)`;
323
+ }
298
324
  if (!g.isDecisive) {
299
- return ` • ${g.goalName}: COLLECTING (directional ${pctFmt(g.lift)}, since ${g.collectingSince || "—"})`;
325
+ return ` • ${g.goalName}: COLLECTING (directional ${pctFmt(g.lift)}, ${totalConversions.toLocaleString()} conversions since ${g.collectingSince || "—"})`;
300
326
  }
301
327
  const ci = g.liftCI
302
328
  ? ` [${pctFmt(g.liftCI.lower)}, ${pctFmt(g.liftCI.upper)}]`
@@ -306,6 +332,12 @@ export const measurementTools = {
306
332
  : "";
307
333
  return ` • ${g.goalName}: ${pctFmt(g.lift)} vs holdout${ci} — DECISIVE${rev}`;
308
334
  });
335
+ if (unmeasured.length > 0) {
336
+ for (const u of unmeasured) {
337
+ const evLabel = u.eventName ? ` (${u.eventName})` : "";
338
+ lines.push(` • ${u.name}${evLabel}: NO EVENTS YET (no holdout-tracked traffic since this key event was added — forward-only)`);
339
+ }
340
+ }
309
341
  return {
310
342
  content: [
311
343
  {
@@ -536,17 +568,20 @@ export const measurementTools = {
536
568
  },
537
569
  },
538
570
  list_key_events: {
539
- description: `${APEX} — The workspace's key events (the actions that matter to the business: Lead captured, Qualified, Revenue realized) in funnel order: which events reach each one, its version, whether it counts people or companies, and which one is the main one. These are the columns get_efforts shows; pass the ids to get_efforts key_event_ids or set_campaign_steps. Make one with create_key_event.`,
540
- schema: z.object({}),
541
- handler: async () => {
542
- const res = await apiGet("/api/key-events");
571
+ description: `${APEX} — The workspace's key events (the actions that matter to the business: Lead captured, Qualified, Revenue realized) in funnel order: which events reach each one, its version, whether it counts people or companies, and which one is the main one. Pass include_archived: true to include archived key events too (needed to find an id for restore_key_event). These are the columns get_efforts shows; pass the ids to get_efforts key_event_ids or set_campaign_steps. Make one with create_key_event.`,
572
+ schema: z.object({
573
+ includeArchived: z.boolean().optional().describe("Include archived key events too (default false)."),
574
+ }),
575
+ handler: async (args = {}) => {
576
+ const q = args.includeArchived ? "?include_archived=1" : "";
577
+ const res = await apiGet(`/api/key-events${q}`);
543
578
  const keyEvents = res.data?.keyEvents ?? [];
544
579
  if (keyEvents.length === 0) {
545
580
  return {
546
581
  content: [
547
582
  {
548
583
  type: "text",
549
- text: `${APEX} No key events yet. Make one with create_key_event (for example Lead captured, reached by application_submitted or audit_booked), or on ${appUrl("/dashboard/conversions")}.`,
584
+ text: `${APEX} No key events yet. Make one with create_key_event (for example Lead captured, reached by application_submitted or audit_booked), or on ${appUrl("/dashboard/key-events")}.`,
550
585
  },
551
586
  ],
552
587
  };
@@ -595,6 +630,7 @@ export const measurementTools = {
595
630
  entityScope: z.enum(["person", "account"]).optional().describe("person (default) or account (a company reaches it when its first person does)."),
596
631
  description: z.string().max(1000).optional(),
597
632
  template: z.string().max(100).optional().describe("The template it follows, e.g. lead_captured."),
633
+ position: z.number().int().min(0).max(999).optional().describe("Optional explicit funnel rank (0 = earliest step). Omit to use automatic funnel order."),
598
634
  }),
599
635
  handler: async (args) => {
600
636
  try {
@@ -605,9 +641,14 @@ export const measurementTools = {
605
641
  ...(args.entityScope ? { entity_scope: args.entityScope } : {}),
606
642
  ...(args.description ? { description: args.description } : {}),
607
643
  ...(args.template ? { template: args.template } : {}),
644
+ ...(typeof args.position === "number" ? { position: args.position } : {}),
608
645
  });
609
646
  const k = res.data?.keyEvent;
610
- return text(k ? `${APEX} Made key event:\n${keyEventLine(k, 0)}\nApex is now checking people's history for it.` : `${APEX} Made key event.`);
647
+ const note = await revenueOverlapNoteFor(k?.category ?? args.category);
648
+ const body = k
649
+ ? `${APEX} Made key event:\n${keyEventLine(k, 0)}\nApex is now checking people's history for it.`
650
+ : `${APEX} Made key event.`;
651
+ return text(note ? `${body}\n\nNote: ${note}` : body);
611
652
  }
612
653
  catch (err) {
613
654
  return text(`${APEX} ${errMsg(err)}`, true);
@@ -615,7 +656,7 @@ export const measurementTools = {
615
656
  },
616
657
  },
617
658
  update_key_event: {
618
- description: `${APEX} — Change a key event. Renaming keeps its version. Changing its events, their conditions or entity_scope makes a new version: people already counted keep the version they reached, and running tests keep the one they started with. is_current_goal true makes it the workspace's main goal: the one key event Home, Attribution and Channels count when no other is picked. A workspace has one, so it takes the place of the last. Tests, journeys and segments name their own key event and ignore it. Workspace admin.`,
659
+ description: `${APEX} — Change a key event. Renaming or changing position keeps its version. Changing its events, their conditions or entity_scope makes a new version: people already counted keep the version they reached, and running tests keep the one they started with. is_current_goal true makes it the workspace's main goal: the one key event Home, Attribution and Channels count when no other is picked. A workspace has one, so it takes the place of the last. Tests, journeys and segments name their own key event and ignore it. Workspace admin.`,
619
660
  schema: z.object({
620
661
  keyEventId: z.string().min(1).describe("From list_key_events."),
621
662
  name: z.string().min(1).max(200).optional(),
@@ -623,6 +664,7 @@ export const measurementTools = {
623
664
  category: keyEventCategorySchema.optional(),
624
665
  entityScope: z.enum(["person", "account"]).optional(),
625
666
  description: z.string().max(1000).optional(),
667
+ position: z.number().int().min(0).max(999).nullable().optional().describe("Explicit funnel rank (0 = earliest), or null to reset to automatic order."),
626
668
  isCurrentGoal: z.literal(true).optional().describe("Make it the workspace's main goal, in place of the one before."),
627
669
  }),
628
670
  handler: async (args) => {
@@ -633,23 +675,146 @@ export const measurementTools = {
633
675
  ...(args.category ? { category: args.category } : {}),
634
676
  ...(args.entityScope ? { entity_scope: args.entityScope } : {}),
635
677
  ...(args.description !== undefined ? { description: args.description } : {}),
678
+ ...(args.position !== undefined ? { position: args.position } : {}),
636
679
  ...(args.isCurrentGoal ? { is_current_goal: true } : {}),
637
680
  });
638
681
  const k = res.data?.keyEvent;
639
- return text(k ? `${APEX} Saved:\n${keyEventLine(k, 0)}` : `${APEX} Saved.`);
682
+ const note = await revenueOverlapNoteFor(k?.category ?? args.category);
683
+ const body = k ? `${APEX} Saved:\n${keyEventLine(k, 0)}` : `${APEX} Saved.`;
684
+ return text(note ? `${body}\n\nNote: ${note}` : body);
685
+ }
686
+ catch (err) {
687
+ return text(`${APEX} ${errMsg(err)}`, true);
688
+ }
689
+ },
690
+ },
691
+ get_revenue_sources: {
692
+ description: `${APEX} — Where this workspace's revenue comes from: connected billing and CRM tools (Stripe, Shopify, QuickBooks, HubSpot), which source currently counts as primary, the active Revenue key event and whether each tracked event dedupes with billing or counts as a separate money stream, plus any suspected duplicate revenue waiting for review.`,
693
+ schema: z.object({}),
694
+ handler: async () => {
695
+ try {
696
+ const res = await apiGet("/api/revenue/sources");
697
+ const d = res.data;
698
+ if (!d)
699
+ return text(`${APEX} Couldn't load revenue sources.`, true);
700
+ const lines = [
701
+ `${APEX} Revenue sources`,
702
+ `${"═".repeat(40)}`,
703
+ `Counting now: ${d.countingNow ?? (d.needsReferee ? "none (pick one with set_revenue_source_of_truth)" : "none yet")}${d.revenueSourceOfTruth ? " (picked)" : d.isProvisional ? " (automatic until you pick)" : ""}`,
704
+ ];
705
+ if (d.connectedIntegrations.length > 0) {
706
+ lines.push("Connected billing/CRM:", ...d.connectedIntegrations.map((c) => ` • ${c.label}: ${c.isCounting ? "counting" : c.isLive ? "live (not primary)" : "connected"}`));
707
+ }
708
+ else {
709
+ lines.push("Connected billing/CRM: none");
710
+ }
711
+ if (d.revenueKeyEvent) {
712
+ lines.push(`Revenue key event: ${d.revenueKeyEvent.name} [${d.revenueKeyEvent.id}] (${d.revenueKeyEvent.category})`);
713
+ for (const s of d.revenueKeyEvent.sources) {
714
+ lines.push(` • ${s.eventName ?? s.type}: ${s.revenueStream === "additive" ? "separate money stream (adds alongside billing)" : "same sales (dedupe with billing)"}`);
715
+ }
716
+ }
717
+ else {
718
+ lines.push("Revenue key event: none set (built-in purchases count by default)");
719
+ }
720
+ if (d.suspectedDuplicateCount > 0) {
721
+ lines.push(`Suspected duplicates: $${d.suspectedDuplicateUsd.toFixed(2)} across ${d.suspectedDuplicateCount} ${d.suspectedDuplicateCount === 1 ? "sale" : "sales"}. Review on ${appUrl("/dashboard/settings/attribution")}.`);
722
+ }
723
+ if (d.overlapWarning)
724
+ lines.push("", `Note: ${d.overlapWarning}`);
725
+ return text(lines.join("\n"));
640
726
  }
641
727
  catch (err) {
642
728
  return text(`${APEX} ${errMsg(err)}`, true);
643
729
  }
644
730
  },
645
731
  },
646
- delete_key_event: {
647
- description: `${APEX} — Delete a key event nothing uses. Apex refuses while a journey, a segment, a campaign, a target, a test that is not finished, or an ad platform send uses it, and the reply says which: take it out of each one first (get_key_event_usage lists them). Do not work around a refusal; tell the user what uses it. Finished tests keep their results. Prefer update_key_event when the meaning changed. Workspace admin.`,
732
+ set_revenue_source_of_truth: {
733
+ description: `${APEX} — Pick which single revenue source counts as the workspace's primary source of truth (stripe, shopify, quickbooks, hubspot, server, sdk, manual). Call first with confirm omitted/false to preview how historical revenue would change, then call again with confirm: true to apply the restatement. Workspace admin.`,
734
+ schema: z.object({
735
+ sourceOfTruth: z
736
+ .enum(["stripe", "shopify", "quickbooks", "hubspot", "server", "sdk", "manual"])
737
+ .describe("The source that should count as primary revenue."),
738
+ confirm: z
739
+ .boolean()
740
+ .optional()
741
+ .describe("Omit or false to preview the restatement impact without writing; true to apply it."),
742
+ }),
743
+ handler: async (args) => {
744
+ try {
745
+ if (!args.confirm) {
746
+ const res = await apiPost("/api/revenue/referee", {
747
+ sourceOfTruth: args.sourceOfTruth,
748
+ previewOnly: true,
749
+ });
750
+ const p = res.data?.preview;
751
+ if (!p)
752
+ return text(`${APEX} Preview unavailable.`, true);
753
+ return text([
754
+ `${APEX} Preview: switch revenue source of truth to ${args.sourceOfTruth}`,
755
+ `${"═".repeat(40)}`,
756
+ `Before: $${p.beforeUsd.toFixed(2)} → After: $${p.afterUsd.toFixed(2)} (change: ${p.deltaUsd >= 0 ? "+" : ""}$${p.deltaUsd.toFixed(2)})`,
757
+ `Events reflagged: ${p.eventsReflagged}, people recalculated: ${p.affectedLeads}`,
758
+ `Nothing changed yet. Call set_revenue_source_of_truth again with source_of_truth: "${args.sourceOfTruth}" and confirm: true to apply.`,
759
+ ].join("\n"));
760
+ }
761
+ const res = await apiPost("/api/revenue/referee", {
762
+ sourceOfTruth: args.sourceOfTruth,
763
+ acknowledgeRestatement: true,
764
+ });
765
+ const d = res.data;
766
+ return text(`${APEX} Revenue source of truth is now ${d?.sourceOfTruth ?? args.sourceOfTruth} (${d?.eventsReflagged ?? 0} events updated, ${d?.affectedLeads ?? 0} people recalculated).`);
767
+ }
768
+ catch (err) {
769
+ return text(`${APEX} ${errMsg(err)}`, true);
770
+ }
771
+ },
772
+ },
773
+ reorder_key_events: {
774
+ description: `${APEX} — Set the workspace's funnel order for its active key events (earliest step first). Pass key_event_ids in the exact sequence customers move through your product; any active key event omitted from the list stays after the ones you named. Workspace admin.`,
775
+ schema: z.object({
776
+ keyEventIds: z.array(z.string().min(1)).min(1).max(200).describe("Active key event IDs in funnel order, earliest step first."),
777
+ }),
778
+ handler: async ({ keyEventIds }) => {
779
+ try {
780
+ const res = await apiPost("/api/key-events/reorder", {
781
+ key_event_ids: keyEventIds,
782
+ });
783
+ const keyEvents = res.data?.keyEvents ?? [];
784
+ const lines = [`${APEX} Updated key event funnel order`, `${"═".repeat(40)}`, ...keyEvents.map(keyEventLine)];
785
+ return text(lines.join("\n"));
786
+ }
787
+ catch (err) {
788
+ return text(`${APEX} ${errMsg(err)}`, true);
789
+ }
790
+ },
791
+ },
792
+ archive_key_event: {
793
+ description: `${APEX} — Archive a key event nothing active uses. It stops counting new people and leaves every picker, while keeping its version history, who reached it, and old reports intact. Bring it back anytime with restore_key_event. Apex refuses while an active journey, an active segment, a campaign, a target, a test that is not finished, or an ad platform send uses it, and the reply says which: take it out of each one first (get_key_event_usage lists them). Do not work around a refusal; tell the user what uses it. Finished tests and archived segments do not stand in the way. Prefer update_key_event when the meaning changed. Workspace admin.`,
648
794
  schema: z.object({ keyEventId: z.string().min(1).describe("From list_key_events.") }),
649
795
  handler: async ({ keyEventId }) => {
650
796
  try {
651
- await apiDelete(`/api/key-events/${encodeURIComponent(keyEventId)}`);
652
- return text(`${APEX} Deleted ${keyEventId}.`);
797
+ const res = await apiPost(`/api/key-events/${encodeURIComponent(keyEventId)}/archive`, {});
798
+ const k = res.data?.keyEvent;
799
+ return text(k
800
+ ? `${APEX} Archived "${k.name}" [${k.id}]. It stopped counting new people and left every picker; its history and versions are kept. Bring it back anytime with restore_key_event.`
801
+ : `${APEX} Archived ${keyEventId}. Bring it back anytime with restore_key_event.`);
802
+ }
803
+ catch (err) {
804
+ return text(`${APEX} ${errMsg(err)}`, true);
805
+ }
806
+ },
807
+ },
808
+ restore_key_event: {
809
+ description: `${APEX} — Bring an archived key event back. It returns to every picker, starts counting new people again, and scans history for events heard while it was archived. Use list_key_events with include_archived: true to find archived ids. Workspace admin.`,
810
+ schema: z.object({ keyEventId: z.string().min(1).describe("From list_key_events with include_archived: true.") }),
811
+ handler: async ({ keyEventId }) => {
812
+ try {
813
+ const res = await apiPost(`/api/key-events/${encodeURIComponent(keyEventId)}/restore`, {});
814
+ const k = res.data?.keyEvent;
815
+ return text(k
816
+ ? `${APEX} Brought back:\n${keyEventLine(k, 0)}\nApex is now checking history for events heard while it was archived.`
817
+ : `${APEX} Brought ${keyEventId} back.`);
653
818
  }
654
819
  catch (err) {
655
820
  return text(`${APEX} ${errMsg(err)}`, true);
@@ -696,14 +861,14 @@ export const measurementTools = {
696
861
  },
697
862
  },
698
863
  get_key_event_usage: {
699
- description: `${APEX} — Where a key event is used: the Adaptive Journeys, segments, tests, campaigns and targets that name it, and what each does with it (goal, starts when reached, guardrail, judged on it). Read it before update_key_event, delete_key_event or accepting a merge. Id from list_key_events.`,
864
+ description: `${APEX} — Where a key event is used: the Adaptive Journeys, active segments, tests, campaigns, partner programs paying on it, and targets that name it, and what each does with it (goal, starts when reached, guardrail, judged on it, pays partners). Read it before update_key_event, archive_key_event or accepting a merge. Id from list_key_events.`,
700
865
  schema: z.object({ keyEventId: z.string().min(1).describe("From list_key_events.") }),
701
866
  handler: async ({ keyEventId }) => {
702
867
  try {
703
868
  const res = await apiGet(`/api/key-events/${encodeURIComponent(keyEventId)}/usage`);
704
869
  const usage = res.data?.usage ?? [];
705
870
  if (usage.length === 0)
706
- return text(`${APEX} Nothing uses ${keyEventId} yet. No journey, segment, test, campaign or target names it.`);
871
+ return text(`${APEX} Nothing uses ${keyEventId} yet. No journey, segment, test, campaign, partner program or target names it.`);
707
872
  const lines = [`${APEX} Used in ${usage.length} place${usage.length === 1 ? "" : "s"}`, ...usage.map(keyEventUseLine)];
708
873
  return text(lines.join("\n"));
709
874
  }
@@ -712,6 +877,57 @@ export const measurementTools = {
712
877
  }
713
878
  },
714
879
  },
880
+ get_key_event_timing: {
881
+ description: `${APEX} — How long it takes people or companies to go from one key event to another (e.g. Trial started to Paid, or Qualified to Revenue), overall and broken down by campaign. Omit to_key_event_id to measure time to the workspace's primary revenue key event (or purchases by default). Ids come from list_key_events.`,
882
+ schema: z.object({
883
+ fromKeyEventId: z.string().min(1).describe("Starting key event id from list_key_events."),
884
+ toKeyEventId: z
885
+ .string()
886
+ .min(1)
887
+ .optional()
888
+ .describe("Ending key event id from list_key_events. Omit to measure time to the workspace's primary revenue key event (or purchases)."),
889
+ scope: z.enum(["person", "account"]).optional().describe("Count per person or per company (defaults to the starting key event's scope)."),
890
+ campaignId: z.string().min(1).optional().describe("Filter to a single Apex campaign id."),
891
+ start: z.string().optional().describe("Only count people/companies who reached the starting key event on or after this ISO date."),
892
+ end: z.string().optional().describe("Only count people/companies who reached the starting key event on or before this ISO date."),
893
+ }),
894
+ handler: async (args) => {
895
+ try {
896
+ const params = new URLSearchParams({ from_key_event_id: args.fromKeyEventId });
897
+ if (args.toKeyEventId)
898
+ params.set("to_key_event_id", args.toKeyEventId);
899
+ if (args.scope)
900
+ params.set("scope", args.scope);
901
+ if (args.campaignId)
902
+ params.set("campaign_id", args.campaignId);
903
+ if (args.start)
904
+ params.set("start", args.start);
905
+ if (args.end)
906
+ params.set("end", args.end);
907
+ const res = await apiGet(`/api/key-events/timing?${params.toString()}`);
908
+ const d = res.data;
909
+ if (!d)
910
+ return text(`${APEX} Couldn't read key event timing.`, true);
911
+ const unit = d.scope === "account" ? "companies" : "people";
912
+ const fmtDur = (hours, days) => hours === null ? "—" : days !== null && days >= 2 ? `${days}d` : `${hours}h`;
913
+ const pct = (r) => `${Math.round(r * 1000) / 10}%`;
914
+ const lines = [
915
+ `${APEX} ${d.from.name} → ${d.to.name} (${unit})`,
916
+ `Overall: ${d.overall.reachedTo}/${d.overall.reachedFrom} (${pct(d.overall.conversionRate)}) · median ${fmtDur(d.overall.medianHours, d.overall.medianDays)}`,
917
+ ];
918
+ if (d.byCampaign.length > 0) {
919
+ lines.push("", "By campaign:");
920
+ for (const row of d.byCampaign) {
921
+ lines.push(` • ${row.campaignName}: ${row.reachedTo}/${row.reachedFrom} (${pct(row.conversionRate)}) · median ${fmtDur(row.medianHours, row.medianDays)}`);
922
+ }
923
+ }
924
+ return text(lines.join("\n"));
925
+ }
926
+ catch (err) {
927
+ return text(`${APEX} ${errMsg(err)}`, true);
928
+ }
929
+ },
930
+ },
715
931
  suggest_key_events: {
716
932
  description: `${APEX} — What Apex suggests about key events, from the events it hears: events that mean the same moment and should count as one key event, a single event that is a standard moment (order_placed is a purchase) with no key event for it yet, events to add to a key event the workspace has, and two key events that count the same thing. Each comes with why and how sure Apex is. Apex only lists what it is sure enough about, so an empty answer is normal for a new workspace. Show the owner the suggestion and the why, then accept_key_event_suggestion or dismiss_key_event_suggestion on their answer. Never accept on your own.`,
717
933
  schema: z.object({}),
@@ -1656,7 +1872,10 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1656
1872
  .describe("Include archived sources. Defaults to false."),
1657
1873
  }),
1658
1874
  handler: async ({ includeArchived }) => {
1659
- const proj = getActiveWorkspace();
1875
+ const proj = await resolveActiveWorkspace();
1876
+ if (!proj) {
1877
+ return text("No active workspace. Use switch_workspace first (or set APEX_WORKSPACE_KEY).", true);
1878
+ }
1660
1879
  const qs = includeArchived ? "?includeArchived=true" : "";
1661
1880
  const json = await apiGet(`/api/workspaces/${proj}/data-sources${qs}`);
1662
1881
  const sources = json.data ?? [];
@@ -1676,7 +1895,10 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1676
1895
  name: z.string().describe("Display name, e.g. 'Marketing site' or 'Backend API'."),
1677
1896
  }),
1678
1897
  handler: async ({ kind, name }) => {
1679
- const proj = getActiveWorkspace();
1898
+ const proj = await resolveActiveWorkspace();
1899
+ if (!proj) {
1900
+ return text("No active workspace. Use switch_workspace first (or set APEX_WORKSPACE_KEY).", true);
1901
+ }
1680
1902
  const json = await apiPost(`/api/workspaces/${proj}/data-sources`, { kind, name });
1681
1903
  const s = json.data;
1682
1904
  return { content: [{ type: "text", text: `✓ Created data source **${s.name}** (${s.kind}) — ${s.status} · \`${s.id}\`` }] };
@@ -1688,7 +1910,10 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1688
1910
  id: z.string().describe("The data source id (ds_...)."),
1689
1911
  }),
1690
1912
  handler: async ({ id }) => {
1691
- const proj = getActiveWorkspace();
1913
+ const proj = await resolveActiveWorkspace();
1914
+ if (!proj) {
1915
+ return text("No active workspace. Use switch_workspace first (or set APEX_WORKSPACE_KEY).", true);
1916
+ }
1692
1917
  const json = await apiGet(`/api/workspaces/${proj}/data-sources/${encodeURIComponent(id)}/health`);
1693
1918
  const h = json.data;
1694
1919
  return { content: [{ type: "text", text: `# ${h.kind} source ${h.id}\n\n- status: **${h.status}**\n- first seen: ${h.firstSeenAt ?? "never"}\n- last seen: ${h.lastSeenAt ?? "never"}` }] };
@@ -1754,7 +1979,7 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1754
1979
  description: `${APEX} — Live wiring verification for the active workspace: which canonical events have been received (tier: waiting → detected → verified), which identify traits (first_name, email, …) are arriving, per-data-source status, and which journey/communication templates are Ready to run. Call this AFTER instrumenting tracking code to verify your own work — iterate until each wired event reports "detected". Presence-only: never returns end-user values.`,
1755
1980
  schema: z.object({}),
1756
1981
  handler: async () => {
1757
- const workspaceKey = getActiveWorkspace();
1982
+ const workspaceKey = await resolveActiveWorkspace();
1758
1983
  if (!workspaceKey) {
1759
1984
  return {
1760
1985
  content: [{ type: "text", text: "No active workspace. Use switch_workspace first (or set APEX_WORKSPACE_KEY)." }],
@@ -1768,9 +1993,16 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1768
1993
  const sourceLines = d.sources.map((s) => `- ${s.name} (${s.kind}): ${s.status}${s.lastSeenAt ? ` — last event ${s.lastSeenAt}` : ""}`);
1769
1994
  const readyTemplates = d.templates.filter((t) => t.ready);
1770
1995
  const blockedTemplates = d.templates.filter((t) => !t.ready);
1996
+ // Always list every journey template (so setup-referenced templates like
1997
+ // `mobile-install-nudge` are never pushed off by communication templates),
1998
+ // while capping non-journey blocked templates at 10.
1999
+ const blockedJourneys = blockedTemplates.filter((t) => t.templateKind === "journey");
2000
+ const blockedOther = blockedTemplates
2001
+ .filter((t) => t.templateKind !== "journey")
2002
+ .slice(0, 10);
1771
2003
  const templateLines = [
1772
- ...readyTemplates.map((t) => `- ✅ ${t.title} (${t.templateKind}, id: ${t.templateId}) — Ready to run${t.templateKind === "journey" ? ` → create_journey_from_template({ templateId: "${t.templateId}" })` : ""}`),
1773
- ...blockedTemplates.slice(0, 10).map((t) => `- ⏳ ${t.title} (${t.templateKind}, id: ${t.templateId}) — needs ${[...t.missingEvents, ...t.missingTraits].join(", ") || "?"}`),
2004
+ ...readyTemplates.map((t) => `- ✅ ${t.title} (${t.templateKind}, id: ${t.templateId}) — Ready to run${t.templateKind === "journey" ? ` → create_journey_from_template({ template_id: "${t.templateId}" })` : ""}`),
2005
+ ...[...blockedJourneys, ...blockedOther].map((t) => `- ⏳ ${t.title} (${t.templateKind}, id: ${t.templateId}) — needs ${[...t.missingEvents, ...t.missingTraits].join(", ") || "?"}`),
1774
2006
  ];
1775
2007
  const milestones = [
1776
2008
  d.milestones.firstEventAt ? `First event: ${d.milestones.firstEventAt}` : "First event: not yet",
@@ -1814,10 +2046,14 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1814
2046
  }))
1815
2047
  .min(1)
1816
2048
  .describe("Every instrumentation opportunity found in the scan — both already-wired events (wired: true) and the gaps you propose to wire."),
1817
- summary: z.string().optional().describe("One-paragraph scan summary for the merchant — include what you're deliberately NOT wiring and why."),
2049
+ summary: z
2050
+ .string()
2051
+ .max(500)
2052
+ .optional()
2053
+ .describe("One-paragraph scan summary for the merchant (max 500 characters) — include what you're deliberately NOT wiring and why."),
1818
2054
  }),
1819
2055
  handler: async (args) => {
1820
- const workspaceKey = getActiveWorkspace();
2056
+ const workspaceKey = await resolveActiveWorkspace();
1821
2057
  if (!workspaceKey) {
1822
2058
  return {
1823
2059
  content: [{ type: "text", text: "No active workspace. Use switch_workspace first (or set APEX_WORKSPACE_KEY)." }],
@@ -1849,7 +2085,7 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1849
2085
  visitorId: z.string().optional().describe("Visitor id (default a test id)"),
1850
2086
  }),
1851
2087
  handler: async (args) => {
1852
- const workspaceKey = getActiveWorkspace();
2088
+ const workspaceKey = await resolveActiveWorkspace();
1853
2089
  if (!workspaceKey) {
1854
2090
  return { content: [{ type: "text", text: "No active workspace. Run /apex-login or set APEX_WORKSPACE_KEY." }] };
1855
2091
  }