@apex-inc/mcp-server 0.63.0 → 0.65.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.
@@ -23,16 +23,72 @@ const keyEventSourceSchema = z.object({
23
23
  where: z.array(keyEventConditionSchema).max(10).optional().describe("Conditions on the event's data, all must hold."),
24
24
  });
25
25
  const keyEventCategorySchema = z
26
- .enum(["purchase", "lead", "qualified_lead", "activation", "signup", "subscribe", "add_to_cart", "engagement", "other"])
26
+ .enum([
27
+ "purchase",
28
+ "lead",
29
+ "qualified_lead",
30
+ "activation",
31
+ "signup",
32
+ "subscribe",
33
+ "add_to_cart",
34
+ "engagement",
35
+ "expansion",
36
+ "referral",
37
+ "completion",
38
+ "retention",
39
+ "advocacy",
40
+ "churn",
41
+ "other",
42
+ ])
27
43
  .describe("What kind of step it is; sets its place in the funnel.");
28
44
  function keyEventLine(k, i) {
29
45
  const tags = [
30
- k.isCurrentGoal ? "main" : null,
46
+ k.isCurrentGoal ? "main goal" : null,
31
47
  k.entityScope === "account" ? "counts companies" : null,
32
48
  k.definitionVersion > 1 ? `v${k.definitionVersion}` : null,
33
49
  ].filter(Boolean);
34
50
  return ` ${i + 1}. ${k.name} [${k.id}]${tags.length ? ` (${tags.join(", ")})` : ""}: ${k.counts}`;
35
51
  }
52
+ const KEY_EVENT_USE_KIND = {
53
+ journey: "Adaptive Journey",
54
+ segment: "Segment",
55
+ test: "Test",
56
+ campaign: "Campaign",
57
+ target: "Target",
58
+ };
59
+ function keyEventUseLine(u) {
60
+ const kind = KEY_EVENT_USE_KIND[u.kind] ?? "Used by";
61
+ return ` • ${kind} "${u.name}" [${u.id}]${u.status ? ` (${u.status})` : ""}: ${u.role}. ${appUrl(u.href)}`;
62
+ }
63
+ function keyEventFindingLine(f) {
64
+ const sign = f.metricDelta > 0 ? "+" : "";
65
+ const version = f.keyEvent?.version ? ` on v${f.keyEvent.version}` : "";
66
+ return ` Finding ${f.evaluatedAt.slice(0, 10)}: test ${f.experimentId} ${f.classification}${version}, ${sign}${f.metricDelta}% (${f.statisticalSignificance}% sure)`;
67
+ }
68
+ /** How sure Apex is, in the same words the dashboard uses. */
69
+ function sureWords(confidence) {
70
+ if (confidence >= 0.95)
71
+ return "Apex is sure";
72
+ if (confidence >= 0.8)
73
+ return "Apex is fairly sure";
74
+ return "Apex thinks this is likely";
75
+ }
76
+ function keyEventSuggestionLines(s, nameOf) {
77
+ const named = (id) => `${nameOf.get(id) ?? id} [${id}]`;
78
+ const ids = s.keyEventIds ?? [];
79
+ const what = s.kind === "merge_key_events"
80
+ ? `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]}`;
86
+ return [
87
+ ` ${what}`,
88
+ ` suggestion_id ${s.id}. ${sureWords(s.confidence)} (${Math.round(s.confidence * 100)}%).`,
89
+ ...s.evidence.map((e) => ` • ${e.detail}`),
90
+ ];
91
+ }
36
92
  const NOT_LINKED = {
37
93
  missing_email: "no email",
38
94
  missing_api_key: "sent without an Apex key",
@@ -500,7 +556,7 @@ export const measurementTools = {
500
556
  },
501
557
  },
