@apex-inc/mcp-server 0.66.0 → 0.69.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,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,6 +45,17 @@ 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
61
  k.archivedAt ? `archived ${k.archivedAt.slice(0, 10)}` : null,
@@ -87,9 +102,10 @@ function keyEventSuggestionLines(s, nameOf) {
87
102
  : s.events.length > 1
88
103
  ? `Make "${s.name}" a key event, reached by ${s.events.join(", ")}`
89
104
  : `Make "${s.name}" a key event, reached by ${s.events[0]}`;
105
+ const autoNote = s.autoSetup ? " Ready for automatic setup." : "";
90
106
  return [
91
107
  ` ${what}`,
92
- ` suggestion_id ${s.id}. ${sureWords(s.confidence)} (${Math.round(s.confidence * 100)}%).`,
108
+ ` suggestion_id ${s.id}. ${sureWords(s.confidence)} (${Math.round(s.confidence * 100)}%).${autoNote}`,
93
109
  ...s.evidence.map((e) => ` • ${e.detail}`),
94
110
  ];
95
111
  }
@@ -629,7 +645,11 @@ export const measurementTools = {
629
645
  ...(typeof args.position === "number" ? { position: args.position } : {}),
630
646
  });
631
647
  const k = res.data?.keyEvent;
632
- return text(k ? `${APEX} Made key event:\n${keyEventLine(k, 0)}\nApex is now checking people's history for it.` : `${APEX} Made key event.`);
648
+ const note = await revenueOverlapNoteFor(k?.category ?? args.category);
649
+ const body = k
650
+ ? `${APEX} Made key event:\n${keyEventLine(k, 0)}\nApex is now checking people's history for it.`
651
+ : `${APEX} Made key event.`;
652
+ return text(note ? `${body}\n\nNote: ${note}` : body);
633
653
  }
634
654
  catch (err) {
635
655
  return text(`${APEX} ${errMsg(err)}`, true);
@@ -660,7 +680,91 @@ export const measurementTools = {
660
680
  ...(args.isCurrentGoal ? { is_current_goal: true } : {}),
661
681
  });
662
682
  const k = res.data?.keyEvent;
