@carrierllc/mcp 0.13.62 → 0.13.64

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.
package/dist/index.js CHANGED
@@ -40,6 +40,7 @@ import {
40
40
  loadStorefrontBrand,
41
41
  locationParams,
42
42
  locationZoneCreateParams,
43
+ marketingSnapshot,
43
44
  mccToIso,
44
45
  mergeEnvLocal,
45
46
  modifySubscriberContactInfoFromTool,
@@ -48,6 +49,7 @@ import {
48
49
  networkDefaultPartition,
49
50
  networkEventRows,
50
51
  networkEventsOverPeriodParams,
52
+ ocsArray,
51
53
  ocsHlrBitrate,
52
54
  ocsHlrBitrateFromBps,
53
55
  ocsLocalDateTime,
@@ -68,21 +70,28 @@ import {
68
70
  recordToolDescription,
69
71
  recurringIdForPackage,
70
72
  recurringPackageParams,
73
+ regionalArpu,
74
+ regionalArpuPeriod,
71
75
  renderHtml,
76
+ renderMarketingContext,
77
+ renderRegionalArpu,
72
78
  repairPlanFor,
73
79
  scopeListSubscriberParams,
74
80
  setNetworkDefault,
75
81
  staleActivePackages,
76
82
  storefrontClerkUrls,
83
+ subscriberIccid,
77
84
  subscriberIdParams,
85
+ subscriberListEnvelope,
78
86
  subscriberRows,
79
87
  subscriberSimId,
88
+ subscriberStatusVerdict,
80
89
  summarizeNetworkEvents,
81
90
  usageOverPeriodParams,
82
91
  verifyStorefront,
83
92
  withOcsListSummary,
84
93
  withTemplateResellerId
85
- } from "./chunk-SZR42TUZ.js";
94
+ } from "./chunk-2S75JA45.js";
86
95
  import "./chunk-SHKKVIIA.js";
87
96
 
88
97
  // src/index.ts
@@ -1113,7 +1122,7 @@ function boundTariffResult(raw, opts = {}) {
1113
1122
  const cap = opts.maxRules ?? (verbose ? TARIFF_VERBOSE_MAX_RULES : TARIFF_MAX_RULES);
1114
1123
  const kept = matched.slice(0, cap);
1115
1124
  const truncated = kept.length < matched.length;
1116
- const result2 = {
1125
+ const result3 = {
1117
1126
  resellerId,
1118
1127
  totalRules: all.length,
1119
1128
  matchedRules: matched.length,
@@ -1123,22 +1132,22 @@ function boundTariffResult(raw, opts = {}) {
1123
1132
  rules: []
1124
1133
  };
1125
1134
  if (country !== void 0 || trafficType !== void 0) {
1126
- result2.filters = {};
1127
- if (country !== void 0) result2.filters.country = country;
1128
- if (trafficType !== void 0) result2.filters.trafficType = trafficType;
1135
+ result3.filters = {};
1136
+ if (country !== void 0) result3.filters.country = country;
1137
+ if (trafficType !== void 0) result3.filters.trafficType = trafficType;
1129
1138
  }
1130
1139
  if (verbose) {
1131
- result2.rules = kept;
1132
- if (truncated) result2.note = truncationNote("tariff", kept.length, matched.length);
1133
- return result2;
1140
+ result3.rules = kept;
1141
+ if (truncated) result3.note = truncationNote("tariff", kept.length, matched.length);
1142
+ return result3;
1134
1143
  }
1135
1144
  const currencies = new Set(
1136
1145
  kept.map((r) => r.currency?.currencycode).filter((c) => typeof c === "string")
1137
1146
  );
1138
1147
  const hoistCurrency = currencies.size === 1;
1139
- if (hoistCurrency) result2.currency = [...currencies][0];
1148
+ if (hoistCurrency) result3.currency = [...currencies][0];
1140
1149
  const columns = trafficType ? RATE_COLUMNS[trafficType] : ALL_RATE_COLUMNS;
1141
- result2.rules = kept.map((r) => {
1150
+ result3.rules = kept.map((r) => {
1142
1151
  const op = r.operator ?? {};
1143
1152
  const row = {};
1144
1153
  if (op.countryIso2 !== void 0) row.iso = op.countryIso2;
@@ -1160,14 +1169,14 @@ function boundTariffResult(raw, opts = {}) {
1160
1169
  }
1161
1170
  }
1162
1171
  if (!hoistCurrency) legend.cur = "ISO-4217 currency code";
1163
- result2.fields = legend;
1172
+ result3.fields = legend;
1164
1173
  const notes = [];
1165
1174
  if (truncated) notes.push(truncationNote("tariff", kept.length, matched.length));
1166
1175
  notes.push(
1167
1176
  `Projected result: nested operator detail (mccMncs, tadigs, continent, countryCode, utcOffset), the sponsor object, plan ids (roamingplanruleid, roamingplanid, sponsoridx) and the validity/discount flags (startdate, enddate, isDiscounted, hidden, dailyCap) are omitted. Pass verbose=true for the full untouched rule shape (capped at ${TARIFF_VERBOSE_MAX_RULES} rows \u2014 use 'country'/'trafficType' with it).`
1168
1177
  );
1169
- result2.note = notes.join(" ");
1170
- return result2;
1178
+ result3.note = notes.join(" ");
1179
+ return result3;
1171
1180
  }
1172
1181
  var ZONE_FIELD_LEGEND = {
1173
1182
  zoneId: "location zone id \u2014 pass to package-template tools",
@@ -1180,22 +1189,22 @@ function boundZonesResult(raw, opts = {}) {
1180
1189
  const { verbose = false, resellerId } = opts;
1181
1190
  const maxZones = opts.maxZones ?? ZONES_MAX_ZONES;
1182
1191
  const maxOperators = opts.maxOperators ?? (verbose ? ZONES_VERBOSE_MAX_OPERATORS : ZONES_MAX_OPERATORS);
1183
- const totalOperators = all.reduce((n, z28) => n + (z28.operators?.length ?? 0), 0);
1192
+ const totalOperators = all.reduce((n, z29) => n + (z29.operators?.length ?? 0), 0);
1184
1193
  const keptZones = all.slice(0, maxZones);
1185
1194
  let budget = maxOperators;
1186
1195
  let returnedOperators = 0;
1187
- const zones = keptZones.map((z28) => {
1188
- const ops = z28.operators ?? [];
1196
+ const zones = keptZones.map((z29) => {
1197
+ const ops = z29.operators ?? [];
1189
1198
  const take = Math.max(0, Math.min(ops.length, budget));
1190
1199
  budget -= take;
1191
1200
  returnedOperators += take;
1192
1201
  const sliced = ops.slice(0, take);
1193
1202
  if (verbose) {
1194
- return { ...z28, operators: sliced, operatorCount: ops.length };
1203
+ return { ...z29, operators: sliced, operatorCount: ops.length };
1195
1204
  }
1196
1205
  return {
1197
- zoneId: z28.zoneId,
1198
- zoneName: z28.zoneName,
1206
+ zoneId: z29.zoneId,
1207
+ zoneName: z29.zoneName,
1199
1208
  operatorCount: ops.length,
1200
1209
  operators: sliced.map((o) => ({
1201
1210
  net: o.networkId,
@@ -1205,7 +1214,7 @@ function boundZonesResult(raw, opts = {}) {
1205
1214
  };
1206
1215
  });
1207
1216
  const truncated = keptZones.length < all.length || returnedOperators < totalOperators;
1208
- const result2 = {
1217
+ const result3 = {
1209
1218
  resellerId,
1210
1219
  totalZones: all.length,
1211
1220
  returnedZones: keptZones.length,
@@ -1218,13 +1227,13 @@ function boundZonesResult(raw, opts = {}) {
1218
1227
  const notes = [];
1219
1228
  if (truncated) notes.push(truncationNote("zones", returnedOperators, totalOperators));
1220
1229
  if (!verbose) {
1221
- result2.fields = ZONE_FIELD_LEGEND;
1230
+ result3.fields = ZONE_FIELD_LEGEND;
1222
1231
  notes.push(
1223
1232
  `Projected result: per-operator mccMncs, tadigs, continent, countryCode, countryName and utcOffset are omitted, as is the repeated reseller object. Pass verbose=true for the full untouched zone shape (capped at ${ZONES_VERBOSE_MAX_OPERATORS} operator entries).`
1224
1233
  );
1225
1234
  }
1226
- if (notes.length) result2.note = notes.join(" ");
1227
- return result2;
1235
+ if (notes.length) result3.note = notes.join(" ");
1236
+ return result3;
1228
1237
  }
1229
1238
 
1230
1239
  // src/tools.ts
@@ -1397,11 +1406,11 @@ function wrapHandler(toolName, ocsMethod, requiredScope, ctx, handler, options)
1397
1406
  ]
1398
1407
  };
1399
1408
  }
1400
- let result2;
1409
+ let result3;
1401
1410
  try {
1402
1411
  const skipToken = typeof options?.skipUserToken === "function" ? options.skipUserToken(args) : options?.skipUserToken;
1403
1412
  const token2 = skipToken ? "" : await ctx.getUserToken(ctx.props.sub);
1404
- result2 = extra === void 0 ? await handler(args, token2) : await handler(args, token2, extra);
1413
+ result3 = extra === void 0 ? await handler(args, token2) : await handler(args, token2, extra);
1405
1414
  } catch (err9) {
1406
1415
  try {
1407
1416
  Sentry.captureException(err9, {
@@ -1428,30 +1437,30 @@ function wrapHandler(toolName, ocsMethod, requiredScope, ctx, handler, options)
1428
1437
  content: [{ type: "text", text: `Error: ${message}` }]
1429
1438
  };
1430
1439
  }
1431
- const handledOcsCode = result2.ocsStatusCode;
1440
+ const handledOcsCode = result3.ocsStatusCode;
1432
1441
  if (handledOcsCode !== void 0) {
1433
- const { ocsStatusCode: _auditOnly, ...clientResult } = result2;
1442
+ const { ocsStatusCode: _auditOnly, ...clientResult } = result3;
1434
1443
  void _auditOnly;
1435
- result2 = clientResult;
1444
+ result3 = clientResult;
1436
1445
  }
1437
1446
  ctx.audit({
1438
1447
  tool_name: toolName,
1439
1448
  ocs_method: ocsMethod,
1440
- status: result2.isError ? "error" : "ok",
1449
+ status: result3.isError ? "error" : "ok",
1441
1450
  dry_run: isDryRun,
1442
1451
  duration_ms: Date.now() - start,
1443
1452
  ...handledOcsCode !== void 0 ? { ocs_status_code: handledOcsCode } : {}
1444
1453
  });
1445
- if (!result2.isError && !isDryRun) {
1454
+ if (!result3.isError && !isDryRun) {
1446
1455
  recordUsage(ctx.env, ctx.props.sub, ctx.props.tier);
1447
1456
  }
1448
- return result2;
1457
+ return result3;
1449
1458
  };
1450
1459
  }
1451
1460
  async function ocsCall(env, token2, method, params = {}, listKind) {
1452
1461
  const client2 = new OcsClient(env.CARRIER_OCS_BASE_URL, token2);
1453
- const result2 = await client2.call(method, params);
1454
- const payload = listKind ? withOcsListSummary(result2, listKind) : result2;
1462
+ const result3 = await client2.call(method, params);
1463
+ const payload = listKind ? withOcsListSummary(result3, listKind) : result3;
1455
1464
  return {
1456
1465
  content: [{ type: "text", text: JSON.stringify(payload, null, 2) }]
1457
1466
  };
@@ -2749,7 +2758,7 @@ function registerAllTools(server2, ctx) {
2749
2758
  }
2750
2759
 
2751
2760
  // src/intelligence.ts
2752
- import { z as z2 } from "zod";
2761
+ import { z as z3 } from "zod";
2753
2762
 
2754
2763
  // ../../packages/ocs-spec/ocs-methods.json
2755
2764
  var ocs_methods_default = {
@@ -3829,7 +3838,8 @@ var ocsIntelligenceMethods = ocsSpec.v1_intelligence_methods;
3829
3838
  var ocsBacklog = ocsSpec.v1_1_backlog;
3830
3839
  var ocsAppMethods = ocsSpec.v1_app_methods;
3831
3840
 
3832
- // src/intelligence.ts
3841
+ // src/marketing-intelligence.ts
3842
+ import { z as z2 } from "zod";
3833
3843
  async function safeCall(env, token2, method, params = {}) {
3834
3844
  try {
3835
3845
  const client2 = new OcsClient(env.CARRIER_OCS_BASE_URL, token2);
@@ -3839,12 +3849,118 @@ async function safeCall(env, token2, method, params = {}) {
3839
3849
  return { data: null, error: err9 instanceof Error ? err9.message : String(err9) };
3840
3850
  }
3841
3851
  }
3852
+ function result(text, isError = false) {
3853
+ return { content: [{ type: "text", text }], ...isError ? { isError: true } : {} };
3854
+ }
3855
+ function registerMarketingIntelligenceTool(server2, ctx) {
3856
+ server2.registerTool("marketing_intelligence", {
3857
+ title: "Marketing Intelligence Report",
3858
+ description: "Reports regional ARPU from historical rated subscriber charges, measured subscribers, and catalogue coverage. Countries and currencies remain separate; missing charges are reported.",
3859
+ inputSchema: {
3860
+ accountId: z2.number().optional().describe("Filter to a specific account"),
3861
+ start: z2.string().optional().describe("Usage period start (YYYY-MM-DD, maximum seven inclusive days)"),
3862
+ end: z2.string().optional().describe("Usage period end (YYYY-MM-DD, default today UTC)")
3863
+ },
3864
+ annotations: { readOnlyHint: true }
3865
+ }, async ({ accountId, start, end }) => {
3866
+ let period;
3867
+ try {
3868
+ period = regionalArpuPeriod(start, end);
3869
+ } catch (err9) {
3870
+ return result(err9 instanceof Error ? err9.message : String(err9), true);
3871
+ }
3872
+ const token2 = await ctx.getUserToken(ctx.props.sub);
3873
+ const params = {};
3874
+ const accountIds = tenantAccountIds(ctx.managedAuth);
3875
+ if (accountIds?.length === 0) return result("Subscriber not found", true);
3876
+ if (!ctx.managedAuth.managed && accountIds !== void 0 && accountId !== void 0 && !accountIds.includes(accountId)) return result("Account not found", true);
3877
+ if (accountIds !== void 0) {
3878
+ params.accountId = accountId !== void 0 && accountIds.includes(accountId) ? accountId : accountIds[0];
3879
+ } else if (accountId !== void 0) {
3880
+ params.accountId = accountId;
3881
+ }
3882
+ const scope = await scopeListSubscriberParams({
3883
+ params,
3884
+ managed: ctx.managedAuth.managed,
3885
+ preferredAccountId: ctx.managedAuth.preferredAccountId,
3886
+ call: async (method, callParams) => {
3887
+ const response = await safeCall(ctx.env, token2, method, callParams);
3888
+ if (response.error) throw new Error(response.error);
3889
+ return response.data;
3890
+ }
3891
+ });
3892
+ if (!scope.ok) return result(scope.message, true);
3893
+ const [subsResult, templatesResult, resellerId] = await Promise.all([
3894
+ safeCall(ctx.env, token2, "listSubscriber", scope.params),
3895
+ safeCall(ctx.env, token2, "listPrepaidPackageTemplate", {}),
3896
+ getDefaultResellerId(ctx.env, token2)
3897
+ ]);
3898
+ if (subsResult.error) return result(`Failed to fetch subscribers: ${subsResult.error}`, true);
3899
+ const subscribers = ocsArray(subsResult.data, ["subscriberList", "subscribers", "subscriber"]);
3900
+ const distinct = [...new Map(subscribers.map((sub, index) => [subscriberIccid(sub) || `missing-iccid:${index}`, sub])).entries()];
3901
+ const sample = distinct.slice(0, 100);
3902
+ const reads = [];
3903
+ const snapshots = [];
3904
+ for (let i = 0; i < sample.length; i += 10) {
3905
+ reads.push(...await Promise.all(sample.slice(i, i + 10).map(async ([subscriber, sub]) => {
3906
+ const iccid = subscriberIccid(sub);
3907
+ if (!iccid) return { subscriber, data: null, error: "Missing subscriber ICCID" };
3908
+ const access = await assertManagedIccidAccess(
3909
+ ctx.env.CARRIER_OCS_BASE_URL,
3910
+ { ...ctx.managedAuth, token: token2 },
3911
+ iccid
3912
+ );
3913
+ if (!access.ok) return { subscriber, data: null, error: access.error };
3914
+ const usage = await safeCall(ctx.env, token2, "subscriberUsageOverPeriod", {
3915
+ subscriber: { iccid },
3916
+ period
3917
+ });
3918
+ const current = await safeCall(ctx.env, token2, "getSingleSubscriber", { iccid });
3919
+ if (!isManagedSubscriberDenied(ctx.managedAuth, current.data)) {
3920
+ snapshots.push(marketingSnapshot(sub, current.data));
3921
+ }
3922
+ return { subscriber, data: usage.data, error: usage.error };
3923
+ })));
3924
+ }
3925
+ const envelope = subscriberListEnvelope(subsResult.data);
3926
+ const total = typeof envelope?.nbFound === "number" && Number.isFinite(envelope.nbFound) ? Math.max(distinct.length, envelope.nbFound) : distinct.length;
3927
+ const report = regionalArpu(reads, {
3928
+ period,
3929
+ total_subscribers: total,
3930
+ truncated: envelope?.hasMore === true || envelope?.truncated === true || sample.length < distinct.length
3931
+ });
3932
+ const sections = ["# Marketing Intelligence Report\n", renderRegionalArpu(report)];
3933
+ if (scope.defaultAccount) sections.push(scope.defaultAccount.note);
3934
+ const zonesResult = await safeCall(ctx.env, token2, "listDetailedLocationZone", resellerId);
3935
+ const zones = ocsArray(zonesResult.data, "zones");
3936
+ const templates = ocsArray(templatesResult.data, "templates");
3937
+ sections.push(
3938
+ `
3939
+ ## Coverage Catalog
3940
+ - Location zones available: ${zonesResult.error ? `Unavailable (${zonesResult.error})` : zones.length}
3941
+ - Package templates available: ${templatesResult.error ? `Unavailable (${templatesResult.error})` : templates.length}`
3942
+ );
3943
+ sections.push(renderMarketingContext(snapshots, sample.length, templates));
3944
+ return result(sections.join("\n"));
3945
+ });
3946
+ }
3947
+
3948
+ // src/intelligence.ts
3949
+ async function safeCall2(env, token2, method, params = {}) {
3950
+ try {
3951
+ const client2 = new OcsClient(env.CARRIER_OCS_BASE_URL, token2);
3952
+ const data = await client2.call(method, params);
3953
+ return { data, error: null };
3954
+ } catch (err9) {
3955
+ return { data: null, error: err9 instanceof Error ? err9.message : String(err9) };
3956
+ }
3957
+ }
3842
3958
  async function fetchActiveSubscribers(env, token2, accountId, resellerId) {
3843
3959
  let accountIds;
3844
3960
  if (accountId !== void 0) {
3845
3961
  accountIds = [accountId];
3846
3962
  } else {
3847
- const accountsResult = await safeCall(
3963
+ const accountsResult = await safeCall2(
3848
3964
  env,
3849
3965
  token2,
3850
3966
  "listResellerAccount",
@@ -3857,7 +3973,7 @@ async function fetchActiveSubscribers(env, token2, accountId, resellerId) {
3857
3973
  }
3858
3974
  const aggregated = [];
3859
3975
  for (const acctId of accountIds) {
3860
- const subResult = await safeCall(
3976
+ const subResult = await safeCall2(
3861
3977
  env,
3862
3978
  token2,
3863
3979
  "listSubscriber",
@@ -3868,7 +3984,7 @@ async function fetchActiveSubscribers(env, token2, accountId, resellerId) {
3868
3984
  }
3869
3985
  return { data: filterActiveSubscribers(aggregated), error: null };
3870
3986
  }
3871
- function result(text, isError = false) {
3987
+ function result2(text, isError = false) {
3872
3988
  return { content: [{ type: "text", text }], ...isError ? { isError: true } : {} };
3873
3989
  }
3874
3990
  function registerIntelligenceTools(server2, ctx) {
@@ -3876,7 +3992,7 @@ function registerIntelligenceTools(server2, ctx) {
3876
3992
  title: "Diagnose Subscriber Issues",
3877
3993
  description: "Smart diagnostic that chains multiple API calls to analyze why a subscriber may be offline, throttled, or having connectivity issues. Returns a structured diagnosis with root cause analysis and recommended actions.",
3878
3994
  inputSchema: {
3879
- iccid: z2.string().describe("The subscriber ICCID to diagnose")
3995
+ iccid: z3.string().describe("The subscriber ICCID to diagnose")
3880
3996
  },
3881
3997
  annotations: { readOnlyHint: true }
3882
3998
  }, async ({ iccid }) => {
@@ -3884,20 +4000,17 @@ function registerIntelligenceTools(server2, ctx) {
3884
4000
  const findings = [];
3885
4001
  const actions = [];
3886
4002
  let severity = "healthy";
3887
- const sub = await safeCall(ctx.env, token2, "getSingleSubscriber", { iccid });
3888
- if (sub.error) return result(`Failed to fetch subscriber: ${sub.error}`, true);
3889
- if (!sub.data) return result("Subscriber not found", true);
4003
+ const sub = await safeCall2(ctx.env, token2, "getSingleSubscriber", { iccid });
4004
+ if (sub.error) return result2(`Failed to fetch subscriber: ${sub.error}`, true);
4005
+ if (!sub.data) return result2("Subscriber not found", true);
3890
4006
  const status = (extractSubscriberStatus(sub.data) ?? "").toUpperCase();
3891
4007
  const balance = Number(sub.data.balance ?? 0);
3892
- if (status === "") {
3893
- findings.push("OCS status could not be read from the subscriber record");
3894
- if (severity === "healthy") severity = "info";
3895
- } else if (status !== "ACTIVE") {
3896
- findings.push(`OCS status is ${status} (not ACTIVE)`);
3897
- actions.push(`Reactivate subscriber via modify_subscriber_status`);
3898
- severity = "critical";
3899
- }
3900
- const pkgs = await safeCall(ctx.env, token2, "listSubscriberPrepaidPackages", { iccid });
4008
+ const verdict = subscriberStatusVerdict(status);
4009
+ if (verdict.finding) findings.push(verdict.finding);
4010
+ if (verdict.action) actions.push(verdict.action);
4011
+ if (verdict.severity === "critical") severity = "critical";
4012
+ else if (verdict.severity === "info" && severity === "healthy") severity = "info";
4013
+ const pkgs = await safeCall2(ctx.env, token2, "listSubscriberPrepaidPackages", { iccid });
3901
4014
  const allPkgs = prepaidPackageRows(pkgs.data);
3902
4015
  const activePkgs = allPkgs.filter((p) => isActivePackage(p));
3903
4016
  const stalePkgs = staleActivePackages(allPkgs);
@@ -3949,7 +4062,7 @@ function registerIntelligenceTools(server2, ctx) {
3949
4062
  if (severity !== "critical") severity = "warning";
3950
4063
  }
3951
4064
  const simId = subscriberSimId(sub.data);
3952
- const sim = simId !== void 0 ? await safeCall(ctx.env, token2, "getSimProviderStatus", simId) : { data: null, error: null };
4065
+ const sim = simId !== void 0 ? await safeCall2(ctx.env, token2, "getSimProviderStatus", simId) : { data: null, error: null };
3953
4066
  if (sim.data) {
3954
4067
  const simStatus = (extractSimProviderStatus(sim.data) ?? "").toUpperCase();
3955
4068
  if (simStatus && !["ENABLED", "ACTIVE", "ACTIVATED"].includes(simStatus)) {
@@ -3960,7 +4073,7 @@ function registerIntelligenceTools(server2, ctx) {
3960
4073
  }
3961
4074
  const now = /* @__PURE__ */ new Date();
3962
4075
  const eventWindow = lastNDaysPeriod(3, now);
3963
- const events = await safeCall(ctx.env, token2, "subscriberNetworkEventsOverPeriod", {
4076
+ const events = await safeCall2(ctx.env, token2, "subscriberNetworkEventsOverPeriod", {
3964
4077
  subscriber: { iccid },
3965
4078
  period: eventWindow
3966
4079
  });
@@ -3998,7 +4111,7 @@ function registerIntelligenceTools(server2, ctx) {
3998
4111
  }
3999
4112
  }
4000
4113
  const imsiForBitrate = imsiFromSubscriberRecord(sub.data) ?? null;
4001
- const bitrate = imsiForBitrate ? await safeCall(ctx.env, token2, "hlrGetBitrate", { imsi: imsiForBitrate }) : { data: null, error: null };
4114
+ const bitrate = imsiForBitrate ? await safeCall2(ctx.env, token2, "hlrGetBitrate", { imsi: imsiForBitrate }) : { data: null, error: null };
4002
4115
  if (bitrate.data) {
4003
4116
  const rate = Number(bitrate.data.bitrate ?? bitrate.data.maxBitrate ?? 0);
4004
4117
  if (rate > 0 && rate < 1e6) {
@@ -4028,26 +4141,26 @@ function registerIntelligenceTools(server2, ctx) {
4028
4141
  `- Balance: ${balance}`,
4029
4142
  `- Active Packages: ${pkgs.error ? "unknown" : activePkgs.length}`
4030
4143
  ].join("\n");
4031
- return result(report);
4144
+ return result2(report);
4032
4145
  });
4033
4146
  server2.registerTool("fleet_health", {
4034
4147
  title: "Fleet Health Dashboard",
4035
4148
  description: "Aggregates eSIM status counts, low-balance accounts, and provides a fleet-wide health summary in a single call. Identifies accounts that need attention.",
4036
4149
  inputSchema: {
4037
- accountId: z2.number().optional().describe("Filter to a specific account (omit for all)")
4150
+ accountId: z3.number().optional().describe("Filter to a specific account (omit for all)")
4038
4151
  },
4039
4152
  annotations: { readOnlyHint: true }
4040
4153
  }, async ({ accountId }) => {
4041
4154
  const token2 = await ctx.getUserToken(ctx.props.sub);
4042
4155
  const resellerId = await getDefaultResellerId(ctx.env, token2).catch(() => void 0);
4043
4156
  const [statusResult, accountsResult, resellerInfoResult] = await Promise.all([
4044
- safeCall(
4157
+ safeCall2(
4045
4158
  ctx.env,
4046
4159
  token2,
4047
4160
  "esimStatusPerAccount",
4048
4161
  accountId !== void 0 ? { accountId } : resellerId !== void 0 ? { resellerId } : {}
4049
4162
  ),
4050
- safeCall(
4163
+ safeCall2(
4051
4164
  ctx.env,
4052
4165
  token2,
4053
4166
  "listResellerAccount",
@@ -4057,7 +4170,7 @@ function registerIntelligenceTools(server2, ctx) {
4057
4170
  // parent is out of credit, and that is the one state which silently
4058
4171
  // zeroes every rating group (2026-08-28: reseller 1170 at 0.00 while
4059
4172
  // fleet_health reported "require no action").
4060
- resellerId !== void 0 ? safeCall(
4173
+ resellerId !== void 0 ? safeCall2(
4061
4174
  ctx.env,
4062
4175
  token2,
4063
4176
  "getResellerInfo",
@@ -4172,15 +4285,15 @@ Package-only accounts at 0 balance require no action.`);
4172
4285
  ## Errors`);
4173
4286
  if (statusResult.error) sections.push(`- esimStatusPerAccount: ${statusResult.error}`);
4174
4287
  if (accountsResult.error) sections.push(`- listResellerAccount: ${accountsResult.error}`);
4175
- return result(sections.join("\n"), true);
4288
+ return result2(sections.join("\n"), true);
4176
4289
  }
4177
- return result(sections.join("\n"));
4290
+ return result2(sections.join("\n"));
4178
4291
  });
4179
4292
  server2.registerTool("detect_usage_anomalies", {
4180
4293
  title: "Detect Usage Anomalies",
4181
4294
  description: "Analyzes a subscriber's recent usage patterns over the last 7 days to detect anomalies: sudden spikes, unusual off-hours activity, or consumption rates that would exhaust the package before expiry.",
4182
4295
  inputSchema: {
4183
- iccid: z2.string().describe("The subscriber ICCID to analyze")
4296
+ iccid: z3.string().describe("The subscriber ICCID to analyze")
4184
4297
  },
4185
4298
  annotations: { readOnlyHint: true }
4186
4299
  }, async ({ iccid }) => {
@@ -4188,13 +4301,13 @@ Package-only accounts at 0 balance require no action.`);
4188
4301
  const now = /* @__PURE__ */ new Date();
4189
4302
  const usagePeriod = lastNDaysPeriod(OCS_MAX_USAGE_WINDOW_DAYS, now);
4190
4303
  const [usageResult, pkgResult] = await Promise.all([
4191
- safeCall(ctx.env, token2, "subscriberUsageOverPeriod", {
4304
+ safeCall2(ctx.env, token2, "subscriberUsageOverPeriod", {
4192
4305
  subscriber: { iccid },
4193
4306
  period: usagePeriod
4194
4307
  }),
4195
- safeCall(ctx.env, token2, "listSubscriberPrepaidPackages", { iccid })
4308
+ safeCall2(ctx.env, token2, "listSubscriberPrepaidPackages", { iccid })
4196
4309
  ]);
4197
- if (usageResult.error) return result(`Failed to fetch usage: ${usageResult.error}`, true);
4310
+ if (usageResult.error) return result2(`Failed to fetch usage: ${usageResult.error}`, true);
4198
4311
  const sections = [`# Usage Anomaly Report: ${iccid}
4199
4312
  `];
4200
4313
  const anomalies = [];
@@ -4255,13 +4368,13 @@ Package-only accounts at 0 balance require no action.`);
4255
4368
  sections.push(`
4256
4369
  ## No anomalies detected \u2014 usage appears normal.`);
4257
4370
  }
4258
- return result(sections.join("\n"));
4371
+ return result2(sections.join("\n"));
4259
4372
  });
4260
4373
  server2.registerTool("optimize_package", {
4261
4374
  title: "Package Optimization Advisor",
4262
4375
  description: "Compares a subscriber's actual usage against their current package and all available templates. Recommends better-fit packages to reduce waste or prevent overages. Calculates potential savings.",
4263
4376
  inputSchema: {
4264
- iccid: z2.string().describe("The subscriber ICCID to optimize")
4377
+ iccid: z3.string().describe("The subscriber ICCID to optimize")
4265
4378
  },
4266
4379
  annotations: { readOnlyHint: true }
4267
4380
  }, async ({ iccid }) => {
@@ -4269,12 +4382,12 @@ Package-only accounts at 0 balance require no action.`);
4269
4382
  const now = /* @__PURE__ */ new Date();
4270
4383
  const usagePeriod = lastNDaysPeriod(OCS_MAX_USAGE_WINDOW_DAYS, now);
4271
4384
  const [usageResult, pkgResult, templatesResult] = await Promise.all([
4272
- safeCall(ctx.env, token2, "subscriberUsageOverPeriod", {
4385
+ safeCall2(ctx.env, token2, "subscriberUsageOverPeriod", {
4273
4386
  subscriber: { iccid },
4274
4387
  period: usagePeriod
4275
4388
  }),
4276
- safeCall(ctx.env, token2, "listSubscriberPrepaidPackages", { iccid }),
4277
- safeCall(ctx.env, token2, "listPrepaidPackageTemplate", {})
4389
+ safeCall2(ctx.env, token2, "listSubscriberPrepaidPackages", { iccid }),
4390
+ safeCall2(ctx.env, token2, "listPrepaidPackageTemplate", {})
4278
4391
  ]);
4279
4392
  const sections = [`# Package Optimization: ${iccid}
4280
4393
  `];
@@ -4340,13 +4453,13 @@ Package-only accounts at 0 balance require no action.`);
4340
4453
  sections.push(`
4341
4454
  *No usage data available \u2014 cannot recommend packages without usage history.*`);
4342
4455
  }
4343
- return result(sections.join("\n"));
4456
+ return result2(sections.join("\n"));
4344
4457
  });
4345
4458
  server2.registerTool("churn_risk", {
4346
4459
  title: "Churn Risk Assessment",
4347
4460
  description: "Analyzes a subscriber's usage trends, package status, balance, and activity to produce a churn risk score (0-100) with contributing factors and retention recommendations.",
4348
4461
  inputSchema: {
4349
- iccid: z2.string().describe("The subscriber ICCID to assess")
4462
+ iccid: z3.string().describe("The subscriber ICCID to assess")
4350
4463
  },
4351
4464
  annotations: { readOnlyHint: true }
4352
4465
  }, async ({ iccid }) => {
@@ -4354,13 +4467,13 @@ Package-only accounts at 0 balance require no action.`);
4354
4467
  const now = /* @__PURE__ */ new Date();
4355
4468
  const usagePeriod = lastNDaysPeriod(OCS_MAX_USAGE_WINDOW_DAYS, now);
4356
4469
  const [subResult, usageResult, pkgResult, activeResult] = await Promise.all([
4357
- safeCall(ctx.env, token2, "getSingleSubscriber", { iccid }),
4358
- safeCall(ctx.env, token2, "subscriberUsageOverPeriod", {
4470
+ safeCall2(ctx.env, token2, "getSingleSubscriber", { iccid }),
4471
+ safeCall2(ctx.env, token2, "subscriberUsageOverPeriod", {
4359
4472
  subscriber: { iccid },
4360
4473
  period: usagePeriod
4361
4474
  }),
4362
- safeCall(ctx.env, token2, "listSubscriberPrepaidPackages", { iccid }),
4363
- safeCall(ctx.env, token2, "getSubscriberActivePeriod", { iccid })
4475
+ safeCall2(ctx.env, token2, "listSubscriberPrepaidPackages", { iccid }),
4476
+ safeCall2(ctx.env, token2, "getSubscriberActivePeriod", { iccid })
4364
4477
  ]);
4365
4478
  let riskScore = 0;
4366
4479
  const factors = [];
@@ -4462,14 +4575,14 @@ Package-only accounts at 0 balance require no action.`);
4462
4575
  sections.push("1. No immediate action required");
4463
4576
  sections.push("2. Continue monitoring via regular fleet_health checks");
4464
4577
  }
4465
- return result(sections.join("\n"));
4578
+ return result2(sections.join("\n"));
4466
4579
  });
4467
4580
  server2.registerTool("audit_network_coverage", {
4468
4581
  title: "Network Coverage Audit",
4469
4582
  description: "Analyzes which networks your subscribers are actually connecting to in a given country or across all countries. Compares against your steering lists to identify mismatches \u2014 subscribers roaming on expensive or non-preferred networks. Use this to answer: 'Am I using the right networks in country X?'",
4470
4583
  inputSchema: {
4471
- accountId: z2.number().optional().describe("Filter to a specific account"),
4472
- limit: z2.number().optional().describe("Max subscribers to sample (default 50)")
4584
+ accountId: z3.number().optional().describe("Filter to a specific account"),
4585
+ limit: z3.number().optional().describe("Max subscribers to sample (default 50)")
4473
4586
  },
4474
4587
  annotations: { readOnlyHint: true }
4475
4588
  }, async ({ accountId, limit: sampleLimit }) => {
@@ -4478,9 +4591,9 @@ Package-only accounts at 0 balance require no action.`);
4478
4591
  const resellerId = await getDefaultResellerId(ctx.env, token2);
4479
4592
  const [subsResult, steeringResult] = await Promise.all([
4480
4593
  fetchActiveSubscribers(ctx.env, token2, accountId, resellerId),
4481
- safeCall(ctx.env, token2, "listSteeringList", resellerId)
4594
+ safeCall2(ctx.env, token2, "listSteeringList", resellerId)
4482
4595
  ]);
4483
- if (subsResult.error) return result(`Failed to fetch subscribers: ${subsResult.error}`, true);
4596
+ if (subsResult.error) return result2(`Failed to fetch subscribers: ${subsResult.error}`, true);
4484
4597
  const sections = [`# Network Coverage Audit
4485
4598
  `];
4486
4599
  const steeringMap = /* @__PURE__ */ new Map();
@@ -4500,7 +4613,7 @@ Package-only accounts at 0 balance require no action.`);
4500
4613
  const batch = subs.slice(i, i + batchSize);
4501
4614
  const locations = await Promise.all(
4502
4615
  batch.map(
4503
- (s) => safeCall(ctx.env, token2, "getSubscriberLocation", {
4616
+ (s) => safeCall2(ctx.env, token2, "getSubscriberLocation", {
4504
4617
  iccid: String(s.iccid ?? "")
4505
4618
  })
4506
4619
  )
@@ -4542,129 +4655,16 @@ ${networksSorted.length} different networks in ${country} \u2014 possible steeri
4542
4655
  } else {
4543
4656
  sections.push("No location data available for sampled subscribers.");
4544
4657
  }
4545
- return result(sections.join("\n"));
4546
- });
4547
- server2.registerTool("marketing_intelligence", {
4548
- title: "Marketing Intelligence Report",
4549
- description: "Analyzes your subscriber base to identify high-growth markets, underserved regions, and revenue concentration. Answers: 'Which countries should I target with marketing?' and 'Where are my most valuable subscribers?'",
4550
- inputSchema: {
4551
- accountId: z2.number().optional().describe("Filter to a specific account")
4552
- },
4553
- annotations: { readOnlyHint: true }
4554
- }, async ({ accountId }) => {
4555
- const token2 = await ctx.getUserToken(ctx.props.sub);
4556
- const params = {};
4557
- if (accountId !== void 0) params.accountId = accountId;
4558
- const [subsResult, templatesResult, resellerId] = await Promise.all([
4559
- safeCall(ctx.env, token2, "listSubscriber", params),
4560
- safeCall(ctx.env, token2, "listPrepaidPackageTemplate", {}),
4561
- getDefaultResellerId(ctx.env, token2)
4562
- ]);
4563
- const zonesResult = await safeCall(
4564
- ctx.env,
4565
- token2,
4566
- "listDetailedLocationZone",
4567
- resellerId
4568
- );
4569
- const sections = [`# Marketing Intelligence Report
4570
- `];
4571
- if (subsResult.data && Array.isArray(subsResult.data)) {
4572
- const total = subsResult.data.length;
4573
- sections.push(`## Fleet Size: ${total} subscribers sampled
4574
- `);
4575
- const sample = subsResult.data.slice(0, 100);
4576
- const countryData = /* @__PURE__ */ new Map();
4577
- const batchSize = 10;
4578
- for (let i = 0; i < sample.length; i += batchSize) {
4579
- const batch = sample.slice(i, i + batchSize);
4580
- const locations = await Promise.all(
4581
- batch.map(
4582
- (s) => safeCall(ctx.env, token2, "getSubscriberLocation", {
4583
- iccid: String(s.iccid ?? "")
4584
- })
4585
- )
4586
- );
4587
- for (let j = 0; j < batch.length; j++) {
4588
- const loc = locations[j];
4589
- const sub = batch[j];
4590
- const country = loc.data ? String(loc.data.country ?? loc.data.countryCode ?? "Unknown") : "Unknown";
4591
- if (!countryData.has(country)) {
4592
- countryData.set(country, { subscribers: 0, activePackages: 0, totalBalance: 0 });
4593
- }
4594
- const cd = countryData.get(country);
4595
- cd.subscribers++;
4596
- cd.totalBalance += Number(sub.balance ?? 0);
4597
- }
4598
- }
4599
- if (countryData.size > 0) {
4600
- const sorted = [...countryData.entries()].sort((a, b) => b[1].subscribers - a[1].subscribers);
4601
- sections.push(`## Subscriber Concentration by Country`);
4602
- sections.push(`| Country | Subscribers | % of Fleet | Avg Balance |`);
4603
- sections.push(`|---------|-----------|------------|-------------|`);
4604
- for (const [country, data] of sorted) {
4605
- const pct = (data.subscribers / sample.length * 100).toFixed(1);
4606
- const avgBal = (data.totalBalance / data.subscribers).toFixed(2);
4607
- sections.push(`| ${country} | ${data.subscribers} | ${pct}% | ${avgBal} |`);
4608
- }
4609
- sections.push(`
4610
- ## Market Insights`);
4611
- const topMarket = sorted[0];
4612
- if (topMarket) {
4613
- sections.push(`- **Strongest market**: ${topMarket[0]} (${topMarket[1].subscribers} subscribers)`);
4614
- if (topMarket[1].subscribers / sample.length > 0.5) {
4615
- sections.push(` Revenue concentration risk \u2014 >50% of fleet in one market`);
4616
- }
4617
- }
4618
- const highValue = sorted.filter(([, d]) => d.subscribers >= 3).sort((a, b) => b[1].totalBalance / b[1].subscribers - a[1].totalBalance / a[1].subscribers).slice(0, 3);
4619
- if (highValue.length > 0) {
4620
- sections.push(`
4621
- ### High-Value Markets (by avg balance)`);
4622
- for (const [country, data] of highValue) {
4623
- sections.push(`- **${country}**: avg balance ${(data.totalBalance / data.subscribers).toFixed(2)} (${data.subscribers} subs)`);
4624
- }
4625
- }
4626
- const emerging = sorted.filter(([, d]) => d.subscribers >= 1 && d.subscribers <= 3);
4627
- if (emerging.length > 0) {
4628
- sections.push(`
4629
- ### Emerging Markets (early traction, 1-3 subscribers)`);
4630
- sections.push(`These markets show initial demand \u2014 consider targeted campaigns:`);
4631
- for (const [country, data] of emerging) {
4632
- sections.push(`- ${country}: ${data.subscribers} subscriber(s)`);
4633
- }
4634
- }
4635
- }
4636
- }
4637
- if (zonesResult.data && Array.isArray(zonesResult.data)) {
4638
- sections.push(`
4639
- ## Coverage Catalog`);
4640
- sections.push(`- Location zones available: ${zonesResult.data.length}`);
4641
- }
4642
- if (templatesResult.data && Array.isArray(templatesResult.data)) {
4643
- sections.push(`- Package templates available: ${templatesResult.data.length}`);
4644
- const prices = templatesResult.data.map((t) => Number(t.price ?? t.cost ?? 0)).filter((p) => p > 0);
4645
- if (prices.length > 0) {
4646
- const avgPrice = prices.reduce((a, b) => a + b, 0) / prices.length;
4647
- const minPrice = Math.min(...prices);
4648
- const maxPrice = Math.max(...prices);
4649
- sections.push(`
4650
- ### Pricing Range`);
4651
- sections.push(`- Min: ${minPrice.toFixed(2)} | Avg: ${avgPrice.toFixed(2)} | Max: ${maxPrice.toFixed(2)}`);
4652
- }
4653
- }
4654
- sections.push(`
4655
- ## Recommended Actions`);
4656
- sections.push(`1. Run \`audit_network_coverage\` to verify network quality in top markets`);
4657
- sections.push(`2. Run \`high_cost_subscribers\` to identify margin pressure`);
4658
- sections.push(`3. Consider creating regional package templates for emerging markets`);
4659
- return result(sections.join("\n"));
4658
+ return result2(sections.join("\n"));
4660
4659
  });
4660
+ registerMarketingIntelligenceTool(server2, ctx);
4661
4661
  server2.registerTool("high_cost_subscribers", {
4662
4662
  title: "High Cost Subscriber Report",
4663
4663
  description: "Identifies subscribers with disproportionately high data consumption relative to their package value. Finds subscribers burning through data at rates that erode margins. Answers: 'Which subscribers are costing me money?'",
4664
4664
  inputSchema: {
4665
- accountId: z2.number().optional().describe("Filter to a specific account"),
4666
- limit: z2.number().optional().describe("Max subscribers to analyze (default 100)"),
4667
- thresholdPct: z2.number().optional().describe("Usage % threshold to flag (default 80)")
4665
+ accountId: z3.number().optional().describe("Filter to a specific account"),
4666
+ limit: z3.number().optional().describe("Max subscribers to analyze (default 100)"),
4667
+ thresholdPct: z3.number().optional().describe("Usage % threshold to flag (default 80)")
4668
4668
  },
4669
4669
  annotations: { readOnlyHint: true }
4670
4670
  }, async ({ accountId, limit: maxLimit, thresholdPct }) => {
@@ -4673,8 +4673,8 @@ ${networksSorted.length} different networks in ${country} \u2014 possible steeri
4673
4673
  const threshold = thresholdPct ?? 80;
4674
4674
  const resellerId = await getDefaultResellerId(ctx.env, token2);
4675
4675
  const subsResult = await fetchActiveSubscribers(ctx.env, token2, accountId, resellerId);
4676
- if (subsResult.error) return result(`Failed to fetch subscribers: ${subsResult.error}`, true);
4677
- if (!subsResult.data || subsResult.data.length === 0) return result("No subscribers found", true);
4676
+ if (subsResult.error) return result2(`Failed to fetch subscribers: ${subsResult.error}`, true);
4677
+ if (!subsResult.data || subsResult.data.length === 0) return result2("No subscribers found", true);
4678
4678
  const sections = [`# High Cost Subscriber Report
4679
4679
  `];
4680
4680
  const now = /* @__PURE__ */ new Date();
@@ -4688,12 +4688,12 @@ ${networksSorted.length} different networks in ${country} \u2014 possible steeri
4688
4688
  batch.map(async (sub) => {
4689
4689
  const iccid = String(sub.iccid ?? "");
4690
4690
  const [usage, pkgs, loc] = await Promise.all([
4691
- safeCall(ctx.env, token2, "subscriberUsageOverPeriod", {
4691
+ safeCall2(ctx.env, token2, "subscriberUsageOverPeriod", {
4692
4692
  subscriber: { iccid },
4693
4693
  period: usagePeriod
4694
4694
  }),
4695
- safeCall(ctx.env, token2, "listSubscriberPrepaidPackages", { iccid }),
4696
- safeCall(ctx.env, token2, "getSubscriberLocation", { iccid })
4695
+ safeCall2(ctx.env, token2, "listSubscriberPrepaidPackages", { iccid }),
4696
+ safeCall2(ctx.env, token2, "getSubscriberLocation", { iccid })
4697
4697
  ]);
4698
4698
  const dailyRows = extractDailyUsage(usage.data);
4699
4699
  const dailyAvgBytes = dailyRows.length > 0 ? dailyRows.reduce((sum, r) => sum + r.bytes, 0) / dailyRows.length : 0;
@@ -4767,39 +4767,39 @@ ${networksSorted.length} different networks in ${country} \u2014 possible steeri
4767
4767
  sections.push(`3. Run \`optimize_package\` on flagged ICCIDs to find better-fit plans`);
4768
4768
  sections.push(`4. Negotiate better wholesale rates for high-volume countries`);
4769
4769
  }
4770
- return result(sections.join("\n"));
4770
+ return result2(sections.join("\n"));
4771
4771
  });
4772
4772
  server2.registerTool("detect_country_entry", {
4773
4773
  title: "Detect Country Entry",
4774
4774
  description: "Detects when a subscriber has entered a new country by reading networkInfo.lastMcc from getSingleSubscriber (one cheap OCS call \u2014 avoids the per-call cost of getSubscriberLocationByCellId). Resolves MCC \u2192 ISO 3166-1 alpha-2 and optionally diffs against a caller-supplied expectedCountry to return countryChanged. Designed for downstream country-entry upsell workflows (e.g. mango.talk SMS/push offers). NOT AN AI TOOL: this is a deterministic MCC lookup and returns no model-written analysis, unlike the eight intelligence composites. COST NOTE: This tool makes exactly one OCS call per invocation. Consumers running polling crons MUST enforce their own rate floor \u2014 this layer provides no throttle.",
4775
4775
  inputSchema: {
4776
- subscriber: z2.union([
4777
- z2.object({ subscriberId: z2.number() }).describe("Internal subscriber ID"),
4778
- z2.object({ imsi: z2.string() }).describe("IMSI"),
4779
- z2.object({ iccid: z2.string() }).describe("ICCID"),
4780
- z2.object({ msisdn: z2.string() }).describe("MSISDN / phone number"),
4781
- z2.object({ multiImsi: z2.string() }).describe("Multi-IMSI identifier"),
4782
- z2.object({ activationCode: z2.string() }).describe("eSIM activation code")
4776
+ subscriber: z3.union([
4777
+ z3.object({ subscriberId: z3.number() }).describe("Internal subscriber ID"),
4778
+ z3.object({ imsi: z3.string() }).describe("IMSI"),
4779
+ z3.object({ iccid: z3.string() }).describe("ICCID"),
4780
+ z3.object({ msisdn: z3.string() }).describe("MSISDN / phone number"),
4781
+ z3.object({ multiImsi: z3.string() }).describe("Multi-IMSI identifier"),
4782
+ z3.object({ activationCode: z3.string() }).describe("eSIM activation code")
4783
4783
  ]).describe("Subscriber identifier (use exactly one field)"),
4784
- expectedCountry: z2.string().length(2).transform((code) => code.toUpperCase()).optional().describe(
4784
+ expectedCountry: z3.string().length(2).transform((code) => code.toUpperCase()).optional().describe(
4785
4785
  'Caller\u2019s last-known ISO 3166-1 alpha-2 country for this subscriber (e.g. "RU"). When provided, countryChanged is included in the response.'
4786
4786
  )
4787
4787
  },
4788
4788
  annotations: { readOnlyHint: true }
4789
4789
  }, async ({ subscriber, expectedCountry }) => {
4790
4790
  const token2 = await ctx.getUserToken(ctx.props.sub);
4791
- const sub = await safeCall(
4791
+ const sub = await safeCall2(
4792
4792
  ctx.env,
4793
4793
  token2,
4794
4794
  "getSingleSubscriber",
4795
4795
  subscriber
4796
4796
  );
4797
- if (sub.error) return result(`Failed to fetch subscriber: ${sub.error}`, true);
4798
- if (!sub.data) return result("Subscriber not found", true);
4797
+ if (sub.error) return result2(`Failed to fetch subscriber: ${sub.error}`, true);
4798
+ if (!sub.data) return result2("Subscriber not found", true);
4799
4799
  const subscriberId = sub.data.subscriberId ?? sub.data.id ?? ("subscriberId" in subscriber ? subscriber.subscriberId : void 0);
4800
4800
  const networkInfo = sub.data.networkInfo;
4801
4801
  if (networkInfo === null || networkInfo === void 0 || typeof networkInfo !== "object") {
4802
- return result(
4802
+ return result2(
4803
4803
  JSON.stringify({ status: "no_location_data", subscriberId: subscriberId ?? null })
4804
4804
  );
4805
4805
  }
@@ -4807,7 +4807,7 @@ ${networksSorted.length} different networks in ${country} \u2014 possible steeri
4807
4807
  const lastMnc = networkInfo.lastMnc != null ? Number(networkInfo.lastMnc) : null;
4808
4808
  const lastSeenAtUtc = networkInfo.time != null ? String(networkInfo.time) : null;
4809
4809
  if (lastMcc === null || isNaN(lastMcc)) {
4810
- return result(
4810
+ return result2(
4811
4811
  JSON.stringify({ status: "no_location_data", subscriberId: subscriberId ?? null })
4812
4812
  );
4813
4813
  }
@@ -4825,14 +4825,14 @@ ${networksSorted.length} different networks in ${country} \u2014 possible steeri
4825
4825
  response.expectedCountry = expectedCountry;
4826
4826
  response.countryChanged = currentCountry !== null ? currentCountry !== expectedCountry : null;
4827
4827
  }
4828
- return result(JSON.stringify(response, null, 2));
4828
+ return result2(JSON.stringify(response, null, 2));
4829
4829
  });
4830
4830
  }
4831
4831
 
4832
4832
  // src/tools-backlog.ts
4833
- import { z as z3 } from "zod";
4833
+ import { z as z4 } from "zod";
4834
4834
  var DRY_RUN_FIELD2 = {
4835
- dry_run: z3.boolean().optional().describe(
4835
+ dry_run: z4.boolean().optional().describe(
4836
4836
  "If true, do not call OCS \u2014 return the would-be request for confirmation"
4837
4837
  )
4838
4838
  };
@@ -4862,9 +4862,9 @@ function registerAllBacklogTools(server2, ctx) {
4862
4862
  title: "Assign Phone Number to Subscriber",
4863
4863
  description: "Use this to assign a phone number (MSISDN) to a subscriber. Supports both fake/test MSISDNs and real production MSISDNs via the `phone_type` parameter. Required for MSISDN assignment workflows before activating voice services. Params: `iccid` (subscriber identifier), `phone_number` (E.164 format, e.g. +31612345678), `phone_type` ('fake' for test/dev, 'real' for production). Returns: updated subscriber record with the new MSISDN. Do NOT use this to check a subscriber's current MSISDN \u2014 use `get_subscriber` instead.",
4864
4864
  inputSchema: {
4865
- iccid: z3.string().describe("The subscriber ICCID (20-digit ICC identifier)"),
4866
- phone_number: z3.string().describe("E.164 phone number to assign (e.g. +31612345678)"),
4867
- phone_type: z3.enum(["fake", "real"]).describe(
4865
+ iccid: z4.string().describe("The subscriber ICCID (20-digit ICC identifier)"),
4866
+ phone_number: z4.string().describe("E.164 phone number to assign (e.g. +31612345678)"),
4867
+ phone_type: z4.enum(["fake", "real"]).describe(
4868
4868
  "'fake' assigns a test/dev MSISDN (affectSubscriberFakePhoneNumber in OCS); 'real' assigns a production MSISDN (affectSubscriberRealPhoneNumber in OCS)"
4869
4869
  ),
4870
4870
  ...DRY_RUN_FIELD2
@@ -4879,9 +4879,9 @@ function registerAllBacklogTools(server2, ctx) {
4879
4879
  async ({ iccid, phone_number, phone_type }, token2) => {
4880
4880
  const ocsMethod = phone_type === "fake" ? "affectSubscriberFakePhoneNumber" : "affectSubscriberRealPhoneNumber";
4881
4881
  const client2 = new OcsClient(ctx.env.CARRIER_OCS_BASE_URL, token2);
4882
- const result2 = await client2.call(ocsMethod, { subscriber: iccid, phoneNumber: phone_number });
4882
+ const result3 = await client2.call(ocsMethod, { subscriber: iccid, phoneNumber: phone_number });
4883
4883
  return {
4884
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
4884
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
4885
4885
  };
4886
4886
  }
4887
4887
  )
@@ -4892,14 +4892,14 @@ function registerAllBacklogTools(server2, ctx) {
4892
4892
  title: "Get Location by Cell ID (GeoSense)",
4893
4893
  description: "Powered by Bridge4IP GeoSense \u2014 cell-level location resolution with sub-cell accuracy where available. Use this to resolve a cell tower tuple (radio type + MCC + MNC + LAC + optional cellId) to a latitude/longitude estimate. No subscriber identifier required \u2014 caller supplies cell parameters directly. Useful for fraud detection, roaming cost attribution, and network troubleshooting when you have raw cell info from an external source (e.g. a Relay LU webhook event). Params: `radio_type` ('2G'|'3G'|'4G'|'5G'|'NB-IoT'; also accepts 'NBIOT'|'nb-iot'|'nbiot' \u2014 normalised to 'NB-IoT'), `mcc` (int), `mnc` (int), `lac` (int), `cell_id` (int, optional but strongly recommended for accuracy), `signal_strength` (number dBm, optional). Returns: { latitude, longitude, accuracy } \u2014 accuracy is median error in meters at 50% confidence. Without cell_id accuracy degrades significantly (>10 km). Do NOT use this for bulk fleet location sweeps \u2014 one OCS call per cell tower; use `audit_network_coverage` for fleet-level analysis instead.",
4894
4894
  inputSchema: {
4895
- radio_type: z3.string().transform(normalizeRadioType).refine((v) => VALID_RADIO_TYPES.has(v), {
4895
+ radio_type: z4.string().transform(normalizeRadioType).refine((v) => VALID_RADIO_TYPES.has(v), {
4896
4896
  message: "radio_type must be one of: 2G, 3G, 4G, 5G, NB-IoT (also accepts NBIOT, nb-iot, nbiot)"
4897
4897
  }).describe("Radio access technology type: '2G'|'3G'|'4G'|'5G'|'NB-IoT'. Also accepts 'NBIOT'|'nb-iot'|'nbiot' \u2014 normalised to 'NB-IoT'."),
4898
- mcc: z3.number().int().describe("Mobile Country Code (e.g. 250 for Russia, 234 for UK)"),
4899
- mnc: z3.number().int().describe("Mobile Network Code"),
4900
- lac: z3.number().int().describe("Location Area Code"),
4901
- cell_id: z3.number().int().optional().describe("Cell tower ID \u2014 strongly recommended for accuracy"),
4902
- signal_strength: z3.number().optional().describe("Signal strength in dBm (e.g. -89). Optional, improves accuracy.")
4898
+ mcc: z4.number().int().describe("Mobile Country Code (e.g. 250 for Russia, 234 for UK)"),
4899
+ mnc: z4.number().int().describe("Mobile Network Code"),
4900
+ lac: z4.number().int().describe("Location Area Code"),
4901
+ cell_id: z4.number().int().optional().describe("Cell tower ID \u2014 strongly recommended for accuracy"),
4902
+ signal_strength: z4.number().optional().describe("Signal strength in dBm (e.g. -89). Optional, improves accuracy.")
4903
4903
  },
4904
4904
  annotations: { readOnlyHint: true }
4905
4905
  },
@@ -4920,9 +4920,9 @@ function registerAllBacklogTools(server2, ctx) {
4920
4920
  const params = { radioType: radio_type, mcc, mnc, lac };
4921
4921
  if (cell_id !== void 0) params.cellId = cell_id;
4922
4922
  if (signal_strength !== void 0) params.signalStrength = signal_strength;
4923
- const result2 = await client2.call("getSubscriberLocationByCellId", params);
4923
+ const result3 = await client2.call("getSubscriberLocationByCellId", params);
4924
4924
  return {
4925
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
4925
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
4926
4926
  };
4927
4927
  }
4928
4928
  )
@@ -4933,7 +4933,7 @@ function registerAllBacklogTools(server2, ctx) {
4933
4933
  title: "List Destination Lists",
4934
4934
  description: "Use this to retrieve the full catalog of destination lists available to this reseller. A destination list is a named set of phone number prefixes (country codes) that control which numbers a subscriber may call on a voice/SMS package. Returns: array of destination list records, each with `id`, `name`, and prefix count. Do NOT use this to read the prefixes inside a specific list \u2014 use `list_destination_prefixes` with a known `destinationListId` for that. Do NOT use this for data-only eSIM products without MOC voice; destination lists only apply to packages with voice/SMS allowances.",
4935
4935
  inputSchema: {
4936
- resellerId: z3.number().optional().describe("Reseller ID (omit to use the token owner's reseller)")
4936
+ resellerId: z4.number().optional().describe("Reseller ID (omit to use the token owner's reseller)")
4937
4937
  },
4938
4938
  annotations: { readOnlyHint: true }
4939
4939
  },
@@ -4953,9 +4953,9 @@ function registerAllBacklogTools(server2, ctx) {
4953
4953
  return resolvedId;
4954
4954
  })();
4955
4955
  const client2 = new OcsClient(ctx.env.CARRIER_OCS_BASE_URL, token2);
4956
- const result2 = await client2.call("listDetailedDestinationList", id);
4956
+ const result3 = await client2.call("listDetailedDestinationList", id);
4957
4957
  return {
4958
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
4958
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
4959
4959
  };
4960
4960
  }
4961
4961
  )
@@ -4966,8 +4966,8 @@ function registerAllBacklogTools(server2, ctx) {
4966
4966
  title: "Modify Subscriber Mobile Plan",
4967
4967
  description: "Use this to change the mobile pricing plan assigned to a specific subscriber. The mobile plan determines per-country rates for data, voice, and SMS. Changing the plan takes effect immediately on the next OCS rating cycle. Params: `iccid` (subscriber identifier), `mobile_plan_id` (integer plan ID \u2014 obtain valid plan IDs from the OCS reseller settings or `get_tariff`). Returns: updated subscriber record confirming the new plan assignment. Do NOT use this to change package allowances \u2014 use `modify_package_limits` for that. Do NOT use this to change account-level pricing \u2014 this only affects the individual subscriber.",
4968
4968
  inputSchema: {
4969
- iccid: z3.string().describe("The subscriber ICCID (20-digit ICC identifier)"),
4970
- mobile_plan_id: z3.number().describe("The mobile pricing plan ID to assign to this subscriber"),
4969
+ iccid: z4.string().describe("The subscriber ICCID (20-digit ICC identifier)"),
4970
+ mobile_plan_id: z4.number().describe("The mobile pricing plan ID to assign to this subscriber"),
4971
4971
  ...DRY_RUN_FIELD2
4972
4972
  },
4973
4973
  annotations: { destructiveHint: true }
@@ -4979,12 +4979,12 @@ function registerAllBacklogTools(server2, ctx) {
4979
4979
  ctx,
4980
4980
  async ({ iccid, mobile_plan_id }, token2) => {
4981
4981
  const client2 = new OcsClient(ctx.env.CARRIER_OCS_BASE_URL, token2);
4982
- const result2 = await client2.call(
4982
+ const result3 = await client2.call(
4983
4983
  "modifySubscriberMobilePlan",
4984
4984
  { subscriberId: { iccid }, mobilePlanId: mobile_plan_id }
4985
4985
  );
4986
4986
  return {
4987
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
4987
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
4988
4988
  };
4989
4989
  }
4990
4990
  )
@@ -4995,11 +4995,11 @@ function registerAllBacklogTools(server2, ctx) {
4995
4995
  title: "Modify Subscriber Package Active Period",
4996
4996
  description: "Use this to change the start and/or end date of a prepaid package's active period for a specific subscriber. This controls WHEN the package runs, not what it contains. Useful for scheduling packages in advance (e.g. activate on arrival date) or extending a package that would otherwise expire while the subscriber is still travelling. Params: `iccid` (subscriber identifier), `package_id` (from `list_subscriber_packages`), `start_date` (ISO 8601 date, optional), `end_date` (ISO 8601 date, optional). Returns: updated package record with new active period. Do NOT use this to change a package's data/voice allowance \u2014 use `modify_package_limits`. Do NOT use this to change the expiry date of a package \u2014 use `modify_package_expiry`.",
4997
4997
  inputSchema: {
4998
- iccid: z3.string().describe("The subscriber ICCID (20-digit ICC identifier)"),
4999
- package_id: z3.number().describe("The subscriber package ID (from list_subscriber_packages)"),
5000
- start_date: z3.string().optional().describe("New start date in ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss)"),
5001
- end_date: z3.string().optional().describe("New end date in ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss)"),
5002
- comment: z3.string().optional().describe(
4998
+ iccid: z4.string().describe("The subscriber ICCID (20-digit ICC identifier)"),
4999
+ package_id: z4.number().describe("The subscriber package ID (from list_subscriber_packages)"),
5000
+ start_date: z4.string().optional().describe("New start date in ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss)"),
5001
+ end_date: z4.string().optional().describe("New end date in ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss)"),
5002
+ comment: z4.string().optional().describe(
5003
5003
  "Audit note stored on the OCS package record. OCS requires this field, so a default is sent when it is omitted."
5004
5004
  ),
5005
5005
  ...DRY_RUN_FIELD2
@@ -5027,12 +5027,12 @@ function registerAllBacklogTools(server2, ctx) {
5027
5027
  comment,
5028
5028
  current
5029
5029
  });
5030
- const result2 = await client2.call(
5030
+ const result3 = await client2.call(
5031
5031
  "modifySubscriberPrepaidPackageActivePeriod",
5032
5032
  params
5033
5033
  );
5034
5034
  return {
5035
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
5035
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
5036
5036
  };
5037
5037
  }
5038
5038
  )
@@ -5043,8 +5043,8 @@ function registerAllBacklogTools(server2, ctx) {
5043
5043
  title: "Modify Subscriber VoIP Plan",
5044
5044
  description: "Use this to change the VoIP pricing plan assigned to a specific subscriber. VoIP plans control billing rates for VoIP calls made through the OCS platform, separate from the standard mobile plan's call rates. Params: `iccid` (subscriber identifier), `voip_plan_id` (integer VoIP plan ID from the OCS reseller settings). Returns: updated subscriber record confirming the new VoIP plan. Do NOT use this for mobile (non-VoIP) plan changes \u2014 use `modify_subscriber_mobile_plan`. For data-only eSIM products without VoIP services this tool has no effect.",
5045
5045
  inputSchema: {
5046
- iccid: z3.string().describe("The subscriber ICCID (20-digit ICC identifier)"),
5047
- voip_plan_id: z3.number().describe("The VoIP pricing plan ID to assign to this subscriber"),
5046
+ iccid: z4.string().describe("The subscriber ICCID (20-digit ICC identifier)"),
5047
+ voip_plan_id: z4.number().describe("The VoIP pricing plan ID to assign to this subscriber"),
5048
5048
  ...DRY_RUN_FIELD2
5049
5049
  },
5050
5050
  annotations: { destructiveHint: true }
@@ -5056,12 +5056,12 @@ function registerAllBacklogTools(server2, ctx) {
5056
5056
  ctx,
5057
5057
  async ({ iccid, voip_plan_id }, token2) => {
5058
5058
  const client2 = new OcsClient(ctx.env.CARRIER_OCS_BASE_URL, token2);
5059
- const result2 = await client2.call(
5059
+ const result3 = await client2.call(
5060
5060
  "modifySubscriberVoipPlan",
5061
5061
  { subscriberId: { iccid }, voipPlanId: voip_plan_id }
5062
5062
  );
5063
5063
  return {
5064
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
5064
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
5065
5065
  };
5066
5066
  }
5067
5067
  )
@@ -5072,7 +5072,7 @@ function registerAllBacklogTools(server2, ctx) {
5072
5072
  title: "Push Steering List to Subscriber Device",
5073
5073
  description: "Use this AFTER `modify_subscriber_steering_list` to actively push the updated OPLMN (operator preference list) to the subscriber's physical eSIM/SIM. Without this call, the steering list assignment change is recorded in OCS but the device continues using the old operator preference list until it performs a network re-registration. This is required for immediate operator switching (e.g. steering a subscriber away from an expensive roaming partner in real time). Params: `iccid` (subscriber identifier). Returns: push confirmation from OCS with delivery status. Do NOT call this without first calling `modify_subscriber_steering_list` \u2014 pushing without an assigned steering list is a no-op and wastes an OCS call.",
5074
5074
  inputSchema: {
5075
- iccid: z3.string().describe("The subscriber ICCID (20-digit ICC identifier)"),
5075
+ iccid: z4.string().describe("The subscriber ICCID (20-digit ICC identifier)"),
5076
5076
  ...DRY_RUN_FIELD2
5077
5077
  },
5078
5078
  annotations: { destructiveHint: true }
@@ -5084,12 +5084,12 @@ function registerAllBacklogTools(server2, ctx) {
5084
5084
  ctx,
5085
5085
  async ({ iccid }, token2) => {
5086
5086
  const client2 = new OcsClient(ctx.env.CARRIER_OCS_BASE_URL, token2);
5087
- const result2 = await client2.call(
5087
+ const result3 = await client2.call(
5088
5088
  "pushSteeringToSubs",
5089
5089
  { iccid }
5090
5090
  );
5091
5091
  return {
5092
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
5092
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
5093
5093
  };
5094
5094
  }
5095
5095
  )
@@ -5100,7 +5100,7 @@ function registerAllBacklogTools(server2, ctx) {
5100
5100
  title: "Reset Subscriber Green Zone Counter",
5101
5101
  description: "ADMIN: Use this to reset the Green Zone (Greenzone) volume counter for a subscriber. The Green Zone counter tracks bytes consumed on the reseller-defined whitelist of hosts/IPs after the subscriber's bundle is depleted \u2014 NOT the Diameter Gz/Gy accounting interface. Typically used after a billing dispute or test-cycle reset. This operation is IRREVERSIBLE \u2014 volumeOnGZ is permanently zeroed. Params: `iccid` (subscriber identifier). Returns: new counter state with volumeOnGZ (bytes, normally 0 after reset), lastResetDate, lastUpdateDate. Always call `get_subscriber` with `with_gz_counter=true` first to capture the snapshot. Do NOT use this to pause data usage \u2014 use `set_subscriber_traffic_restrictions` with `dataAllowed=false` instead.",
5102
5102
  inputSchema: {
5103
- iccid: z3.string().describe("The subscriber ICCID (20-digit ICC identifier)"),
5103
+ iccid: z4.string().describe("The subscriber ICCID (20-digit ICC identifier)"),
5104
5104
  ...DRY_RUN_FIELD2
5105
5105
  },
5106
5106
  annotations: { destructiveHint: true }
@@ -5112,9 +5112,9 @@ function registerAllBacklogTools(server2, ctx) {
5112
5112
  ctx,
5113
5113
  async ({ iccid }, token2) => {
5114
5114
  const client2 = new OcsClient(ctx.env.CARRIER_OCS_BASE_URL, token2);
5115
- const result2 = await client2.call("resetSubsGzCounter", { iccid });
5115
+ const result3 = await client2.call("resetSubsGzCounter", { iccid });
5116
5116
  return {
5117
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
5117
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
5118
5118
  };
5119
5119
  }
5120
5120
  )
@@ -5125,7 +5125,7 @@ function registerAllBacklogTools(server2, ctx) {
5125
5125
  title: "Carrier Webhook / Relay Flag Status",
5126
5126
  description: "Use this to check the current Bridge4IP webhook and relay flag configuration for this reseller. Returns the active state of all four traffic relay flags: Relay LU (Update Location \u2014 cell tower changes, closest to country-change signal), Relay Gy (mobile data usage events), Relay VoIP (VoIP usage events), Relay calls+SMS (call and SMS events). Also returns which notification webhooks are enabled (prepaid package usage threshold, reseller low credit, ES2 eSIM status, recurring packages) as a passthrough object. All relay/notification configuration is done in the OCS portal UI \u2014 this tool is READ-ONLY and reflects current state. Relay LU is the highest-value flag: when active, Bridge4IP pushes real-time Update Location events (mcc, mnc, lac, cellId) to the configured HTTP endpoint.",
5127
5127
  inputSchema: {
5128
- reseller_id: z3.number().int().optional().describe("Reseller ID (omit to use the token owner's reseller)")
5128
+ reseller_id: z4.number().int().optional().describe("Reseller ID (omit to use the token owner's reseller)")
5129
5129
  },
5130
5130
  annotations: { readOnlyHint: true }
5131
5131
  },
@@ -5145,7 +5145,7 @@ function registerAllBacklogTools(server2, ctx) {
5145
5145
  const raw = await client2.call("getResellerInfo", params);
5146
5146
  const traffic = raw.trafficInfo ?? {};
5147
5147
  const notification = raw.notificationInfo ?? {};
5148
- const result2 = {
5148
+ const result3 = {
5149
5149
  resellerId: raw.id ?? resellerId,
5150
5150
  traffic: {
5151
5151
  relayGy: traffic.relayGy === true,
@@ -5156,7 +5156,7 @@ function registerAllBacklogTools(server2, ctx) {
5156
5156
  notification
5157
5157
  };
5158
5158
  return {
5159
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
5159
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
5160
5160
  };
5161
5161
  }
5162
5162
  )
@@ -5167,7 +5167,7 @@ function registerAllBacklogTools(server2, ctx) {
5167
5167
  title: "List VoIP Tariffs",
5168
5168
  description: "Use this to list VoIP tariff definitions available to a reseller. Despite the OCS method name (listSubscriberVoipTariff), this is a reseller-level catalog listing \u2014 not a per-ICCID lookup. Use results (or get_reseller_info chargingInfo.voipPlan.id) to feed `list_voip_tariff_rule` for rate detail. Params: `reseller_id` (integer, optional \u2014 omit to use the token owner's reseller). Returns: OCS VoIP tariff records (may be empty when no VoIP catalog is configured). Do NOT use this for mobile wholesale rates \u2014 use `get_tariff` (getCustomerTariff). Do NOT use this to assign a VoIP plan \u2014 use `modify_subscriber_voip_plan`.",
5169
5169
  inputSchema: {
5170
- reseller_id: z3.number().int().positive().optional().describe("Reseller ID (omit to list tariffs for the token owner's reseller)")
5170
+ reseller_id: z4.number().int().positive().optional().describe("Reseller ID (omit to list tariffs for the token owner's reseller)")
5171
5171
  },
5172
5172
  annotations: { readOnlyHint: true }
5173
5173
  },
@@ -5182,9 +5182,9 @@ function registerAllBacklogTools(server2, ctx) {
5182
5182
  if (reseller_id !== void 0) {
5183
5183
  params.resellerId = reseller_id;
5184
5184
  }
5185
- const result2 = await client2.call("listSubscriberVoipTariff", params);
5185
+ const result3 = await client2.call("listSubscriberVoipTariff", params);
5186
5186
  return {
5187
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
5187
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
5188
5188
  };
5189
5189
  }
5190
5190
  )
@@ -5195,7 +5195,7 @@ function registerAllBacklogTools(server2, ctx) {
5195
5195
  title: "List VoIP Tariff Rules",
5196
5196
  description: "Use this to list the rate rules (costs) for a specific VoIP plan/tariff. OCS expects a bare integer plan id in the request body (not an object). Obtain plan ids from `get_reseller_info` \u2192 chargingInfo.voipPlan.id, or from `list_subscriber_voip_tariff`. Params: `voip_plan_id` (integer, required \u2014 VoIP plan/tariff id). Returns: VoIP tariff rule rows for that plan, or an OCS error when the id is unknown. Do NOT use this for mobile (non-VoIP) wholesale rates \u2014 use `get_tariff`. Do NOT use this to change a subscriber's VoIP plan \u2014 use `modify_subscriber_voip_plan`.",
5197
5197
  inputSchema: {
5198
- voip_plan_id: z3.number().int().positive().describe(
5198
+ voip_plan_id: z4.number().int().positive().describe(
5199
5199
  "VoIP plan/tariff ID (bare integer to OCS listVoipTariffRule; from get_reseller_info chargingInfo.voipPlan.id or list_subscriber_voip_tariff)"
5200
5200
  )
5201
5201
  },
@@ -5208,9 +5208,9 @@ function registerAllBacklogTools(server2, ctx) {
5208
5208
  ctx,
5209
5209
  async ({ voip_plan_id }, token2) => {
5210
5210
  const client2 = new OcsClient(ctx.env.CARRIER_OCS_BASE_URL, token2);
5211
- let result2;
5211
+ let result3;
5212
5212
  try {
5213
- result2 = await client2.call("listVoipTariffRule", voip_plan_id);
5213
+ result3 = await client2.call("listVoipTariffRule", voip_plan_id);
5214
5214
  } catch (err9) {
5215
5215
  if (err9 instanceof OcsApiError && err9.code === 11) {
5216
5216
  return {
@@ -5228,7 +5228,7 @@ function registerAllBacklogTools(server2, ctx) {
5228
5228
  throw err9;
5229
5229
  }
5230
5230
  return {
5231
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
5231
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
5232
5232
  };
5233
5233
  }
5234
5234
  )
@@ -5239,8 +5239,8 @@ function registerAllBacklogTools(server2, ctx) {
5239
5239
  title: "Change Network Profile of Location Zone",
5240
5240
  description: "Use this to attach or change the network profile on an existing location zone. A network profile defines sponsor/roaming configuration used when the zone is referenced by package templates. Params: `location_zone_id` (integer from list_detailed_location_zones), `network_profile_id` (integer from list_network_profiles). Returns: OCS confirmation of the updated zone/profile binding. Do NOT use this to create a new location zone \u2014 use `create_location_zone` (which requires networkProfileId at creation time). Do NOT use this for edit/delete of zone TADIG lists \u2014 those remain UI-agent-only (G-19).",
5241
5241
  inputSchema: {
5242
- location_zone_id: z3.number().int().positive().describe("Location zone ID (locationZoneId / zoneId from list_detailed_location_zones)"),
5243
- network_profile_id: z3.number().int().positive().describe("Network profile ID (from list_network_profiles)"),
5242
+ location_zone_id: z4.number().int().positive().describe("Location zone ID (locationZoneId / zoneId from list_detailed_location_zones)"),
5243
+ network_profile_id: z4.number().int().positive().describe("Network profile ID (from list_network_profiles)"),
5244
5244
  ...DRY_RUN_FIELD2
5245
5245
  },
5246
5246
  annotations: { destructiveHint: true }
@@ -5255,12 +5255,12 @@ function registerAllBacklogTools(server2, ctx) {
5255
5255
  network_profile_id
5256
5256
  }, token2) => {
5257
5257
  const client2 = new OcsClient(ctx.env.CARRIER_OCS_BASE_URL, token2);
5258
- const result2 = await client2.call("changeNetworkProfileOfLocationZone", {
5258
+ const result3 = await client2.call("changeNetworkProfileOfLocationZone", {
5259
5259
  locationZoneId: location_zone_id,
5260
5260
  networkProfileId: network_profile_id
5261
5261
  });
5262
5262
  return {
5263
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
5263
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
5264
5264
  };
5265
5265
  }
5266
5266
  )
@@ -5268,10 +5268,10 @@ function registerAllBacklogTools(server2, ctx) {
5268
5268
  }
5269
5269
 
5270
5270
  // src/tools-carrier-ask.ts
5271
- import { z as z16 } from "zod";
5271
+ import { z as z17 } from "zod";
5272
5272
 
5273
5273
  // src/tools-ui-agent.ts
5274
- import { z as z4 } from "zod";
5274
+ import { z as z5 } from "zod";
5275
5275
 
5276
5276
  // src/ui-agent-stub.ts
5277
5277
  var REMOTE_MCP_URL = "https://mcp.carrier.llc/mcp";
@@ -5561,13 +5561,13 @@ function wrapPortalHandler(toolName, gapId, requiredScope, ctx, runtime, optIn,
5561
5561
  throw err9;
5562
5562
  }
5563
5563
  try {
5564
- const result2 = await runUiAgent(
5564
+ const result3 = await runUiAgent(
5565
5565
  fullPrompt,
5566
5566
  `Carrier CLI UI Agent: ${toolName} (${gapId})`,
5567
5567
  runtime.env,
5568
5568
  { ownerSub: ctx.props.sub, redact }
5569
5569
  );
5570
- if (!result2.task_id) {
5570
+ if (!result3.task_id) {
5571
5571
  ctx.audit({
5572
5572
  tool_name: toolName,
5573
5573
  ocs_method: ocsMethod,
@@ -5584,38 +5584,38 @@ function wrapPortalHandler(toolName, gapId, requiredScope, ctx, runtime, optIn,
5584
5584
  true
5585
5585
  );
5586
5586
  }
5587
- runtime.dispatchedTaskIds.add(result2.task_id);
5587
+ runtime.dispatchedTaskIds.add(result3.task_id);
5588
5588
  ctx.audit({
5589
5589
  tool_name: toolName,
5590
5590
  ocs_method: ocsMethod,
5591
- status: result2.status === "error" ? "error" : "ui_agent_dispatched",
5591
+ status: result3.status === "error" ? "error" : "ui_agent_dispatched",
5592
5592
  dry_run: false,
5593
5593
  duration_ms: Date.now() - start,
5594
5594
  event_type: "ui_agent_dispatch",
5595
- manus_task_id: result2.task_id
5595
+ manus_task_id: result3.task_id
5596
5596
  // AE blob position is the contract; the name is history
5597
5597
  });
5598
5598
  return jsonResult({
5599
- status: result2.status === "stopped" ? "ui_agent_completed" : result2.status === "waiting" ? "ui_agent_awaiting_input" : result2.status,
5599
+ status: result3.status === "stopped" ? "ui_agent_completed" : result3.status === "waiting" ? "ui_agent_awaiting_input" : result3.status,
5600
5600
  tool: toolName,
5601
5601
  gap_id: gapId,
5602
5602
  // Held still across the vendor swap and across transports: MCP clients
5603
5603
  // and the console read these names.
5604
- steel_task_id: result2.task_id,
5605
- steel_session_viewer_url: result2.session_viewer_url,
5604
+ steel_task_id: result3.task_id,
5605
+ steel_session_viewer_url: result3.session_viewer_url,
5606
5606
  // Redacted defensively. `runUiAgent` already applies the same redactor
5607
5607
  // before the record is stored, so this is the second of two passes over
5608
5608
  // the fields an agent can echo its instructions into. Field-by-field
5609
5609
  // rather than over the serialised JSON: a password containing a quote
5610
5610
  // or a backslash is escaped by JSON.stringify and would no longer match
5611
5611
  // a plain substring replace.
5612
- result: result2.result ? {
5613
- ...result2.result,
5614
- summary: redact(result2.result.summary),
5615
- ...result2.result.entity_id !== void 0 ? { entity_id: redact(result2.result.entity_id) } : {},
5616
- ...result2.result.error_message !== void 0 ? { error_message: redact(result2.result.error_message) } : {}
5612
+ result: result3.result ? {
5613
+ ...result3.result,
5614
+ summary: redact(result3.result.summary),
5615
+ ...result3.result.entity_id !== void 0 ? { entity_id: redact(result3.result.entity_id) } : {},
5616
+ ...result3.result.error_message !== void 0 ? { error_message: redact(result3.result.error_message) } : {}
5617
5617
  } : void 0,
5618
- cost_usd: result2.spend?.costUsd,
5618
+ cost_usd: result3.spend?.costUsd,
5619
5619
  session_spend_usd: runtime.spend.costUsd,
5620
5620
  runs_remaining_this_session: runtime.budget.remaining,
5621
5621
  note: "The run completed in-process \u2014 a local CLI has no background runtime, so this call blocked for its duration.",
@@ -5653,9 +5653,9 @@ function registerAllUiAgentTools(server2, ctx, runtime, optIn = readPortalOptIn(
5653
5653
  title: "Create Steering List (UI Agent)",
5654
5654
  description: "Creates a new network steering list (OPLMN preference configuration) via the OCS web dashboard. This operation is not available via the OCS REST API. A browser agent is dispatched to perform the operation. Params: `name` (steering list name), `description` (optional)." + NOTE,
5655
5655
  inputSchema: {
5656
- name: z4.string().describe("Name for the new steering list"),
5657
- description: z4.string().optional().describe("Optional description for the steering list"),
5658
- dry_run: z4.boolean().optional().describe("Preview the agent prompt without dispatching")
5656
+ name: z5.string().describe("Name for the new steering list"),
5657
+ description: z5.string().optional().describe("Optional description for the steering list"),
5658
+ dry_run: z5.boolean().optional().describe("Preview the agent prompt without dispatching")
5659
5659
  }
5660
5660
  },
5661
5661
  gated(
@@ -5674,11 +5674,11 @@ function registerAllUiAgentTools(server2, ctx, runtime, optIn = readPortalOptIn(
5674
5674
  title: "Build Steering List (UI Agent)",
5675
5675
  description: "Adds or removes operators (MCC-MNC) from an existing steering list via the OCS web dashboard. This operation is not available via the OCS REST API. Params: `steering_list_id`, `add_operators` (array of MCC-MNC to add), `remove_operators` (array to remove), `operator_type` ('priority' or 'excluded')." + NOTE,
5676
5676
  inputSchema: {
5677
- steering_list_id: z4.number().describe("ID of the steering list to modify"),
5678
- add_operators: z4.array(z4.string()).optional().describe("MCC-MNC codes to add (e.g. ['20801', '26201'])"),
5679
- remove_operators: z4.array(z4.string()).optional().describe("MCC-MNC codes to remove"),
5680
- operator_type: z4.enum(["priority", "excluded"]).default("priority").describe("Whether operators are priority or excluded"),
5681
- dry_run: z4.boolean().optional().describe("Preview the agent prompt without dispatching")
5677
+ steering_list_id: z5.number().describe("ID of the steering list to modify"),
5678
+ add_operators: z5.array(z5.string()).optional().describe("MCC-MNC codes to add (e.g. ['20801', '26201'])"),
5679
+ remove_operators: z5.array(z5.string()).optional().describe("MCC-MNC codes to remove"),
5680
+ operator_type: z5.enum(["priority", "excluded"]).default("priority").describe("Whether operators are priority or excluded"),
5681
+ dry_run: z5.boolean().optional().describe("Preview the agent prompt without dispatching")
5682
5682
  }
5683
5683
  },
5684
5684
  gated(
@@ -5697,9 +5697,9 @@ function registerAllUiAgentTools(server2, ctx, runtime, optIn = readPortalOptIn(
5697
5697
  title: "Set Account Steering List (UI Agent)",
5698
5698
  description: "Assigns or removes a steering list at the account level via the OCS web dashboard. The subscriber-level counterpart `modify_subscriber_steering_list` is available via API; this account-level operation is UI-only. Params: `account_id`, `steering_list_id` (0 to remove)." + NOTE,
5699
5699
  inputSchema: {
5700
- account_id: z4.number().describe("Account ID to assign the steering list to"),
5701
- steering_list_id: z4.number().describe("Steering list ID to assign (0 to remove/unset)"),
5702
- dry_run: z4.boolean().optional().describe("Preview the agent prompt without dispatching")
5700
+ account_id: z5.number().describe("Account ID to assign the steering list to"),
5701
+ steering_list_id: z5.number().describe("Steering list ID to assign (0 to remove/unset)"),
5702
+ dry_run: z5.boolean().optional().describe("Preview the agent prompt without dispatching")
5703
5703
  }
5704
5704
  },
5705
5705
  gated(
@@ -5718,11 +5718,11 @@ function registerAllUiAgentTools(server2, ctx, runtime, optIn = readPortalOptIn(
5718
5718
  title: "Request Reseller Relay Change",
5719
5719
  description: "Drafts a parent-reseller/support request for Relay Gy, calls/SMS relay, or VoIP relay when those portal controls are read-only at the current reseller tier. Does not send the request or mutate the portal.",
5720
5720
  inputSchema: {
5721
- reseller_id: z4.number().optional().describe("Reseller id; defaults to the authenticated reseller"),
5722
- relay_gy: z4.boolean().optional().describe("Desired Relay Gy state"),
5723
- relay_calls_sms: z4.boolean().optional().describe("Desired calls/SMS relay state"),
5724
- relay_voip: z4.boolean().optional().describe("Desired VoIP relay state"),
5725
- reason: z4.string().optional().describe("Operational reason for the requested change")
5721
+ reseller_id: z5.number().optional().describe("Reseller id; defaults to the authenticated reseller"),
5722
+ relay_gy: z5.boolean().optional().describe("Desired Relay Gy state"),
5723
+ relay_calls_sms: z5.boolean().optional().describe("Desired calls/SMS relay state"),
5724
+ relay_voip: z5.boolean().optional().describe("Desired VoIP relay state"),
5725
+ reason: z5.string().optional().describe("Operational reason for the requested change")
5726
5726
  }
5727
5727
  },
5728
5728
  async (args) => {
@@ -5814,10 +5814,10 @@ function registerAllUiAgentTools(server2, ctx, runtime, optIn = readPortalOptIn(
5814
5814
  title: "Create Account (UI Agent)",
5815
5815
  description: "Creates a new sub-account under the reseller via the OCS web dashboard. This operation is not available via the OCS REST API. Params: `name` (account name), `description` (optional), `initial_balance` (optional, default 0)." + NOTE,
5816
5816
  inputSchema: {
5817
- name: z4.string().describe("Name for the new account"),
5818
- description: z4.string().optional().describe("Optional description"),
5819
- initial_balance: z4.number().optional().describe("Initial balance in account currency (default 0)"),
5820
- dry_run: z4.boolean().optional().describe("Preview the agent prompt without dispatching")
5817
+ name: z5.string().describe("Name for the new account"),
5818
+ description: z5.string().optional().describe("Optional description"),
5819
+ initial_balance: z5.number().optional().describe("Initial balance in account currency (default 0)"),
5820
+ dry_run: z5.boolean().optional().describe("Preview the agent prompt without dispatching")
5821
5821
  }
5822
5822
  },
5823
5823
  gated(
@@ -5836,10 +5836,10 @@ function registerAllUiAgentTools(server2, ctx, runtime, optIn = readPortalOptIn(
5836
5836
  title: "Create Destination List (UI Agent)",
5837
5837
  description: "Creates a new destination list (named set of phone number prefixes for MOC call permissions) via the OCS web dashboard. Params: `name`, `prefixes` (array of prefix strings), `description`." + NOTE,
5838
5838
  inputSchema: {
5839
- name: z4.string().describe("Name for the new destination list"),
5840
- prefixes: z4.array(z4.string()).optional().describe("Phone number prefixes to include (e.g. ['+31', '+49'])"),
5841
- description: z4.string().optional().describe("Optional description"),
5842
- dry_run: z4.boolean().optional().describe("Preview the agent prompt without dispatching")
5839
+ name: z5.string().describe("Name for the new destination list"),
5840
+ prefixes: z5.array(z5.string()).optional().describe("Phone number prefixes to include (e.g. ['+31', '+49'])"),
5841
+ description: z5.string().optional().describe("Optional description"),
5842
+ dry_run: z5.boolean().optional().describe("Preview the agent prompt without dispatching")
5843
5843
  }
5844
5844
  },
5845
5845
  gated(
@@ -5858,11 +5858,11 @@ function registerAllUiAgentTools(server2, ctx, runtime, optIn = readPortalOptIn(
5858
5858
  title: "Edit Destination List (UI Agent)",
5859
5859
  description: "Edits an existing destination list via the OCS web dashboard. Params: `destination_list_id`, `add_prefixes`, `remove_prefixes`, `new_name`." + NOTE,
5860
5860
  inputSchema: {
5861
- destination_list_id: z4.number().describe("ID of the destination list to edit"),
5862
- add_prefixes: z4.array(z4.string()).optional().describe("Prefixes to add"),
5863
- remove_prefixes: z4.array(z4.string()).optional().describe("Prefixes to remove"),
5864
- new_name: z4.string().optional().describe("Rename the destination list"),
5865
- dry_run: z4.boolean().optional().describe("Preview the agent prompt without dispatching")
5861
+ destination_list_id: z5.number().describe("ID of the destination list to edit"),
5862
+ add_prefixes: z5.array(z5.string()).optional().describe("Prefixes to add"),
5863
+ remove_prefixes: z5.array(z5.string()).optional().describe("Prefixes to remove"),
5864
+ new_name: z5.string().optional().describe("Rename the destination list"),
5865
+ dry_run: z5.boolean().optional().describe("Preview the agent prompt without dispatching")
5866
5866
  }
5867
5867
  },
5868
5868
  gated(
@@ -5881,8 +5881,8 @@ function registerAllUiAgentTools(server2, ctx, runtime, optIn = readPortalOptIn(
5881
5881
  title: "Delete Destination List (UI Agent)",
5882
5882
  description: "Deletes a destination list via the OCS web dashboard. Params: `destination_list_id`. WARNING: This is destructive and cannot be undone." + NOTE,
5883
5883
  inputSchema: {
5884
- destination_list_id: z4.number().describe("ID of the destination list to delete"),
5885
- dry_run: z4.boolean().optional().describe("Preview the agent prompt without dispatching")
5884
+ destination_list_id: z5.number().describe("ID of the destination list to delete"),
5885
+ dry_run: z5.boolean().optional().describe("Preview the agent prompt without dispatching")
5886
5886
  }
5887
5887
  },
5888
5888
  gated(
@@ -5901,8 +5901,8 @@ function registerAllUiAgentTools(server2, ctx, runtime, optIn = readPortalOptIn(
5901
5901
  title: "Delete Package Template (UI Agent)",
5902
5902
  description: "Deletes a package template from the product catalog via the OCS web dashboard. This operation is not available via the OCS REST API. Params: `template_id`. WARNING: This is destructive." + NOTE,
5903
5903
  inputSchema: {
5904
- template_id: z4.number().describe("ID of the package template to delete"),
5905
- dry_run: z4.boolean().optional().describe("Preview the agent prompt without dispatching")
5904
+ template_id: z5.number().describe("ID of the package template to delete"),
5905
+ dry_run: z5.boolean().optional().describe("Preview the agent prompt without dispatching")
5906
5906
  }
5907
5907
  },
5908
5908
  gated(
@@ -5921,11 +5921,11 @@ function registerAllUiAgentTools(server2, ctx, runtime, optIn = readPortalOptIn(
5921
5921
  title: "Edit Location Zone (UI Agent)",
5922
5922
  description: "Edits an existing location zone via the OCS web dashboard. `create_location_zone` is available via API; edit is UI-only. Params: `zone_id`, `new_name`, `add_countries`, `remove_countries`." + NOTE,
5923
5923
  inputSchema: {
5924
- zone_id: z4.number().describe("ID of the location zone to edit"),
5925
- new_name: z4.string().optional().describe("Rename the location zone"),
5926
- add_countries: z4.array(z4.string()).optional().describe("ISO country codes to add (e.g. ['NL', 'DE'])"),
5927
- remove_countries: z4.array(z4.string()).optional().describe("ISO country codes to remove"),
5928
- dry_run: z4.boolean().optional().describe("Preview the agent prompt without dispatching")
5924
+ zone_id: z5.number().describe("ID of the location zone to edit"),
5925
+ new_name: z5.string().optional().describe("Rename the location zone"),
5926
+ add_countries: z5.array(z5.string()).optional().describe("ISO country codes to add (e.g. ['NL', 'DE'])"),
5927
+ remove_countries: z5.array(z5.string()).optional().describe("ISO country codes to remove"),
5928
+ dry_run: z5.boolean().optional().describe("Preview the agent prompt without dispatching")
5929
5929
  }
5930
5930
  },
5931
5931
  gated(
@@ -5944,8 +5944,8 @@ function registerAllUiAgentTools(server2, ctx, runtime, optIn = readPortalOptIn(
5944
5944
  title: "Delete Location Zone (UI Agent)",
5945
5945
  description: "Deletes a location zone via the OCS web dashboard. `create_location_zone` is available via API; delete is UI-only. Params: `zone_id`. WARNING: Zones in use by active templates may not be deletable." + NOTE,
5946
5946
  inputSchema: {
5947
- zone_id: z4.number().describe("ID of the location zone to delete"),
5948
- dry_run: z4.boolean().optional().describe("Preview the agent prompt without dispatching")
5947
+ zone_id: z5.number().describe("ID of the location zone to delete"),
5948
+ dry_run: z5.boolean().optional().describe("Preview the agent prompt without dispatching")
5949
5949
  }
5950
5950
  },
5951
5951
  gated(
@@ -5961,7 +5961,7 @@ function registerAllUiAgentTools(server2, ctx, runtime, optIn = readPortalOptIn(
5961
5961
  }
5962
5962
 
5963
5963
  // src/tools-ui-agent-ask.ts
5964
- import { z as z5 } from "zod";
5964
+ import { z as z6 } from "zod";
5965
5965
  var UI_AGENT_ASK_TOOL_SCOPES = {
5966
5966
  ui_agent_reply: "write",
5967
5967
  ui_agent_list_pending: "read"
@@ -6013,8 +6013,8 @@ function registerUiAgentAskTools(server2, ctx, runtime) {
6013
6013
  title: "Reply to Paused UI Agent Task",
6014
6014
  description: "Resumes a browser automation task that paused to ask a question. Use ui_agent_list_pending to find tasks waiting for input. Provide the task_id and your reply (e.g. a 2FA code, a field value, or a yes/no answer). The reply content is never recorded in audit logs \u2014 only its length is logged.",
6015
6015
  inputSchema: {
6016
- task_id: z5.string().describe("Task ID to resume (from ui_agent_list_pending)"),
6017
- reply: z5.string().describe(
6016
+ task_id: z6.string().describe("Task ID to resume (from ui_agent_list_pending)"),
6017
+ reply: z6.string().describe(
6018
6018
  "Your answer to the agent's question (e.g. a 2FA code or confirmation)"
6019
6019
  )
6020
6020
  }
@@ -6184,7 +6184,7 @@ function registerUiAgentAskTools(server2, ctx, runtime) {
6184
6184
  }
6185
6185
 
6186
6186
  // src/carrier-api-tools.ts
6187
- import { z as z6 } from "zod";
6187
+ import { z as z7 } from "zod";
6188
6188
  var CARRIER_API_TOOL_SCOPES = {
6189
6189
  list_connectivity_offering_templates: "read",
6190
6190
  create_benefit_campaign: "write",
@@ -6291,12 +6291,12 @@ function registerCarrierApiTools(server2, ctx) {
6291
6291
  title: "Create a benefit campaign",
6292
6292
  description: "Create a member-benefit campaign: a capped number of eSIM claims for one offering revision, each costing a fixed amount from your sponsor wallet. Calls POST /v1/connectivity/benefit-campaigns on api.carrier.llc with your own MCP access token and returns the new campaign id. Needs write scope. A campaign cannot be deleted once created. cost_cents above the deployment ceiling is rejected with cost_above_limit and creates nothing. Params: offering_id, revision (>=1), max_claims (>=1), cost_cents (>=1, per claim), expires_at (epoch milliseconds), product_id (optional, an active product of your organization). Do NOT use this to claim or issue an eSIM \u2014 that is claim_benefit and issue_benefit_claim.",
6293
6293
  inputSchema: {
6294
- offering_id: z6.string().min(1).max(200).describe("Offering the campaign issues from."),
6295
- revision: z6.number().int().min(1).max(Number.MAX_SAFE_INTEGER).describe("Offering revision, 1 or higher."),
6296
- max_claims: z6.number().int().min(1).max(Number.MAX_SAFE_INTEGER).describe("Most claims the campaign accepts."),
6297
- cost_cents: z6.number().int().min(1).max(Number.MAX_SAFE_INTEGER).describe("Cost of one claim in cents. The API enforces a ceiling."),
6298
- expires_at: z6.number().int().min(1).max(Number.MAX_SAFE_INTEGER).describe("Expiry as epoch milliseconds."),
6299
- product_id: z6.string().min(1).max(200).optional().describe("Optional product to issue from.")
6294
+ offering_id: z7.string().min(1).max(200).describe("Offering the campaign issues from."),
6295
+ revision: z7.number().int().min(1).max(Number.MAX_SAFE_INTEGER).describe("Offering revision, 1 or higher."),
6296
+ max_claims: z7.number().int().min(1).max(Number.MAX_SAFE_INTEGER).describe("Most claims the campaign accepts."),
6297
+ cost_cents: z7.number().int().min(1).max(Number.MAX_SAFE_INTEGER).describe("Cost of one claim in cents. The API enforces a ceiling."),
6298
+ expires_at: z7.number().int().min(1).max(Number.MAX_SAFE_INTEGER).describe("Expiry as epoch milliseconds."),
6299
+ product_id: z7.string().min(1).max(200).optional().describe("Optional product to issue from.")
6300
6300
  },
6301
6301
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true }
6302
6302
  },
@@ -6326,8 +6326,8 @@ function registerCarrierApiTools(server2, ctx) {
6326
6326
  title: "Claim a benefit",
6327
6327
  description: "Claim one benefit from a campaign for an external reference, which places a hold on the sponsor wallet. Calls POST /v1/connectivity/benefit-campaigns/{id}/claims on api.carrier.llc with your own MCP access token. Needs write scope. Safe to repeat with the same external_ref: the same claim comes back (HTTP 200) and nothing is held twice. Results: 201 held, 200 replay of an existing claim, 202 funding outcome unknown (repeat the call), 402 wallet cannot fund the claim, 409 campaign paused, expired or full. Params: campaign_id (cbc_ plus 32 hex), external_ref (1 to 200 characters, your own reference for the person). Do NOT use this to issue the eSIM \u2014 that is issue_benefit_claim, called with the claim id from this result.",
6328
6328
  inputSchema: {
6329
- campaign_id: z6.string().regex(CAMPAIGN_ID_PATTERN).describe("Campaign id, cbc_ followed by 32 hex characters."),
6330
- external_ref: z6.string().min(1).max(200).describe("Your own reference for the claimant, 1 to 200 characters.")
6329
+ campaign_id: z7.string().regex(CAMPAIGN_ID_PATTERN).describe("Campaign id, cbc_ followed by 32 hex characters."),
6330
+ external_ref: z7.string().min(1).max(200).describe("Your own reference for the claimant, 1 to 200 characters.")
6331
6331
  },
6332
6332
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true }
6333
6333
  },
@@ -6353,8 +6353,8 @@ function registerCarrierApiTools(server2, ctx) {
6353
6353
  title: "Issue the eSIM for a held claim",
6354
6354
  description: "Issue ONE REAL eSIM for a held claim and settle the wallet hold. This spends money and cannot be undone. Calls POST /v1/connectivity/benefit-campaigns/{id}/claims/{claimId}/issue on api.carrier.llc with your own MCP access token. Needs write scope. A retry returns the same eSIM and never a second one, but do not retry blindly: on 202 the outcome is unknown and the hold is kept, so wait and call again once. Results: 200 settled with the eSIM, 202 outcome unknown, 404 not found (or issuing is switched off), 409 the claim is not issuable. Params: campaign_id (cbc_ plus 32 hex), claim_id (cbl_ plus 32 hex, from claim_benefit). No other params. Do NOT use this before claim_benefit returned a held claim.",
6355
6355
  inputSchema: {
6356
- campaign_id: z6.string().regex(CAMPAIGN_ID_PATTERN).describe("Campaign id, cbc_ followed by 32 hex characters."),
6357
- claim_id: z6.string().regex(CLAIM_ID_PATTERN).describe("Claim id from claim_benefit, cbl_ followed by 32 hex characters.")
6356
+ campaign_id: z7.string().regex(CAMPAIGN_ID_PATTERN).describe("Campaign id, cbc_ followed by 32 hex characters."),
6357
+ claim_id: z7.string().regex(CLAIM_ID_PATTERN).describe("Claim id from claim_benefit, cbl_ followed by 32 hex characters.")
6358
6358
  },
6359
6359
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
6360
6360
  },
@@ -6380,8 +6380,8 @@ function registerCarrierApiTools(server2, ctx) {
6380
6380
  title: "Pause or resume a benefit campaign",
6381
6381
  description: "Pause a campaign so it accepts no new claims, or resume it. Calls POST /v1/connectivity/benefit-campaigns/{id}/status on api.carrier.llc with your own MCP access token. Needs write scope. Pausing blocks NEW claims; it does not release holds that were already made. Params: campaign_id (cbc_ plus 32 hex), status (active or paused).",
6382
6382
  inputSchema: {
6383
- campaign_id: z6.string().regex(CAMPAIGN_ID_PATTERN).describe("Campaign id, cbc_ followed by 32 hex characters."),
6384
- status: z6.enum(["active", "paused"]).describe("The status to set.")
6383
+ campaign_id: z7.string().regex(CAMPAIGN_ID_PATTERN).describe("Campaign id, cbc_ followed by 32 hex characters."),
6384
+ status: z7.enum(["active", "paused"]).describe("The status to set.")
6385
6385
  },
6386
6386
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true }
6387
6387
  },
@@ -6407,9 +6407,9 @@ function registerCarrierApiTools(server2, ctx) {
6407
6407
  title: "Issue a claim right for a booking reference",
6408
6408
  description: "Issue ONE single-use right for one external booking or member reference, which the claimant presents to claim a benefit. Calls POST /v1/connectivity/benefit-campaigns/{id}/entitlements on api.carrier.llc with your own MCP access token. Needs write scope. The token is returned once and is never stored in plain text; a second right for the same reference is refused. Params: campaign_id (cbc_ plus 32 hex), external_ref (1 to 200 characters), ttl_ms (optional lifetime in milliseconds).",
6409
6409
  inputSchema: {
6410
- campaign_id: z6.string().regex(CAMPAIGN_ID_PATTERN).describe("Campaign id, cbc_ followed by 32 hex characters."),
6411
- external_ref: z6.string().min(1).max(200).describe("Your own reference for the person, 1 to 200 characters."),
6412
- ttl_ms: z6.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional().describe("Lifetime of the right in milliseconds. Defaults to 30 days.")
6410
+ campaign_id: z7.string().regex(CAMPAIGN_ID_PATTERN).describe("Campaign id, cbc_ followed by 32 hex characters."),
6411
+ external_ref: z7.string().min(1).max(200).describe("Your own reference for the person, 1 to 200 characters."),
6412
+ ttl_ms: z7.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional().describe("Lifetime of the right in milliseconds. Defaults to 30 days.")
6413
6413
  },
6414
6414
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true }
6415
6415
  },
@@ -6438,8 +6438,8 @@ function registerCarrierApiTools(server2, ctx) {
6438
6438
  title: "Close a claim whose issuance outcome is unknown",
6439
6439
  description: "Ask the provider what happened to a claim whose issuance ended in an unknown outcome. Calls POST /v1/connectivity/benefit-campaigns/{id}/claims/{claimId}/reconcile on api.carrier.llc with your own MCP access token. Needs write scope. It never dispatches a second eSIM: it reads the existing issuance under the same claim id. Results: 200 the claim is closed, 202 the outcome is still unknown (call again later), 409 the claim never started issuing or is not held. Params: campaign_id (cbc_ plus 32 hex), claim_id (cbl_ plus 32 hex).",
6440
6440
  inputSchema: {
6441
- campaign_id: z6.string().regex(CAMPAIGN_ID_PATTERN).describe("Campaign id, cbc_ followed by 32 hex characters."),
6442
- claim_id: z6.string().regex(CLAIM_ID_PATTERN).describe("Claim id, cbl_ followed by 32 hex characters.")
6441
+ campaign_id: z7.string().regex(CAMPAIGN_ID_PATTERN).describe("Campaign id, cbc_ followed by 32 hex characters."),
6442
+ claim_id: z7.string().regex(CLAIM_ID_PATTERN).describe("Claim id, cbl_ followed by 32 hex characters.")
6443
6443
  },
6444
6444
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true }
6445
6445
  },
@@ -6465,11 +6465,11 @@ function registerCarrierApiTools(server2, ctx) {
6465
6465
  title: "Record one experiment event",
6466
6466
  description: "Record ONE event of an experiment: what a participant saw or did. Calls POST /v1/connectivity/experiment-events on api.carrier.llc with your own MCP access token. Needs write scope. Safe to repeat with the same event_id: the event is stored once and the replay returns 200. Params: event_id (your own id for this event), experiment_id, revision (>=1), link (the participant), measure (viewed, confirmed, issued or first_data).",
6467
6467
  inputSchema: {
6468
- event_id: z6.string().min(1).max(200).describe("Your own id for this event."),
6469
- experiment_id: z6.string().min(1).max(200).describe("The experiment this event belongs to."),
6470
- revision: z6.number().int().min(1).max(Number.MAX_SAFE_INTEGER).describe("The revision of the experiment."),
6471
- link: z6.string().min(1).max(200).describe("The participant this event is about."),
6472
- measure: z6.enum(["viewed", "confirmed", "issued", "first_data"]).describe("What the participant did.")
6468
+ event_id: z7.string().min(1).max(200).describe("Your own id for this event."),
6469
+ experiment_id: z7.string().min(1).max(200).describe("The experiment this event belongs to."),
6470
+ revision: z7.number().int().min(1).max(Number.MAX_SAFE_INTEGER).describe("The revision of the experiment."),
6471
+ link: z7.string().min(1).max(200).describe("The participant this event is about."),
6472
+ measure: z7.enum(["viewed", "confirmed", "issued", "first_data"]).describe("What the participant did.")
6473
6473
  },
6474
6474
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true }
6475
6475
  },
@@ -6498,9 +6498,9 @@ function registerCarrierApiTools(server2, ctx) {
6498
6498
  title: "Counts for one experiment",
6499
6499
  description: "Count the events of one experiment per measure inside a time window. Calls GET /v1/connectivity/experiment-events/{experimentId}/report on api.carrier.llc with your own MCP access token. Needs read scope. The counts describe what happened; they do not say why. A measure without events is absent, never zero. Params: experiment_id, from and to (epoch milliseconds, to is exclusive).",
6500
6500
  inputSchema: {
6501
- experiment_id: z6.string().min(1).max(200).describe("The experiment to report on."),
6502
- from: z6.number().int().min(0).max(Number.MAX_SAFE_INTEGER).describe("Start of the window, epoch milliseconds."),
6503
- to: z6.number().int().min(0).max(Number.MAX_SAFE_INTEGER).describe("End of the window, epoch milliseconds, exclusive.")
6501
+ experiment_id: z7.string().min(1).max(200).describe("The experiment to report on."),
6502
+ from: z7.number().int().min(0).max(Number.MAX_SAFE_INTEGER).describe("Start of the window, epoch milliseconds."),
6503
+ to: z7.number().int().min(0).max(Number.MAX_SAFE_INTEGER).describe("End of the window, epoch milliseconds, exclusive.")
6504
6504
  },
6505
6505
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
6506
6506
  },
@@ -6522,7 +6522,7 @@ function registerCarrierApiTools(server2, ctx) {
6522
6522
  }
6523
6523
 
6524
6524
  // src/tools-ui-agent-schedule.ts
6525
- import { z as z7 } from "zod";
6525
+ import { z as z8 } from "zod";
6526
6526
  var UI_AGENT_SCHEDULE_TOOL_SCOPES = {
6527
6527
  ui_agent_schedule_create: "admin",
6528
6528
  ui_agent_schedule_list: "read",
@@ -6560,14 +6560,14 @@ function registerScheduleAndUsageTools(server2, ctx, runtime) {
6560
6560
  title: "Create UI Agent Schedule",
6561
6561
  description: "Creates a recurring browser-agent run on a cron schedule, to automate periodic OCS audits, fleet health checks, or any recurring browser-automation task. Minimum interval: 5 minutes. Requires admin scope." + STDIO_NOTE,
6562
6562
  inputSchema: {
6563
- name: z7.string().describe("Human-readable name for this schedule"),
6564
- cron: z7.string().describe(
6563
+ name: z8.string().describe("Human-readable name for this schedule"),
6564
+ cron: z8.string().describe(
6565
6565
  "Standard 5-field cron expression (minute hour day month weekday). Minimum interval: 5 minutes. Example: '0 */6 * * *' = every 6 hours."
6566
6566
  ),
6567
- prompt_template: z7.string().describe(
6567
+ prompt_template: z8.string().describe(
6568
6568
  "Agent prompt/task template the browser agent will execute on each run"
6569
6569
  ),
6570
- profile: z7.string().optional().describe(
6570
+ profile: z8.string().optional().describe(
6571
6571
  "Browser-agent profile to use. Defaults to the deployment's configured profile."
6572
6572
  )
6573
6573
  }
@@ -6589,7 +6589,7 @@ function registerScheduleAndUsageTools(server2, ctx, runtime) {
6589
6589
  title: "Delete UI Agent Schedule",
6590
6590
  description: "Permanently deletes a recurring browser-agent schedule. This cannot be undone. Use ui_agent_schedule_pause to temporarily suspend instead. Requires admin scope." + STDIO_NOTE,
6591
6591
  inputSchema: {
6592
- schedule_id: z7.string().describe("ID of the schedule to delete")
6592
+ schedule_id: z8.string().describe("ID of the schedule to delete")
6593
6593
  }
6594
6594
  },
6595
6595
  async () => !ctx.props.scope.includes("admin") ? scopeDenied(ctx, "ui_agent_schedule_delete", "admin") : uiAgentStubError("ui_agent_schedule_delete", "recurring_runtime")
@@ -6600,7 +6600,7 @@ function registerScheduleAndUsageTools(server2, ctx, runtime) {
6600
6600
  title: "Pause UI Agent Schedule",
6601
6601
  description: "Pauses an active recurring browser-agent schedule. The schedule is preserved and can be resumed later with ui_agent_schedule_resume. Requires admin scope." + STDIO_NOTE,
6602
6602
  inputSchema: {
6603
- schedule_id: z7.string().describe("ID of the schedule to pause")
6603
+ schedule_id: z8.string().describe("ID of the schedule to pause")
6604
6604
  }
6605
6605
  },
6606
6606
  async () => !ctx.props.scope.includes("admin") ? scopeDenied(ctx, "ui_agent_schedule_pause", "admin") : uiAgentStubError("ui_agent_schedule_pause", "recurring_runtime")
@@ -6611,7 +6611,7 @@ function registerScheduleAndUsageTools(server2, ctx, runtime) {
6611
6611
  title: "Resume UI Agent Schedule",
6612
6612
  description: "Resumes a paused recurring browser-agent schedule. Requires admin scope." + STDIO_NOTE,
6613
6613
  inputSchema: {
6614
- schedule_id: z7.string().describe("ID of the schedule to resume")
6614
+ schedule_id: z8.string().describe("ID of the schedule to resume")
6615
6615
  }
6616
6616
  },
6617
6617
  async () => !ctx.props.scope.includes("admin") ? scopeDenied(ctx, "ui_agent_schedule_resume", "admin") : uiAgentStubError("ui_agent_schedule_resume", "recurring_runtime")
@@ -6668,7 +6668,7 @@ function registerScheduleAndUsageTools(server2, ctx, runtime) {
6668
6668
  }
6669
6669
 
6670
6670
  // src/wallet-tools.ts
6671
- import { z as z8 } from "zod";
6671
+ import { z as z9 } from "zod";
6672
6672
  import * as Sentry2 from "@sentry/cloudflare";
6673
6673
 
6674
6674
  // src/audit-schema.ts
@@ -6996,15 +6996,15 @@ async function createTopupCheckout(env, args) {
6996
6996
  } else {
6997
6997
  params.set("customer_creation", "always");
6998
6998
  }
6999
- const result2 = await stripePostForm(
6999
+ const result3 = await stripePostForm(
7000
7000
  stripeKey,
7001
7001
  "/v1/checkout/sessions",
7002
7002
  params
7003
7003
  );
7004
- if (!result2.ok) {
7005
- throw new Error(`Stripe checkout session create failed: ${JSON.stringify(result2.data)}`);
7004
+ if (!result3.ok) {
7005
+ throw new Error(`Stripe checkout session create failed: ${JSON.stringify(result3.data)}`);
7006
7006
  }
7007
- return { id: result2.data.id, url: result2.data.url };
7007
+ return { id: result3.data.id, url: result3.data.url };
7008
7008
  }
7009
7009
  async function runAutoTopup(env, args) {
7010
7010
  const stripeKey = env.STRIPE_SECRET_KEY;
@@ -7128,13 +7128,13 @@ function registerWalletTools(server2, ctx) {
7128
7128
  // — returns null here. Requiring a number turned that, the most common
7129
7129
  // state a new operator is in, into an output validation error.
7130
7130
  outputSchema: {
7131
- org_id: z8.string().describe("Carrier organisation the wallet belongs to"),
7132
- balance_eur_cents: z8.number().int().describe("Current balance in EUR cents"),
7133
- auto_topup_enabled: z8.boolean(),
7134
- auto_topup_threshold_cents: z8.number().int().nullable().describe(
7131
+ org_id: z9.string().describe("Carrier organisation the wallet belongs to"),
7132
+ balance_eur_cents: z9.number().int().describe("Current balance in EUR cents"),
7133
+ auto_topup_enabled: z9.boolean(),
7134
+ auto_topup_threshold_cents: z9.number().int().nullable().describe(
7135
7135
  "Balance at or below which an auto top-up fires, EUR cents. Null when auto-top-up is unconfigured."
7136
7136
  ),
7137
- auto_topup_pack_cents: z8.number().int().nullable().describe(
7137
+ auto_topup_pack_cents: z9.number().int().nullable().describe(
7138
7138
  "Amount an auto top-up charges, EUR cents. Null when auto-top-up is unconfigured."
7139
7139
  )
7140
7140
  },
@@ -7176,7 +7176,7 @@ function registerWalletTools(server2, ctx) {
7176
7176
  title: "Wallet Top-up Checkout",
7177
7177
  description: "Create a Stripe Checkout link so a human can top up the Carrier prepaid wallet by card. This tool charges nothing itself: it returns a hosted URL, and the wallet is credited (pack amount + bonus) only after someone completes the payment in a browser. Params: `pack` (optional \u2014 pack id `pack_25`/`pack_50`/`pack_100`/`pack_500`/`pack_1000`/`pack_2500`/`pack_5000`, or an exact EUR-cents amount matching a catalog pack; omit to list the packs and their bonuses without creating a session). Returns: { pack_id, pack_eur_cents, bonus_eur_cents, checkout_session_id, checkout_url } \u2014 amounts in EUR cents. Do NOT use this when the wallet must be funded now with no human in the loop \u2014 use `wallet_auto_topup`, which charges the saved card immediately. Do NOT use this to move money in OCS \u2014 `modify_account_balance` and `modify_subscriber_balance` are unrelated ledgers.",
7178
7178
  inputSchema: {
7179
- pack: z8.string().optional().describe(
7179
+ pack: z9.string().optional().describe(
7180
7180
  "Pack id (pack_25/pack_50/pack_100/pack_500/pack_1000/pack_2500/pack_5000) or exact EUR-cents amount. Omit to list packs."
7181
7181
  )
7182
7182
  },
@@ -7189,21 +7189,21 @@ function registerWalletTools(server2, ctx) {
7189
7189
  * documented here. Marking either arm required would break the other.
7190
7190
  */
7191
7191
  outputSchema: {
7192
- packs: z8.array(
7193
- z8.object({
7194
- id: z8.string(),
7195
- eur_cents: z8.number().int(),
7196
- bonus_pct: z8.number(),
7197
- bonus_eur_cents: z8.number().int(),
7198
- credited_eur_cents: z8.number().int()
7192
+ packs: z9.array(
7193
+ z9.object({
7194
+ id: z9.string(),
7195
+ eur_cents: z9.number().int(),
7196
+ bonus_pct: z9.number(),
7197
+ bonus_eur_cents: z9.number().int(),
7198
+ credited_eur_cents: z9.number().int()
7199
7199
  })
7200
7200
  ).optional().describe("Catalogue arm \u2014 present only when `pack` was omitted."),
7201
- org_id: z8.string().optional().describe("Session arm."),
7202
- pack_id: z8.string().optional().describe("Session arm."),
7203
- pack_eur_cents: z8.number().int().optional().describe("Session arm."),
7204
- bonus_eur_cents: z8.number().int().optional().describe("Session arm."),
7205
- checkout_session_id: z8.string().optional().describe("Session arm."),
7206
- checkout_url: z8.string().nullable().optional().describe("Session arm. Stripe may return null for a session URL.")
7201
+ org_id: z9.string().optional().describe("Session arm."),
7202
+ pack_id: z9.string().optional().describe("Session arm."),
7203
+ pack_eur_cents: z9.number().int().optional().describe("Session arm."),
7204
+ bonus_eur_cents: z9.number().int().optional().describe("Session arm."),
7205
+ checkout_session_id: z9.string().optional().describe("Session arm."),
7206
+ checkout_url: z9.string().nullable().optional().describe("Session arm. Stripe may return null for a session URL.")
7207
7207
  },
7208
7208
  annotations: annotationsFor("wallet_topup_checkout", "write")
7209
7209
  },
@@ -7260,7 +7260,7 @@ function registerWalletTools(server2, ctx) {
7260
7260
  title: "Wallet Auto Top-up (charges card now)",
7261
7261
  description: "Charge the organisation's saved card off-session, right now, and credit the Carrier prepaid wallet with the pack. This spends real money without any browser step or human confirmation, so only call it when the user has asked to be charged. Params: `pack_cents` (optional integer, EUR cents \u2014 must match a catalog pack; omit to use the organisation's configured auto-top-up pack). Returns on success: { org_id, charged: true, credited_eur_cents, balance_after_cents, payment_intent_id } \u2014 amounts in EUR cents. Returns { charged: false, reason } as an error when the card declines or no payment method is saved. Do NOT use this to let a human pay in a browser \u2014 use `wallet_topup_checkout`, which only returns a link. Do NOT use this to change the threshold that triggers automatic top-ups; this tool performs one charge and does not edit the configuration. Do NOT use this to credit an OCS reseller account or subscriber \u2014 see `modify_account_balance` and `modify_subscriber_balance`.",
7262
7262
  inputSchema: {
7263
- pack_cents: z8.number().int().positive().optional().describe("Override pack amount in EUR cents (must match a catalog pack).")
7263
+ pack_cents: z9.number().int().positive().optional().describe("Override pack amount in EUR cents (must match a catalog pack).")
7264
7264
  },
7265
7265
  /**
7266
7266
  * Only the charged arm is described here — `charged: false` returns
@@ -7275,12 +7275,12 @@ function registerWalletTools(server2, ctx) {
7275
7275
  * into a validation error.
7276
7276
  */
7277
7277
  outputSchema: {
7278
- org_id: z8.string(),
7279
- charged: z8.literal(true),
7280
- credited_eur_cents: z8.number().int(),
7281
- balance_after_cents: z8.number().int().optional().describe("Absent when the charge succeeded but crediting is pending."),
7282
- payment_intent_id: z8.string().optional(),
7283
- note: z8.string().optional().describe("Present when the charge landed but the credit is still pending.")
7278
+ org_id: z9.string(),
7279
+ charged: z9.literal(true),
7280
+ credited_eur_cents: z9.number().int(),
7281
+ balance_after_cents: z9.number().int().optional().describe("Absent when the charge succeeded but crediting is pending."),
7282
+ payment_intent_id: z9.string().optional(),
7283
+ note: z9.string().optional().describe("Present when the charge landed but the credit is still pending.")
7284
7284
  },
7285
7285
  annotations: annotationsFor("wallet_auto_topup", "write")
7286
7286
  },
@@ -7290,32 +7290,32 @@ function registerWalletTools(server2, ctx) {
7290
7290
  const orgId = defaultOrgId;
7291
7291
  const start = Date.now();
7292
7292
  try {
7293
- const result2 = await runAutoTopup(env, { orgId, sub: props2.sub, packCents: pack_cents });
7293
+ const result3 = await runAutoTopup(env, { orgId, sub: props2.sub, packCents: pack_cents });
7294
7294
  writeAudit(env, {
7295
7295
  tool_name: "wallet_auto_topup",
7296
7296
  ocs_method: "stripe.payment_intent.off_session",
7297
- status: result2.charged ? "ok" : "error",
7297
+ status: result3.charged ? "ok" : "error",
7298
7298
  dry_run: false,
7299
7299
  duration_ms: Date.now() - start,
7300
7300
  sub: props2.sub,
7301
7301
  reseller_id: props2.reseller_id
7302
7302
  });
7303
- if (!result2.charged) {
7303
+ if (!result3.charged) {
7304
7304
  return err(
7305
- JSON.stringify({ org_id: orgId, charged: false, reason: result2.reason })
7305
+ JSON.stringify({ org_id: orgId, charged: false, reason: result3.reason })
7306
7306
  );
7307
7307
  }
7308
7308
  return okStructured({
7309
7309
  org_id: orgId,
7310
7310
  charged: true,
7311
- credited_eur_cents: result2.creditedCents,
7311
+ credited_eur_cents: result3.creditedCents,
7312
7312
  // Spread rather than assign, so the key is absent instead of set to
7313
7313
  // `undefined`. JSON.stringify drops an undefined value anyway, so
7314
7314
  // assigning it would make `content` and `structuredContent` disagree
7315
7315
  // about whether the field is there.
7316
- ...result2.balanceAfterCents !== void 0 ? { balance_after_cents: result2.balanceAfterCents } : {},
7317
- ...result2.paymentIntentId !== void 0 ? { payment_intent_id: result2.paymentIntentId } : {},
7318
- ...result2.reason ? { note: result2.reason } : {}
7316
+ ...result3.balanceAfterCents !== void 0 ? { balance_after_cents: result3.balanceAfterCents } : {},
7317
+ ...result3.paymentIntentId !== void 0 ? { payment_intent_id: result3.paymentIntentId } : {},
7318
+ ...result3.reason ? { note: result3.reason } : {}
7319
7319
  });
7320
7320
  } catch (e) {
7321
7321
  Sentry2.captureException(e);
@@ -7326,7 +7326,7 @@ function registerWalletTools(server2, ctx) {
7326
7326
  }
7327
7327
 
7328
7328
  // src/stripe-connect-tools.ts
7329
- import { z as z9 } from "zod";
7329
+ import { z as z10 } from "zod";
7330
7330
  import * as Sentry3 from "@sentry/cloudflare";
7331
7331
 
7332
7332
  // src/binding-unavailable.ts
@@ -7482,7 +7482,7 @@ function registerStripeConnectTools(server2, ctx) {
7482
7482
  title: "Stripe Connect Status",
7483
7483
  description: "Read-only: returns the Stripe Connect account status, capabilities, and requirements for the authenticated operator.",
7484
7484
  inputSchema: {
7485
- operator_id: z9.string().optional().describe("Override operator_id (admin use). Defaults to caller's org/user.")
7485
+ operator_id: z10.string().optional().describe("Override operator_id (admin use). Defaults to caller's org/user.")
7486
7486
  },
7487
7487
  annotations: annotationsFor("stripe_connect_status", "read")
7488
7488
  },
@@ -7506,9 +7506,9 @@ function registerStripeConnectTools(server2, ctx) {
7506
7506
  if (!accountId) {
7507
7507
  return ok(JSON.stringify({ status: "not_connected", operator_id: opId }));
7508
7508
  }
7509
- const result2 = await stripeGet(stripeKey, `/v1/accounts/${accountId}`);
7510
- if (!result2.ok) return err2(`Stripe error: ${JSON.stringify(result2.data)}`);
7511
- const a = result2.data;
7509
+ const result3 = await stripeGet(stripeKey, `/v1/accounts/${accountId}`);
7510
+ if (!result3.ok) return err2(`Stripe error: ${JSON.stringify(result3.data)}`);
7511
+ const a = result3.data;
7512
7512
  const status = a.charges_enabled && a.details_submitted ? "active" : "pending";
7513
7513
  writeAudit(env, {
7514
7514
  tool_name: "stripe_connect_status",
@@ -7543,8 +7543,8 @@ function registerStripeConnectTools(server2, ctx) {
7543
7543
  title: "List Stripe Payouts",
7544
7544
  description: "List money Stripe has already sent from the operator's connected account to their bank, newest first. Read-only. Params: `limit` (1-50, default 10), `status` (optional Stripe payout status, e.g. 'paid', 'pending', 'failed'). Returns: { payouts: [{ id, amount, currency, status, arrival_date, automatic, created }], has_more } \u2014 amount in the currency's smallest unit. Do NOT use this for money still sitting at Stripe and not yet paid out \u2014 use `stripe_connect_balance`.",
7545
7545
  inputSchema: {
7546
- limit: z9.number().int().min(1).max(50).default(10).describe("Number of payouts to return."),
7547
- status: z9.enum(["pending", "paid", "failed", "canceled", "in_transit"]).optional().describe("Filter by payout status.")
7546
+ limit: z10.number().int().min(1).max(50).default(10).describe("Number of payouts to return."),
7547
+ status: z10.enum(["pending", "paid", "failed", "canceled", "in_transit"]).optional().describe("Filter by payout status.")
7548
7548
  },
7549
7549
  annotations: annotationsFor("stripe_connect_payouts", "read")
7550
7550
  },
@@ -7559,8 +7559,8 @@ function registerStripeConnectTools(server2, ctx) {
7559
7559
  if (!accountId) return err2("No connected Stripe account found.");
7560
7560
  const params = new URLSearchParams({ limit: String(limit) });
7561
7561
  if (status) params.set("status", status);
7562
- const result2 = await stripeGet(stripeKey, `/v1/payouts?${params.toString()}`, accountId);
7563
- if (!result2.ok) return err2(`Stripe error: ${JSON.stringify(result2.data)}`);
7562
+ const result3 = await stripeGet(stripeKey, `/v1/payouts?${params.toString()}`, accountId);
7563
+ if (!result3.ok) return err2(`Stripe error: ${JSON.stringify(result3.data)}`);
7564
7564
  writeAudit(env, {
7565
7565
  tool_name: "stripe_connect_payouts",
7566
7566
  ocs_method: "stripe.payouts.list",
@@ -7570,7 +7570,7 @@ function registerStripeConnectTools(server2, ctx) {
7570
7570
  sub: props2.sub,
7571
7571
  reseller_id: props2.reseller_id
7572
7572
  });
7573
- return ok(JSON.stringify({ payouts: result2.data.data, has_more: result2.data.has_more }));
7573
+ return ok(JSON.stringify({ payouts: result3.data.data, has_more: result3.data.has_more }));
7574
7574
  } catch (e) {
7575
7575
  Sentry3.captureException(e);
7576
7576
  return err2(`Error: ${e instanceof Error ? e.message : "unknown"}`);
@@ -7583,8 +7583,8 @@ function registerStripeConnectTools(server2, ctx) {
7583
7583
  title: "Stripe Connect Charges",
7584
7584
  description: "List recent payments (charges) on the operator's connected Stripe account, e.g. storefront purchases. Read-only. Params: limit (1-100), starting_after (charge id for paging). Returns: { charges: [{ id, amount, amount_refunded, currency, status, paid, captured, refunded, created, payment_intent, payment_method_type, metadata }], has_more }. Do NOT use this for payouts to the bank \u2014 use `stripe_connect_payouts`.",
7585
7585
  inputSchema: {
7586
- limit: z9.number().int().min(1).max(100).default(20).describe("Number of charges to return."),
7587
- starting_after: z9.string().regex(/^(ch|py)_[A-Za-z0-9]+$/).optional().describe("Charge id to page after.")
7586
+ limit: z10.number().int().min(1).max(100).default(20).describe("Number of charges to return."),
7587
+ starting_after: z10.string().regex(/^(ch|py)_[A-Za-z0-9]+$/).optional().describe("Charge id to page after.")
7588
7588
  },
7589
7589
  annotations: annotationsFor("stripe_connect_charges_list", "read")
7590
7590
  },
@@ -7599,12 +7599,12 @@ function registerStripeConnectTools(server2, ctx) {
7599
7599
  if (!accountId) return err2("No connected Stripe account found.");
7600
7600
  const params = new URLSearchParams({ limit: String(limit) });
7601
7601
  if (starting_after) params.set("starting_after", starting_after);
7602
- const result2 = await stripeGet(
7602
+ const result3 = await stripeGet(
7603
7603
  stripeKey,
7604
7604
  `/v1/charges?${params.toString()}`,
7605
7605
  accountId
7606
7606
  );
7607
- if (!result2.ok) return err2(`Stripe error: ${JSON.stringify(result2.data)}`);
7607
+ if (!result3.ok) return err2(`Stripe error: ${JSON.stringify(result3.data)}`);
7608
7608
  writeAudit(env, {
7609
7609
  tool_name: "stripe_connect_charges_list",
7610
7610
  ocs_method: "stripe.charges.list",
@@ -7614,7 +7614,7 @@ function registerStripeConnectTools(server2, ctx) {
7614
7614
  sub: props2.sub,
7615
7615
  reseller_id: props2.reseller_id
7616
7616
  });
7617
- const charges = (result2.data.data ?? []).map((ch) => ({
7617
+ const charges = (result3.data.data ?? []).map((ch) => ({
7618
7618
  id: ch["id"],
7619
7619
  amount: ch["amount"],
7620
7620
  amount_refunded: ch["amount_refunded"],
@@ -7628,7 +7628,7 @@ function registerStripeConnectTools(server2, ctx) {
7628
7628
  payment_method_type: ch["payment_method_details"]?.type ?? null,
7629
7629
  metadata: ch["metadata"]
7630
7630
  }));
7631
- return ok(JSON.stringify({ charges, has_more: result2.data.has_more }));
7631
+ return ok(JSON.stringify({ charges, has_more: result3.data.has_more }));
7632
7632
  } catch (e) {
7633
7633
  Sentry3.captureException(e);
7634
7634
  return err2(`stripe_connect_charges_list failed: ${e instanceof Error ? e.message : String(e)}`);
@@ -7652,8 +7652,8 @@ function registerStripeConnectTools(server2, ctx) {
7652
7652
  if (!stripeKey) return err2("Stripe not configured");
7653
7653
  const accountId = await getAccountId();
7654
7654
  if (!accountId) return err2("No connected Stripe account found.");
7655
- const result2 = await stripeGet(stripeKey, `/v1/balance`, accountId);
7656
- if (!result2.ok) return err2(`Stripe error: ${JSON.stringify(result2.data)}`);
7655
+ const result3 = await stripeGet(stripeKey, `/v1/balance`, accountId);
7656
+ if (!result3.ok) return err2(`Stripe error: ${JSON.stringify(result3.data)}`);
7657
7657
  writeAudit(env, {
7658
7658
  tool_name: "stripe_connect_balance",
7659
7659
  ocs_method: "stripe.balance.read",
@@ -7665,8 +7665,8 @@ function registerStripeConnectTools(server2, ctx) {
7665
7665
  });
7666
7666
  return ok(JSON.stringify({
7667
7667
  account_id: accountId,
7668
- available: result2.data.available ?? [],
7669
- pending: result2.data.pending ?? []
7668
+ available: result3.data.available ?? [],
7669
+ pending: result3.data.pending ?? []
7670
7670
  }));
7671
7671
  } catch (e) {
7672
7672
  Sentry3.captureException(e);
@@ -7680,10 +7680,10 @@ function registerStripeConnectTools(server2, ctx) {
7680
7680
  title: "Refund a Charge (moves real money)",
7681
7681
  description: "Refund money to a customer on one charge in the operator's connected Stripe account. This returns real funds and Stripe cannot reverse a refund once issued. Two-step by design: call without `confirm_token` to get a token and a summary of what would be refunded, then call again with that token to execute. The token expires in 5 minutes. Params: `charge_id` (Stripe charge id, `ch_...`), `amount_cents` (optional integer in the charge's smallest currency unit \u2014 omit for a full refund), `reason` ('duplicate' | 'fraudulent' | 'requested_by_customer', optional), `confirm_token`. Returns: the refund id and status. Requires `write` scope. Do NOT use this on a payment that was authorized but not captured \u2014 cancel its PaymentIntent instead (Stripe POST /v1/payment_intents/:id/cancel). Do NOT use this to contest a chargeback \u2014 read the case with `stripe_connect_dispute_list` first, since refunding a disputed charge can cost the operator twice.",
7682
7682
  inputSchema: {
7683
- charge_id: z9.string().min(1).describe("Stripe charge ID (ch_...)."),
7684
- amount_cents: z9.number().int().min(1).optional().describe("Partial refund amount in cents. Omit for full refund."),
7685
- reason: z9.enum(["duplicate", "fraudulent", "requested_by_customer"]).optional(),
7686
- confirm_token: z9.string().optional().describe("Confirmation token from previous call. Required to execute.")
7683
+ charge_id: z10.string().min(1).describe("Stripe charge ID (ch_...)."),
7684
+ amount_cents: z10.number().int().min(1).optional().describe("Partial refund amount in cents. Omit for full refund."),
7685
+ reason: z10.enum(["duplicate", "fraudulent", "requested_by_customer"]).optional(),
7686
+ confirm_token: z10.string().optional().describe("Confirmation token from previous call. Required to execute.")
7687
7687
  },
7688
7688
  annotations: annotationsFor("stripe_connect_refund", "write")
7689
7689
  },
@@ -7712,14 +7712,14 @@ Call again with confirm_token="${token2}" to execute. Token expires in 5 minutes
7712
7712
  const params = { charge: charge_id };
7713
7713
  if (amount_cents) params.amount = String(amount_cents);
7714
7714
  if (reason) params.reason = reason;
7715
- const result2 = await stripePost(
7715
+ const result3 = await stripePost(
7716
7716
  stripeKey,
7717
7717
  "/v1/refunds",
7718
7718
  params,
7719
7719
  accountId,
7720
7720
  refundIdempotencyKey(props2.sub, charge_id, amount_cents, reason)
7721
7721
  );
7722
- if (!result2.ok) return err2(`Stripe error: ${JSON.stringify(result2.data)}`);
7722
+ if (!result3.ok) return err2(`Stripe error: ${JSON.stringify(result3.data)}`);
7723
7723
  writeAudit(env, {
7724
7724
  tool_name: toolName,
7725
7725
  ocs_method: "stripe.refund.create",
@@ -7729,7 +7729,7 @@ Call again with confirm_token="${token2}" to execute. Token expires in 5 minutes
7729
7729
  sub: props2.sub,
7730
7730
  reseller_id: props2.reseller_id
7731
7731
  });
7732
- return ok(`Refund issued: ${result2.data.id} \u2014 status: ${result2.data.status}`);
7732
+ return ok(`Refund issued: ${result3.data.id} \u2014 status: ${result3.data.status}`);
7733
7733
  } catch (e) {
7734
7734
  Sentry3.captureException(e);
7735
7735
  return err2(`Error: ${e instanceof Error ? e.message : "unknown"}`);
@@ -7742,8 +7742,8 @@ Call again with confirm_token="${token2}" to execute. Token expires in 5 minutes
7742
7742
  title: "List Chargeback Disputes",
7743
7743
  description: "List chargebacks customers have raised with their bank against the operator's connected Stripe account. Read-only \u2014 responding to one is Dashboard work. Params: `limit` (1-50, default 10), `status` (optional Stripe dispute status, e.g. 'needs_response', 'under_review'). Returns: { disputes: [{ id, charge, amount, currency, status, reason, evidence_details.due_by }], has_more } \u2014 amount in the currency's smallest unit, `due_by` a Unix timestamp or null. Do NOT use this for charges Stripe is holding for fraud review before they settle \u2014 those are `radar_review_list`. Check this before refunding: refunding a disputed charge can cost the operator the amount twice.",
7744
7744
  inputSchema: {
7745
- limit: z9.number().int().min(1).max(50).default(10),
7746
- status: z9.string().optional().describe("Filter by dispute status (e.g. needs_response, under_review).")
7745
+ limit: z10.number().int().min(1).max(50).default(10),
7746
+ status: z10.string().optional().describe("Filter by dispute status (e.g. needs_response, under_review).")
7747
7747
  },
7748
7748
  annotations: annotationsFor("stripe_connect_dispute_list", "read")
7749
7749
  },
@@ -7758,8 +7758,8 @@ Call again with confirm_token="${token2}" to execute. Token expires in 5 minutes
7758
7758
  if (!accountId) return err2("No connected Stripe account found.");
7759
7759
  const params = new URLSearchParams({ limit: String(limit) });
7760
7760
  if (status) params.set("status", status);
7761
- const result2 = await stripeGet(stripeKey, `/v1/disputes?${params.toString()}`, accountId);
7762
- if (!result2.ok) return err2(`Stripe error: ${JSON.stringify(result2.data)}`);
7761
+ const result3 = await stripeGet(stripeKey, `/v1/disputes?${params.toString()}`, accountId);
7762
+ if (!result3.ok) return err2(`Stripe error: ${JSON.stringify(result3.data)}`);
7763
7763
  writeAudit(env, {
7764
7764
  tool_name: "stripe_connect_dispute_list",
7765
7765
  ocs_method: "stripe.disputes.list",
@@ -7769,7 +7769,7 @@ Call again with confirm_token="${token2}" to execute. Token expires in 5 minutes
7769
7769
  sub: props2.sub,
7770
7770
  reseller_id: props2.reseller_id
7771
7771
  });
7772
- return ok(JSON.stringify({ disputes: result2.data.data, has_more: result2.data.has_more }));
7772
+ return ok(JSON.stringify({ disputes: result3.data.data, has_more: result3.data.has_more }));
7773
7773
  } catch (e) {
7774
7774
  Sentry3.captureException(e);
7775
7775
  return err2(`Error: ${e instanceof Error ? e.message : "unknown"}`);
@@ -7782,8 +7782,8 @@ Call again with confirm_token="${token2}" to execute. Token expires in 5 minutes
7782
7782
  title: "List Radar Fraud Reviews",
7783
7783
  description: "List the Stripe Radar fraud reviews waiting on a manual approve/decline decision, newest first. Reads only \u2014 deciding a review is a separate call. Params: `open_only` (boolean, default true; Stripe lists open reviews only, so false returns the same set), `limit` (1-50, default 10). Returns: { reviews: [{ id (`prv_...`), charge, reason, opened_reason, closed_reason, created, closed }], has_more }. Call this first to get the `review_id` that `radar_review_approve` and `radar_review_decline` require. Do NOT use this for chargebacks the customer has already raised with their bank \u2014 use `stripe_connect_dispute_list`.",
7784
7784
  inputSchema: {
7785
- open_only: z9.boolean().default(true).describe("Stripe lists only open (undecided) reviews; kept for compatibility."),
7786
- limit: z9.number().int().min(1).max(50).default(10)
7785
+ open_only: z10.boolean().default(true).describe("Stripe lists only open (undecided) reviews; kept for compatibility."),
7786
+ limit: z10.number().int().min(1).max(50).default(10)
7787
7787
  },
7788
7788
  annotations: annotationsFor("radar_review_list", "read")
7789
7789
  },
@@ -7800,9 +7800,9 @@ Call again with confirm_token="${token2}" to execute. Token expires in 5 minutes
7800
7800
  const stripeKey = env.STRIPE_ORG_SECRET_KEY ?? env.STRIPE_SECRET_KEY;
7801
7801
  if (!stripeKey) return err2("Stripe not configured");
7802
7802
  const params = new URLSearchParams({ limit: String(limit) });
7803
- const result2 = await stripeGet(stripeKey, `/v1/reviews?${params.toString()}`);
7804
- if (!result2.ok) return err2(`Stripe error: ${JSON.stringify(result2.data)}`);
7805
- const reviews = open_only ? result2.data.data.filter((r) => r.open !== false) : result2.data.data;
7803
+ const result3 = await stripeGet(stripeKey, `/v1/reviews?${params.toString()}`);
7804
+ if (!result3.ok) return err2(`Stripe error: ${JSON.stringify(result3.data)}`);
7805
+ const reviews = open_only ? result3.data.data.filter((r) => r.open !== false) : result3.data.data;
7806
7806
  writeAudit(env, {
7807
7807
  tool_name: "radar_review_list",
7808
7808
  ocs_method: "stripe.radar.reviews.list",
@@ -7812,7 +7812,7 @@ Call again with confirm_token="${token2}" to execute. Token expires in 5 minutes
7812
7812
  sub: props2.sub,
7813
7813
  reseller_id: props2.reseller_id
7814
7814
  });
7815
- return ok(JSON.stringify({ reviews, has_more: result2.data.has_more }));
7815
+ return ok(JSON.stringify({ reviews, has_more: result3.data.has_more }));
7816
7816
  } catch (e) {
7817
7817
  Sentry3.captureException(e);
7818
7818
  return err2(`Error: ${e instanceof Error ? e.message : "unknown"}`);
@@ -7825,8 +7825,8 @@ Call again with confirm_token="${token2}" to execute. Token expires in 5 minutes
7825
7825
  title: "Approve Radar Review (captures charge)",
7826
7826
  description: "Clear a Stripe Radar fraud review so the held charge is captured and the money is taken. Approving overrides Radar's fraud signal, so a genuinely fraudulent charge approved here usually returns later as a chargeback plus a fee. Two-step by design: call without `confirm_token` to get a token, then call again with it to execute. Params: `review_id` (`prv_...`, from `radar_review_list`), `confirm_token`. Requires `admin` scope. Do NOT call this to turn a suspicious charge away \u2014 Stripe has no review decline; refund the charge (`stripe_connect_refund`) or cancel an uncaptured PaymentIntent. Do NOT call this to return money on a charge that already went through \u2014 that is `stripe_connect_refund`.",
7827
7827
  inputSchema: {
7828
- review_id: z9.string().min(1).describe("Stripe Radar review ID (prv_...)."),
7829
- confirm_token: z9.string().optional()
7828
+ review_id: z10.string().min(1).describe("Stripe Radar review ID (prv_...)."),
7829
+ confirm_token: z10.string().optional()
7830
7830
  },
7831
7831
  annotations: annotationsFor("radar_review_approve", "admin")
7832
7832
  },
@@ -7853,13 +7853,13 @@ Call again with confirm_token="${token2}" to execute. Expires in 5 minutes.`
7853
7853
  try {
7854
7854
  const stripeKey = env.STRIPE_ORG_SECRET_KEY ?? env.STRIPE_SECRET_KEY;
7855
7855
  if (!stripeKey) return err2("Stripe not configured");
7856
- const result2 = await stripePost(
7856
+ const result3 = await stripePost(
7857
7857
  stripeKey,
7858
7858
  // POST /v1/reviews/:id/approve (docs.stripe.com/api/radar/reviews/approve).
7859
7859
  `/v1/reviews/${encodeURIComponent(review_id)}/approve`,
7860
7860
  {}
7861
7861
  );
7862
- if (!result2.ok) return err2(`Stripe error: ${JSON.stringify(result2.data)}`);
7862
+ if (!result3.ok) return err2(`Stripe error: ${JSON.stringify(result3.data)}`);
7863
7863
  writeAudit(env, {
7864
7864
  tool_name: toolName,
7865
7865
  ocs_method: "stripe.radar.review.approve",
@@ -7882,8 +7882,8 @@ Call again with confirm_token="${token2}" to execute. Expires in 5 minutes.`
7882
7882
  title: "Decline Radar Review (not supported by Stripe)",
7883
7883
  description: "Always refuses and calls nothing: Stripe has no endpoint to decline a Radar review (its Reviews API only lists, retrieves and approves). Payments in review have usually already been processed. To turn one away, refund the charge on Carrier's platform account in Stripe itself (Dashboard, or platform-scoped POST /v1/refunds with no Stripe-Account header): `stripe_connect_refund` always acts as the operator's connected account, so it will NOT find a platform charge from this review list. or, for a payment authorized but not captured, cancel its PaymentIntent (Stripe POST /v1/payment_intents/:id/cancel); either closes the review. Params: `review_id` (`prv_...`), `confirm_token` (ignored). Requires `admin` scope. Do NOT call this expecting a charge to be blocked; nothing happens.",
7884
7884
  inputSchema: {
7885
- review_id: z9.string().min(1),
7886
- confirm_token: z9.string().optional()
7885
+ review_id: z10.string().min(1),
7886
+ confirm_token: z10.string().optional()
7887
7887
  },
7888
7888
  annotations: annotationsFor("radar_review_decline", "admin")
7889
7889
  },
@@ -7904,9 +7904,9 @@ Call again with confirm_token="${token2}" to execute. Expires in 5 minutes.`
7904
7904
  title: "Add Value to Radar List",
7905
7905
  description: "Add one value to an existing Stripe Radar value list, changing how every future charge is scored. Whether the value ends up blocked or allowed depends entirely on which list you name in `value_list_id` \u2014 this tool does not choose, and putting a value on the allow list when you meant the block list silently lets fraud through. Confirm the list's purpose before calling. Two-step by design: call without `confirm_token` to get a token, then call again with it to execute. Params: `value_list_id` (`rsl_...`, an existing list), `value` (one email, IP address, card fingerprint, or ISO country code \u2014 one item per call), `confirm_token`. Requires `admin` scope. Do NOT use this to decide a single charge that is already under review \u2014 use `radar_review_approve` or `radar_review_decline`. Do NOT use this to create a list or a rule: only `value` is added, and rules cannot be edited through this API at all (see `radar_rule_toggle`).",
7906
7906
  inputSchema: {
7907
- value_list_id: z9.string().min(1).describe("Stripe Radar value list ID (rsl_...)."),
7908
- value: z9.string().min(1).describe("The value to add (email, IP address, country code, etc.)."),
7909
- confirm_token: z9.string().optional()
7907
+ value_list_id: z10.string().min(1).describe("Stripe Radar value list ID (rsl_...)."),
7908
+ value: z10.string().min(1).describe("The value to add (email, IP address, country code, etc.)."),
7909
+ confirm_token: z10.string().optional()
7910
7910
  },
7911
7911
  annotations: annotationsFor("radar_value_list_add", "admin")
7912
7912
  },
@@ -7933,12 +7933,12 @@ Expires in 5 minutes.`
7933
7933
  try {
7934
7934
  const stripeKey = env.STRIPE_ORG_SECRET_KEY ?? env.STRIPE_SECRET_KEY;
7935
7935
  if (!stripeKey) return err2("Stripe not configured");
7936
- const result2 = await stripePost(
7936
+ const result3 = await stripePost(
7937
7937
  stripeKey,
7938
7938
  "/v1/radar/value_list_items",
7939
7939
  { value_list: value_list_id, value }
7940
7940
  );
7941
- if (!result2.ok) return err2(`Stripe error: ${JSON.stringify(result2.data)}`);
7941
+ if (!result3.ok) return err2(`Stripe error: ${JSON.stringify(result3.data)}`);
7942
7942
  writeAudit(env, {
7943
7943
  tool_name: toolName,
7944
7944
  ocs_method: "stripe.radar.value_list.add",
@@ -7961,8 +7961,8 @@ Expires in 5 minutes.`
7961
7961
  title: "Radar Rule Toggle (instructions only)",
7962
7962
  description: "Return the Stripe Dashboard steps for enabling or disabling a Radar rule. This tool changes nothing: Stripe has no public API for rule state, so the call always succeeds and the rule stays exactly as it was. Never report the rule as toggled. Params: `rule_id` (Stripe Radar rule id), `enabled` (true for the enable instructions, false for disable). Returns: the Dashboard URL and steps for a human to follow. Requires `admin` scope. Do NOT use this when a change must actually take effect from an agent \u2014 the only Radar state reachable through this API is value-list membership, via `radar_value_list_add`.",
7963
7963
  inputSchema: {
7964
- rule_id: z9.string().min(1).describe("Stripe Radar rule ID."),
7965
- enabled: z9.boolean().describe("true = enable, false = disable.")
7964
+ rule_id: z10.string().min(1).describe("Stripe Radar rule ID."),
7965
+ enabled: z10.boolean().describe("true = enable, false = disable.")
7966
7966
  },
7967
7967
  annotations: annotationsFor("radar_rule_toggle", "admin")
7968
7968
  },
@@ -7987,7 +7987,7 @@ Note: If you need this automated, use the Radar for Platforms beta \u2014 contac
7987
7987
  }
7988
7988
 
7989
7989
  // src/tools-storefront-logo.ts
7990
- import { z as z10 } from "zod";
7990
+ import { z as z11 } from "zod";
7991
7991
  var STOREFRONT_LOGO_TOOL_SCOPES = {
7992
7992
  generate_storefront_logo: "read"
7993
7993
  };
@@ -8000,9 +8000,9 @@ function registerStorefrontLogoTools(server2, env = {}, props2) {
8000
8000
  title: "Generate Storefront Logo",
8001
8001
  description: "Generate a storefront logo (SVG always; PNG when an image key is configured on the Carrier worker). Works for any authenticated Carrier MCP user \u2014 no local image-API key required. Write the SVG to public/brand/logo.svg in the storefront.",
8002
8002
  inputSchema: {
8003
- name: z10.string().min(1).describe("Brand / shop name, e.g. Bananas"),
8004
- accent: z10.string().regex(/^#?[0-9A-Fa-f]{6}$/).optional().describe("Accent hex, e.g. #FF8A00"),
8005
- tagline: z10.string().optional().describe("Optional tagline for AI-enhanced marks")
8003
+ name: z11.string().min(1).describe("Brand / shop name, e.g. Bananas"),
8004
+ accent: z11.string().regex(/^#?[0-9A-Fa-f]{6}$/).optional().describe("Accent hex, e.g. #FF8A00"),
8005
+ tagline: z11.string().optional().describe("Optional tagline for AI-enhanced marks")
8006
8006
  },
8007
8007
  annotations: annotationsFor("generate_storefront_logo", "read")
8008
8008
  },
@@ -8036,7 +8036,7 @@ function registerStorefrontLogoTools(server2, env = {}, props2) {
8036
8036
  }
8037
8037
 
8038
8038
  // src/tools-storefront-deploy.ts
8039
- import { z as z11 } from "zod";
8039
+ import { z as z12 } from "zod";
8040
8040
  var STOREFRONT_DEPLOY_TOOL_SCOPES = {
8041
8041
  list_deploy_targets: "read",
8042
8042
  deploy_storefront: "write",
@@ -8053,7 +8053,7 @@ function registerStorefrontDeployTools(server2, props2) {
8053
8053
  title: "List Deploy Targets",
8054
8054
  description: "Report which storefront deploy hosts (Cloudflare, Vercel, Netlify, Fly) are installed, logged in, and ready on this machine, and which one a deploy would pick.",
8055
8055
  inputSchema: {
8056
- dir: z11.string().min(1).describe("Path to the scaffolded storefront directory")
8056
+ dir: z12.string().min(1).describe("Path to the scaffolded storefront directory")
8057
8057
  },
8058
8058
  annotations: annotationsFor("list_deploy_targets", "read")
8059
8059
  },
@@ -8079,17 +8079,17 @@ function registerStorefrontDeployTools(server2, props2) {
8079
8079
  title: "Deploy Storefront",
8080
8080
  description: "Build and deploy a scaffolded storefront to whichever host is available on this machine, then push its runtime secrets (CARRIER_API_KEY, CLERK_SECRET_KEY) to that host.",
8081
8081
  inputSchema: {
8082
- dir: z11.string().min(1).describe("Path to the scaffolded storefront directory"),
8083
- target: z11.enum(TARGET_IDS).optional().describe("Force a host instead of auto-detecting"),
8084
- name: z11.string().optional().describe("Project/worker name (defaults from brand)"),
8085
- force: z11.boolean().optional().describe(
8082
+ dir: z12.string().min(1).describe("Path to the scaffolded storefront directory"),
8083
+ target: z12.enum(TARGET_IDS).optional().describe("Force a host instead of auto-detecting"),
8084
+ name: z12.string().optional().describe("Project/worker name (defaults from brand)"),
8085
+ force: z12.boolean().optional().describe(
8086
8086
  'Acknowledge the scaffold-default-name risk: required when the resolved name is the scaffold default "storefront"'
8087
8087
  ),
8088
- skip_build: z11.boolean().optional().describe("Deploy the existing build without rebuilding"),
8089
- push_secrets: z11.boolean().optional().describe("Stage runtime secrets on the host before deploy (default true)"),
8090
- provision_clerk: z11.boolean().optional().default(true).describe("Provision and configure Clerk automatically (default true)"),
8091
- verify: z11.boolean().optional().describe("Probe the deployed URL and report whether it actually serves (default true)"),
8092
- domain: z11.boolean().optional().describe("Route the brand domain to the deployment (Cloudflare provisions DNS + cert)")
8088
+ skip_build: z12.boolean().optional().describe("Deploy the existing build without rebuilding"),
8089
+ push_secrets: z12.boolean().optional().describe("Stage runtime secrets on the host before deploy (default true)"),
8090
+ provision_clerk: z12.boolean().optional().default(true).describe("Provision and configure Clerk automatically (default true)"),
8091
+ verify: z12.boolean().optional().describe("Probe the deployed URL and report whether it actually serves (default true)"),
8092
+ domain: z12.boolean().optional().describe("Route the brand domain to the deployment (Cloudflare provisions DNS + cert)")
8093
8093
  },
8094
8094
  annotations: annotationsFor("deploy_storefront", "write")
8095
8095
  },
@@ -8153,7 +8153,7 @@ function registerStorefrontDeployTools(server2, props2) {
8153
8153
  const built = await buildSite(dir, buildFor);
8154
8154
  if (!built) return err4(`Build failed for ${buildFor}. Run the build locally to see why.`);
8155
8155
  }
8156
- const result2 = await deploySite(dir, brand, {
8156
+ const result3 = await deploySite(dir, brand, {
8157
8157
  preferred,
8158
8158
  pushSecrets: push_secrets !== false,
8159
8159
  customDomain: domain === true,
@@ -8164,29 +8164,29 @@ function registerStorefrontDeployTools(server2, props2) {
8164
8164
  explicitName: name,
8165
8165
  force: force === true
8166
8166
  });
8167
- if (!result2.ok) {
8168
- return err4(result2.reason ?? "Deploy failed.");
8167
+ if (!result3.ok) {
8168
+ return err4(result3.reason ?? "Deploy failed.");
8169
8169
  }
8170
- if (provision_clerk !== false && result2.url) {
8170
+ if (provision_clerk !== false && result3.url) {
8171
8171
  const secretKey = clerkCredentials?.secretKey ?? (await discoverSecrets(dir, process.env)).CLERK_SECRET_KEY;
8172
8172
  if (secretKey) {
8173
8173
  const configured = await configureClerkInstance(
8174
8174
  secretKey,
8175
- storefrontClerkUrls(result2.url, brand.domain)
8175
+ storefrontClerkUrls(result3.url, brand.domain)
8176
8176
  );
8177
8177
  clerkConfigured = configured.applied;
8178
8178
  clerkConfigureFailures = configured.failed;
8179
8179
  }
8180
8180
  }
8181
- const verification = verify !== false && result2.url ? await verifyStorefront(result2.url, dir, process.env) : void 0;
8181
+ const verification = verify !== false && result3.url ? await verifyStorefront(result3.url, dir, process.env) : void 0;
8182
8182
  const repairHint = skip_build && clerkEnvWritten.includes("NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY") ? "Clerk keys were written to .env.local, but the publishable key is only inlined at build time; rebuild and redeploy to apply it." : verification && !verification.ok ? repairPlanFor(verification.diagnosis)?.note ?? verification.summary : void 0;
8183
8183
  return ok3({
8184
8184
  deployed: true,
8185
- target: result2.target,
8186
- project: result2.projectName,
8187
- url: result2.url ?? null,
8188
- secrets_staged: result2.secrets?.pushed ?? [],
8189
- secrets_failed: result2.secrets?.failed ?? [],
8185
+ target: result3.target,
8186
+ project: result3.projectName,
8187
+ url: result3.url ?? null,
8188
+ secrets_staged: result3.secrets?.pushed ?? [],
8189
+ secrets_failed: result3.secrets?.failed ?? [],
8190
8190
  clerk_provisioned: clerkProvisioned,
8191
8191
  clerk_tier: clerkTier,
8192
8192
  clerk_configured: clerkConfigured.length,
@@ -8196,7 +8196,7 @@ function registerStorefrontDeployTools(server2, props2) {
8196
8196
  diagnosis: verification?.ok === false ? verification.diagnosis : void 0,
8197
8197
  probes: verification ? formatProbes(verification.probes) : void 0,
8198
8198
  repair_hint: repairHint,
8199
- warning: result2.secrets?.pushed.includes("CARRIER_API_KEY") ? void 0 : "CARRIER_API_KEY was not staged \u2014 / and /shop will return 500 until it is set."
8199
+ warning: result3.secrets?.pushed.includes("CARRIER_API_KEY") ? void 0 : "CARRIER_API_KEY was not staged \u2014 / and /shop will return 500 until it is set."
8200
8200
  });
8201
8201
  } catch (e) {
8202
8202
  return err4(e instanceof Error ? e.message : "deploy failed");
@@ -8209,11 +8209,11 @@ function registerStorefrontDeployTools(server2, props2) {
8209
8209
  title: "Provision Storefront Clerk App",
8210
8210
  description: "Create a Clerk application (Platform API) or reuse Clerk keys already on this machine, write them into the storefront .env.local, and configure allowed origins and redirect URLs on the instance.",
8211
8211
  inputSchema: {
8212
- dir: z11.string().min(1).describe("Path to the scaffolded storefront directory"),
8213
- name: z11.string().optional().describe("Clerk application name (defaults from brand)"),
8214
- production: z11.boolean().optional().describe("Also create a production instance (Platform API only)"),
8215
- no_create: z11.boolean().optional().describe("Never create a new application; only reuse existing keys"),
8216
- url: z11.string().optional().describe("Deployed URL to whitelist as origin and redirect")
8212
+ dir: z12.string().min(1).describe("Path to the scaffolded storefront directory"),
8213
+ name: z12.string().optional().describe("Clerk application name (defaults from brand)"),
8214
+ production: z12.boolean().optional().describe("Also create a production instance (Platform API only)"),
8215
+ no_create: z12.boolean().optional().describe("Never create a new application; only reuse existing keys"),
8216
+ url: z12.string().optional().describe("Deployed URL to whitelist as origin and redirect")
8217
8217
  },
8218
8218
  annotations: annotationsFor("provision_storefront_clerk", "write")
8219
8219
  },
@@ -8226,7 +8226,7 @@ function registerStorefrontDeployTools(server2, props2) {
8226
8226
  if (denied) return denied;
8227
8227
  try {
8228
8228
  const brand = await loadStorefrontBrand(dir, name ? { name } : void 0);
8229
- const result2 = await provisionClerk({
8229
+ const result3 = await provisionClerk({
8230
8230
  name: name ?? brand.name,
8231
8231
  domain: brand.domain,
8232
8232
  production: production === true,
@@ -8235,28 +8235,28 @@ function registerStorefrontDeployTools(server2, props2) {
8235
8235
  storefront: dir,
8236
8236
  cli: clerkCliDeps()
8237
8237
  });
8238
- if (!result2.ok || !result2.credentials) {
8238
+ if (!result3.ok || !result3.credentials) {
8239
8239
  return ok3({
8240
8240
  provisioned: false,
8241
- tier: result2.tier,
8242
- reason: result2.reason,
8243
- guidance: result2.guidance ?? []
8241
+ tier: result3.tier,
8242
+ reason: result3.reason,
8243
+ guidance: result3.guidance ?? []
8244
8244
  });
8245
8245
  }
8246
8246
  const written = await mergeEnvLocal(dir, {
8247
- NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: result2.credentials.publishableKey,
8248
- CLERK_SECRET_KEY: result2.credentials.secretKey
8247
+ NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: result3.credentials.publishableKey,
8248
+ CLERK_SECRET_KEY: result3.credentials.secretKey
8249
8249
  });
8250
8250
  const { allowedOrigins, redirectUrls } = storefrontClerkUrls(url, brand.domain);
8251
- const configured = await configureClerkInstance(result2.credentials.secretKey, {
8251
+ const configured = await configureClerkInstance(result3.credentials.secretKey, {
8252
8252
  allowedOrigins,
8253
8253
  redirectUrls
8254
8254
  });
8255
8255
  return ok3({
8256
8256
  provisioned: true,
8257
- tier: result2.tier,
8258
- application_id: result2.credentials.applicationId ?? null,
8259
- instance_id: result2.credentials.instanceId ?? null,
8257
+ tier: result3.tier,
8258
+ application_id: result3.credentials.applicationId ?? null,
8259
+ instance_id: result3.credentials.instanceId ?? null,
8260
8260
  env_written: written,
8261
8261
  configured: configured.applied,
8262
8262
  configure_failures: configured.failed
@@ -8269,7 +8269,7 @@ function registerStorefrontDeployTools(server2, props2) {
8269
8269
  }
8270
8270
 
8271
8271
  // src/tools-storefront-plan.ts
8272
- import { z as z12 } from "zod";
8272
+ import { z as z13 } from "zod";
8273
8273
 
8274
8274
  // src/lib/storefront-plan-update.ts
8275
8275
  var STRIPE_PRICE_ID_RE = /^price_[A-Za-z0-9_]+$/;
@@ -8375,14 +8375,14 @@ function registerStorefrontPlanTools(server2, props2, call = (path, body2) => {
8375
8375
  server2.registerTool(name, {
8376
8376
  title: name === "list_storefronts" ? "List Storefronts" : "Get Storefront",
8377
8377
  description: "Read hosted storefront plans including stored OCS account ids and account_status.",
8378
- inputSchema: name === "get_storefront" ? { storefront_id: z12.string().min(1) } : {},
8378
+ inputSchema: name === "get_storefront" ? { storefront_id: z13.string().min(1) } : {},
8379
8379
  annotations: annotationsFor(name, "read")
8380
8380
  }, async (args) => {
8381
8381
  const denied = denyUnlessScoped(props2, name, STOREFRONT_PLAN_TOOL_SCOPES);
8382
8382
  if (denied) return denied;
8383
8383
  try {
8384
- const result2 = await read("storefront_id" in args ? String(args.storefront_id) : void 0);
8385
- return result2.ok ? ok4(JSON.stringify(result2.body)) : err5(JSON.stringify(result2.body));
8384
+ const result3 = await read("storefront_id" in args ? String(args.storefront_id) : void 0);
8385
+ return result3.ok ? ok4(JSON.stringify(result3.body)) : err5(JSON.stringify(result3.body));
8386
8386
  } catch (e) {
8387
8387
  return err5(e instanceof Error ? e.message : "storefront read failed");
8388
8388
  }
@@ -8394,14 +8394,14 @@ function registerStorefrontPlanTools(server2, props2, call = (path, body2) => {
8394
8394
  title: "Update Storefront Plan",
8395
8395
  description: "Change the retail price, whether a plan is for sale, its OCS account, its display order, or the stored Stripe Price on the caller's own hosted storefront. The plan must already exist. A price of zero or less is refused. stripe_price_id and stripe_price_mode are set together; null clears both. The id must look like price_\u2026 and be 1-255 characters. A plan on another storefront is not found and is left unchanged. The Price is stored, not yet charged. This does not create a Stripe Price, and a buyer cannot set one. The later checkout must verify the Price on the connected account.",
8396
8396
  inputSchema: {
8397
- ocs_account_id: z12.number().int().positive().optional().describe("Owned OCS account override. Omit for automatic resolution."),
8398
- storefront_id: z12.string().min(1).describe("Id of the hosted storefront"),
8399
- slug: z12.string().min(1).describe("Plan slug, such as eu-1gb"),
8400
- price_cents: z12.number().int().positive().optional().describe("Retail price in minor units. Must be greater than zero. Omit to leave the price."),
8401
- active: z12.boolean().optional().describe("Whether the plan is for sale. Omit to leave it."),
8402
- sort_order: z12.number().int().nonnegative().optional().describe("Display order, lowest first. Omit to leave it."),
8403
- stripe_price_id: z12.string().regex(/^price_[A-Za-z0-9_]+$/).max(255).nullable().optional().describe("Existing Stripe Price id (price_\u2026, 1-255 characters), stored, not yet charged. Set with stripe_price_mode. Null clears both. Omit to leave them."),
8404
- stripe_price_mode: z12.enum(["test", "live"]).nullable().optional().describe("test or live. Set with stripe_price_id. Null clears both. Omit to leave them.")
8397
+ ocs_account_id: z13.number().int().positive().optional().describe("Owned OCS account override. Omit for automatic resolution."),
8398
+ storefront_id: z13.string().min(1).describe("Id of the hosted storefront"),
8399
+ slug: z13.string().min(1).describe("Plan slug, such as eu-1gb"),
8400
+ price_cents: z13.number().int().positive().optional().describe("Retail price in minor units. Must be greater than zero. Omit to leave the price."),
8401
+ active: z13.boolean().optional().describe("Whether the plan is for sale. Omit to leave it."),
8402
+ sort_order: z13.number().int().nonnegative().optional().describe("Display order, lowest first. Omit to leave it."),
8403
+ stripe_price_id: z13.string().regex(/^price_[A-Za-z0-9_]+$/).max(255).nullable().optional().describe("Existing Stripe Price id (price_\u2026, 1-255 characters), stored, not yet charged. Set with stripe_price_mode. Null clears both. Omit to leave them."),
8404
+ stripe_price_mode: z13.enum(["test", "live"]).nullable().optional().describe("test or live. Set with stripe_price_id. Null clears both. Omit to leave them.")
8405
8405
  },
8406
8406
  annotations: annotationsFor("update_storefront_plan", "write")
8407
8407
  },
@@ -8418,9 +8418,9 @@ function registerStorefrontPlanTools(server2, props2, call = (path, body2) => {
8418
8418
  });
8419
8419
  if (!update.ok) return err5(update.message);
8420
8420
  try {
8421
- const result2 = await call(`${storefront_id}/${slug}`, update.body);
8422
- const text = JSON.stringify(result2.body);
8423
- return result2.ok ? ok4(text) : err5(text);
8421
+ const result3 = await call(`${storefront_id}/${slug}`, update.body);
8422
+ const text = JSON.stringify(result3.body);
8423
+ return result3.ok ? ok4(text) : err5(text);
8424
8424
  } catch (e) {
8425
8425
  return err5(e instanceof Error ? e.message : "plan update failed");
8426
8426
  }
@@ -8429,7 +8429,7 @@ function registerStorefrontPlanTools(server2, props2, call = (path, body2) => {
8429
8429
  }
8430
8430
 
8431
8431
  // src/tools-atlas.ts
8432
- import { z as z13 } from "zod";
8432
+ import { z as z14 } from "zod";
8433
8433
 
8434
8434
  // src/atlas-public.ts
8435
8435
  var ATLAS_PUBLIC_BASE_URL = "https://atlas.carrier.llc";
@@ -8487,13 +8487,13 @@ var ATLAS_TOOL_SCOPES = {
8487
8487
  get_atlas_network_status: "read"
8488
8488
  };
8489
8489
  var coverageSchema = {
8490
- country: z13.string().regex(/^[A-Za-z]{2}$/, "country must be a 2-letter ISO code").describe("ISO 3166-1 alpha-2 country code, for example JP or NL"),
8491
- status: z13.enum(["up", "degraded", "down", "unknown"]).optional().describe("Keep only networks whose latest probe has this status"),
8492
- technology: z13.enum(["2G", "3G", "4G", "5G"]).optional().describe("Keep only networks of this radio generation")
8490
+ country: z14.string().regex(/^[A-Za-z]{2}$/, "country must be a 2-letter ISO code").describe("ISO 3166-1 alpha-2 country code, for example JP or NL"),
8491
+ status: z14.enum(["up", "degraded", "down", "unknown"]).optional().describe("Keep only networks whose latest probe has this status"),
8492
+ technology: z14.enum(["2G", "3G", "4G", "5G"]).optional().describe("Keep only networks of this radio generation")
8493
8493
  };
8494
8494
  var networkSchema = {
8495
- mcc: z13.string().regex(/^\d{3}$/, "mcc must be 3 digits").describe("Mobile Country Code"),
8496
- mnc: z13.string().regex(/^\d{2,3}$/, "mnc must be 2 or 3 digits").describe("Mobile Network Code")
8495
+ mcc: z14.string().regex(/^\d{3}$/, "mcc must be 3 digits").describe("Mobile Country Code"),
8496
+ mnc: z14.string().regex(/^\d{2,3}$/, "mnc must be 2 or 3 digits").describe("Mobile Network Code")
8497
8497
  };
8498
8498
  function jsonResult3(body2) {
8499
8499
  return {
@@ -8548,15 +8548,15 @@ function registerAtlasTools(server2, ctx) {
8548
8548
  }
8549
8549
 
8550
8550
  // src/tools-network-default.ts
8551
- import { z as z14 } from "zod";
8551
+ import { z as z15 } from "zod";
8552
8552
  var NETWORK_DEFAULT_TOOL_SCOPES = {
8553
8553
  get_network_default: "read",
8554
8554
  set_network_default: "write",
8555
8555
  plan_network_default: "read"
8556
8556
  };
8557
- var choiceShape = z14.object({
8558
- mode: z14.enum(NETWORK_DEFAULT_MODES),
8559
- steeringListId: z14.number().int().positive().optional()
8557
+ var choiceShape = z15.object({
8558
+ mode: z15.enum(NETWORK_DEFAULT_MODES),
8559
+ steeringListId: z15.number().int().positive().optional()
8560
8560
  }).describe("`cheapest_available`, `all`, or `custom` with a steeringListId from list_steering_lists");
8561
8561
  function ioFor(ctx, token2) {
8562
8562
  const kv = ctx.env.CARRIER_USERS;
@@ -8611,9 +8611,9 @@ function registerNetworkDefaultTools(server2, ctx) {
8611
8611
  title: "Set Network Default",
8612
8612
  description: "Use this to set the organisation's network default to `cheapest_available`, `all`, or `custom` (a steering list id from `list_steering_lists`, which must exist). This only stores the setting. It changes no SIM, writes nothing to OCS and does not migrate existing customers: it applies to NEW assignments. A single assignment can still override it with `plan_network_default`'s `simOverride`. Params: `mode` (required), `steeringListId` (required when mode is `custom`), `dry_run` (preview only). Do NOT use this to assign a list to one SIM \u2014 use `modify_subscriber_steering_list`.",
8613
8613
  inputSchema: {
8614
- mode: z14.enum(NETWORK_DEFAULT_MODES).describe("cheapest_available | all | custom"),
8615
- steeringListId: z14.number().int().positive().optional().describe("Required when mode is custom"),
8616
- dry_run: z14.boolean().optional().describe("If true, validate and return what would be stored; store nothing")
8614
+ mode: z15.enum(NETWORK_DEFAULT_MODES).describe("cheapest_available | all | custom"),
8615
+ steeringListId: z15.number().int().positive().optional().describe("Required when mode is custom"),
8616
+ dry_run: z15.boolean().optional().describe("If true, validate and return what would be stored; store nothing")
8617
8617
  },
8618
8618
  annotations: { readOnlyHint: false, idempotentHint: true, destructiveHint: false }
8619
8619
  },
@@ -8642,10 +8642,10 @@ function registerNetworkDefaultTools(server2, ctx) {
8642
8642
  title: "Plan Network Default",
8643
8643
  description: "Use this to see which networks a SIM would be given in one or more countries, before anything is assigned. By default that is the cheapest available network per country (lowest data rate above zero, among rules really in force). Precedence: `simOverride`, then `packageOverride`, then the org default, then `cheapest_available`. Read only: `applied` is always false. If the tariff is missing or cannot be compared it falls back to ALL networks and says so in `warnings` and `summary` (`fellBackToAll: true`); never present that as a cheapest choice. The price basis is the wholesale data rate per MB, not the end price. Creating a steering list has no OCS REST method, so when no existing list matches the result is `needs_list`, not a created list. Params: `countries` (ISO-3166 alpha-2 codes, required), `simOverride`, `packageOverride`, `resellerId` (optional).",
8644
8644
  inputSchema: {
8645
- countries: z14.array(z14.string().length(2)).min(1).describe('ISO-3166 alpha-2 codes, e.g. ["CA"]'),
8645
+ countries: z15.array(z15.string().length(2)).min(1).describe('ISO-3166 alpha-2 codes, e.g. ["CA"]'),
8646
8646
  simOverride: choiceShape.optional(),
8647
8647
  packageOverride: choiceShape.optional(),
8648
- resellerId: z14.number().int().positive().optional().describe("Omit to use the token owner's reseller")
8648
+ resellerId: z15.number().int().positive().optional().describe("Omit to use the token owner's reseller")
8649
8649
  },
8650
8650
  annotations: { readOnlyHint: true }
8651
8651
  },
@@ -8660,7 +8660,7 @@ function registerNetworkDefaultTools(server2, ctx) {
8660
8660
  }
8661
8661
 
8662
8662
  // src/affiliate-tools.ts
8663
- import { z as z15 } from "zod";
8663
+ import { z as z16 } from "zod";
8664
8664
  var AFFILIATE_TOOL_SCOPES = {
8665
8665
  affiliate_status: "read",
8666
8666
  affiliate_commissions: "read",
@@ -8731,7 +8731,7 @@ function registerAffiliateTools(server2, ctx) {
8731
8731
  title: "Affiliate Commissions",
8732
8732
  description: "Read-only: returns the list of commission records for the authenticated operator.",
8733
8733
  inputSchema: {
8734
- limit: z15.number().int().min(1).max(200).optional().default(50).describe("Maximum number of commission records to return (1-200, default: 50).")
8734
+ limit: z16.number().int().min(1).max(200).optional().default(50).describe("Maximum number of commission records to return (1-200, default: 50).")
8735
8735
  },
8736
8736
  annotations: annotationsFor("affiliate_commissions", "read")
8737
8737
  },
@@ -10882,15 +10882,15 @@ function registerAllCarrierAskTools(server2, ctx) {
10882
10882
  title: "Natural Language Carrier Tool Router",
10883
10883
  description: "Use this when you want to perform a carrier operation but don't know which specific tool to call. Describe your intent in plain language and carrier_ask will identify the correct tool(s) and suggest the required parameters. For simple read intents, it executes directly and returns results. For destructive operations it returns a confirm_token that you must pass in a second call. Params: `intent` (string \u2014 natural language description of what you want to do), `context` (optional: iccid, account_id, reseller_id if already known). Returns: RouteResult \u2014 confirmed | pending_confirm | ambiguous | none. Do NOT use this when you know the right tool \u2014 direct calls are faster and cheaper.",
10884
10884
  inputSchema: {
10885
- intent: z16.string().min(3).describe(
10885
+ intent: z17.string().min(3).describe(
10886
10886
  "Natural-language description of the operation to perform (e.g. 'suspend ICCID 89316 until next month', 'show fleet health', 'assign Europe 5GB package to subscriber 89316...')"
10887
10887
  ),
10888
- context: z16.object({
10889
- iccid: z16.string().optional().describe("Subscriber ICCID if already known"),
10890
- account_id: z16.number().optional().describe("Account ID if already known"),
10891
- reseller_id: z16.number().optional().describe("Reseller ID if already known")
10888
+ context: z17.object({
10889
+ iccid: z17.string().optional().describe("Subscriber ICCID if already known"),
10890
+ account_id: z17.number().optional().describe("Account ID if already known"),
10891
+ reseller_id: z17.number().optional().describe("Reseller ID if already known")
10892
10892
  }).optional().describe("Optional pre-resolved context to improve routing accuracy"),
10893
- confirm_token: z16.string().optional().describe(
10893
+ confirm_token: z17.string().optional().describe(
10894
10894
  "One-time token from a previous carrier_ask call with confirm_required=true. Providing this executes the previously staged destructive operation."
10895
10895
  )
10896
10896
  }
@@ -11094,7 +11094,7 @@ function registerAllCarrierAskTools(server2, ctx) {
11094
11094
  title: "Describe a Carrier Tool",
11095
11095
  description: "Get full documentation for any registered Carrier MCP tool: description, parameters, 2-3 example invocations, required scope, destructive flag, and guidance. Params: `tool_name` (exact MCP tool name, e.g. 'assign_package'). Returns: structured tool metadata. Does NOT execute the tool.",
11096
11096
  inputSchema: {
11097
- tool_name: z16.string().describe("The exact MCP tool name to describe (e.g. 'assign_package', 'hlr_set_bitrate')")
11097
+ tool_name: z17.string().describe("The exact MCP tool name to describe (e.g. 'assign_package', 'hlr_set_bitrate')")
11098
11098
  }
11099
11099
  },
11100
11100
  wrapHandler(
@@ -11187,7 +11187,7 @@ function buildExamples(toolName) {
11187
11187
  }
11188
11188
 
11189
11189
  // src/list-recent-ocs-events.ts
11190
- import { z as z17 } from "zod";
11190
+ import { z as z18 } from "zod";
11191
11191
 
11192
11192
  // ../../packages/ocs-spec/src/ocs-event-buffer-read.ts
11193
11193
  var LIFECYCLE_RESELLER_ID2 = 1170;
@@ -11316,10 +11316,10 @@ var ALLOWED_EVENT_TYPES = [
11316
11316
  "usage.anomaly"
11317
11317
  ];
11318
11318
  var listRecentOcsEventsSchema = {
11319
- iccid: z17.string().regex(/^\d{19,20}$/).describe("ICCID, 19 or 20 digits, ITU-T E.118 format"),
11320
- limit: z17.number().int().min(1).max(50).default(20).describe("Max events to return, newest first"),
11321
- event_types: z17.array(z17.enum(ALLOWED_EVENT_TYPES)).optional().describe("Filter to specific event types"),
11322
- since: z17.string().datetime().optional().describe("ISO-8601 timestamp; only events after this point")
11319
+ iccid: z18.string().regex(/^\d{19,20}$/).describe("ICCID, 19 or 20 digits, ITU-T E.118 format"),
11320
+ limit: z18.number().int().min(1).max(50).default(20).describe("Max events to return, newest first"),
11321
+ event_types: z18.array(z18.enum(ALLOWED_EVENT_TYPES)).optional().describe("Filter to specific event types"),
11322
+ since: z18.string().datetime().optional().describe("ISO-8601 timestamp; only events after this point")
11323
11323
  };
11324
11324
  async function listRecentOcsEvents2(iccid, limit, eventTypes, since, kv) {
11325
11325
  return listRecentOcsEvents(iccid, limit, eventTypes, since, kv);
@@ -11360,7 +11360,7 @@ function registerListRecentOcsEventsTool(server2, ctx) {
11360
11360
  "OCS_EVENT_ROUTING",
11361
11361
  "the OCS event ring buffer"
11362
11362
  );
11363
- const result2 = await listRecentOcsEvents2(
11363
+ const result3 = await listRecentOcsEvents2(
11364
11364
  iccid,
11365
11365
  limit,
11366
11366
  event_types,
@@ -11368,7 +11368,7 @@ function registerListRecentOcsEventsTool(server2, ctx) {
11368
11368
  env.OCS_EVENT_ROUTING
11369
11369
  );
11370
11370
  return {
11371
- content: [{ type: "text", text: JSON.stringify(result2, null, 2) }]
11371
+ content: [{ type: "text", text: JSON.stringify(result3, null, 2) }]
11372
11372
  };
11373
11373
  } catch (err9) {
11374
11374
  const message = err9 instanceof Error ? err9.message : String(err9);
@@ -11382,7 +11382,7 @@ function registerListRecentOcsEventsTool(server2, ctx) {
11382
11382
  }
11383
11383
 
11384
11384
  // src/tools-rate-governor.ts
11385
- import { z as z18 } from "zod";
11385
+ import { z as z19 } from "zod";
11386
11386
  var MONITORED_ENDPOINTS = [
11387
11387
  "subscriberNetworkEventsOverPeriod",
11388
11388
  // 30/min
@@ -11414,7 +11414,7 @@ function registerRateLimitStatusTool(server2, ctx) {
11414
11414
  title: "API Rate-Limit Governor Status",
11415
11415
  description: "Inspect Bridge4IP OCS rate-limit governor state \u2014 bucket fill levels, per-endpoint limits, and 80% alert thresholds. Use this to answer: 'are we rate limited', 'check ocs quota', 'how full is the rate limit bucket', 'rate limit status'. Params: `endpoint` (optional \u2014 OCS camelCase method name to inspect a single bucket, e.g. 'subscriberUsageOverPeriod'; omit for all monitored endpoints). Returns: per-endpoint { limit_per_min, batch_cap_per_min, calls_in_window, batch_calls_in_window, utilisation_pct, alert (true when \u226580% of limit) }. Note: counts come from the in-process sliding-window log (same key as OCS calls: API token + endpoint) \u2014 they reset when the Worker isolate recycles. Use as a relative signal, not an exact counter. Do NOT use this to adjust limits \u2014 limits are set by Bridge4IP contract and cannot be changed via MCP.",
11416
11416
  inputSchema: {
11417
- endpoint: z18.string().optional().describe(
11417
+ endpoint: z19.string().optional().describe(
11418
11418
  "OCS method name in camelCase (e.g. 'subscriberUsageOverPeriod'). Omit to return status for all monitored endpoints."
11419
11419
  )
11420
11420
  },
@@ -11470,7 +11470,7 @@ function registerRateLimitStatusTool(server2, ctx) {
11470
11470
  }
11471
11471
 
11472
11472
  // src/tools-depletion-events.ts
11473
- import { z as z19 } from "zod";
11473
+ import { z as z20 } from "zod";
11474
11474
  function ok6(payload) {
11475
11475
  return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] };
11476
11476
  }
@@ -11498,10 +11498,10 @@ function registerDepletionEventsTool(server2, ctx) {
11498
11498
  title: "Subscriber Bundle Depletion Events",
11499
11499
  description: "Look up bundle depletion events for a subscriber (or list recent fleet-wide depletions). Returns the most recent bundle.depleted event stored when the prepaid usage webhook received a last_slice notification. Events are retained for 7 days. Use subscriberId to check a specific subscriber, or omit to list the 20 most recent fleet-wide depletions. Requires 'read' scope.",
11500
11500
  inputSchema: {
11501
- subscriberId: z19.string().optional().describe(
11501
+ subscriberId: z20.string().optional().describe(
11502
11502
  "OCS subscriber ID to look up. Omit to list the 20 most recent fleet-wide depletions."
11503
11503
  ),
11504
- since: z19.string().optional().describe(
11504
+ since: z20.string().optional().describe(
11505
11505
  "ISO-8601 timestamp \u2014 only return events at or after this time (for single-subscriber lookup)."
11506
11506
  )
11507
11507
  },
@@ -11616,7 +11616,7 @@ function registerDepletionEventsTool(server2, ctx) {
11616
11616
  }
11617
11617
 
11618
11618
  // src/tools-country-history.ts
11619
- import { z as z20 } from "zod";
11619
+ import { z as z21 } from "zod";
11620
11620
  function isoDate(now, daysAgo = 0) {
11621
11621
  const d = new Date(now.getTime() - daysAgo * 864e5);
11622
11622
  return d.toISOString().slice(0, 10);
@@ -11639,10 +11639,10 @@ function registerCountryHistoryTool(server2, ctx) {
11639
11639
  title: "Subscriber Country History",
11640
11640
  description: "Return cross-border movement history for a subscriber, reconstructed from OCS Gy charging events. Reads `gyAnswer.events` from `subscriberNetworkEventsOverPeriod` \u2014 every Gy record carries its own country, operator and MCC \u2014 and collapses consecutive same-country records into stays with first-seen and last-seen timestamps. This needs no webhook: it works with Relay LU and Relay Gy off. Relay `country.entered` events from the 24h ring-buffer are merged in as a supplement when present. Use this to answer: 'where has subscriber X traveled', 'show country history for ICCID', 'border crossings for this SIM'. Params: `subscriberId` (ICCID, 19\u201320 digits), `startDate`/`endDate` (YYYY-MM-DD, max 7 days apart, default the last 7 days), `limit` (1\u201350, default 20, newest first). Returns: `stays` ({ country, country_name, first_seen, last_seen, operators, mccs, event_count, used_bytes }), `transitions` ({ from, to, at }), and `country_events` in the legacy flat shape. `used_bytes` already handles the string-typed `usedUnits` and its 'N/A' values. Do NOT use this for raw per-session records \u2014 use `subscriber_network_events` for those.",
11641
11641
  inputSchema: {
11642
- subscriberId: z20.string().regex(/^\d{19,20}$/, "subscriberId must be a 19\u201320 digit ICCID").describe("Subscriber ICCID (19\u201320 digits, ITU-T E.118)"),
11643
- startDate: z20.string().regex(/^\d{4}-\d{2}-\d{2}$/, "startDate must be YYYY-MM-DD").optional().describe("Start of the period, YYYY-MM-DD inclusive (default: 7 days ago)"),
11644
- endDate: z20.string().regex(/^\d{4}-\d{2}-\d{2}$/, "endDate must be YYYY-MM-DD").optional().describe("End of the period, YYYY-MM-DD inclusive, max 7 days from start (default: today)"),
11645
- limit: z20.number().int().min(1).max(50).default(20).optional().describe("Maximum number of country_events to return, newest first (default 20, max 50)")
11642
+ subscriberId: z21.string().regex(/^\d{19,20}$/, "subscriberId must be a 19\u201320 digit ICCID").describe("Subscriber ICCID (19\u201320 digits, ITU-T E.118)"),
11643
+ startDate: z21.string().regex(/^\d{4}-\d{2}-\d{2}$/, "startDate must be YYYY-MM-DD").optional().describe("Start of the period, YYYY-MM-DD inclusive (default: 7 days ago)"),
11644
+ endDate: z21.string().regex(/^\d{4}-\d{2}-\d{2}$/, "endDate must be YYYY-MM-DD").optional().describe("End of the period, YYYY-MM-DD inclusive, max 7 days from start (default: today)"),
11645
+ limit: z21.number().int().min(1).max(50).default(20).optional().describe("Maximum number of country_events to return, newest first (default 20, max 50)")
11646
11646
  },
11647
11647
  annotations: { readOnlyHint: true, idempotentHint: true }
11648
11648
  },
@@ -11750,7 +11750,7 @@ function registerCountryHistoryTool(server2, ctx) {
11750
11750
  }
11751
11751
 
11752
11752
  // src/apps/fleet-health-app.ts
11753
- import { z as z21 } from "zod";
11753
+ import { z as z22 } from "zod";
11754
11754
  import {
11755
11755
  registerAppTool,
11756
11756
  registerAppResource,
@@ -11798,7 +11798,7 @@ function toFleetInput(raw) {
11798
11798
 
11799
11799
  // src/apps/fleet-health-app.ts
11800
11800
  var FLEET_APP_RESOURCE_URI = "ui://fleet-health-dashboard";
11801
- async function safeCall2(client2, method, params) {
11801
+ async function safeCall3(client2, method, params) {
11802
11802
  try {
11803
11803
  return { data: await client2.call(method, params), error: null };
11804
11804
  } catch (err9) {
@@ -11812,8 +11812,8 @@ async function loadFleet(ctx, accountId) {
11812
11812
  const statusParams = accountId !== void 0 ? { accountId } : resellerId !== void 0 ? { resellerId } : {};
11813
11813
  const accountParams = resellerId !== void 0 ? { resellerId } : {};
11814
11814
  const [status, accounts] = await Promise.all([
11815
- safeCall2(client2, "esimStatusPerAccount", statusParams),
11816
- safeCall2(client2, "listResellerAccount", accountParams)
11815
+ safeCall3(client2, "esimStatusPerAccount", statusParams),
11816
+ safeCall3(client2, "listResellerAccount", accountParams)
11817
11817
  ]);
11818
11818
  return toFleetInput({
11819
11819
  status: status.data,
@@ -11866,7 +11866,7 @@ function registerFleetHealthApp(server2, ctx) {
11866
11866
  title: "Fleet Health Dashboard",
11867
11867
  description: "Draw the fleet overview as an interactive panel: eSIM status, per-account breakdown and low-balance alerts. Returns structuredContent for the panel, so it only helps a client that can render MCP UI resources. Do NOT use this when the answer has to be readable text, or in any headless or scripted context \u2014 `fleet_health` returns the same data as prose.",
11868
11868
  inputSchema: {
11869
- accountId: z21.number().optional().describe("Filter to a specific account (omit for all)")
11869
+ accountId: z22.number().optional().describe("Filter to a specific account (omit for all)")
11870
11870
  },
11871
11871
  annotations: { readOnlyHint: true },
11872
11872
  _meta: {
@@ -11909,7 +11909,7 @@ function registerFleetHealthApp(server2, ctx) {
11909
11909
  }
11910
11910
 
11911
11911
  // src/apps/provisioning-wizard.ts
11912
- import { z as z22 } from "zod";
11912
+ import { z as z23 } from "zod";
11913
11913
  import {
11914
11914
  registerAppTool as registerAppTool2,
11915
11915
  registerAppResource as registerAppResource2,
@@ -12014,10 +12014,10 @@ function registerProvisioningWizard(server2, ctx) {
12014
12014
  title: "eSIM Provisioning Wizard",
12015
12015
  description: "Interactive 3-step wizard to provision an eSIM: select subscriber, choose package template, preview (dry_run) and confirm execution.",
12016
12016
  inputSchema: {
12017
- step: z22.enum(["init", "select-package", "preview", "confirm"]).describe("Current wizard step"),
12018
- wizardId: z22.string().optional().describe("Wizard session ID (absent on init)"),
12019
- subscriber_iccid: z22.string().optional().describe("Subscriber ICCID (required for select-package)"),
12020
- package_template_id: z22.number().optional().describe("Package template ID (required for preview)")
12017
+ step: z23.enum(["init", "select-package", "preview", "confirm"]).describe("Current wizard step"),
12018
+ wizardId: z23.string().optional().describe("Wizard session ID (absent on init)"),
12019
+ subscriber_iccid: z23.string().optional().describe("Subscriber ICCID (required for select-package)"),
12020
+ package_template_id: z23.number().optional().describe("Package template ID (required for preview)")
12021
12021
  },
12022
12022
  _meta: {
12023
12023
  ui: {
@@ -12248,7 +12248,7 @@ function registerProvisioningWizard(server2, ctx) {
12248
12248
  isError: true
12249
12249
  };
12250
12250
  }
12251
- const result2 = await safeCallWithToken(
12251
+ const result3 = await safeCallWithToken(
12252
12252
  client2,
12253
12253
  token2,
12254
12254
  "affectPackageToSubscriber",
@@ -12258,12 +12258,12 @@ function registerProvisioningWizard(server2, ctx) {
12258
12258
  }
12259
12259
  );
12260
12260
  await deleteWizardSession(ctx.env, ctx.props.sub, wizardId);
12261
- if (result2.error) {
12261
+ if (result3.error) {
12262
12262
  return {
12263
12263
  content: [
12264
12264
  {
12265
12265
  type: "text",
12266
- text: `Provisioning failed: ${result2.error}`
12266
+ text: `Provisioning failed: ${result3.error}`
12267
12267
  }
12268
12268
  ],
12269
12269
  isError: true
@@ -12274,7 +12274,7 @@ function registerProvisioningWizard(server2, ctx) {
12274
12274
  structuredContent: {
12275
12275
  wizardId,
12276
12276
  step: "done",
12277
- result: result2.data
12277
+ result: result3.data
12278
12278
  }
12279
12279
  };
12280
12280
  }
@@ -12287,7 +12287,7 @@ function registerProvisioningWizard(server2, ctx) {
12287
12287
  }
12288
12288
 
12289
12289
  // src/apps/balance-topup.ts
12290
- import { z as z23 } from "zod";
12290
+ import { z as z24 } from "zod";
12291
12291
  import {
12292
12292
  registerAppTool as registerAppTool3,
12293
12293
  registerAppResource as registerAppResource3,
@@ -12340,9 +12340,9 @@ function registerBalanceTopupApp(server2, ctx) {
12340
12340
  title: "Balance Top-up Form",
12341
12341
  description: "Adjust the OCS reseller-account balance behind one subscriber, through a form panel the user can review before it commits. Defaults to preview: a call that omits `preview` returns a projection and writes nothing. Only `preview: false` performs the OCS write. Params: `iccid` (subscriber identifier used to find the account), `delta` (amount to add when positive, deduct when negative), `preview` (boolean, default true). Requires `admin` scope plus recent MFA, and a client that can render UI panels. Do NOT use this in a headless or scripted context \u2014 call `modify_account_balance` directly, which takes an `accountId` and needs no panel. Do NOT use this for a subscriber's own balance \u2014 the `iccid` here only locates the account; per-subscriber money is `modify_subscriber_balance`. Do NOT use this for the Carrier prepaid wallet or MCP credits \u2014 see `wallet_topup_checkout` and `credit_balance`.",
12342
12342
  inputSchema: {
12343
- iccid: z23.string().describe("The subscriber ICCID for the account lookup"),
12344
- delta: z23.number().describe("Amount to add (positive) or deduct (negative) from the account balance"),
12345
- preview: z23.boolean().default(true).describe("If true, return preview without writing. If false, execute the balance change.")
12343
+ iccid: z24.string().describe("The subscriber ICCID for the account lookup"),
12344
+ delta: z24.number().describe("Amount to add (positive) or deduct (negative) from the account balance"),
12345
+ preview: z24.boolean().default(true).describe("If true, return preview without writing. If false, execute the balance change.")
12346
12346
  },
12347
12347
  annotations: { destructiveHint: true },
12348
12348
  _meta: {
@@ -12361,13 +12361,13 @@ function registerBalanceTopupApp(server2, ctx) {
12361
12361
  const token2 = await ctx.getUserToken(ctx.props.sub);
12362
12362
  const client2 = new OcsClient(ctx.env.CARRIER_OCS_BASE_URL, token2);
12363
12363
  if (preview === true) {
12364
- const result2 = await safeCallWithToken2(
12364
+ const result3 = await safeCallWithToken2(
12365
12365
  client2,
12366
12366
  token2,
12367
12367
  "getSingleSubscriber",
12368
12368
  { iccid }
12369
12369
  );
12370
- const currentBalance = result2.data ? Number(result2.data["balance"] ?? result2.data["accountBalance"] ?? 0) : 0;
12370
+ const currentBalance = result3.data ? Number(result3.data["balance"] ?? result3.data["accountBalance"] ?? 0) : 0;
12371
12371
  const newBalance2 = currentBalance + delta;
12372
12372
  const structured2 = {
12373
12373
  iccid,
@@ -12425,7 +12425,7 @@ function registerAllApps(server2, ctx) {
12425
12425
  }
12426
12426
 
12427
12427
  // src/prompts.ts
12428
- import { z as z24 } from "zod";
12428
+ import { z as z25 } from "zod";
12429
12429
  function registerAllPrompts(server2) {
12430
12430
  server2.registerPrompt(
12431
12431
  "fleet_health_report",
@@ -12461,7 +12461,7 @@ Format as a structured report with sections, tables, and actionable recommendati
12461
12461
  {
12462
12462
  title: "Subscriber Deep Dive",
12463
12463
  description: "Comprehensive analysis of a single subscriber: profile, packages, usage patterns, location history, recommendations.",
12464
- argsSchema: { iccid: z24.string().describe("The subscriber ICCID to analyse") }
12464
+ argsSchema: { iccid: z25.string().describe("The subscriber ICCID to analyse") }
12465
12465
  },
12466
12466
  async ({ iccid }) => ({
12467
12467
  messages: [
@@ -12560,7 +12560,7 @@ Analyze and present:
12560
12560
  {
12561
12561
  title: "Bulk Operations Planner",
12562
12562
  description: "Plan bulk operations safely: mass package assignments, account migrations, balance adjustments, or status changes.",
12563
- argsSchema: { operation: z24.string().describe("Describe the bulk operation you want to perform") }
12563
+ argsSchema: { operation: z25.string().describe("Describe the bulk operation you want to perform") }
12564
12564
  },
12565
12565
  async ({ operation }) => ({
12566
12566
  messages: [
@@ -12593,7 +12593,7 @@ NEVER execute destructive operations without confirmation.`
12593
12593
  }
12594
12594
 
12595
12595
  // src/tools-pricing.ts
12596
- import { z as z25 } from "zod";
12596
+ import { z as z26 } from "zod";
12597
12597
  function registerAllPricingTools(server2, ctx) {
12598
12598
  const allTools = [...PRICING_TOOLS, ...PROJECTS_TOOLS];
12599
12599
  for (const tool of allTools) {
@@ -12657,7 +12657,7 @@ function buildPricingHandler(tool, ctx) {
12657
12657
  }
12658
12658
  }
12659
12659
  try {
12660
- const result2 = await tool.handler(ctx.env, ctx.props, args);
12660
+ const result3 = await tool.handler(ctx.env, ctx.props, args);
12661
12661
  recordUsage(ctx.env, ctx.props.sub, tier);
12662
12662
  deductCredits(ctx.env, ctx.props.sub, tier, tool.scope);
12663
12663
  ctx.audit({
@@ -12671,7 +12671,7 @@ function buildPricingHandler(tool, ctx) {
12671
12671
  content: [
12672
12672
  {
12673
12673
  type: "text",
12674
- text: JSON.stringify(result2, null, 2)
12674
+ text: JSON.stringify(result3, null, 2)
12675
12675
  }
12676
12676
  ]
12677
12677
  };
@@ -12696,23 +12696,23 @@ function toolNameToTitle(name) {
12696
12696
  }
12697
12697
  function buildZodSchema(schema) {
12698
12698
  const properties = schema.properties ?? {};
12699
- const result2 = {};
12699
+ const result3 = {};
12700
12700
  for (const [key, prop] of Object.entries(properties)) {
12701
12701
  let field;
12702
12702
  if (prop.enum) {
12703
- field = z25.enum(prop.enum);
12703
+ field = z26.enum(prop.enum);
12704
12704
  } else if (prop.type === "number") {
12705
- field = z25.number();
12705
+ field = z26.number();
12706
12706
  } else if (prop.type === "boolean") {
12707
- field = z25.boolean();
12707
+ field = z26.boolean();
12708
12708
  } else if (prop.type === "array") {
12709
12709
  if (prop.items?.type === "number") {
12710
- field = z25.array(z25.number());
12710
+ field = z26.array(z26.number());
12711
12711
  } else {
12712
- field = z25.array(z25.string());
12712
+ field = z26.array(z26.string());
12713
12713
  }
12714
12714
  } else {
12715
- field = z25.string();
12715
+ field = z26.string();
12716
12716
  }
12717
12717
  const required = schema.required ?? [];
12718
12718
  if (!required.includes(key)) {
@@ -12721,13 +12721,13 @@ function buildZodSchema(schema) {
12721
12721
  if (prop.description) {
12722
12722
  field = field.describe(prop.description);
12723
12723
  }
12724
- result2[key] = field;
12724
+ result3[key] = field;
12725
12725
  }
12726
- return result2;
12726
+ return result3;
12727
12727
  }
12728
12728
 
12729
12729
  // src/tools-greenzone.ts
12730
- import { z as z26 } from "zod";
12730
+ import { z as z27 } from "zod";
12731
12731
 
12732
12732
  // src/greenzone-whitelist.ts
12733
12733
  var STATE_KEY = "greenzone:state";
@@ -13018,9 +13018,9 @@ function registerGreenzoneTools(server2, ctx) {
13018
13018
  title: "Greenzone Whitelist \u2014 Add",
13019
13019
  description: "Add a hostname and/or IP address to the Bridge4IP Greenzone whitelist. The Greenzone whitelist controls which hosts/IPs are exempt from data charging after a subscriber's bundle is depleted. This operates via browser automation (Kapture) against the OCS portal \u2014 no REST API exists for this surface. Provide `host` (e.g. 'example.com') and/or `ip` (e.g. '203.0.113.0/24'). At least one of host or ip must be provided. Returns Kapture step sequence for Claude Code to execute. Requires 'write' scope and Kapture running in Sam's Chrome.",
13020
13020
  inputSchema: {
13021
- host: z26.string().optional().describe("Hostname to whitelist (e.g. 'example.com')"),
13022
- ip: z26.string().optional().describe("IP address or CIDR to whitelist (e.g. '203.0.113.0/24')"),
13023
- dry_run: z26.boolean().optional().describe("If true, return the Kapture steps without executing portal automation")
13021
+ host: z27.string().optional().describe("Hostname to whitelist (e.g. 'example.com')"),
13022
+ ip: z27.string().optional().describe("IP address or CIDR to whitelist (e.g. '203.0.113.0/24')"),
13023
+ dry_run: z27.boolean().optional().describe("If true, return the Kapture steps without executing portal automation")
13024
13024
  },
13025
13025
  annotations: { destructiveHint: true }
13026
13026
  },
@@ -13079,9 +13079,9 @@ function registerGreenzoneTools(server2, ctx) {
13079
13079
  title: "Greenzone Whitelist \u2014 Remove",
13080
13080
  description: "Remove a hostname and/or IP address from the Bridge4IP Greenzone whitelist. This operates via browser automation (Kapture) against the OCS portal. Provide `host` and/or `ip` to remove \u2014 at least one required. Returns Kapture step sequence for Claude Code to execute. Requires 'write' scope and Kapture running in Sam's Chrome.",
13081
13081
  inputSchema: {
13082
- host: z26.string().optional().describe("Hostname to remove from whitelist"),
13083
- ip: z26.string().optional().describe("IP address or CIDR to remove from whitelist"),
13084
- dry_run: z26.boolean().optional().describe("If true, return the Kapture steps without executing portal automation")
13082
+ host: z27.string().optional().describe("Hostname to remove from whitelist"),
13083
+ ip: z27.string().optional().describe("IP address or CIDR to remove from whitelist"),
13084
+ dry_run: z27.boolean().optional().describe("If true, return the Kapture steps without executing portal automation")
13085
13085
  },
13086
13086
  annotations: { destructiveHint: true }
13087
13087
  },
@@ -13140,7 +13140,7 @@ function registerGreenzoneTools(server2, ctx) {
13140
13140
  title: "Greenzone Whitelist \u2014 List",
13141
13141
  description: "List current Greenzone whitelist entries from the KV cache. Returns all whitelisted hosts and IPs, when the state was last synced, and whether the last hourly reconciliation detected drift from the portal. This is a fast read from KV \u2014 no browser automation required. Use `from_portal: true` to trigger a live portal read via Kapture instead of KV. Requires 'read' scope.",
13142
13142
  inputSchema: {
13143
- from_portal: z26.boolean().optional().describe(
13143
+ from_portal: z27.boolean().optional().describe(
13144
13144
  "When true, return Kapture steps to read live portal state instead of KV cache"
13145
13145
  )
13146
13146
  },
@@ -13192,7 +13192,7 @@ function registerGreenzoneTools(server2, ctx) {
13192
13192
  }
13193
13193
 
13194
13194
  // src/tools-ui-agent-generic.ts
13195
- import { z as z27 } from "zod";
13195
+ import { z as z28 } from "zod";
13196
13196
  var COST_PER_STEP_USD = 0.014;
13197
13197
  var SESSION_OVERHEAD_USD = 5e-3;
13198
13198
  function estimateCostUsd2(steps) {
@@ -13234,13 +13234,13 @@ function registerUiAgentGenericTools(server2, ctx, runtime) {
13234
13234
  title: "Dispatch Generic Browsing Agent",
13235
13235
  description: "Send a plain-language task to a hosted browsing agent, which drives a real browser on the open web \u2014 navigating pages, searching, extracting content, filling forms outside the OCS portal. Each run costs roughly $0.20-1.00 in model spend against your own BROWSER_USE_API_KEY, so treat it as the expensive last resort, not a lookup. Limited to CARRIER_BROWSER_USE_MAX_RUNS runs per CLI session (default 10). Params: `prompt` (1-4000 chars \u2014 name the target URL and the exact data or action), `max_steps` (1-30, default 15; prices the dry-run estimate only), `dry_run` (true returns only `estimated_cost_usd` and creates no session). Returns the finished result: unlike the hosted Worker, a local CLI has no background runtime, so this call blocks for the length of the run. Requires `write` scope. Do NOT use this to work out which Carrier tool answers a request \u2014 that is `carrier_ask`, which costs nothing. Do NOT use this for anything the OCS API already covers; every other tool here is faster, free, and audited.",
13236
13236
  inputSchema: {
13237
- prompt: z27.string().min(1).max(4e3).describe(
13237
+ prompt: z28.string().min(1).max(4e3).describe(
13238
13238
  "Natural-language task description for the browsing agent. Be specific: include target URLs, data to extract, or actions to perform."
13239
13239
  ),
13240
- max_steps: z27.number().int().min(1).max(30).optional().describe(
13240
+ max_steps: z28.number().int().min(1).max(30).optional().describe(
13241
13241
  "Advisory step budget (1\u201330, default 15). Prices the dry-run estimate; the hosted agent sets its own depth."
13242
13242
  ),
13243
- dry_run: z27.boolean().optional().describe(
13243
+ dry_run: z28.boolean().optional().describe(
13244
13244
  "Preview cost estimate without dispatching. Returns estimated_cost_usd only \u2014 no browser session is created."
13245
13245
  )
13246
13246
  }
@@ -13312,31 +13312,31 @@ function registerUiAgentGenericTools(server2, ctx, runtime) {
13312
13312
  throw err9;
13313
13313
  }
13314
13314
  try {
13315
- const result2 = await runUiAgent(
13315
+ const result3 = await runUiAgent(
13316
13316
  prompt,
13317
13317
  "Carrier CLI browsing agent",
13318
13318
  runtime.env
13319
13319
  );
13320
- runtime.dispatchedTaskIds.add(result2.task_id);
13320
+ runtime.dispatchedTaskIds.add(result3.task_id);
13321
13321
  ctx.audit({
13322
13322
  tool_name: toolName,
13323
13323
  ocs_method: "[ui-agent:generic-ask]",
13324
- status: result2.status === "error" ? "error" : "ok",
13324
+ status: result3.status === "error" ? "error" : "ok",
13325
13325
  dry_run: false,
13326
13326
  duration_ms: Date.now() - start,
13327
13327
  event_type: "ui_agent_dispatch"
13328
13328
  });
13329
13329
  return {
13330
- ...result2.status === "error" ? { isError: true } : {},
13330
+ ...result3.status === "error" ? { isError: true } : {},
13331
13331
  content: [
13332
13332
  {
13333
13333
  type: "text",
13334
13334
  text: JSON.stringify(
13335
13335
  {
13336
- status: result2.status,
13337
- task_id: result2.task_id,
13338
- ...result2.session_viewer_url ? { session_viewer_url: result2.session_viewer_url } : {},
13339
- result: result2.result,
13336
+ status: result3.status,
13337
+ task_id: result3.task_id,
13338
+ ...result3.session_viewer_url ? { session_viewer_url: result3.session_viewer_url } : {},
13339
+ result: result3.result,
13340
13340
  session_spend_usd: runtime.spend.costUsd,
13341
13341
  runs_remaining_this_session: runtime.budget.remaining,
13342
13342
  note: "The run completed in-process. Task records live only for this CLI session \u2014 ui_agent_status can read this task_id until the process exits."
@@ -13377,7 +13377,7 @@ function registerUiAgentGenericTools(server2, ctx, runtime) {
13377
13377
  title: "Poll Browsing Agent Task Status",
13378
13378
  description: "Returns the current state of a browsing-agent task by `task_id`, including its result once finished. In the local CLI, ui_agent_ask already returns the finished result, so this is mainly for re-reading a task within the same session. Task records do not survive the CLI process exiting. Requires `read` scope.",
13379
13379
  inputSchema: {
13380
- task_id: z27.string().describe("Task ID returned by ui_agent_ask")
13380
+ task_id: z28.string().describe("Task ID returned by ui_agent_ask")
13381
13381
  }
13382
13382
  },
13383
13383
  async (args) => {