502
558
  get_key_event: {
503
- description: `${APEX} — One key event: the events that reach it and their conditions, every earlier version, and the ad platform conversions linked to it. Id from list_key_events.`,
559
+ description: `${APEX} — One key event: the events that reach it and their conditions, every earlier version, the ad platform conversions linked to it, and the finished tests that were judged on it (so results that counted the same outcome line up). Id from list_key_events.`,
504
560
  schema: z.object({ keyEventId: z.string().min(1).describe("From list_key_events.") }),
505
561
  handler: async ({ keyEventId }) => {
506
562
  try {
@@ -514,6 +570,15 @@ export const measurementTools = {
514
570
  }
515
571
  for (const l of res.data?.links ?? [])
516
572
  lines.push(` Linked: ${l.integration ?? "platform"} ${l.platformActionName ?? ""}`.trimEnd());
573
+ // Finished tests judged on it, so results that counted the same outcome line up.
574
+ try {
575
+ const findings = await apiGet(`/api/outcomes?key_event_id=${encodeURIComponent(keyEventId)}`);
576
+ for (const f of (Array.isArray(findings) ? findings : []).slice(0, 10))
577
+ lines.push(keyEventFindingLine(f));
578
+ }
579
+ catch {
580
+ /* the key event itself is the answer; findings are extra */
581
+ }
517
582
  return text(lines.join("\n"));
518
583
  }
519
584
  catch (err) {
@@ -550,7 +615,7 @@ export const measurementTools = {
550
615
  },
551
616
  },
552
617
  update_key_event: {
553
- 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 main one Attribution leads with. Workspace admin.`,
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.`,
554
619
  schema: z.object({
555
620
  keyEventId: z.string().min(1).describe("From list_key_events."),
556
621
  name: z.string().min(1).max(200).optional(),
@@ -558,7 +623,7 @@ export const measurementTools = {
558
623
  category: keyEventCategorySchema.optional(),
559
624
  entityScope: z.enum(["person", "account"]).optional(),
560
625
  description: z.string().max(1000).optional(),
561
- isCurrentGoal: z.literal(true).optional().describe("Make it the main key event."),
626
+ isCurrentGoal: z.literal(true).optional().describe("Make it the workspace's main goal, in place of the one before."),
562
627
  }),
563
628
  handler: async (args) => {
564
629
  try {
@@ -579,7 +644,7 @@ export const measurementTools = {
579
644
  },
580
645
  },
581
646
  delete_key_event: {
582
- description: `${APEX} — Delete a key event. Campaign steps, ad platform sends and tests that use it stop counting it. Prefer update_key_event when the meaning changed. Workspace admin.`,
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.`,
583
648
  schema: z.object({ keyEventId: z.string().min(1).describe("From list_key_events.") }),
584
649
  handler: async ({ keyEventId }) => {
585
650
  try {
@@ -630,6 +695,88 @@ export const measurementTools = {
630
695
  }
631
696
  },
632
697
  },
698
+ 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.`,
700
+ schema: z.object({ keyEventId: z.string().min(1).describe("From list_key_events.") }),
701
+ handler: async ({ keyEventId }) => {
702
+ try {
703
+ const res = await apiGet(`/api/key-events/${encodeURIComponent(keyEventId)}/usage`);
704
+ const usage = res.data?.usage ?? [];
705
+ if (usage.length === 0)
706
+ return text(`${APEX} Nothing uses ${keyEventId} yet. No journey, segment, test, campaign or target names it.`);
707
+ const lines = [`${APEX} Used in ${usage.length} place${usage.length === 1 ? "" : "s"}`, ...usage.map(keyEventUseLine)];
708
+ return text(lines.join("\n"));
709
+ }
710
+ catch (err) {
711
+ return text(`${APEX} ${errMsg(err)}`, true);
712
+ }
713
+ },
714
+ },
715
+ suggest_key_events: {
716
+ 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
+ schema: z.object({}),
718
+ handler: async () => {
719
+ try {
720
+ const res = await apiGet("/api/key-events/suggestions");
721
+ const d = res.data;
722
+ if (!d)
723
+ return text(`${APEX} Couldn't read the suggestions.`, true);
724
+ const nameOf = new Map(d.keyEvents.map((k) => [k.id, k.name]));
725
+ if (d.suggestions.length === 0) {
726
+ const uncounted = d.events.filter((e) => e.keyEventIds.length === 0).length;
727
+ return text(d.events.length === 0
728
+ ? `${APEX} No suggestions. Apex hasn't heard an event from this workspace yet.`
729
+ : `${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.`);
730
+ }
731
+ const lines = [`${APEX} ${d.suggestions.length} suggestion${d.suggestions.length === 1 ? "" : "s"}`, `${"═".repeat(40)}`];
732
+ for (const s of d.suggestions)
733
+ lines.push(...keyEventSuggestionLines(s, nameOf), "");
734
+ lines.push(`Review them on ${appUrl("/dashboard/key-events")}.`);
735
+ return text(lines.join("\n"));
736
+ }
737
+ catch (err) {
738
+ return text(`${APEX} ${errMsg(err)}`, true);
739
+ }
740
+ },
741
+ },
742
+ accept_key_event_suggestion: {
743
+ 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.`,
744
+ schema: z.object({
745
+ suggestionId: z.string().min(1).describe("From suggest_key_events."),
746
+ name: z.string().min(1).max(120).optional().describe("Call the key event something else."),
747
+ events: z.array(z.string().min(1)).min(1).max(20).optional().describe("Keep only these of the suggested events."),
748
+ 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."),
749
+ }),
750
+ handler: async (args) => {
751
+ try {
752
+ const res = await apiPost(`/api/key-events/suggestions/${encodeURIComponent(args.suggestionId)}/accept`, {
753
+ ...(args.name ? { name: args.name } : {}),
754
+ ...(args.events ? { events: args.events } : {}),
755
+ ...(args.keepKeyEventId ? { keep_key_event_id: args.keepKeyEventId } : {}),
756
+ });
757
+ const k = res.data?.keyEvent;
758
+ if (!k)
759
+ return text(`${APEX} Accepted.`);
760
+ return text([`${APEX} Accepted. The key event now reads:`, keyEventLine(k, 0)].join("\n"));
761
+ }
762
+ catch (err) {
763
+ return text(`${APEX} ${errMsg(err)}`, true);
764
+ }
765
+ },
766
+ },
767
+ dismiss_key_event_suggestion: {
768
+ 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.`,
769
+ schema: z.object({ suggestionId: z.string().min(1).describe("From suggest_key_events.") }),
770
+ handler: async ({ suggestionId }) => {
771
+ try {
772
+ await apiPost(`/api/key-events/suggestions/${encodeURIComponent(suggestionId)}/dismiss`, {});
773
+ return text(`${APEX} Dismissed. Apex won't suggest it again.`);
774
+ }
775
+ catch (err) {
776
+ return text(`${APEX} ${errMsg(err)}`, true);
777
+ }
778
+ },
779
+ },
633
780
  list_next_moves: {
634
781
  description: `${APEX} — "What should I do next?" The ranked moves Apex shows on Attribution and the home page, from one engine: broken tracking to fix, spend that isn't paying, efforts worth scaling, and insight checks. Scope it to one effort with grain + ref (an ad's moves also show on its channel). If a source or check couldn't be read the reply says so, so a short list never means nothing to do.`,
635
782
  schema: z.object({
@@ -1367,7 +1514,7 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1367
1514
  },
1368
1515
  },
1369
1516
  define_event: {
1370
- description: `${APEX} — Define a governed custom event in the workspace's Schema (the customer-extensible registry). Promotes one of the merchant's own events to a first-class, typed, versioned definition that behaves like a canonical Apex Spec event (selectable as a journey trigger/goal, resolvable as comm tokens, validated at ingest). Names must be snake_case and CANNOT shadow a canonical Apex Spec event — call get_event_spec first and reuse the canonical event when one fits. Propose the schema from the merchant's observed payloads (get_schema) and codebase, then confirm with them before defining.`,
1517
+ description: `${APEX} — Define a governed custom event in the workspace's Schema (the customer-extensible registry). Promotes one of the merchant's own events to a first-class, typed, versioned definition that behaves like a canonical Apex Spec event (selectable as a journey trigger/goal, resolvable as comm tokens, validated at ingest). Name it the way Apex Spec events are named: the thing, then a past-tense verb (report_exported, never export_report). Names must be snake_case and CANNOT shadow a canonical Apex Spec event — call get_event_spec first and reuse the canonical event when one fits. Propose the schema from the merchant's observed payloads (get_schema) and codebase, then confirm with them before defining.`,
1371
1518
  schema: z.object({
1372
1519
  name: z.string().describe("snake_case event name, not already in the Apex Spec"),
1373
1520
  description: z.string().describe("One sentence: when this event fires"),
@@ -1799,7 +1946,7 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1799
1946
  },
1800
1947
  },
1801
1948
  list_conversions: {
1802
- description: `${APEX} — List the workspace's Conversions (owned-event definitions of valued actions, e.g. "Purchase", "Signup"). Call this when the user asks what conversions are defined. The starred primary is the current goal Attribution leads with; it does not pick the funnel stages and it is not the experiment default. Experiments name their own metric; the funnel follows the workspace conversion model.`,
1949
+ description: `${APEX} — List the workspace's Conversions (owned-event definitions of valued actions, e.g. "Purchase", "Signup"). Call this when the user asks what conversions are defined. The one marked primary is the workspace's main goal (the dashboard calls it Main goal), the one Attribution leads with; it does not pick the funnel stages and it is not the experiment default. Experiments name their own metric; the funnel follows the workspace conversion model.`,
1803
1950
  schema: z.object({}),
1804
1951
  handler: async () => {
1805
1952
  const conversions = await apiGet("/api/conversion-goals");
@@ -1878,7 +2025,7 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1878
2025
  },
1879
2026
  },
1880
2027
  set_primary_conversion: {
1881
- description: `${APEX} — Make a Conversion the workspace's current goal (the starred primary). Attribution, get_efforts and next moves lead with it, and it replaces any goal picked before. It does not set experiment defaults or the funnel stages; experiments name their own metric. Pass the conversion id from list_conversions.`,
2028
+ description: `${APEX} — Make a Conversion the workspace's main goal (the dashboard calls it Main goal; it was the primary conversion before). Same as update_key_event with is_current_goal true. Attribution, get_efforts and next moves lead with it, and it replaces any goal picked before. It does not set experiment defaults or the funnel stages; experiments name their own metric. Pass the conversion id from list_conversions.`,
1882
2029
  schema: z.object({
1883
2030
  conversionId: z.string().describe("The conversion id to promote (from list_conversions)."),
1884
2031
  }),