663
- return text(k ? `${APEX} Saved:\n${keyEventLine(k, 0)}` : `${APEX} Saved.`);
683
+ const note = await revenueOverlapNoteFor(k?.category ?? args.category);
684
+ const body = k ? `${APEX} Saved:\n${keyEventLine(k, 0)}` : `${APEX} Saved.`;
685
+ return text(note ? `${body}\n\nNote: ${note}` : body);
686
+ }
687
+ catch (err) {
688
+ return text(`${APEX} ${errMsg(err)}`, true);
689
+ }
690
+ },
691
+ },
692
+ get_revenue_sources: {
693
+ 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.`,
694
+ schema: z.object({}),
695
+ handler: async () => {
696
+ try {
697
+ const res = await apiGet("/api/revenue/sources");
698
+ const d = res.data;
699
+ if (!d)
700
+ return text(`${APEX} Couldn't load revenue sources.`, true);
701
+ const lines = [
702
+ `${APEX} Revenue sources`,
703
+ `${"═".repeat(40)}`,
704
+ `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)" : ""}`,
705
+ ];
706
+ if (d.connectedIntegrations.length > 0) {
707
+ lines.push("Connected billing/CRM:", ...d.connectedIntegrations.map((c) => ` • ${c.label}: ${c.isCounting ? "counting" : c.isLive ? "live (not primary)" : "connected"}`));
708
+ }
709
+ else {
710
+ lines.push("Connected billing/CRM: none");
711
+ }
712
+ if (d.revenueKeyEvent) {
713
+ lines.push(`Revenue key event: ${d.revenueKeyEvent.name} [${d.revenueKeyEvent.id}] (${d.revenueKeyEvent.category})`);
714
+ for (const s of d.revenueKeyEvent.sources) {
715
+ lines.push(` • ${s.eventName ?? s.type}: ${s.revenueStream === "additive" ? "separate money stream (adds alongside billing)" : "same sales (dedupe with billing)"}`);
716
+ }
717
+ }
718
+ else {
719
+ lines.push("Revenue key event: none set (built-in purchases count by default)");
720
+ }
721
+ if (d.suspectedDuplicateCount > 0) {
722
+ lines.push(`Suspected duplicates: $${d.suspectedDuplicateUsd.toFixed(2)} across ${d.suspectedDuplicateCount} ${d.suspectedDuplicateCount === 1 ? "sale" : "sales"}. Review on ${appUrl("/dashboard/settings/attribution")}.`);
723
+ }
724
+ if (d.overlapWarning)
725
+ lines.push("", `Note: ${d.overlapWarning}`);
726
+ return text(lines.join("\n"));
727
+ }
728
+ catch (err) {
729
+ return text(`${APEX} ${errMsg(err)}`, true);
730
+ }
731
+ },
732
+ },
733
+ set_revenue_source_of_truth: {
734
+ 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.`,
735
+ schema: z.object({
736
+ sourceOfTruth: z
737
+ .enum(["stripe", "shopify", "quickbooks", "hubspot", "server", "sdk", "manual"])
738
+ .describe("The source that should count as primary revenue."),
739
+ confirm: z
740
+ .boolean()
741
+ .optional()
742
+ .describe("Omit or false to preview the restatement impact without writing; true to apply it."),
743
+ }),
744
+ handler: async (args) => {
745
+ try {
746
+ if (!args.confirm) {
747
+ const res = await apiPost("/api/revenue/referee", {
748
+ sourceOfTruth: args.sourceOfTruth,
749
+ previewOnly: true,
750
+ });
751
+ const p = res.data?.preview;
752
+ if (!p)
753
+ return text(`${APEX} Preview unavailable.`, true);
754
+ return text([
755
+ `${APEX} Preview: switch revenue source of truth to ${args.sourceOfTruth}`,
756
+ `${"═".repeat(40)}`,
757
+ `Before: $${p.beforeUsd.toFixed(2)} → After: $${p.afterUsd.toFixed(2)} (change: ${p.deltaUsd >= 0 ? "+" : ""}$${p.deltaUsd.toFixed(2)})`,
758
+ `Events reflagged: ${p.eventsReflagged}, people recalculated: ${p.affectedLeads}`,
759
+ `Nothing changed yet. Call set_revenue_source_of_truth again with source_of_truth: "${args.sourceOfTruth}" and confirm: true to apply.`,
760
+ ].join("\n"));
761
+ }
762
+ const res = await apiPost("/api/revenue/referee", {
763
+ sourceOfTruth: args.sourceOfTruth,
764
+ acknowledgeRestatement: true,
765
+ });
766
+ const d = res.data;
767
+ return text(`${APEX} Revenue source of truth is now ${d?.sourceOfTruth ?? args.sourceOfTruth} (${d?.eventsReflagged ?? 0} events updated, ${d?.affectedLeads ?? 0} people recalculated).`);
664
768
  }
665
769
  catch (err) {
666
770
  return text(`${APEX} ${errMsg(err)}`, true);
@@ -758,14 +862,14 @@ export const measurementTools = {
758
862
  },
759
863
  },
760
864
  get_key_event_usage: {
761
- description: `${APEX} — Where a key event is used: the Adaptive Journeys, active 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, archive_key_event or accepting a merge. Id from list_key_events.`,
865
+ 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.`,
762
866
  schema: z.object({ keyEventId: z.string().min(1).describe("From list_key_events.") }),
763
867
  handler: async ({ keyEventId }) => {
764
868
  try {
765
869
  const res = await apiGet(`/api/key-events/${encodeURIComponent(keyEventId)}/usage`);
766
870
  const usage = res.data?.usage ?? [];
767
871
  if (usage.length === 0)
768
- return text(`${APEX} Nothing uses ${keyEventId} yet. No journey, segment, test, campaign or target names it.`);
872
+ return text(`${APEX} Nothing uses ${keyEventId} yet. No journey, segment, test, campaign, partner program or target names it.`);
769
873
  const lines = [`${APEX} Used in ${usage.length} place${usage.length === 1 ? "" : "s"}`, ...usage.map(keyEventUseLine)];
770
874
  return text(lines.join("\n"));
771
875
  }
@@ -774,8 +878,59 @@ export const measurementTools = {
774
878
  }
775
879
  },
776
880
  },
