@apex-inc/mcp-server 0.60.1 → 0.61.1

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.
@@ -9,6 +9,32 @@ import { composeLetterDocument, letterBlocksFromDocument, letterBlockSchema } fr
9
9
  import { previewImages } from "../preview-images.js";
10
10
  import { commExperimentCreateBody, commExperimentVariantSchema, } from "../comm-experiment-create.js";
11
11
  import { APEX, errMsg, appUrl, journeyLink, tenantOk, tenantMismatch, } from "../tool-shared.js";
12
+ const QUIET_CAUSE = {
13
+ rules: "its rules changed",
14
+ import: "an import added them",
15
+ records: "a key event changed or late data arrived",
16
+ };
17
+ /** The people changes added without starting the journey, in one line. */
18
+ function joinedQuietlyLine(c) {
19
+ const q = c?.joinedQuietly;
20
+ const n = q ? (q.wouldStart ?? q.added) : 0;
21
+ if (!c || !q || n === 0)
22
+ return `Nobody joined ${c?.segmentName ?? "the segment"} through a change without starting.`;
23
+ const why = q.causes.map((x) => QUIET_CAUSE[x] ?? x).join(" or ");
24
+ return `${n.toLocaleString("en-US")} ${n === 1 ? "person" : "people"} joined ${c.segmentName} since ${q.since.slice(0, 10)} because ${why}, and this journey didn't start for them.`;
25
+ }
26
+ function everyoneInSegmentLine(c) {
27
+ if (!c)
28
+ return "Couldn't count the people in this segment.";
29
+ const people = (n) => `${n.toLocaleString("en-US")} ${n === 1 ? "person" : "people"}`;
30
+ if (c.inSegment === 0)
31
+ return `Nobody is in ${c.segmentName} yet.`;
32
+ if (c.wouldStart === null) {
33
+ return `${c.capped ? "At least " : ""}${people(c.inSegment)} in ${c.segmentName}; anyone this journey already ran for is skipped.`;
34
+ }
35
+ const been = c.alreadyBeenIn ? ` ${people(c.alreadyBeenIn)} already went through it in the last 90 days and won't start again.` : "";
36
+ return `${c.capped ? "At least " : ""}${people(c.wouldStart)} in ${c.segmentName} would start.${been}`;
37
+ }
12
38
  export const letterTools = {
13
39
  recommend_communications: {
14
40
  description: "Get recommended lifecycle communications for your vertical and conversion model. Returns a prioritized list of emails and push notifications to set up.",
@@ -903,14 +929,25 @@ export const letterTools = {
903
929
  },
904
930
  },
905
931
  set_journey_trigger: {
906
- description: `${APEX} — Set the entry trigger (the event that enrolls subjects) on a draft journey's trigger step. Pass event_name (the Apex Spec event, e.g. user_signed_up). A trig-* contract id is storage-only — prefer the Spec name.`,
932
+ description: `${APEX} — Set the entry trigger (what enrolls subjects) on a draft journey's trigger step. Pass event_name (the Apex Spec event, e.g. user_signed_up), or key_event_id (from list_key_events) to start it when someone reaches one of the workspace's key events: every event that reaches it counts, from now on, and people Apex finds in their history never start it. A trig-* contract id is storage-only — prefer the Spec name.`,
907
933
  schema: z.object({
908
934
  journeyId: z.string(),
909
935
  eventName: z.string().optional().describe("Apex Spec event name that enrolls subjects (e.g. user_signed_up). Preferred."),
936
+ keyEventId: z.string().optional().describe("Key event id from list_key_events: start when someone reaches it."),
910
937
  triggerContractId: z.string().optional().describe("Storage id from list_trigger_contracts. Prefer event_name."),
911
938
  }),
912
- handler: async ({ journeyId, eventName, triggerContractId, }) => {
939
+ handler: async ({ journeyId, eventName, keyEventId, triggerContractId, }) => {
913
940
  try {
941
+ if (keyEventId) {
942
+ const j = await apiGet(`/api/journeys/${encodeURIComponent(journeyId)}`);
943
+ const steps = (j.steps ?? []).map((s) => s.type === "trigger" ? { ...s, trigger: { type: "audience_entry", audienceId: "", keyEventId } } : s);
944
+ const updated = await apiPatch(`/api/journeys/${encodeURIComponent(journeyId)}`, { steps });
945
+ if (!tenantOk(updated.workspaceKey))
946
+ return tenantMismatch();
947
+ return {
948
+ content: [{ type: "text", text: `${APEX} Journey ${journeyId} now starts when someone reaches key event ${keyEventId}, from when it is published. View it: ${journeyLink(journeyId)}` }],
949
+ };
950
+ }
914
951
  const cdata = await apiGet("/api/journeys/trigger-contracts");
915
952
  const contracts = cdata.contracts ?? [];
916
953
  let resolvedId = triggerContractId;
@@ -1057,12 +1094,22 @@ export const letterTools = {
1057
1094
  },
1058
1095
  },
1059
1096
  add_journey_branch: {
1060
- description: `${APEX} — Insert a CONDITIONAL content branch: evaluate one condition and send a different communication to each side, then both continue where the flow went before. Goes after the step that leads into the exit unless after_step_id says otherwise. Use this for true content branching (e.g. "cart value > $100 → VIP email, else standard email", or "clicked the welcome letter → next-step letter, else a reminder"). For the simpler "skip the next send if they already converted" case, use add_journey_exit instead. The condition is an attribute test (field_path + operator + value), an event test (event_fired / event_not_fired within a window), or how they responded to the letter the journey just sent (letter_opened / letter_clicked): the journey waits up to wait_days for the open or click, then takes the other side. A letter branch has to come right after that send. Prefer letter_clicked; opens are inflated by mail apps that preload images.`,
1097
+ description: `${APEX} — Insert a CONDITIONAL content branch: evaluate one condition and send a different communication to each side, then both continue where the flow went before. Goes after the step that leads into the exit unless after_step_id says otherwise. Use this for true content branching (e.g. "cart value > $100 → VIP email, else standard email", or "clicked the welcome letter → next-step letter, else a reminder"). For the simpler "skip the next send if they already converted" case, use add_journey_exit instead. The condition is an attribute test (field_path + operator + value), an event test (event_fired / event_not_fired within a window), a key event test (key_event_reached / key_event_not_reached + key_event_id from list_key_events; window_days bounds the first time; scope "account" asks about their company), or how they responded to the letter the journey just sent (letter_opened / letter_clicked): the journey waits up to wait_days for the open or click, then takes the other side. A letter branch has to come right after that send. Prefer letter_clicked; opens are inflated by mail apps that preload images.`,
1061
1098
  schema: z.object({
1062
1099
  journeyId: z.string(),
1063
1100
  afterStepId: z.string().optional().describe("Step the branch goes after (default: the step that leads into the exit). For letter_opened / letter_clicked this must be the send step."),
1064
1101
  condition: z.object({
1065
- kind: z.enum(["attribute", "event_fired", "event_not_fired", "letter_opened", "letter_clicked"]),
1102
+ kind: z.enum([
1103
+ "attribute",
1104
+ "event_fired",
1105
+ "event_not_fired",
1106
+ "key_event_reached",
1107
+ "key_event_not_reached",
1108
+ "letter_opened",
1109
+ "letter_clicked",
1110
+ ]),
1111
+ key_event_id: z.string().optional().describe("key event only: the id from list_key_events."),
1112
+ scope: z.enum(["person", "account"]).optional().describe("key event only: account = their company reached it."),
1066
1113
  field_path: z.string().optional().describe("attribute only: dotted path, e.g. 'cart.valueCents' or 'plan'."),
1067
1114
  operator: z
1068
1115
  .enum(["equals", "not_equals", "greater_than", "less_than", "in", "exists", "not_exists"])
@@ -1073,7 +1120,7 @@ export const letterTools = {
1073
1120
  .optional()
1074
1121
  .describe("attribute only: the comparison value (omit for exists/not_exists)."),
1075
1122
  event_name: z.string().optional().describe("event only: the canonical event, e.g. 'purchase'."),
1076
- window_days: z.number().optional().describe("event only: look-back window in days (omit = ever)."),
1123
+ window_days: z.number().optional().describe("event and key event only: look-back window in days (omit = ever)."),
1077
1124
  wait_days: z.number().optional().describe("letter_opened / letter_clicked only: days to wait for the open or click before taking the other side (1-30, default 3)."),
1078
1125
  }),
1079
1126
  whenTrueCommId: z.string().describe("Communication to send when the condition matches."),
@@ -1106,6 +1153,17 @@ export const letterTools = {
1106
1153
  else if (c.kind === "letter_opened" || c.kind === "letter_clicked") {
1107
1154
  condition = { kind: c.kind, ...(c.wait_days !== undefined ? { waitDays: c.wait_days } : {}) };
1108
1155
  }
1156
+ else if (c.kind === "key_event_reached" || c.kind === "key_event_not_reached") {
1157
+ if (!c.key_event_id) {
1158
+ return { content: [{ type: "text", text: `${APEX} A key event condition needs key_event_id. list_key_events has them.` }], isError: true };
1159
+ }
1160
+ condition = {
1161
+ kind: c.kind,
1162
+ keyEventId: c.key_event_id,
1163
+ ...(c.window_days ? { windowDays: c.window_days } : {}),
1164
+ ...(c.scope ? { scope: c.scope } : {}),
1165
+ };
1166
+ }
1109
1167
  else {
1110
1168
  if (!c.event_name) {
1111
1169
  return { content: [{ type: "text", text: `${APEX} An event condition needs event_name.` }], isError: true };
@@ -1136,7 +1194,7 @@ export const letterTools = {
1136
1194
  },
1137
1195
  },
1138
1196
  publish_journey: {
1139
- description: `${APEX} — Publish a draft journey so it runs on live trigger events. SAFETY: defaults to a dry-run (validation only) — pass confirmLive:true to actually publish to real customers. Email sends require a verified sender domain or publish is blocked. If this path is already live or a test is measuring it, stop and ask. Do not pass confirmTreatmentChange unless they picked an out.`,
1197
+ description: `${APEX} — Publish a draft journey so it runs on live trigger events. SAFETY: defaults to a dry-run (validation only) — pass confirmLive:true to actually publish to real customers. Email sends require a verified sender domain or publish is blocked. A journey that starts when someone joins a segment starts only people who join from now on; pass who_starts:"everyone_already_in" only when the owner asked for the people already in the segment too (ask them, and say how many: start_people_already_in_segment without confirm counts them). If this path is already live or a test is measuring it, stop and ask. Do not pass confirmTreatmentChange unless they picked an out.`,
1140
1198
  schema: z.object({
1141
1199
  journeyId: z.string(),
1142
1200
  confirmLive: z.boolean().optional().describe("Set true to publish for real. Omitted/false = dry-run validation only."),
@@ -1144,8 +1202,12 @@ export const letterTools = {
1144
1202
  .boolean()
1145
1203
  .optional()
1146
1204
  .describe("Publish anyway when this path is live or a test is measuring it. Only pass true after they picked an out."),
1205
+ whoStarts: z
1206
+ .enum(["from_now_on", "everyone_already_in"])
1207
+ .optional()
1208
+ .describe("For a journey that starts when someone joins a segment. from_now_on (default): only people who join after publish. everyone_already_in: the people already in the segment start too, once."),
1147
1209
  }),
1148
- handler: async ({ journeyId, confirmLive, confirmTreatmentChange, }) => {
1210
+ handler: async ({ journeyId, confirmLive, confirmTreatmentChange, whoStarts, }) => {
1149
1211
  const path = `/api/journeys/${encodeURIComponent(journeyId)}/publish`;
1150
1212
  // Non-blocking coverage warnings ("we couldn't verify these until the
1151
1213
  // journey fires") — surfaced so an agent can preview before publishing.
@@ -1180,7 +1242,57 @@ export const letterTools = {
1180
1242
  const res = await apiPost(path, {});
1181
1243
  if (!tenantOk(res.workspaceKey))
1182
1244
  return tenantMismatch();
1183
- return { content: [{ type: "text", text: `${APEX} Published journey ${journeyId} — it is now live on trigger events.${warnText(res?.warnings)} View it: ${journeyLink(journeyId)}` }] };
1245
+ let everyone = "";
1246
+ if (whoStarts === "everyone_already_in") {
1247
+ try {
1248
+ const started = await apiPost(`/api/journeys/${encodeURIComponent(journeyId)}/everyone-in-segment`, {});
1249
+ everyone = `\n${everyoneInSegmentLine(started.data)} They start within a minute.`;
1250
+ }
1251
+ catch (err) {
1252
+ everyone = `\nThe people already in the segment did not start: ${errMsg(err)} Retry with start_people_already_in_segment.`;
1253
+ }
1254
+ }
1255
+ return { content: [{ type: "text", text: `${APEX} Published journey ${journeyId} — it is now live on trigger events.${everyone}${warnText(res?.warnings)} View it: ${journeyLink(journeyId)}` }] };
1256
+ }
1257
+ catch (err) {
1258
+ return { content: [{ type: "text", text: `${APEX} ${errMsg(err)}` }], isError: true };
1259
+ }
1260
+ },
1261
+ },
1262
+ start_people_already_in_segment: {
1263
+ description: `${APEX} — A live journey that starts when someone joins a segment only starts people who join after it went live. This starts the people already in the segment too, once each, within a minute. Nobody this journey ran for in the last 90 days starts again. SAFETY: without confirm it only counts who would start; tell the owner the number and pass confirm:true only after they say yes. Not for a Milestone's journey (the Milestone chooses who starts). who:"joined_quietly" covers only the people a rule edit, an import, a key event change or late data put in the segment without starting it (Apex never starts those on its own).`,
1264
+ schema: z.object({
1265
+ journeyId: z.string(),
1266
+ confirm: z.boolean().optional().describe("Set true to start them. Omitted/false = count only."),
1267
+ who: z
1268
+ .enum(["everyone", "joined_quietly"])
1269
+ .optional()
1270
+ .describe('"everyone" (default): everyone in the segment. "joined_quietly": only the people changes added without starting them.'),
1271
+ }),
1272
+ handler: async ({ journeyId, confirm, who = "everyone" }) => {
1273
+ const path = `/api/journeys/${encodeURIComponent(journeyId)}/everyone-in-segment`;
1274
+ const line = who === "joined_quietly" ? joinedQuietlyLine : everyoneInSegmentLine;
1275
+ try {
1276
+ if (!confirm) {
1277
+ const counted = await apiGet(who === "joined_quietly" ? `${path}?from=last_sweep` : path);
1278
+ return {
1279
+ content: [
1280
+ {
1281
+ type: "text",
1282
+ text: `${APEX} ${line(counted.data)} Nothing started yet. Re-call with confirm:true once the owner agrees.`,
1283
+ },
1284
+ ],
1285
+ };
1286
+ }
1287
+ const started = await apiPost(path, { who });
1288
+ return {
1289
+ content: [
1290
+ {
1291
+ type: "text",
1292
+ text: `${APEX} ${line(started.data)} They start within a minute. View it: ${journeyLink(journeyId)}`,
1293
+ },
1294
+ ],
1295
+ };
1184
1296
  }
1185
1297
  catch (err) {
1186
1298
  return { content: [{ type: "text", text: `${APEX} ${errMsg(err)}` }], isError: true };
@@ -1349,6 +1461,58 @@ export const letterTools = {
1349
1461
  };
1350
1462
  },
1351
1463
  },
1464
+ set_journey_goal: {
1465
+ description: `${APEX} — Set what a journey is aiming at (its goal): one of the workspace's key events (key_event_id from list_key_events; preferred: its form, page and conditions apply, and every event that reaches it counts) or one event (event_name). window_days is how long after entering someone has to reach it (default 14). clear: true removes the goal. The journey's calibrated impact and the tests inside it are judged on it, and a test started from a letter is named after it. Edits the draft; publish_journey makes it live. Workspace admin.`,
1466
+ schema: z.object({
1467
+ journeyId: z.string(),
1468
+ keyEventId: z.string().optional().describe("Key event id from list_key_events. Give this or event_name."),
1469
+ eventName: z.string().optional().describe("One event, e.g. purchase. Give this or key_event_id."),
1470
+ windowDays: z.number().int().min(1).max(365).optional().describe("Days after entering to reach it (default 14)."),
1471
+ clear: z.boolean().optional().describe("Remove the goal."),
1472
+ }),
1473
+ handler: async (args) => {
1474
+ try {
1475
+ if (!args.clear && !args.keyEventId && !args.eventName) {
1476
+ return { content: [{ type: "text", text: `${APEX} Give key_event_id (from list_key_events) or event_name, or clear: true.` }], isError: true };
1477
+ }
1478
+ const guard = await refuseLiveApexObject({ journeyIds: [args.journeyId], purpose: "draft" });
1479
+ if (guard.stop)
1480
+ return { content: [{ type: "text", text: guard.text }] };
1481
+ let patch;
1482
+ let said;
1483
+ if (args.clear) {
1484
+ patch = { goalKeyEventId: null, goalEventName: "" };
1485
+ said = "no goal";
1486
+ }
1487
+ else if (args.keyEventId) {
1488
+ const read = await apiGet(`/api/key-events/${encodeURIComponent(args.keyEventId)}`);
1489
+ const keyEvent = read.data?.keyEvent;
1490
+ if (!keyEvent) {
1491
+ return { content: [{ type: "text", text: `${APEX} No key event ${args.keyEventId}. list_key_events has the ids.` }], isError: true };
1492
+ }
1493
+ const named = keyEvent.sources.find((s) => s.type === "custom_event" && s.eventName)?.eventName ?? "";
1494
+ patch = { goalKeyEventId: args.keyEventId, goalEventName: named };
1495
+ said = `the key event "${keyEvent.name}"`;
1496
+ }
1497
+ else {
1498
+ patch = { goalKeyEventId: null, goalEventName: args.eventName };
1499
+ said = args.eventName;
1500
+ }
1501
+ if (args.windowDays !== undefined)
1502
+ patch.goalEventWindowDays = args.windowDays;
1503
+ const saved = await apiPatch(`/api/journeys/${encodeURIComponent(args.journeyId)}`, patch);
1504
+ if (!tenantOk(saved.workspaceKey))
1505
+ return tenantMismatch();
1506
+ const window = args.clear ? "" : ` within ${saved.goalEventWindowDays ?? 14} days`;
1507
+ return {
1508
+ content: [{ type: "text", text: `${APEX} Journey ${args.journeyId} now aims at ${said}${window} (draft). publish_journey makes it live: ${journeyLink(args.journeyId)}` }],
1509
+ };
1510
+ }
1511
+ catch (err) {
1512
+ return { content: [{ type: "text", text: `${APEX} ${errMsg(err)}` }], isError: true };
1513
+ }
1514
+ },
1515
+ },
1352
1516
  // ─── Accounts (B2B-000 rollup + B2B-001 groups) ───────────────────────,
1353
1517
  list_journey_exits: {
1354
1518
  description: `${APEX} — Just the exit-rules block of one journey. Cheaper than get_journey for audit loops that only need to know "does this journey suppress purchase / unsubscribe?".`,
@@ -1368,26 +1532,36 @@ export const letterTools = {
1368
1532
  },
1369
1533
  },
1370
1534
  add_journey_exit: {
1371
- description: `${APEX} — Append a new exit rule to a journey's draft. Rule fires when the chosen trigger contract's event lands on a contact with an in-flight execution — Apex stops the execution and skips any pending sends. Re-publish required for the rule to take effect on live runs.`,
1535
+ description: `${APEX} — Append a new exit rule to a journey's draft. Rule fires when the chosen trigger contract's event, or any event that reaches the chosen key event, lands on a contact with an in-flight execution — Apex stops the execution and skips any pending sends. Prefer key_event_id (from list_key_events) when the reason to stop is one of the workspace's key events: it applies the key event's form, page and conditions, and every event that reaches it counts. Re-publish required for the rule to take effect on live runs.`,
1372
1536
  schema: z.object({
1373
1537
  journeyId: z.string(),
1374
1538
  triggerContractId: z
1375
1539
  .string()
1376
- .describe("Trigger-contract id, e.g. trig-in-app-purchase"),
1540
+ .optional()
1541
+ .describe("Trigger-contract id, e.g. trig-in-app-purchase. Give this or key_event_id."),
1542
+ keyEventId: z.string().optional().describe("Key event id from list_key_events. Give this or trigger_contract_id."),
1377
1543
  label: z.string().optional(),
1378
1544
  enabled: z.boolean().optional().default(true),
1379
1545
  }),
1380
- handler: async ({ journeyId, triggerContractId, label, enabled, }) => {
1546
+ handler: async ({ journeyId, triggerContractId, keyEventId, label, enabled, }) => {
1547
+ if (!triggerContractId && !keyEventId) {
1548
+ return {
1549
+ content: [{ type: "text", text: `${APEX} An exit rule needs trigger_contract_id or key_event_id.` }],
1550
+ isError: true,
1551
+ };
1552
+ }
1381
1553
  const body = await apiPost(`/api/journeys/${encodeURIComponent(journeyId)}/exit-rules`, {
1382
- triggerContractId,
1554
+ ...(triggerContractId ? { triggerContractId } : {}),
1555
+ ...(keyEventId ? { keyEventId } : {}),
1383
1556
  ...(label !== undefined && { label }),
1384
1557
  enabled: enabled !== false,
1385
1558
  });
1559
+ const on = body.data.keyEventId ? `key event ${body.data.keyEventId}` : body.data.triggerContractId;
1386
1560
  return {
1387
1561
  content: [
1388
1562
  {
1389
1563
  type: "text",
1390
- text: `Added exit rule ${body.data.id} → ${body.data.triggerContractId}. Publish the journey for it to apply to new executions.`,
1564
+ text: `Added exit rule ${body.data.id} → ${on}. Publish the journey for it to apply to new executions.`,
1391
1565
  },
1392
1566
  ],
1393
1567
  };
@@ -1449,7 +1623,8 @@ export const letterTools = {
1449
1623
  if (!goalLooksLikePurchase)
1450
1624
  continue;
1451
1625
  const hasPurchaseExit = (j.exitEvents ?? []).some((r) => r.enabled !== false &&
1452
- (r.triggerContractId.includes("purchase") ||
1626
+ ((!!j.goalKeyEventId && r.keyEventId === j.goalKeyEventId) ||
1627
+ (r.triggerContractId ?? "").includes("purchase") ||
1453
1628
  (r.label ?? "").toLowerCase().includes("purchase")));
1454
1629
  if (!hasPurchaseExit) {
1455
1630
  findings.push({
@@ -1491,7 +1666,7 @@ export const letterTools = {
1491
1666
  },
1492
1667
  },
1493
1668
  create_segment: {
1494
- description: `${APEX} — Create a segment from friendly "conditions" (compiled server-side) OR a raw predicate. Conditions grammar: match all|any of groups; each group match all|any of conditions; each condition is an event ({verb:"has"|"hasnt", event, window_days?}) or a trait ({attribute, op:"is"|"is_not"|"exists", value?}). This is the same grammar the dashboard chip builder speaks.`,
1669
+ description: `${APEX} — Create a segment from friendly "conditions" (compiled server-side) OR a raw predicate. Conditions grammar: match all|any of groups; each group match all|any of conditions; each condition is an event ({verb:"has"|"hasnt", event, window_days?}), a key event ({verb:"has"|"hasnt", key_event_id, window_days?, scope?:"person"|"account"}; ids from list_key_events; window_days bounds the first time it was reached; scope "account" means their company reached it), or a trait ({attribute, op:"is"|"is_not"|"exists", value?}). Prefer a key event over the raw events behind it: it is what Attribution counts, conditions included. This is the same grammar the dashboard chip builder speaks.`,
1495
1670
  schema: z.object({
1496
1671
  name: z.string().describe("Segment name"),
1497
1672
  description: z.string().optional(),
@@ -1504,6 +1679,8 @@ export const letterTools = {
1504
1679
  conditions: z.array(z.object({
1505
1680
  verb: z.enum(["has", "hasnt"]).optional(),
1506
1681
  event: z.string().optional(),
1682
+ key_event_id: z.string().optional(),
1683
+ scope: z.enum(["person", "account"]).optional(),
1507
1684
  window_days: z.number().optional(),
1508
1685
  attribute: z.string().optional(),
1509
1686
  op: z.enum(["is", "is_not", "exists"]).optional(),