@apex-inc/mcp-server 0.65.0 → 0.66.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.
@@ -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
  }
@@ -43,11 +43,13 @@ const keyEventCategorySchema = z
43
43
  .describe("What kind of step it is; sets its place in the funnel.");
44
44
  function keyEventLine(k, i) {
45
45
  const tags = [
46
- k.isCurrentGoal ? "main goal" : null,
46
+ k.archivedAt ? `archived ${k.archivedAt.slice(0, 10)}` : null,
47
+ k.isCurrentGoal && !k.archivedAt ? "main goal" : null,
47
48
  k.entityScope === "account" ? "counts companies" : null,
48
49
  k.definitionVersion > 1 ? `v${k.definitionVersion}` : null,
49
50
  ].filter(Boolean);
50
- return ` ${i + 1}. ${k.name} [${k.id}]${tags.length ? ` (${tags.join(", ")})` : ""}: ${k.counts}`;
51
+ const head = ` ${i + 1}. ${k.name} [${k.id}]${tags.length ? ` (${tags.join(", ")})` : ""}: ${k.counts}`;
52
+ return k.nameWarning ? `${head}\n ⚠ ${k.nameWarning}` : head;
51
53
  }
52
54
  const KEY_EVENT_USE_KIND = {
53
55
  journey: "Adaptive Journey",
@@ -78,11 +80,13 @@ function keyEventSuggestionLines(s, nameOf) {
78
80
  const ids = s.keyEventIds ?? [];
79
81
  const what = s.kind === "merge_key_events"
80
82
  ? `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]}`;
83
+ : s.kind === "restore_key_event"
84
+ ? `Bring back archived key event "${s.name}"${ids[0] ? ` [${ids[0]}]` : ""}: ${s.events.join(", ")} arrived again`
85
+ : s.kind === "extend_key_event"
86
+ ? `Add ${s.events.join(", ")} to ${ids[0] ? named(ids[0]) : s.name}`
87
+ : s.events.length > 1
88
+ ? `Make "${s.name}" a key event, reached by ${s.events.join(", ")}`
89
+ : `Make "${s.name}" a key event, reached by ${s.events[0]}`;
86
90
  return [
87
91
  ` ${what}`,
88
92
  ` suggestion_id ${s.id}. ${sureWords(s.confidence)} (${Math.round(s.confidence * 100)}%).`,
@@ -283,7 +287,8 @@ export const measurementTools = {
283
287
  const q = days && days !== "all" ? `?days=${days}` : "?days=all";
284
288
  const res = await apiGet(`/api/growth/reality${q}`);
285
289
  const goals = res.data?.goals ?? [];
286
- if (goals.length === 0) {
290
+ const unmeasured = res.data?.unmeasuredKeyEvents ?? [];
291
+ if (goals.length === 0 && unmeasured.length === 0) {
287
292
  return {
288
293
  content: [
289
294
  {
@@ -295,8 +300,14 @@ export const measurementTools = {
295
300
  }
296
301
  const pctFmt = (v) => v == null ? "—" : `${v > 0 ? "+" : ""}${(v * 100).toFixed(1)}%`;
297
302
  const lines = goals.map((g) => {
303
+ const totalConversions = (g.counts?.exposedConversions ?? 0) + (g.counts?.holdoutConversions ?? 0);
304
+ if (totalConversions === 0) {
305
+ const evLabel = g.eventName ? `${g.eventName} ` : "";
306
+ const totalSubjects = (g.counts?.exposedSubjects ?? 0) + (g.counts?.holdoutSubjects ?? 0);
307
+ 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)`;
308
+ }
298
309
  if (!g.isDecisive) {
299
- return ` • ${g.goalName}: COLLECTING (directional ${pctFmt(g.lift)}, since ${g.collectingSince || "—"})`;
310
+ return ` • ${g.goalName}: COLLECTING (directional ${pctFmt(g.lift)}, ${totalConversions.toLocaleString()} conversions since ${g.collectingSince || "—"})`;
300
311
  }
301
312
  const ci = g.liftCI
302
313
  ? ` [${pctFmt(g.liftCI.lower)}, ${pctFmt(g.liftCI.upper)}]`
@@ -306,6 +317,12 @@ export const measurementTools = {
306
317
  : "";
307
318
  return ` • ${g.goalName}: ${pctFmt(g.lift)} vs holdout${ci} — DECISIVE${rev}`;
308
319
  });
320
+ if (unmeasured.length > 0) {
321
+ for (const u of unmeasured) {
322
+ const evLabel = u.eventName ? ` (${u.eventName})` : "";
323
+ lines.push(` • ${u.name}${evLabel}: NO EVENTS YET (no holdout-tracked traffic since this key event was added — forward-only)`);
324
+ }
325
+ }
309
326
  return {
310
327
  content: [
311
328
  {
@@ -536,17 +553,20 @@ export const measurementTools = {
536
553
  },
537
554
  },
538
555
  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");
556
+ 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.`,
557
+ schema: z.object({
558
+ includeArchived: z.boolean().optional().describe("Include archived key events too (default false)."),
559
+ }),
560
+ handler: async (args = {}) => {
561
+ const q = args.includeArchived ? "?include_archived=1" : "";
562
+ const res = await apiGet(`/api/key-events${q}`);
543
563
  const keyEvents = res.data?.keyEvents ?? [];
544
564
  if (keyEvents.length === 0) {
545
565
  return {
546
566
  content: [
547
567
  {
548
568
  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")}.`,
569
+ 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
570
  },
551
571
  ],
552
572
  };
@@ -595,6 +615,7 @@ export const measurementTools = {
595
615
  entityScope: z.enum(["person", "account"]).optional().describe("person (default) or account (a company reaches it when its first person does)."),
596
616
  description: z.string().max(1000).optional(),
597
617
  template: z.string().max(100).optional().describe("The template it follows, e.g. lead_captured."),
618
+ position: z.number().int().min(0).max(999).optional().describe("Optional explicit funnel rank (0 = earliest step). Omit to use automatic funnel order."),
598
619
  }),
599
620
  handler: async (args) => {
600
621
  try {
@@ -605,6 +626,7 @@ export const measurementTools = {
605
626
  ...(args.entityScope ? { entity_scope: args.entityScope } : {}),
606
627
  ...(args.description ? { description: args.description } : {}),
607
628
  ...(args.template ? { template: args.template } : {}),
629
+ ...(typeof args.position === "number" ? { position: args.position } : {}),
608
630
  });
609
631
  const k = res.data?.keyEvent;
610
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.`);
@@ -615,7 +637,7 @@ export const measurementTools = {
615
637
  },
616
638
  },
617
639
  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.`,
640
+ 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
641
  schema: z.object({
620
642
  keyEventId: z.string().min(1).describe("From list_key_events."),
621
643
  name: z.string().min(1).max(200).optional(),
@@ -623,6 +645,7 @@ export const measurementTools = {
623
645
  category: keyEventCategorySchema.optional(),
624
646
  entityScope: z.enum(["person", "account"]).optional(),
625
647
  description: z.string().max(1000).optional(),
648
+ position: z.number().int().min(0).max(999).nullable().optional().describe("Explicit funnel rank (0 = earliest), or null to reset to automatic order."),
626
649
  isCurrentGoal: z.literal(true).optional().describe("Make it the workspace's main goal, in place of the one before."),
627
650
  }),
628
651
  handler: async (args) => {
@@ -633,6 +656,7 @@ export const measurementTools = {
633
656
  ...(args.category ? { category: args.category } : {}),
634
657
  ...(args.entityScope ? { entity_scope: args.entityScope } : {}),
635
658
  ...(args.description !== undefined ? { description: args.description } : {}),
659
+ ...(args.position !== undefined ? { position: args.position } : {}),
636
660
  ...(args.isCurrentGoal ? { is_current_goal: true } : {}),
637
661
  });
638
662
  const k = res.data?.keyEvent;
@@ -643,13 +667,51 @@ export const measurementTools = {
643
667
  }
644
668
  },
645
669
  },
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.`,
670
+ reorder_key_events: {
671
+ 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.`,
672
+ schema: z.object({
673
+ keyEventIds: z.array(z.string().min(1)).min(1).max(200).describe("Active key event IDs in funnel order, earliest step first."),
674
+ }),
675
+ handler: async ({ keyEventIds }) => {
676
+ try {
677
+ const res = await apiPost("/api/key-events/reorder", {
678
+ key_event_ids: keyEventIds,
679
+ });
680
+ const keyEvents = res.data?.keyEvents ?? [];
681
+ const lines = [`${APEX} Updated key event funnel order`, `${"═".repeat(40)}`, ...keyEvents.map(keyEventLine)];
682
+ return text(lines.join("\n"));
683
+ }
684
+ catch (err) {
685
+ return text(`${APEX} ${errMsg(err)}`, true);
686
+ }
687
+ },
688
+ },
689
+ archive_key_event: {
690
+ 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
691
  schema: z.object({ keyEventId: z.string().min(1).describe("From list_key_events.") }),
649
692
  handler: async ({ keyEventId }) => {
650
693
  try {
651
- await apiDelete(`/api/key-events/${encodeURIComponent(keyEventId)}`);
652
- return text(`${APEX} Deleted ${keyEventId}.`);
694
+ const res = await apiPost(`/api/key-events/${encodeURIComponent(keyEventId)}/archive`, {});
695
+ const k = res.data?.keyEvent;
696
+ return text(k
697
+ ? `${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.`
698
+ : `${APEX} Archived ${keyEventId}. Bring it back anytime with restore_key_event.`);
699
+ }
700
+ catch (err) {
701
+ return text(`${APEX} ${errMsg(err)}`, true);
702
+ }
703
+ },
704
+ },
705
+ restore_key_event: {
706
+ 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.`,
707
+ schema: z.object({ keyEventId: z.string().min(1).describe("From list_key_events with include_archived: true.") }),
708
+ handler: async ({ keyEventId }) => {
709
+ try {
710
+ const res = await apiPost(`/api/key-events/${encodeURIComponent(keyEventId)}/restore`, {});
711
+ const k = res.data?.keyEvent;
712
+ return text(k
713
+ ? `${APEX} Brought back:\n${keyEventLine(k, 0)}\nApex is now checking history for events heard while it was archived.`
714
+ : `${APEX} Brought ${keyEventId} back.`);
653
715
  }
654
716
  catch (err) {
655
717
  return text(`${APEX} ${errMsg(err)}`, true);
@@ -696,7 +758,7 @@ export const measurementTools = {
696
758
  },
697
759
  },
698
760
  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.`,
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.`,
700
762
  schema: z.object({ keyEventId: z.string().min(1).describe("From list_key_events.") }),
701
763
  handler: async ({ keyEventId }) => {
702
764
  try {
@@ -1656,7 +1718,10 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1656
1718
  .describe("Include archived sources. Defaults to false."),
1657
1719
  }),
1658
1720
  handler: async ({ includeArchived }) => {
1659
- const proj = getActiveWorkspace();
1721
+ const proj = await resolveActiveWorkspace();
1722
+ if (!proj) {
1723
+ return text("No active workspace. Use switch_workspace first (or set APEX_WORKSPACE_KEY).", true);
1724
+ }
1660
1725
  const qs = includeArchived ? "?includeArchived=true" : "";
1661
1726
  const json = await apiGet(`/api/workspaces/${proj}/data-sources${qs}`);
1662
1727
  const sources = json.data ?? [];
@@ -1676,7 +1741,10 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1676
1741
  name: z.string().describe("Display name, e.g. 'Marketing site' or 'Backend API'."),
1677
1742
  }),
1678
1743
  handler: async ({ kind, name }) => {
1679
- const proj = getActiveWorkspace();
1744
+ const proj = await resolveActiveWorkspace();
1745
+ if (!proj) {
1746
+ return text("No active workspace. Use switch_workspace first (or set APEX_WORKSPACE_KEY).", true);
1747
+ }
1680
1748
  const json = await apiPost(`/api/workspaces/${proj}/data-sources`, { kind, name });
1681
1749
  const s = json.data;
1682
1750
  return { content: [{ type: "text", text: `✓ Created data source **${s.name}** (${s.kind}) — ${s.status} · \`${s.id}\`` }] };
@@ -1688,7 +1756,10 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1688
1756
  id: z.string().describe("The data source id (ds_...)."),
1689
1757
  }),
1690
1758
  handler: async ({ id }) => {
1691
- const proj = getActiveWorkspace();
1759
+ const proj = await resolveActiveWorkspace();
1760
+ if (!proj) {
1761
+ return text("No active workspace. Use switch_workspace first (or set APEX_WORKSPACE_KEY).", true);
1762
+ }
1692
1763
  const json = await apiGet(`/api/workspaces/${proj}/data-sources/${encodeURIComponent(id)}/health`);
1693
1764
  const h = json.data;
1694
1765
  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 +1825,7 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1754
1825
  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
1826
  schema: z.object({}),
1756
1827
  handler: async () => {
1757
- const workspaceKey = getActiveWorkspace();
1828
+ const workspaceKey = await resolveActiveWorkspace();
1758
1829
  if (!workspaceKey) {
1759
1830
  return {
1760
1831
  content: [{ type: "text", text: "No active workspace. Use switch_workspace first (or set APEX_WORKSPACE_KEY)." }],
@@ -1768,9 +1839,16 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1768
1839
  const sourceLines = d.sources.map((s) => `- ${s.name} (${s.kind}): ${s.status}${s.lastSeenAt ? ` — last event ${s.lastSeenAt}` : ""}`);
1769
1840
  const readyTemplates = d.templates.filter((t) => t.ready);
1770
1841
  const blockedTemplates = d.templates.filter((t) => !t.ready);
1842
+ // Always list every journey template (so setup-referenced templates like
1843
+ // `mobile-install-nudge` are never pushed off by communication templates),
1844
+ // while capping non-journey blocked templates at 10.
1845
+ const blockedJourneys = blockedTemplates.filter((t) => t.templateKind === "journey");
1846
+ const blockedOther = blockedTemplates
1847
+ .filter((t) => t.templateKind !== "journey")
1848
+ .slice(0, 10);
1771
1849
  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(", ") || "?"}`),
1850
+ ...readyTemplates.map((t) => `- ✅ ${t.title} (${t.templateKind}, id: ${t.templateId}) — Ready to run${t.templateKind === "journey" ? ` → create_journey_from_template({ template_id: "${t.templateId}" })` : ""}`),
1851
+ ...[...blockedJourneys, ...blockedOther].map((t) => `- ⏳ ${t.title} (${t.templateKind}, id: ${t.templateId}) — needs ${[...t.missingEvents, ...t.missingTraits].join(", ") || "?"}`),
1774
1852
  ];
1775
1853
  const milestones = [
1776
1854
  d.milestones.firstEventAt ? `First event: ${d.milestones.firstEventAt}` : "First event: not yet",
@@ -1814,10 +1892,14 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1814
1892
  }))
1815
1893
  .min(1)
1816
1894
  .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."),
1895
+ summary: z
1896
+ .string()
1897
+ .max(500)
1898
+ .optional()
1899
+ .describe("One-paragraph scan summary for the merchant (max 500 characters) — include what you're deliberately NOT wiring and why."),
1818
1900
  }),
1819
1901
  handler: async (args) => {
1820
- const workspaceKey = getActiveWorkspace();
1902
+ const workspaceKey = await resolveActiveWorkspace();
1821
1903
  if (!workspaceKey) {
1822
1904
  return {
1823
1905
  content: [{ type: "text", text: "No active workspace. Use switch_workspace first (or set APEX_WORKSPACE_KEY)." }],
@@ -1849,7 +1931,7 @@ Events fired through this tool carry a stable synthetic visitorId (mcp-agent-*,
1849
1931
  visitorId: z.string().optional().describe("Visitor id (default a test id)"),
1850
1932
  }),
1851
1933
  handler: async (args) => {
1852
- const workspaceKey = getActiveWorkspace();
1934
+ const workspaceKey = await resolveActiveWorkspace();
1853
1935
  if (!workspaceKey) {
1854
1936
  return { content: [{ type: "text", text: "No active workspace. Run /apex-login or set APEX_WORKSPACE_KEY." }] };
1855
1937
  }