881
+ get_key_event_timing: {
882
+ 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.`,
883
+ schema: z.object({
884
+ fromKeyEventId: z.string().min(1).describe("Starting key event id from list_key_events."),
885
+ toKeyEventId: z
886
+ .string()
887
+ .min(1)
888
+ .optional()
889
+ .describe("Ending key event id from list_key_events. Omit to measure time to the workspace's primary revenue key event (or purchases)."),
890
+ scope: z.enum(["person", "account"]).optional().describe("Count per person or per company (defaults to the starting key event's scope)."),
891
+ campaignId: z.string().min(1).optional().describe("Filter to a single Apex campaign id."),
892
+ start: z.string().optional().describe("Only count people/companies who reached the starting key event on or after this ISO date."),
893
+ end: z.string().optional().describe("Only count people/companies who reached the starting key event on or before this ISO date."),
894
+ }),
895
+ handler: async (args) => {
896
+ try {
897
+ const params = new URLSearchParams({ from_key_event_id: args.fromKeyEventId });
898
+ if (args.toKeyEventId)
899
+ params.set("to_key_event_id", args.toKeyEventId);
900
+ if (args.scope)
901
+ params.set("scope", args.scope);
902
+ if (args.campaignId)
903
+ params.set("campaign_id", args.campaignId);
904
+ if (args.start)
905
+ params.set("start", args.start);
906
+ if (args.end)
907
+ params.set("end", args.end);
908
+ const res = await apiGet(`/api/key-events/timing?${params.toString()}`);
909
+ const d = res.data;
910
+ if (!d)
911
+ return text(`${APEX} Couldn't read key event timing.`, true);
912
+ const unit = d.scope === "account" ? "companies" : "people";
913
+ const fmtDur = (hours, days) => hours === null ? "—" : days !== null && days >= 2 ? `${days}d` : `${hours}h`;
914
+ const pct = (r) => `${Math.round(r * 1000) / 10}%`;
915
+ const lines = [
916
+ `${APEX} ${d.from.name} → ${d.to.name} (${unit})`,
917
+ `Overall: ${d.overall.reachedTo}/${d.overall.reachedFrom} (${pct(d.overall.conversionRate)}) · median ${fmtDur(d.overall.medianHours, d.overall.medianDays)}`,
918
+ ];
919
+ if (d.byCampaign.length > 0) {
920
+ lines.push("", "By campaign:");
921
+ for (const row of d.byCampaign) {
922
+ lines.push(` • ${row.campaignName}: ${row.reachedTo}/${row.reachedFrom} (${pct(row.conversionRate)}) · median ${fmtDur(row.medianHours, row.medianDays)}`);
923
+ }
924
+ }
925
+ return text(lines.join("\n"));
926
+ }
927
+ catch (err) {
928
+ return text(`${APEX} ${errMsg(err)}`, true);
929
+ }
930
+ },
931
+ },
777
932
  suggest_key_events: {
778
- 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.`,
933
+ 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. Also lists key events Apex already set up automatically (each with its suggestion_id so the owner can undo it) and previously declined suggestions. Show the owner the suggestion and the why, then accept_key_event_suggestion, dismiss_key_event_suggestion, or undo_key_event_suggestion on their answer. Never accept on your own.`,
779
934
  schema: z.object({}),
780
935
  handler: async () => {
781
936
  try {
@@ -784,15 +939,42 @@ export const measurementTools = {
784
939
  if (!d)
785
940
  return text(`${APEX} Couldn't read the suggestions.`, true);
786
941
  const nameOf = new Map(d.keyEvents.map((k) => [k.id, k.name]));
787
- if (d.suggestions.length === 0) {
942
+ const setUpByApex = d.keyEvents.flatMap((k) => (k.origins ?? [])
943
+ .filter((o) => o.by === "apex")
944
+ .map((o) => ({ keyEvent: k, origin: o })));
945
+ const declined = d.declined ?? [];
946
+ if (d.suggestions.length === 0 && setUpByApex.length === 0 && declined.length === 0) {
788
947
  const uncounted = d.events.filter((e) => e.keyEventIds.length === 0).length;
789
948
  return text(d.events.length === 0
790
949
  ? `${APEX} No suggestions. Apex hasn't heard an event from this workspace yet.`
791
950
  : `${APEX} No suggestions right now. Apex hears ${d.events.length} event${d.events.length === 1 ? "" : "s"}, ${uncounted} not counted by any key event, and isn't sure enough to group any. Make one by hand with create_key_event.`);
792
951
  }
793
- const lines = [`${APEX} ${d.suggestions.length} suggestion${d.suggestions.length === 1 ? "" : "s"}`, `${"═".repeat(40)}`];
794
- for (const s of d.suggestions)
795
- lines.push(...keyEventSuggestionLines(s, nameOf), "");
952
+ const lines = [];
953
+ if (d.suggestions.length > 0) {
954
+ lines.push(`${APEX} ${d.suggestions.length} suggestion${d.suggestions.length === 1 ? "" : "s"}`, `${"═".repeat(40)}`);
955
+ for (const s of d.suggestions)
956
+ lines.push(...keyEventSuggestionLines(s, nameOf), "");
957
+ }
958
+ else {
959
+ const uncounted = d.events.filter((e) => e.keyEventIds.length === 0).length;
960
+ lines.push(`${APEX} No open suggestions right now (${d.events.length} heard event${d.events.length === 1 ? "" : "s"}, ${uncounted} not counted by any key event).`, "");
961
+ }
962
+ if (setUpByApex.length > 0) {
963
+ lines.push(`Set up by Apex (${setUpByApex.length}) — call undo_key_event_suggestion to take any back:`);
964
+ for (const { keyEvent, origin } of setUpByApex) {
965
+ const evText = origin.events.length > 0 ? ` (${origin.events.join(", ")})` : "";
966
+ const why = origin.reasons[0] ? ` — ${origin.reasons[0]}` : "";
967
+ lines.push(` • ${keyEvent.name} [${keyEvent.id}]${evText} — suggestion_id ${origin.suggestionId}${why}`);
968
+ }
969
+ lines.push("");
970
+ }
971
+ if (declined.length > 0) {
972
+ lines.push(`Previously declined (${declined.length}) — call undo_key_event_suggestion to ask again:`);
973
+ for (const s of declined) {
974
+ lines.push(` • ${s.name} (${s.events.join(", ")}) — suggestion_id ${s.id}`);
975
+ }
976
+ lines.push("");
977
+ }
796
978
  lines.push(`Review them on ${appUrl("/dashboard/key-events")}.`);
797
979
  return text(lines.join("\n"));
798
980
  }
@@ -802,11 +984,12 @@ export const measurementTools = {
802
984
  },
803
985
  },
804
986
  accept_key_event_suggestion: {
805
- description: `${APEX} — Take one suggestion from suggest_key_events, after the owner said yes: makes the key event, adds the events to the one they have, or merges the two. A merge deletes nothing; the key event merged away keeps counting for anything that names it. name calls it something else. events keeps only some of the suggested events; the ones left out are remembered as not belonging. For a merge, keep_key_event_id picks which key event keeps its name; leave it out and the first one the suggestion names is kept (the one in use, then the one the owner named, then a funnel step). Workspace admin.`,
987
+ description: `${APEX} — Take one suggestion from suggest_key_events, after the owner said yes: makes the key event, adds the events to the one they have, or merges the two. A merge deletes nothing; the key event merged away keeps counting for anything that names it. name calls it something else. events keeps only some of the suggested events; pass keep_rest_open: true to leave the other suggested events as an open question instead of saying no to them. For a merge, keep_key_event_id picks which key event keeps its name; leave it out and the first one the suggestion names is kept (the one in use, then the one the owner named, then a funnel step). Workspace admin.`,
806
988
  schema: z.object({
807
989
  suggestionId: z.string().min(1).describe("From suggest_key_events."),
808
990
  name: z.string().min(1).max(120).optional().describe("Call the key event something else."),
809
991
  events: z.array(z.string().min(1)).min(1).max(20).optional().describe("Keep only these of the suggested events."),
992
+ keepRestOpen: z.boolean().optional().describe("When passing events, set true to leave the rest as an open question instead of declining them."),
810
993
  keepKeyEventId: z.string().min(1).optional().describe("For a merge: the id of the key event that keeps its name. One of the ids the suggestion names."),
811
994
  }),
812
995
  handler: async (args) => {
@@ -814,6 +997,7 @@ export const measurementTools = {
814
997
  const res = await apiPost(`/api/key-events/suggestions/${encodeURIComponent(args.suggestionId)}/accept`, {
815
998
  ...(args.name ? { name: args.name } : {}),
816
999
  ...(args.events ? { events: args.events } : {}),
1000
+ ...(args.keepRestOpen !== undefined ? { keep_rest_open: args.keepRestOpen } : {}),
817
1001
  ...(args.keepKeyEventId ? { keep_key_event_id: args.keepKeyEventId } : {}),
818
1002
  });
819
1003
  const k = res.data?.keyEvent;
@@ -827,12 +1011,39 @@ export const measurementTools = {
827
1011
  },
828
1012
  },
829
1013
  dismiss_key_event_suggestion: {
830
- description: `${APEX} — Say no to one suggestion from suggest_key_events, after the owner said no. Apex will not suggest it again and learns from the answer. Workspace admin.`,
831
- schema: z.object({ suggestionId: z.string().min(1).describe("From suggest_key_events.") }),
1014
+ description: `${APEX} — Say no to one suggestion from suggest_key_events, after the owner said no. Apex will not suggest it again and learns from the answer. Pass events on an add-to-key-event suggestion to say no to only those events while leaving the rest as an open question. Workspace admin.`,
1015
+ schema: z.object({
1016
+ suggestionId: z.string().min(1).describe("From suggest_key_events."),
1017
+ events: z.array(z.string().min(1)).min(1).max(20).optional().describe("On an extend_key_event suggestion, decline only these events and leave the rest open."),
1018
+ }),
1019
+ handler: async ({ suggestionId, events }) => {
1020
+ try {
1021
+ await apiPost(`/api/key-events/suggestions/${encodeURIComponent(suggestionId)}/dismiss`, events ? { events } : {});
1022
+ return text(events
1023
+ ? `${APEX} Left out ${events.join(", ")}. The remaining events stay open.`
1024
+ : `${APEX} Dismissed. Apex won't suggest it again.`);
1025
+ }
1026
+ catch (err) {
1027
+ return text(`${APEX} ${errMsg(err)}`, true);
1028
+ }
1029
+ },
1030
+ },
1031
+ undo_key_event_suggestion: {
1032
+ description: `${APEX} — Take back an answer to a key event suggestion — accepted by the owner, set up automatically by Apex, or dismissed. Turns it back into an open question and stops Apex from setting it up automatically again. Refuses (409) if the key event it created is currently used by a journey, segment, active test, or ad platform send. Workspace admin.`,
1033
+ schema: z.object({
1034
+ suggestionId: z.string().min(1).describe("From suggest_key_events (including Set up by Apex or Previously declined)."),
1035
+ }),
832
1036
  handler: async ({ suggestionId }) => {
833
1037
  try {
834
- await apiPost(`/api/key-events/suggestions/${encodeURIComponent(suggestionId)}/dismiss`, {});
835
- return text(`${APEX} Dismissed. Apex won't suggest it again.`);
1038
+ const res = await apiPost(`/api/key-events/suggestions/${encodeURIComponent(suggestionId)}/undo`, {});
1039
+ const k = res.data?.keyEvent;
1040
+ if (!k) {
1041
+ return text(`${APEX} Undone. The key event was removed and the suggestion is back as an open question (Apex won't auto-set it up again).`);
1042
+ }
1043
+ return text([
1044
+ `${APEX} Undone. The suggestion is back as an open question. The key event now reads:`,
1045
+ keyEventLine(k, 0),
1046
+ ].join("\n"));
836
1047
  }
837
1048
  catch (err) {
838
1049
  return text(`${APEX} ${errMsg(err)}`, true);