@usethrottle/mcp 0.4.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib.js CHANGED
@@ -700,7 +700,7 @@ var ACTIONS = [
700
700
  {
701
701
  id: "receivables_aging",
702
702
  title: "Receivables aging",
703
- description: 'Outstanding receivables bucketed by age \u2014 answers "what is overdue and by how long".',
703
+ description: 'Outstanding receivables bucketed by age \u2014 answers "what is overdue and by how long". Totals come back per currency in byCurrency, never summed across currencies.',
704
704
  kind: "read",
705
705
  scopes: ["invoices:read"],
706
706
  input: [
@@ -846,7 +846,7 @@ var ACTIONS = [
846
846
  {
847
847
  id: "list_abandoned_carts",
848
848
  title: "List abandoned carts",
849
- description: "Carts that were started but never finalized, with recovery status \u2014 the abandoned-cart recovery list.",
849
+ description: "Carts that were started but never finalized, with recovery status \u2014 the abandoned-cart recovery list. The summary value comes back per currency in byCurrency, never summed.",
850
850
  kind: "read",
851
851
  scopes: ["carts:read"],
852
852
  input: [
@@ -1087,7 +1087,7 @@ var ACTIONS = [
1087
1087
  {
1088
1088
  id: "get_sales_timeseries",
1089
1089
  title: "Sales over time",
1090
- description: `Order count and gross revenue bucketed by day, week or month over any date range, in the merchant's timezone, optionally compared to the previous period or the same range last year. Use this for "how much did we sell on/last/between\u2026" instead of paging search_orders and adding it up.`,
1090
+ description: `Order count and gross revenue bucketed by day, week or month over any date range, in the merchant's timezone, optionally compared to the previous period or the same range last year. Use this for "how much did we sell on/last/between\u2026" instead of paging search_orders. Amounts come back per currency in byCurrency, never as one total; report each currency separately.`,
1091
1091
  kind: "read",
1092
1092
  scopes: ["orders:read"],
1093
1093
  input: [
@@ -1112,7 +1112,7 @@ var ACTIONS = [
1112
1112
  {
1113
1113
  id: "get_business_summary",
1114
1114
  title: "Business summary",
1115
- description: "How are we doing? Orders/revenue, subscription MRR, receivables and quotes pipeline over a date range, compared to the immediately preceding window of equal length. Note: period=week|month|quarter means the TRAILING 7/30/90 days, not a calendar period \u2014 pass from/to for calendar months.",
1115
+ description: "How are we doing? Orders/revenue, subscription MRR, receivables and quotes pipeline over a date range, compared to the immediately preceding window of equal length. Note: period=week|month|quarter means the TRAILING 7/30/90 days, not a calendar period \u2014 pass from/to for calendar months. Money comes back per currency in byCurrency (revenue, MRR, receivables, quotes), never summed across currencies; report each currency separately.",
1116
1116
  kind: "read",
1117
1117
  scopes: [],
1118
1118
  sectionScopes: ["orders:read", "subscriptions:read", "invoices:read", "quotes:read"],
@@ -1144,7 +1144,7 @@ var ACTIONS = [
1144
1144
  {
1145
1145
  id: "get_top_products",
1146
1146
  title: "Top products",
1147
- description: "Best-selling products over a date range, by revenue or units sold. Line items come from the merchant's own cart payload, so a product is identified by its external reference id when present and by name otherwise. The response carries both the top-N rows (by the chosen sort) and range-wide totals across every matching product, so you can compute what share of total revenue/units the top N represent.",
1147
+ description: "Best-selling products over a date range, by revenue or units sold. Line items come from the merchant's own cart payload, so a product is identified by its external reference id when present and by name otherwise. The response carries both the top-N rows (by the chosen sort) and range-wide totals across every matching product, so you can compute what share of total revenue/units the top N represent. Revenue is per currency (byCurrency on each row and in the totals); rows rank by the main currency, and revenue is never summed across currencies.",
1148
1148
  kind: "read",
1149
1149
  scopes: ["orders:read"],
1150
1150
  input: [
@@ -1169,7 +1169,7 @@ var ACTIONS = [
1169
1169
  {
1170
1170
  id: "get_attention_digest",
1171
1171
  title: "Attention digest",
1172
- description: "What needs attention right now? Open disputes, subscriptions in dunning, overdue Net-N invoices, and webhooks with degraded delivery health \u2014 a point-in-time snapshot, not a time range.",
1172
+ description: "What needs attention right now? Open disputes, subscriptions in dunning, overdue Net-N invoices, and webhooks with degraded delivery health \u2014 a point-in-time snapshot, not a time range. Dispute and overdue-invoice amounts come back per currency in byCurrency, never summed.",
1173
1173
  kind: "read",
1174
1174
  scopes: [],
1175
1175
  sectionScopes: ["payment_disputes:read", "subscriptions:read", "invoices:read", "webhook_deliveries:read"],
@@ -1190,7 +1190,7 @@ var ACTIONS = [
1190
1190
  {
1191
1191
  id: "get_customer_growth",
1192
1192
  title: "Customer growth",
1193
- description: "Customer growth over a date range: signups per day/week/month, how many orders came from first-time versus returning customers, and the highest-value customers in the window.",
1193
+ description: "Customer growth over a date range: signups per day/week/month, how many orders came from first-time versus returning customers, and the highest-value customers in the window. Revenue is per currency in byCurrency (top customers rank by the main currency); customer counts stay all-currency.",
1194
1194
  kind: "read",
1195
1195
  scopes: ["customers:read"],
1196
1196
  input: [
@@ -1218,7 +1218,7 @@ var ACTIONS = [
1218
1218
  {
1219
1219
  id: "get_revenue_breakdown",
1220
1220
  title: "Revenue breakdown",
1221
- description: "Revenue split by one dimension over a date range \u2014 payment method, order source, or currency. Amounts are gross; refunds are not deducted.",
1221
+ description: "Revenue split by one dimension over a date range \u2014 payment method, order source, or currency. Amounts are gross; refunds are not deducted. Amounts are per currency in byCurrency; with dimension=currency each row carries only its own currency.",
1222
1222
  kind: "read",
1223
1223
  scopes: ["orders:read"],
1224
1224
  input: [
@@ -1275,7 +1275,7 @@ var ACTIONS = [
1275
1275
  {
1276
1276
  id: "get_subscription_movement",
1277
1277
  title: "Subscription movement",
1278
- description: "Subscription movement over a date range: new subscriptions, cancellations and net MRR change per day/week/month. Figures are reconstructed from subscription timestamps, not a stored historical snapshot.",
1278
+ description: "Subscription movement over a date range: new subscriptions, cancellations and net MRR change per day/week/month. Figures are reconstructed from subscription timestamps, not a stored historical snapshot. MRR change is per currency in byCurrency, never summed across currencies.",
1279
1279
  kind: "read",
1280
1280
  scopes: ["subscriptions:read"],
1281
1281
  input: [
@@ -1293,15 +1293,15 @@ var ACTIONS = [
1293
1293
  requests: [{ method: "GET", path: "/api/v1/analytics/subscriptions" }],
1294
1294
  channels: ["mcp", "zapier", "make", "n8n"],
1295
1295
  guardrails: [
1296
- "newSubscriptions, churnedSubscriptions and mrrDeltaCents are reconstructed per bucket from subscription created_at/cancelled_at timestamps, not a stored historical MRR snapshot \u2014 never present this series as an audited historical MRR ledger.",
1297
- "mrrDeltaCents for a bucket only credits subscriptions created in that bucket that are still active right now, and only debits subscriptions cancelled in that bucket that already existed when it started. A subscription created AND cancelled inside the same bucket still counts toward both newSubscriptions and churnedSubscriptions but contributes 0 to mrrDeltaCents.",
1298
- "totals is the sum over the full series (the series is never truncated), so totals.newSubscriptions/.churnedSubscriptions/.netMrrDeltaCents always equal the corresponding sums of series[]."
1296
+ "newSubscriptions, churnedSubscriptions and the MRR change (byCurrency) are reconstructed per bucket from subscription created_at/cancelled_at timestamps, not a stored historical MRR snapshot \u2014 never present this series as an audited historical MRR ledger.",
1297
+ "The MRR change for a bucket only credits subscriptions created in that bucket that are still active right now, and only debits subscriptions cancelled in that bucket that already existed when it started. A subscription created AND cancelled inside the same bucket still counts toward both newSubscriptions and churnedSubscriptions but contributes 0 to the MRR change.",
1298
+ "totals is the sum over the full series (the series is never truncated), so totals.newSubscriptions/.churnedSubscriptions always equal the corresponding sums of series[], and totals.byCurrency[] equals the per-currency sums of series[].byCurrency."
1299
1299
  ]
1300
1300
  },
1301
1301
  {
1302
1302
  id: "get_discount_performance",
1303
1303
  title: "Discount performance",
1304
- description: "Discount code performance over a date range: redemption count, revenue on discounted orders, and total discount given per code.",
1304
+ description: "Discount code performance over a date range: redemption count, revenue on discounted orders, and total discount given per code. Revenue and discount given are per currency in byCurrency; codes rank by the main currency.",
1305
1305
  kind: "read",
1306
1306
  scopes: ["discounts:read"],
1307
1307
  input: [
@@ -1319,9 +1319,9 @@ var ACTIONS = [
1319
1319
  requests: [{ method: "GET", path: "/api/v1/analytics/discounts" }],
1320
1320
  channels: ["mcp", "zapier", "make", "n8n"],
1321
1321
  guardrails: [
1322
- 'discountedRevenueCents and discountGivenCents are DIFFERENT measures: discountedRevenueCents is the gross order total on orders that redeemed the code; discountGivenCents is the discount amount taken off those same orders. Never describe discountedRevenueCents as "given away" or discountGivenCents as revenue.',
1323
- "Only orders with status <> draft and a gross-eligible payment_status are counted; refunds are not deducted from discountedRevenueCents, because that needs payment_refunds:read.",
1324
- "rows are the top N codes by discount given; totals is a SEPARATE whole-range aggregate (not a reduction over rows), so totals.redemptions / totals.discountGivenCents stay valid even when rows is truncated by limit."
1322
+ 'In byCurrency, amount (discounted revenue) and discountGiven are DIFFERENT measures: amount is the gross order total on orders that redeemed the code; discountGiven is the discount amount taken off those same orders. Never describe the amount as "given away" or discountGiven as revenue.',
1323
+ "Only orders with status <> draft and a gross-eligible payment_status are counted; refunds are not deducted from the discounted revenue amount, because that needs payment_refunds:read.",
1324
+ "rows are the top N codes by discount given; totals is a SEPARATE whole-range aggregate (not a reduction over rows), so totals.redemptions / totals.byCurrency[].discountGiven stay valid even when rows is truncated by limit."
1325
1325
  ]
1326
1326
  },
1327
1327
  // ------------------------------------------------------------ sandbox write
@@ -2660,55 +2660,699 @@ function applyModifiers(field, type) {
2660
2660
  return field.default === void 0 ? described.optional() : described.default(field.default);
2661
2661
  }
2662
2662
 
2663
- // src/projection.ts
2664
- var S = "scalar";
2665
- var T = "text";
2666
- var PASS = "pass";
2667
- var section = (shape) => ({ __section: shape });
2668
- var oneOf = (values) => ({ __oneOf: new Set(values) });
2669
- function isPrimitive(value) {
2670
- return value === null || ["string", "number", "boolean"].includes(typeof value);
2671
- }
2672
- var TOKEN = /^[^\s@]{0,200}$/;
2673
- var OMITTED = { omitted: S, grantable: T, reason: T };
2674
- var UNAVAILABLE = /^(not readable with this credential \(missing scope\)|not found|unavailable \([^\s@]{0,100}\))$/;
2675
- function project(value, shape) {
2676
- if (value === void 0) return void 0;
2677
- if (shape === PASS) return value;
2678
- if (shape === S) {
2679
- if (!isPrimitive(value)) return void 0;
2680
- return typeof value === "string" && !TOKEN.test(value) ? null : value;
2681
- }
2682
- if (shape === T) return isPrimitive(value) ? value : void 0;
2683
- if ("__oneOf" in shape) {
2684
- if (!isPrimitive(value)) return void 0;
2685
- return typeof value === "string" && !shape.__oneOf.has(value) ? null : value;
2686
- }
2687
- if (Array.isArray(shape)) {
2688
- return Array.isArray(value) ? value.map((item) => project(item, shape[0])) : void 0;
2689
- }
2690
- if ("__section" in shape) {
2691
- if (typeof value === "string") return UNAVAILABLE.test(value) ? value : null;
2692
- if (value && typeof value === "object" && value.omitted === true) {
2693
- return project(value, OMITTED);
2694
- }
2695
- return project(value, shape.__section);
2696
- }
2697
- if (value === null) return null;
2698
- if (typeof value !== "object" || Array.isArray(value)) return void 0;
2699
- const out = {};
2700
- for (const [key, child] of Object.entries(shape)) {
2701
- const projected = project(value[key], child);
2702
- if (projected !== void 0) out[key] = projected;
2663
+ // ../money/dist/index.js
2664
+ var dist_exports = {};
2665
+ __export(dist_exports, {
2666
+ CURRENCIES: () => CURRENCIES,
2667
+ UNCONFIRMED_EXPONENT_CODES: () => UNCONFIRMED_EXPONENT_CODES,
2668
+ UnknownCurrencyError: () => UnknownCurrencyError,
2669
+ currencySymbol: () => currencySymbol,
2670
+ formatMoney: () => formatMoney,
2671
+ isEnableableCurrency: () => isEnableableCurrency,
2672
+ isKnownCurrency: () => isKnownCurrency,
2673
+ minorUnitsOf: () => minorUnitsOf,
2674
+ moneyValue: () => moneyValue,
2675
+ parseMoney: () => parseMoney,
2676
+ toDecimalString: () => toDecimalString,
2677
+ toMinor: () => toMinor
2678
+ });
2679
+ var CURRENCY_ROWS = [
2680
+ ["AED", 2, "AED", false],
2681
+ ["AFN", 2, "AFN", false],
2682
+ ["ALL", 2, "ALL", false],
2683
+ ["AMD", 2, "AMD", false],
2684
+ ["AOA", 2, "AOA", false],
2685
+ ["ARS", 2, "ARS", false],
2686
+ ["AUD", 2, "A$", false],
2687
+ ["AWG", 2, "AWG", false],
2688
+ ["AZN", 2, "AZN", false],
2689
+ ["BAM", 2, "BAM", false],
2690
+ ["BBD", 2, "BBD", false],
2691
+ ["BDT", 2, "BDT", false],
2692
+ ["BHD", 3, "BHD", false],
2693
+ ["BIF", 0, "BIF", false],
2694
+ ["BMD", 2, "BMD", false],
2695
+ ["BND", 2, "BND", false],
2696
+ ["BOB", 2, "BOB", false],
2697
+ ["BOV", 2, "BOV", true],
2698
+ ["BRL", 2, "R$", false],
2699
+ ["BSD", 2, "BSD", false],
2700
+ ["BTN", 2, "BTN", false],
2701
+ ["BWP", 2, "BWP", false],
2702
+ ["BYN", 2, "BYN", false],
2703
+ ["BZD", 2, "BZD", false],
2704
+ ["CAD", 2, "CA$", false],
2705
+ ["CDF", 2, "CDF", false],
2706
+ ["CHE", 2, "CHE", true],
2707
+ ["CHF", 2, "CHF", false],
2708
+ ["CHW", 2, "CHW", true],
2709
+ ["CLF", 4, "CLF", true],
2710
+ ["CLP", 0, "CLP", false],
2711
+ ["CNY", 2, "CN\xA5", false],
2712
+ ["COP", 2, "COP", false],
2713
+ ["COU", 2, "COU", true],
2714
+ ["CRC", 2, "CRC", false],
2715
+ ["CUP", 2, "CUP", false],
2716
+ ["CVE", 2, "CVE", false],
2717
+ ["CZK", 2, "CZK", false],
2718
+ ["DJF", 0, "DJF", false],
2719
+ ["DKK", 2, "DKK", false],
2720
+ ["DOP", 2, "DOP", false],
2721
+ ["DZD", 2, "DZD", false],
2722
+ ["EGP", 2, "EGP", false],
2723
+ ["ERN", 2, "ERN", false],
2724
+ ["ETB", 2, "ETB", false],
2725
+ ["EUR", 2, "\u20AC", false],
2726
+ ["FJD", 2, "FJD", false],
2727
+ ["FKP", 2, "FKP", false],
2728
+ ["GBP", 2, "\xA3", false],
2729
+ ["GEL", 2, "GEL", false],
2730
+ ["GHS", 2, "GHS", false],
2731
+ ["GIP", 2, "GIP", false],
2732
+ ["GMD", 2, "GMD", false],
2733
+ ["GNF", 0, "GNF", false],
2734
+ ["GTQ", 2, "GTQ", false],
2735
+ ["GYD", 2, "GYD", false],
2736
+ ["HKD", 2, "HK$", false],
2737
+ ["HNL", 2, "HNL", false],
2738
+ ["HTG", 2, "HTG", false],
2739
+ ["HUF", 2, "HUF", false],
2740
+ ["IDR", 2, "IDR", false],
2741
+ ["ILS", 2, "\u20AA", false],
2742
+ ["INR", 2, "\u20B9", false],
2743
+ ["IQD", 3, "IQD", false],
2744
+ ["IRR", 2, "IRR", false],
2745
+ ["ISK", 0, "ISK", false],
2746
+ ["JMD", 2, "JMD", false],
2747
+ ["JOD", 3, "JOD", false],
2748
+ ["JPY", 0, "\xA5", false],
2749
+ ["KES", 2, "KES", false],
2750
+ ["KGS", 2, "KGS", false],
2751
+ ["KHR", 2, "KHR", false],
2752
+ ["KMF", 0, "KMF", false],
2753
+ ["KPW", 2, "KPW", false],
2754
+ ["KRW", 0, "\u20A9", false],
2755
+ ["KWD", 3, "KWD", false],
2756
+ ["KYD", 2, "KYD", false],
2757
+ ["KZT", 2, "KZT", false],
2758
+ ["LAK", 2, "LAK", false],
2759
+ ["LBP", 2, "LBP", false],
2760
+ ["LKR", 2, "LKR", false],
2761
+ ["LRD", 2, "LRD", false],
2762
+ ["LSL", 2, "LSL", false],
2763
+ ["LYD", 3, "LYD", false],
2764
+ ["MAD", 2, "MAD", false],
2765
+ ["MDL", 2, "MDL", false],
2766
+ ["MGA", 2, "MGA", false],
2767
+ ["MKD", 2, "MKD", false],
2768
+ ["MMK", 2, "MMK", false],
2769
+ ["MNT", 2, "MNT", false],
2770
+ ["MOP", 2, "MOP", false],
2771
+ ["MRU", 2, "MRU", false],
2772
+ ["MUR", 2, "MUR", false],
2773
+ ["MVR", 2, "MVR", false],
2774
+ ["MWK", 2, "MWK", false],
2775
+ ["MXN", 2, "MX$", false],
2776
+ ["MXV", 2, "MXV", true],
2777
+ ["MYR", 2, "MYR", false],
2778
+ ["MZN", 2, "MZN", false],
2779
+ ["NAD", 2, "NAD", false],
2780
+ ["NGN", 2, "NGN", false],
2781
+ ["NIO", 2, "NIO", false],
2782
+ ["NOK", 2, "NOK", false],
2783
+ ["NPR", 2, "NPR", false],
2784
+ ["NZD", 2, "NZ$", false],
2785
+ ["OMR", 3, "OMR", false],
2786
+ ["PAB", 2, "PAB", false],
2787
+ ["PEN", 2, "PEN", false],
2788
+ ["PGK", 2, "PGK", false],
2789
+ ["PHP", 2, "\u20B1", false],
2790
+ ["PKR", 2, "PKR", false],
2791
+ ["PLN", 2, "PLN", false],
2792
+ ["PYG", 0, "PYG", false],
2793
+ ["QAR", 2, "QAR", false],
2794
+ ["RON", 2, "RON", false],
2795
+ ["RSD", 2, "RSD", false],
2796
+ ["RUB", 2, "RUB", false],
2797
+ ["RWF", 0, "RWF", false],
2798
+ ["SAR", 2, "SAR", false],
2799
+ ["SBD", 2, "SBD", false],
2800
+ ["SCR", 2, "SCR", false],
2801
+ ["SDG", 2, "SDG", false],
2802
+ ["SEK", 2, "SEK", false],
2803
+ ["SGD", 2, "SGD", false],
2804
+ ["SHP", 2, "SHP", false],
2805
+ ["SLE", 2, "SLE", false],
2806
+ ["SOS", 2, "SOS", false],
2807
+ ["SRD", 2, "SRD", false],
2808
+ ["SSP", 2, "SSP", false],
2809
+ ["STN", 2, "STN", false],
2810
+ ["SVC", 2, "SVC", false],
2811
+ ["SYP", 2, "SYP", false],
2812
+ ["SZL", 2, "SZL", false],
2813
+ ["THB", 2, "THB", false],
2814
+ ["TJS", 2, "TJS", false],
2815
+ ["TMT", 2, "TMT", false],
2816
+ ["TND", 3, "TND", false],
2817
+ ["TOP", 2, "TOP", false],
2818
+ ["TRY", 2, "TRY", false],
2819
+ ["TTD", 2, "TTD", false],
2820
+ ["TWD", 2, "NT$", false],
2821
+ ["TZS", 2, "TZS", false],
2822
+ ["UAH", 2, "UAH", false],
2823
+ ["UGX", 0, "UGX", false],
2824
+ ["USD", 2, "$", false],
2825
+ ["USN", 2, "USN", true],
2826
+ ["UYI", 0, "UYI", true],
2827
+ ["UYU", 2, "UYU", false],
2828
+ ["UYW", 4, "UYW", true],
2829
+ ["UZS", 2, "UZS", false],
2830
+ ["VED", 2, "VED", false],
2831
+ ["VES", 2, "VES", false],
2832
+ ["VND", 0, "\u20AB", false],
2833
+ ["VUV", 0, "VUV", false],
2834
+ ["WST", 2, "WST", false],
2835
+ ["XAD", 2, "XAD", true],
2836
+ ["XAF", 0, "FCFA", false],
2837
+ ["XCD", 2, "EC$", false],
2838
+ ["XCG", 2, "Cg.", false],
2839
+ ["XOF", 0, "F\u202FCFA", false],
2840
+ ["XPF", 0, "CFPF", false],
2841
+ ["YER", 2, "YER", false],
2842
+ ["ZAR", 2, "ZAR", false],
2843
+ ["ZMW", 2, "ZMW", false],
2844
+ ["ZWG", 2, "ZWG", false]
2845
+ ];
2846
+ var UnknownCurrencyError = class extends Error {
2847
+ constructor(currency) {
2848
+ super(`Unknown currency code: ${currency}`);
2849
+ this.code = "unknown_currency";
2850
+ this.name = "UnknownCurrencyError";
2851
+ this.currency = currency;
2703
2852
  }
2704
- return out;
2853
+ };
2854
+ var BY_CODE = new Map(
2855
+ CURRENCY_ROWS.map(([code, minorUnits, symbol, fund]) => [code, { minorUnits, symbol, fund }])
2856
+ );
2857
+ var CURRENCIES = Object.freeze(
2858
+ CURRENCY_ROWS.map(([code, minorUnits, symbol]) => Object.freeze({ code, minorUnits, symbol }))
2859
+ );
2860
+ var UNCONFIRMED = /* @__PURE__ */ new Set([
2861
+ "AFN",
2862
+ "BTN",
2863
+ "CDF",
2864
+ "CLP",
2865
+ "COP",
2866
+ "CVE",
2867
+ "ERN",
2868
+ "HUF",
2869
+ "IDR",
2870
+ "IRR",
2871
+ "ISK",
2872
+ "KPW",
2873
+ "LBP",
2874
+ "LRD",
2875
+ "LSL",
2876
+ "MGA",
2877
+ "SDG",
2878
+ "SSP",
2879
+ "SYP",
2880
+ "TJS",
2881
+ "TMT",
2882
+ "TWD",
2883
+ "UGX",
2884
+ "VED",
2885
+ "VES",
2886
+ "ZWG"
2887
+ ]);
2888
+ var UNCONFIRMED_EXPONENT_CODES = Object.freeze({
2889
+ has: (code) => UNCONFIRMED.has(code),
2890
+ get size() {
2891
+ return UNCONFIRMED.size;
2892
+ },
2893
+ forEach: (fn, thisArg) => UNCONFIRMED.forEach((v) => fn.call(thisArg, v, v, UNCONFIRMED_EXPONENT_CODES)),
2894
+ keys: () => UNCONFIRMED.keys(),
2895
+ values: () => UNCONFIRMED.values(),
2896
+ entries: () => UNCONFIRMED.entries(),
2897
+ [Symbol.iterator]: () => UNCONFIRMED.values()
2898
+ });
2899
+ function currencyRow(code) {
2900
+ return BY_CODE.get(code);
2705
2901
  }
2706
- var PAGINATION = { cursor: S, nextCursor: S, hasMore: S };
2707
- var page2 = (row) => ({ data: [row], pagination: PAGINATION });
2708
- var ADDRESS = { countryCode: S };
2709
- var CUSTOMER_REF = { id: S };
2710
- var APPLICATION = { id: S, name: T, slug: S };
2711
- var LIFECYCLE_LABELS = ["Draft", "Pending", "Processing", "Partially fulfilled", "Fulfilled", "Cancelled", "Closed"];
2902
+ function isKnownCurrency(code) {
2903
+ return BY_CODE.has(code);
2904
+ }
2905
+ function minorUnitsOf(code) {
2906
+ const row = BY_CODE.get(code);
2907
+ if (row === void 0) throw new UnknownCurrencyError(code);
2908
+ return row.minorUnits;
2909
+ }
2910
+ function isEnableableCurrency(code) {
2911
+ const row = BY_CODE.get(code);
2912
+ return row !== void 0 && row.minorUnits !== 4 && !row.fund && !UNCONFIRMED.has(code);
2913
+ }
2914
+ var NBSP = "\xA0";
2915
+ function normalizeCode(code) {
2916
+ return typeof code === "string" ? code.trim().toUpperCase() : "";
2917
+ }
2918
+ function displayExponent(normalizedCode) {
2919
+ return currencyRow(normalizedCode)?.minorUnits ?? 2;
2920
+ }
2921
+ function roundHalfAwayFromZero(n) {
2922
+ return n < 0 ? -Math.round(-n) : Math.round(n);
2923
+ }
2924
+ function decimalDigits(abs, exponent, grouped) {
2925
+ const raw = Number.isSafeInteger(abs) ? String(abs) : BigInt(abs).toString();
2926
+ const padded = raw.padStart(exponent + 1, "0");
2927
+ const cut = padded.length - exponent;
2928
+ let integer = padded.slice(0, cut);
2929
+ if (grouped) integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
2930
+ return exponent === 0 ? integer : `${integer}.${padded.slice(cut)}`;
2931
+ }
2932
+ function formatMoney(minor, code, opts) {
2933
+ if (typeof minor !== "number" || !Number.isFinite(minor)) return "\u2014";
2934
+ const c = normalizeCode(code);
2935
+ const row = currencyRow(c);
2936
+ const n = roundHalfAwayFromZero(minor);
2937
+ const sign = n < 0 ? "-" : "";
2938
+ const digits = decimalDigits(Math.abs(n), row?.minorUnits ?? 2, true);
2939
+ if (c === "") return sign + digits;
2940
+ if (row === void 0) return `${sign}${digits}${NBSP}${c}`;
2941
+ const separator = new RegExp("\\p{Sc}$", "u").test(row.symbol) ? "" : NBSP;
2942
+ const text = `${sign}${row.symbol}${separator}${digits}`;
2943
+ return opts?.display === "symbol-code" && row.symbol !== c ? `${text}${NBSP}${c}` : text;
2944
+ }
2945
+ function currencySymbol(code) {
2946
+ const c = normalizeCode(code);
2947
+ return currencyRow(c)?.symbol ?? c;
2948
+ }
2949
+ function toDecimalString(minor, code) {
2950
+ if (typeof minor !== "number" || !Number.isFinite(minor)) return "";
2951
+ const n = roundHalfAwayFromZero(minor);
2952
+ const sign = n < 0 ? "-" : "";
2953
+ return sign + decimalDigits(Math.abs(n), displayExponent(normalizeCode(code)), false);
2954
+ }
2955
+ function moneyValue(amount, currency) {
2956
+ return { amount, currency: normalizeCode(currency), display: formatMoney(amount, currency) };
2957
+ }
2958
+ function toMinorUnits(negative, integer, fraction, exponent) {
2959
+ if (fraction.length > exponent) return null;
2960
+ const n = Number(integer + fraction.padEnd(exponent, "0"));
2961
+ if (!Number.isSafeInteger(n)) return null;
2962
+ return negative && n !== 0 ? -n : n;
2963
+ }
2964
+ function toMinor(decimal, code) {
2965
+ const text = typeof decimal === "number" ? String(decimal) : typeof decimal === "string" ? decimal : "";
2966
+ const m = /^(-?)(\d+)(?:\.(\d+))?$/.exec(text);
2967
+ if (m === null) return null;
2968
+ return toMinorUnits(m[1] === "-", m[2], m[3] ?? "", displayExponent(normalizeCode(code)));
2969
+ }
2970
+ var SPACE = /^[ \u00A0]/;
2971
+ var TRAILING_SPACE = /[ \u00A0]$/;
2972
+ var AMOUNT = /^([1-9]\d{0,2}(?:,\d{3})+|\d+)(?:\.(\d+))?$/;
2973
+ function withoutMarker(text, markers) {
2974
+ for (const marker of markers) {
2975
+ if (text.startsWith(marker)) return text.slice(marker.length).replace(SPACE, "");
2976
+ }
2977
+ for (const marker of markers) {
2978
+ if (text.endsWith(marker)) return text.slice(0, text.length - marker.length).replace(TRAILING_SPACE, "");
2979
+ }
2980
+ return text;
2981
+ }
2982
+ function parseMoney(text, code) {
2983
+ if (typeof text !== "string") return null;
2984
+ const c = normalizeCode(code);
2985
+ let rest = text.trim();
2986
+ const negative = rest.startsWith("-");
2987
+ if (negative) rest = rest.slice(1);
2988
+ if (c !== "") {
2989
+ const symbol = currencySymbol(c);
2990
+ rest = withoutMarker(rest, symbol === c ? [c] : [symbol, c]);
2991
+ }
2992
+ const m = AMOUNT.exec(rest);
2993
+ if (m === null) return null;
2994
+ return toMinorUnits(negative, m[1].replace(/,/g, ""), m[2] ?? "", displayExponent(c));
2995
+ }
2996
+
2997
+ // src/money.ts
2998
+ var M = "money";
2999
+ var DROP = "drop";
3000
+ var MK = (values) => ({ __moneyKeyed: values });
3001
+ var CURRENCY_OF = (sibling, spec) => ({ __currencyOf: { sibling, spec } });
3002
+ var DROP_WHEN = (field, equals) => ({ __dropWhen: { field, equals } });
3003
+ var ORDERS_WINDOW = { grossCents: DROP, avgOrderCents: DROP, refundsCents: DROP, netCents: DROP };
3004
+ var QUOTE_BUCKET = { totalCents: DROP };
3005
+ var LINE_ITEM = {
3006
+ unitPrice: M,
3007
+ subtotal: M,
3008
+ discountAmount: M,
3009
+ taxAmount: M,
3010
+ total: M,
3011
+ // amount: a trial line's renewal price; schedule: per-unit installment amounts.
3012
+ recurring: { amount: M, scheduleUnitTotal: M, schedule: [{ amount: M }] }
3013
+ };
3014
+ var ORDER = {
3015
+ subtotal: M,
3016
+ discountTotal: M,
3017
+ shippingTotal: M,
3018
+ taxTotal: M,
3019
+ total: M,
3020
+ capturedAmount: M,
3021
+ refundedAmount: M,
3022
+ compAmount: M,
3023
+ shippingMethod: { amount: M },
3024
+ lineItems: [LINE_ITEM]
3025
+ };
3026
+ var PAYMENT = { amount: M, capturedAmount: M, usdAmountMinor: DROP };
3027
+ var TRANSACTION = { amount: M };
3028
+ var RETURN = { refundAmount: M, items: [{ amount: M }] };
3029
+ var FULFILLMENT = { detail: { shippingCost: M, insuranceAmount: M } };
3030
+ var SUBSCRIPTION = {
3031
+ amount: M,
3032
+ pendingAmount: M,
3033
+ scheduleTotal: M,
3034
+ nextPaymentAmount: M,
3035
+ paymentSchedule: [{ amount: M, discount: M, net: M }],
3036
+ renewalIssue: { charge: { amount: M } }
3037
+ };
3038
+ var QUOTE_ITEM = {
3039
+ unitPrice: M,
3040
+ subtotal: M,
3041
+ discountAmount: M,
3042
+ taxAmount: M,
3043
+ total: M,
3044
+ recurring: { schedule: [{ amount: M }] }
3045
+ };
3046
+ var QUOTE_REVISION = {
3047
+ subtotal: M,
3048
+ discountTotal: M,
3049
+ shippingTotal: M,
3050
+ taxTotal: M,
3051
+ total: M,
3052
+ depositAmount: M,
3053
+ shippingFlatAmount: M,
3054
+ // MC4-R82: a fixed deposit's `value` is a minor-unit amount (unlabelled, and
3055
+ // `depositAmount` carries it); a percent deposit's `value` is its percent and stays.
3056
+ paymentTerms: { deposit: { value: DROP_WHEN("type", "fixed") } },
3057
+ items: [QUOTE_ITEM],
3058
+ acceptanceSelections: { effectiveTotal: M }
3059
+ };
3060
+ var QUOTE_SUMMARY = { total: M, acceptance: { effectiveTotal: M, effectiveGoodsTotal: M } };
3061
+ var QUOTE = {
3062
+ ...QUOTE_SUMMARY,
3063
+ revisions: [QUOTE_REVISION],
3064
+ // `revision_issued` records the total, `accepted` the effective total, `price_overridden` the new prices.
3065
+ timeline: [{ data: { total: M, effectiveTotal: M, items: [{ unitPrice: M }] } }]
3066
+ };
3067
+ var INVOICE = {
3068
+ subtotal: M,
3069
+ taxTotal: M,
3070
+ shippingTotal: M,
3071
+ discountTotal: M,
3072
+ total: M,
3073
+ amountRefunded: M,
3074
+ billingSnapshot: {
3075
+ lineItems: [{ unitPrice: M, taxAmount: M, discountAmount: M, total: M }],
3076
+ totals: {
3077
+ subtotal: M,
3078
+ taxTotal: M,
3079
+ shippingTotal: M,
3080
+ discountTotal: M,
3081
+ total: M,
3082
+ orderTotal: M,
3083
+ amountPaid: M,
3084
+ compWaived: M,
3085
+ balanceDue: M
3086
+ }
3087
+ }
3088
+ };
3089
+ var DISCOUNT = {
3090
+ value: DROP_WHEN("type", "fixed_amount"),
3091
+ // `min_order`: the legacy alias legacyMinimumOf still reads on old rows.
3092
+ conditions: { minOrder: DROP, min_order: DROP },
3093
+ amounts: MK({ value: M, minOrder: M })
3094
+ };
3095
+ var CART = {
3096
+ subtotal: M,
3097
+ taxTotal: M,
3098
+ discountTotal: M,
3099
+ shippingTotal: M,
3100
+ total: M,
3101
+ lineItems: [LINE_ITEM],
3102
+ items: [LINE_ITEM],
3103
+ appliedDiscount: { amount: M },
3104
+ selectedShipping: { rateAmount: M },
3105
+ taxLines: [{ amount: M }]
3106
+ };
3107
+ var EVENT_DATA = {
3108
+ amount: M,
3109
+ capturedAmount: M,
3110
+ subtotal: M,
3111
+ taxTotal: M,
3112
+ shippingTotal: M,
3113
+ discountTotal: M,
3114
+ total: M,
3115
+ compAmount: M,
3116
+ refundedAmount: M,
3117
+ paymentAmount: M,
3118
+ amountRefunded: M,
3119
+ totalRefunded: M,
3120
+ refundAmount: M,
3121
+ totalAmount: M,
3122
+ unitPrice: M,
3123
+ rateAmount: M,
3124
+ scheduleTotal: M,
3125
+ nextPaymentAmount: M,
3126
+ order: { ...ORDER, items: [LINE_ITEM] },
3127
+ payment: PAYMENT,
3128
+ subscription: SUBSCRIPTION,
3129
+ previous: { amount: M },
3130
+ pending: { amount: M },
3131
+ recurring: { amount: M },
3132
+ cart: CART,
3133
+ lineItems: [LINE_ITEM],
3134
+ items: [{ ...LINE_ITEM, amount: M }],
3135
+ quote: QUOTE_SUMMARY,
3136
+ revision: QUOTE_REVISION,
3137
+ charge: { amount: M, amountCents: M }
3138
+ };
3139
+ var EVENT = { data: EVENT_DATA };
3140
+ var DELIVERY = { payload: { data: EVENT_DATA } };
3141
+ var SESSION = {
3142
+ recurringTerms: { firstChargeAmountMinor: M },
3143
+ subscriptions: [{ amount: M, firstChargeAmount: M, schedule: [{ net: M }] }]
3144
+ };
3145
+ var page2 = (row) => ({ data: [row] });
3146
+ var MONEY_SPECS = {
3147
+ search_orders: page2(ORDER),
3148
+ get_order: {
3149
+ order: ORDER,
3150
+ payments: [PAYMENT],
3151
+ returns: CURRENCY_OF("order", [RETURN]),
3152
+ fulfillments: CURRENCY_OF("order", [FULFILLMENT])
3153
+ },
3154
+ search_payments: page2(PAYMENT),
3155
+ get_payment: { payment: PAYMENT, transactions: [TRANSACTION] },
3156
+ get_customer: { subscriptions: [SUBSCRIPTION] },
3157
+ list_subscriptions: page2(SUBSCRIPTION),
3158
+ get_subscription: SUBSCRIPTION,
3159
+ search_quotes: page2(QUOTE_SUMMARY),
3160
+ get_quote: QUOTE,
3161
+ list_invoices: page2(INVOICE),
3162
+ get_invoice: INVOICE,
3163
+ search_discounts: page2(DISCOUNT),
3164
+ get_discount: DISCOUNT,
3165
+ search_events: page2(EVENT),
3166
+ list_webhook_deliveries: page2(DELIVERY),
3167
+ get_webhook_delivery: DELIVERY,
3168
+ explain_checkout_failure: {
3169
+ session: SESSION,
3170
+ cart: CART,
3171
+ events: [EVENT],
3172
+ recentWebhookDeliveries: [DELIVERY]
3173
+ },
3174
+ // Writes that return a record. Each added line item echoes its cart's
3175
+ // `currency`; the sibling cart's is the fallback for one that does not.
3176
+ seed_test_data: { cart: CART, lineItems: CURRENCY_OF("cart", [LINE_ITEM]), order: ORDER },
3177
+ create_quote: { quote: QUOTE_SUMMARY, revision: QUOTE_REVISION, items: [QUOTE_ITEM] },
3178
+ manage_subscription: SUBSCRIPTION,
3179
+ set_subscription_payment_method: SUBSCRIPTION,
3180
+ // GET /api/v1/stores: `settings.shipping` is stamped with its own currency
3181
+ // (MC1-R74); an unstamped one takes the store's.
3182
+ list_applications: [{ settings: { shipping: { flatRateCents: M, freeThresholdCents: M } } }],
3183
+ // ---------------------------------------------------------------- analytics
3184
+ get_sales_timeseries: {
3185
+ totalGrossCents: DROP,
3186
+ series: [{ grossCents: DROP }],
3187
+ comparison: { totalGrossCents: DROP }
3188
+ },
3189
+ get_business_summary: {
3190
+ orders: { current: ORDERS_WINDOW, previous: ORDERS_WINDOW, deltaPct: DROP },
3191
+ subscriptions: { mrr: { currentCents: DROP, periodStartCents: DROP, deltaPct: DROP } },
3192
+ receivables: { outstandingCents: DROP },
3193
+ quotes: { sent: QUOTE_BUCKET, accepted: QUOTE_BUCKET, expired: QUOTE_BUCKET, declined: QUOTE_BUCKET }
3194
+ },
3195
+ get_attention_digest: {
3196
+ disputes: { totalCents: DROP },
3197
+ overdueInvoices: { totalCents: DROP }
3198
+ },
3199
+ get_top_products: {
3200
+ rows: [{ revenueCents: DROP }],
3201
+ totals: { revenueCents: DROP }
3202
+ },
3203
+ get_customer_growth: {
3204
+ topCustomers: [{ revenueCents: DROP }],
3205
+ totals: { revenueCents: DROP }
3206
+ },
3207
+ get_revenue_breakdown: {
3208
+ rows: [{ grossCents: DROP }],
3209
+ totals: { grossCents: DROP }
3210
+ },
3211
+ get_subscription_movement: {
3212
+ series: [{ mrrDeltaCents: DROP }],
3213
+ totals: { netMrrDeltaCents: DROP }
3214
+ },
3215
+ get_discount_performance: {
3216
+ rows: [{ discountedRevenueCents: DROP, discountGivenCents: DROP }],
3217
+ totals: { discountedRevenueCents: DROP, discountGivenCents: DROP }
3218
+ },
3219
+ receivables_aging: {
3220
+ buckets: [{ total_amount: DROP }],
3221
+ total_outstanding_amount: DROP
3222
+ },
3223
+ // The handler returns `{ carts, summary }`; `summary` is the
3224
+ // /abandoned-carts/summary payload, or optional()'s unavailable string.
3225
+ list_abandoned_carts: {
3226
+ carts: [{ total: M }],
3227
+ summary: { abandonedValue: DROP }
3228
+ }
3229
+ };
3230
+ var isPlainObject3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
3231
+ var join = (path, key) => path ? `${path}.${key}` : key;
3232
+ function knownCode(v) {
3233
+ if (typeof v !== "string") return void 0;
3234
+ const code = v.trim().toUpperCase();
3235
+ return isKnownCurrency(code) ? code : void 0;
3236
+ }
3237
+ function walk2(spec, value, currency, path, unwrapped) {
3238
+ if (spec === DROP) return value;
3239
+ if (spec === M) {
3240
+ if (typeof value !== "number") return value;
3241
+ if (!currency) {
3242
+ unwrapped.push(path);
3243
+ return value;
3244
+ }
3245
+ return moneyValue(value, currency);
3246
+ }
3247
+ if (Array.isArray(spec)) {
3248
+ if (!Array.isArray(value)) return value;
3249
+ return value.map((item, i) => walk2(spec[0], item, currency, `${path}[${i}]`, unwrapped));
3250
+ }
3251
+ if ("__currencyOf" in spec || "__dropWhen" in spec) {
3252
+ throw new Error(`money spec at "${path}": CURRENCY_OF and DROP_WHEN are only valid as an object child`);
3253
+ }
3254
+ if (!isPlainObject3(value)) return value;
3255
+ if ("__moneyKeyed" in spec) {
3256
+ const inner = spec.__moneyKeyed;
3257
+ return Object.fromEntries(
3258
+ Object.entries(value).map(([code, item]) => [
3259
+ code,
3260
+ walk2(inner, item, knownCode(code), join(path, code), unwrapped)
3261
+ ])
3262
+ );
3263
+ }
3264
+ const own = "currency" in value ? knownCode(value.currency) : currency;
3265
+ const out = { ...value };
3266
+ for (const [key, child] of Object.entries(spec)) {
3267
+ if (!(key in value)) continue;
3268
+ if (child === DROP) {
3269
+ delete out[key];
3270
+ continue;
3271
+ }
3272
+ if (typeof child === "object" && "__dropWhen" in child) {
3273
+ const { field, equals } = child.__dropWhen;
3274
+ if (value[field] === equals) delete out[key];
3275
+ continue;
3276
+ }
3277
+ if (typeof child === "object" && "__currencyOf" in child) {
3278
+ const { sibling, spec: inner } = child.__currencyOf;
3279
+ const record = value[sibling];
3280
+ const siblingCurrency = isPlainObject3(record) ? knownCode(record.currency) : void 0;
3281
+ out[key] = walk2(inner, value[key], siblingCurrency, join(path, key), unwrapped);
3282
+ continue;
3283
+ }
3284
+ out[key] = walk2(child, value[key], own, join(path, key), unwrapped);
3285
+ }
3286
+ return out;
3287
+ }
3288
+ function applyMoneySpec(spec, value) {
3289
+ const unwrapped = [];
3290
+ return { value: walk2(spec, value, void 0, "", unwrapped), unwrapped };
3291
+ }
3292
+ function decorateMoney(actionId, value) {
3293
+ const spec = MONEY_SPECS[actionId];
3294
+ return spec ? applyMoneySpec(spec, value) : { value, unwrapped: [] };
3295
+ }
3296
+
3297
+ // src/projection.ts
3298
+ var S = "scalar";
3299
+ var T = "text";
3300
+ var PASS = "pass";
3301
+ var section = (shape) => ({ __section: shape });
3302
+ var oneOf = (values) => ({ __oneOf: new Set(values) });
3303
+ var mapOf = (shape) => ({ __map: shape });
3304
+ var CURRENCY_KEY = /^[A-Z]{3}$/;
3305
+ function isPrimitive(value) {
3306
+ return value === null || ["string", "number", "boolean"].includes(typeof value);
3307
+ }
3308
+ var TOKEN = /^[^\s@]{0,200}$/;
3309
+ var OMITTED = { omitted: S, grantable: T, reason: T };
3310
+ var UNAVAILABLE = /^(not readable with this credential \(missing scope\)|not found|unavailable \([^\s@]{0,100}\))$/;
3311
+ function project(value, shape) {
3312
+ if (value === void 0) return void 0;
3313
+ if (shape === PASS) return value;
3314
+ if (shape === S) {
3315
+ if (!isPrimitive(value)) return void 0;
3316
+ return typeof value === "string" && !TOKEN.test(value) ? null : value;
3317
+ }
3318
+ if (shape === T) return isPrimitive(value) ? value : void 0;
3319
+ if ("__oneOf" in shape) {
3320
+ if (!isPrimitive(value)) return void 0;
3321
+ return typeof value === "string" && !shape.__oneOf.has(value) ? null : value;
3322
+ }
3323
+ if ("__map" in shape) {
3324
+ if (value === null) return null;
3325
+ if (typeof value !== "object" || Array.isArray(value)) return void 0;
3326
+ const entries = Object.entries(value).filter(([code]) => CURRENCY_KEY.test(code)).map(([code, item]) => [code, project(item, shape.__map)]).filter(([, projected]) => projected !== void 0);
3327
+ return Object.fromEntries(entries);
3328
+ }
3329
+ if (Array.isArray(shape)) {
3330
+ return Array.isArray(value) ? value.map((item) => project(item, shape[0])) : void 0;
3331
+ }
3332
+ if ("__section" in shape) {
3333
+ if (typeof value === "string") return UNAVAILABLE.test(value) ? value : null;
3334
+ if (value && typeof value === "object" && value.omitted === true) {
3335
+ return project(value, OMITTED);
3336
+ }
3337
+ return project(value, shape.__section);
3338
+ }
3339
+ if (value === null) return null;
3340
+ if (typeof value !== "object" || Array.isArray(value)) return void 0;
3341
+ const out = {};
3342
+ for (const [key, child] of Object.entries(shape)) {
3343
+ const projected = project(value[key], child);
3344
+ if (projected !== void 0) out[key] = projected;
3345
+ }
3346
+ return out;
3347
+ }
3348
+ var MONEY = { amount: S, currency: S, display: T };
3349
+ var byCurrency = (extra = {}) => [{ ...MONEY, ...extra }];
3350
+ var PAGINATION = { cursor: S, nextCursor: S, hasMore: S };
3351
+ var page3 = (row) => ({ data: [row], pagination: PAGINATION });
3352
+ var ADDRESS = { countryCode: S };
3353
+ var CUSTOMER_REF = { id: S };
3354
+ var APPLICATION = { id: S, name: T, slug: S };
3355
+ var LIFECYCLE_LABELS = ["Draft", "Pending", "Processing", "Partially fulfilled", "Fulfilled", "Cancelled", "Closed"];
2712
3356
  var DISPLAY_QUALIFIERS = [
2713
3357
  "Comped",
2714
3358
  "Awaiting payment",
@@ -2739,23 +3383,23 @@ var LINE_RECURRING = {
2739
3383
  intervalCount: S,
2740
3384
  totalPayments: S,
2741
3385
  trialDays: S,
2742
- // A custom installment schedule: amounts and gaps are numbers and unit tokens, no free text.
2743
- schedule: [{ amount: S, intervalUnit: S, intervalCount: S }]
3386
+ // A custom installment schedule: amounts are money, gaps are numbers and unit tokens, no free text.
3387
+ schedule: [{ amount: MONEY, intervalUnit: S, intervalCount: S }]
2744
3388
  };
2745
- var LINE_ITEM = {
3389
+ var LINE_ITEM2 = {
2746
3390
  id: S,
2747
3391
  type: S,
2748
3392
  quantity: S,
2749
- unitPrice: S,
2750
- subtotal: S,
2751
- discountAmount: S,
2752
- taxAmount: S,
2753
- total: S,
3393
+ unitPrice: MONEY,
3394
+ subtotal: MONEY,
3395
+ discountAmount: MONEY,
3396
+ taxAmount: MONEY,
3397
+ total: MONEY,
2754
3398
  // amount = renewal price on a trial line (whose unitPrice is 0); count = the old display mirror.
2755
- recurring: { ...LINE_RECURRING, amount: S, count: S, scheduleUnitTotal: S },
3399
+ recurring: { ...LINE_RECURRING, amount: MONEY, count: S, scheduleUnitTotal: MONEY },
2756
3400
  subscriptionId: S
2757
3401
  };
2758
- var ORDER = {
3402
+ var ORDER2 = {
2759
3403
  id: S,
2760
3404
  orderNumber: S,
2761
3405
  status: S,
@@ -2764,14 +3408,14 @@ var ORDER = {
2764
3408
  type: S,
2765
3409
  source: S,
2766
3410
  currency: S,
2767
- subtotal: S,
2768
- discountTotal: S,
2769
- shippingTotal: S,
2770
- taxTotal: S,
2771
- total: S,
2772
- capturedAmount: S,
2773
- refundedAmount: S,
2774
- compAmount: S,
3411
+ subtotal: MONEY,
3412
+ discountTotal: MONEY,
3413
+ shippingTotal: MONEY,
3414
+ taxTotal: MONEY,
3415
+ total: MONEY,
3416
+ capturedAmount: MONEY,
3417
+ refundedAmount: MONEY,
3418
+ compAmount: MONEY,
2775
3419
  onHold: S,
2776
3420
  taxReverseCharge: S,
2777
3421
  customerId: S,
@@ -2781,20 +3425,20 @@ var ORDER = {
2781
3425
  shippingAddress: ADDRESS,
2782
3426
  billingAddress: ADDRESS,
2783
3427
  fulfillmentSummary: { itemsFulfilled: S, itemsRemaining: S, itemsTotal: S },
2784
- lineItems: [LINE_ITEM],
3428
+ lineItems: [LINE_ITEM2],
2785
3429
  createdAt: S,
2786
3430
  completedAt: S,
2787
3431
  cancelledAt: S,
2788
3432
  closedAt: S
2789
3433
  };
2790
- var PAYMENT = {
3434
+ var PAYMENT2 = {
2791
3435
  id: S,
2792
3436
  orderId: S,
2793
3437
  status: S,
2794
3438
  method: S,
2795
3439
  processor: S,
2796
- amount: S,
2797
- capturedAmount: S,
3440
+ amount: MONEY,
3441
+ capturedAmount: MONEY,
2798
3442
  currency: S,
2799
3443
  cardBrand: S,
2800
3444
  disputed: S,
@@ -2809,17 +3453,17 @@ var PAYMENT = {
2809
3453
  voidedAt: S,
2810
3454
  createdAt: S
2811
3455
  };
2812
- var RETURN = {
3456
+ var RETURN2 = {
2813
3457
  id: S,
2814
3458
  orderId: S,
2815
3459
  status: S,
2816
3460
  restock: S,
2817
- refundAmount: S,
3461
+ refundAmount: MONEY,
2818
3462
  refundPaymentId: S,
2819
3463
  createdAt: S,
2820
3464
  items: [{ lineItemId: S, quantity: S }]
2821
3465
  };
2822
- var FULFILLMENT = {
3466
+ var FULFILLMENT2 = {
2823
3467
  id: S,
2824
3468
  orderId: S,
2825
3469
  type: S,
@@ -2829,12 +3473,12 @@ var FULFILLMENT = {
2829
3473
  detail: { carrier: T, serviceLevel: T, trackingNumber: T, trackingUrl: T, shippedAt: S, estimatedDelivery: S, actualDelivery: S }
2830
3474
  };
2831
3475
  var CUSTOMER = { id: S, netN: S, acceptsMarketing: S, createdAt: S };
2832
- var SUBSCRIPTION = {
3476
+ var SUBSCRIPTION2 = {
2833
3477
  id: S,
2834
3478
  status: S,
2835
3479
  planName: T,
2836
3480
  planReference: T,
2837
- amount: S,
3481
+ amount: MONEY,
2838
3482
  currency: S,
2839
3483
  interval: S,
2840
3484
  quantity: S,
@@ -2856,22 +3500,22 @@ var SUBSCRIPTION = {
2856
3500
  failureCount: S,
2857
3501
  pendingPlanName: T,
2858
3502
  pendingPlanReference: T,
2859
- pendingAmount: S,
3503
+ pendingAmount: MONEY,
2860
3504
  pendingInterval: S,
2861
3505
  pendingQuantity: S,
2862
3506
  pendingIntervalUnit: S,
2863
3507
  pendingIntervalCount: S,
2864
- scheduleTotal: S,
2865
- nextPaymentAmount: S,
3508
+ scheduleTotal: MONEY,
3509
+ nextPaymentAmount: MONEY,
2866
3510
  // A physical subscription (0236): the method is an enum, and the ship-to is
2867
3511
  // kept to its country like every other address here.
2868
3512
  deliveryMethod: S,
2869
3513
  shippingAddress: ADDRESS,
2870
3514
  paymentSchedule: [{
2871
3515
  index: S,
2872
- amount: S,
2873
- discount: S,
2874
- net: S,
3516
+ amount: MONEY,
3517
+ discount: MONEY,
3518
+ net: MONEY,
2875
3519
  intervalUnit: S,
2876
3520
  intervalCount: S,
2877
3521
  status: S,
@@ -2879,13 +3523,13 @@ var SUBSCRIPTION = {
2879
3523
  }],
2880
3524
  createdAt: S
2881
3525
  };
2882
- var QUOTE_SUMMARY = {
3526
+ var QUOTE_SUMMARY2 = {
2883
3527
  id: S,
2884
3528
  quoteNumber: S,
2885
3529
  status: S,
2886
3530
  source: S,
2887
3531
  currency: S,
2888
- total: S,
3532
+ total: MONEY,
2889
3533
  customerId: S,
2890
3534
  orderId: S,
2891
3535
  expiresAt: S,
@@ -2893,18 +3537,18 @@ var QUOTE_SUMMARY = {
2893
3537
  declinedAt: S,
2894
3538
  createdAt: S
2895
3539
  };
2896
- var QUOTE = {
2897
- ...QUOTE_SUMMARY,
3540
+ var QUOTE2 = {
3541
+ ...QUOTE_SUMMARY2,
2898
3542
  revisions: [{
2899
3543
  id: S,
2900
3544
  revisionNumber: S,
2901
3545
  state: S,
2902
- subtotal: S,
2903
- discountTotal: S,
2904
- shippingTotal: S,
2905
- taxTotal: S,
2906
- total: S,
2907
- depositAmount: S,
3546
+ subtotal: MONEY,
3547
+ discountTotal: MONEY,
3548
+ shippingTotal: MONEY,
3549
+ taxTotal: MONEY,
3550
+ total: MONEY,
3551
+ depositAmount: MONEY,
2908
3552
  shippingMode: S,
2909
3553
  issuedAt: S,
2910
3554
  expiresAt: S,
@@ -2912,808 +3556,536 @@ var QUOTE = {
2912
3556
  items: [{
2913
3557
  type: S,
2914
3558
  quantity: S,
2915
- unitPrice: S,
2916
- subtotal: S,
2917
- discountAmount: S,
2918
- taxAmount: S,
2919
- total: S,
3559
+ unitPrice: MONEY,
3560
+ subtotal: MONEY,
3561
+ discountAmount: MONEY,
3562
+ taxAmount: MONEY,
3563
+ total: MONEY,
2920
3564
  optional: S,
2921
3565
  optionalSelected: S,
2922
- recurring: LINE_RECURRING
2923
- }]
2924
- }],
2925
- // Who commented and when, never what they wrote.
2926
- comments: [{ authorType: S, visibility: S, createdAt: S }],
2927
- timeline: [{ type: S, actorType: S, createdAt: S }]
2928
- };
2929
- var INVOICE = {
2930
- id: S,
2931
- number: S,
2932
- status: S,
2933
- sourceType: S,
2934
- sourceId: S,
2935
- customerId: S,
2936
- currency: S,
2937
- subtotal: S,
2938
- discountTotal: S,
2939
- shippingTotal: S,
2940
- taxTotal: S,
2941
- total: S,
2942
- amountRefunded: S,
2943
- issuedAt: S,
2944
- dueAt: S,
2945
- periodStart: S,
2946
- periodEnd: S,
2947
- createdAt: S,
2948
- billingSnapshot: {
2949
- planName: T,
2950
- period: { start: S, end: S },
2951
- lineItems: [{ quantity: S, unitPrice: S, discountAmount: S, taxAmount: S, total: S }],
2952
- totals: { currency: S, subtotal: S, discountTotal: S, shippingTotal: S, taxTotal: S, total: S },
2953
- payment: { method: S, brand: S, status: S }
2954
- }
2955
- };
2956
- var DISCOUNT = {
2957
- id: S,
2958
- code: T,
2959
- name: T,
2960
- type: S,
2961
- value: S,
2962
- isActive: S,
2963
- startsAt: S,
2964
- endsAt: S,
2965
- usageCount: S,
2966
- usageLimit: S,
2967
- maxRedemptionsPerCustomer: S,
2968
- createdAt: S
2969
- };
2970
- var EVENT = {
2971
- id: S,
2972
- type: S,
2973
- entityType: S,
2974
- entityId: S,
2975
- createdAt: S,
2976
- data: {
2977
- status: S,
2978
- previousStatus: S,
2979
- action: S,
2980
- amount: S,
2981
- currency: S,
2982
- attempt: S,
2983
- orderId: S,
2984
- paymentId: S,
2985
- order: { id: S, orderNumber: S, status: S, paymentStatus: S, currency: S, total: S },
2986
- payment: { id: S, orderId: S, status: S, method: S, amount: S, currency: S },
2987
- subscription: { id: S, status: S, planName: T, amount: S, currency: S, interval: S },
2988
- fulfillment: { id: S, orderId: S, type: S, status: S }
2989
- }
2990
- };
2991
- var DELIVERY = {
2992
- id: S,
2993
- endpointId: S,
2994
- eventId: S,
2995
- eventType: S,
2996
- status: S,
2997
- attemptCount: S,
2998
- lastStatus: S,
2999
- deliveredAt: S,
3000
- nextRetryAt: S,
3001
- createdAt: S,
3002
- replayOf: S
3003
- };
3004
- var MONEY_COUNT = { count: S, totalCents: S };
3005
- var ORDER_PERIOD = { orderCount: S, grossCents: S, netCents: S, refundsCents: S, avgOrderCents: S };
3006
- var OAUTH_PROJECTIONS = {
3007
- whoami: {
3008
- type: S,
3009
- workspace: { name: T, slug: S },
3010
- application: APPLICATION,
3011
- environment: { slug: S, kind: S, providerEnvironment: S },
3012
- note: T
3013
- },
3014
- search_docs: PASS,
3015
- describe_endpoint: PASS,
3016
- validate_payload: PASS,
3017
- search_orders: page2(ORDER),
3018
- get_order: {
3019
- order: ORDER,
3020
- payments: section([PAYMENT]),
3021
- returns: section([RETURN]),
3022
- fulfillments: section([FULFILLMENT])
3023
- },
3024
- search_customers: page2(CUSTOMER),
3025
- get_customer: {
3026
- customer: CUSTOMER,
3027
- addresses: section([{ id: S, isDefault: S, ...ADDRESS }]),
3028
- subscriptions: section([SUBSCRIPTION])
3029
- },
3030
- list_subscriptions: page2(SUBSCRIPTION),
3031
- get_subscription: SUBSCRIPTION,
3032
- search_quotes: page2(QUOTE_SUMMARY),
3033
- get_quote: QUOTE,
3034
- list_invoices: page2(INVOICE),
3035
- get_invoice: INVOICE,
3036
- receivables_aging: {
3037
- buckets: [{ key: S, label: T, count: S, total_amount: S }],
3038
- total_outstanding_amount: S,
3039
- total_outstanding_count: S
3040
- },
3041
- search_discounts: page2(DISCOUNT),
3042
- get_discount: DISCOUNT,
3043
- search_payments: page2(PAYMENT),
3044
- get_payment: {
3045
- payment: PAYMENT,
3046
- transactions: section([{ id: S, type: S, status: S, amount: S, currency: S, createdAt: S }])
3047
- },
3048
- list_abandoned_carts: {
3049
- carts: section([{
3050
- id: S,
3051
- abandonedAt: S,
3052
- currency: S,
3053
- itemCount: S,
3054
- recoveryStatus: S,
3055
- total: S,
3056
- customer: { id: S }
3057
- }]),
3058
- summary: section({ abandonedCount: S, abandonedValue: S, recoveryEmailsSent: S, sinceDays: S })
3059
- },
3060
- search_events: page2(EVENT),
3061
- list_webhook_deliveries: page2(DELIVERY),
3062
- get_webhook_delivery: DELIVERY,
3063
- explain_checkout_failure: {
3064
- note: T,
3065
- hint: T,
3066
- session: {
3067
- id: S,
3068
- status: S,
3069
- cartId: S,
3070
- customerId: S,
3071
- expiresAt: S,
3072
- completedAt: S,
3073
- allowedMethods: [S],
3074
- collect: { shippingAddress: S, billingAddress: S, vatNumber: S },
3075
- shippingAddress: ADDRESS,
3076
- billingAddress: ADDRESS,
3077
- recurringTerms: {
3078
- interval: S,
3079
- intervalUnit: S,
3080
- intervalCount: S,
3081
- totalPayments: S,
3082
- taxApplies: S,
3083
- planChargedToday: S,
3084
- planName: T,
3085
- trialDays: S,
3086
- currency: S,
3087
- firstChargeAmountMinor: S
3088
- },
3089
- hasSubscriptions: S,
3090
- // One entry per subscription line. No `name`: it is the line's name.
3091
- subscriptions: [{
3092
- lineItemId: S,
3093
- amount: S,
3094
- quantity: S,
3095
- interval: S,
3096
- intervalUnit: S,
3097
- intervalCount: S,
3098
- totalPayments: S,
3099
- trialDays: S,
3100
- trialEndsAt: S,
3101
- planChargedToday: S,
3102
- taxApplies: S,
3103
- scheduleGapUnits: [S],
3104
- schedule: [{ net: S, dueAt: S }]
3105
- }]
3106
- },
3107
- cart: section({
3108
- id: S,
3109
- status: S,
3110
- currency: S,
3111
- subtotal: S,
3112
- discountTotal: S,
3113
- shippingTotal: S,
3114
- taxTotal: S,
3115
- total: S,
3116
- itemCount: S,
3117
- items: [LINE_ITEM],
3118
- lineItems: [LINE_ITEM]
3119
- }),
3120
- events: [EVENT],
3121
- eventsUnavailable: T,
3122
- recentWebhookDeliveries: section([DELIVERY])
3123
- },
3124
- list_extension_installations: page2({
3125
- id: S,
3126
- extensionId: S,
3127
- extensionName: T,
3128
- extensionSlug: S,
3129
- versionId: S,
3130
- status: S,
3131
- environmentSlug: S,
3132
- installedAt: S,
3133
- uninstalledAt: S
3134
- }),
3135
- get_connector_routing: {
3136
- paymentRouting: section({
3137
- defaultCascade: [S],
3138
- rules: [{ cascade: [S], conditions: [{ type: S, op: S, currency: S, min: S, max: S, values: [S] }] }]
3139
- }),
3140
- cardDecline: section({ rules: [{ errorCode: S, conditions: [{ type: S, op: S, values: [S] }] }] }),
3141
- otherDecline: section({ rules: [{ errorCode: S, conditions: [{ type: S, op: S, values: [S] }] }] }),
3142
- routingConnectors: section([{ id: S, displayName: T, method: S }])
3143
- },
3144
- get_integration_status: {
3145
- environment: { slug: S, kind: S, providerEnvironment: S },
3146
- workspace: { name: T, slug: S },
3147
- applicationId: S,
3148
- application: APPLICATION,
3149
- connectors: section([{
3150
- id: S,
3151
- displayName: T,
3152
- method: S,
3153
- type: S,
3154
- status: S,
3155
- active: S,
3156
- position: S,
3157
- acceptedCountries: [S],
3158
- acceptedCurrencies: [S],
3159
- threeDSecureEnabled: S,
3160
- createdAt: S
3161
- }]),
3162
- webhookEndpoints: section([{ id: S, isActive: S, enabledEvents: [S], createdAt: S }]),
3163
- unsubscribedEvents: section({ windowDays: S, unsubscribed: [{ type: S, count: S, lastEmittedAt: S }] })
3164
- },
3165
- get_workspace_settings: { name: T, slug: S, brandColor: S, logoUrl: T, onboardingCompletedAt: S },
3166
- // What happened and to which record; not which team member did it.
3167
- get_audit_log: page2({ id: S, action: S, resourceType: S, resourceId: S, createdAt: S }),
3168
- list_applications: [{ id: S, name: T, slug: S, currency: S, isActive: S }],
3169
- // Analytics: computed aggregates, listed field by field all the same.
3170
- get_business_summary: {
3171
- period: S,
3172
- range: RANGE,
3173
- orders: section({ current: ORDER_PERIOD, previous: ORDER_PERIOD, deltaPct: S }),
3174
- subscriptions: section({
3175
- mrr: { currentCents: S, periodStartCents: S, deltaPct: S },
3176
- newSubscriptions: S,
3177
- cancelledSubscriptions: S,
3178
- churnRate: S,
3179
- note: T
3180
- }),
3181
- receivables: section({ outstandingCents: S, outstandingCount: S }),
3182
- quotes: section({ sent: MONEY_COUNT, accepted: MONEY_COUNT, declined: MONEY_COUNT, expired: MONEY_COUNT })
3183
- },
3184
- get_attention_digest: {
3185
- disputes: section({ open: S, totalCents: S }),
3186
- subscriptionsInDunning: section(S),
3187
- overdueInvoices: section(MONEY_COUNT),
3188
- unhealthyWebhooks: section([{ endpointId: S, failureRate: S, attempts7d: S }])
3189
- },
3190
- get_sales_timeseries: {
3191
- application: APPLICATION,
3192
- range: RANGE,
3193
- currency: S,
3194
- days: S,
3195
- note: T,
3196
- series: [{ date: S, grossCents: S, orders: S }],
3197
- totalGrossCents: S,
3198
- totalOrders: S
3199
- },
3200
- // get_top_products has no entry, so it is not offered over OAuth: it ranks
3201
- // products by line-item reference id or name, which a buyer can type.
3202
- get_customer_growth: {
3203
- application: APPLICATION,
3204
- range: RANGE,
3205
- note: T,
3206
- topBy: S,
3207
- signups: { total: S, series: [{ date: S, signups: S }] },
3208
- ordersByCustomerType: { newCustomerOrders: S, returningCustomerOrders: S },
3209
- // The ranking, by id: a top customer's name and email stay behind.
3210
- topCustomers: [{ customerId: S, orderCount: S, revenueCents: S }],
3211
- totals: { customerCount: S, orderCount: S, revenueCents: S }
3212
- },
3213
- get_revenue_breakdown: {
3214
- application: APPLICATION,
3215
- range: RANGE,
3216
- dimension: S,
3217
- note: T,
3218
- rows: [{ key: S, orderCount: S, grossCents: S }],
3219
- totals: { orderCount: S, grossCents: S }
3220
- },
3221
- get_funnel_conversion: {
3222
- application: APPLICATION,
3223
- range: RANGE,
3224
- note: T,
3225
- conversionRate: S,
3226
- stages: [{ name: S, count: S }],
3227
- dropOff: [{ from: S, to: S, ratePct: S }]
3228
- },
3229
- get_subscription_movement: {
3230
- application: APPLICATION,
3231
- range: RANGE,
3232
- note: T,
3233
- series: [{ date: S, newSubscriptions: S, churnedSubscriptions: S, mrrDeltaCents: S }],
3234
- totals: { newSubscriptions: S, churnedSubscriptions: S, netMrrDeltaCents: S }
3235
- },
3236
- get_discount_performance: {
3237
- application: APPLICATION,
3238
- range: RANGE,
3239
- note: T,
3240
- rows: [{ discountId: S, code: T, redemptions: S, discountedRevenueCents: S, discountGivenCents: S }],
3241
- totals: { redemptions: S, discountedRevenueCents: S, discountGivenCents: S }
3242
- }
3243
- };
3244
-
3245
- // src/server.ts
3246
- var VERSION = true ? "0.4.4" : "0.0.0-dev";
3247
- function registerableActions(policy) {
3248
- const isProduction = policy.identity.environment.providerEnvironment === "production";
3249
- return actionsForChannel("mcp").filter((action) => {
3250
- if (!HANDLERS[action.id]) return false;
3251
- if (action.credentialScoped && policy.allowCredentialScoped === false) return false;
3252
- if (!canRunAction(policy.identity.scopes, action)) return false;
3253
- if (action.kind === "read") return true;
3254
- if (action.sandboxOnly) return !isProduction && (policy.allowSandboxWrites ?? true);
3255
- if (!policy.allowWrites) return false;
3256
- return !isProduction || policy.allowLiveWrites;
3257
- });
3258
- }
3259
- function buildInstructions(identity, actions, policy) {
3260
- const isProduction = identity.environment.providerEnvironment === "production";
3261
- const where = [
3262
- identity.workspace?.name ?? identity.workspace?.slug ?? "unknown workspace",
3263
- identity.application?.name ?? identity.application?.slug ?? null
3264
- ].filter(Boolean).join(" / ");
3265
- const liveWrites = actions.filter((a) => a.kind === "write" && !a.sandboxOnly);
3266
- const sandboxWrites = actions.filter((a) => a.kind === "write" && a.sandboxOnly);
3267
- const lines = [
3268
- `Throttle MCP ${VERSION}. Connected to ${where}, environment "${identity.environment.slug}" (${isProduction ? "PRODUCTION \u2014 live data" : "non-production \u2014 not live data"}).`,
3269
- "",
3270
- "Conventions:",
3271
- "- The workspace and environment are fixed for this session and cannot be switched from inside a tool call. Call whoami if you need to state where you are.",
3272
- '- The application can vary per call: pass "applicationId" on a read or analytics tool to reach a different application in this workspace, and call list_applications to see which ones this connection can reach. Omitting applicationId uses the application this connection was authorized for.',
3273
- "- Every analytics result covers exactly ONE application and names it in `application`. Say which application a figure describes. If the user asks about their business as a whole and this connection reaches more than one application, do not answer from the default alone \u2014 call list_applications, then query each and add them up, or ask which application they mean.",
3274
- '- List tools return { data, pagination }. When pagination.hasMore is true, pass pagination.cursor back as "cursor" rather than raising "limit".',
3275
- "- Amounts are integer minor units of the record's currency (2500 = 25.00 in a two-decimal currency; JPY has none, KWD has three).",
3276
- "- Throttle rejects snake_case on public request bodies. Before writing integration code, confirm shapes with describe_endpoint and check bodies with validate_payload instead of guessing field names.",
3277
- "- API errors come back as text with a stable code. On insufficient_scopes, tell the user which scope to add \u2014 do not retry.",
3278
- "- Analytics results may mark a section `omitted`. That means UNKNOWN, never zero. When `grantable` is false the data cannot be read over this connection at all \u2014 say so rather than reporting an absence."
3279
- ];
3280
- if (liveWrites.length === 0) {
3281
- lines.push(
3282
- `- This session is READ-ONLY for real data${policy.allowWrites ? " (no write tools are available to this credential)" : " \u2014 writes were not enabled"}. Say so plainly if asked to change something.`
3283
- );
3284
- if (sandboxWrites.length > 0) {
3285
- lines.push(
3286
- `- ${sandboxWrites.map((a) => a.id).join(", ")} may create data, but only in this non-production environment.`
3287
- );
3288
- }
3289
- } else {
3290
- lines.push(
3291
- `- Write tools are enabled (${liveWrites.map((a) => a.id).join(", ")}). They are irreversible and some are buyer-visible. Confirm with the user before calling one.`
3292
- );
3293
- }
3294
- return lines.join("\n");
3295
- }
3296
- function declareSecuritySchemes(server, actions) {
3297
- const inner = server.server;
3298
- const handlers = inner._requestHandlers;
3299
- const original = handlers?.get("tools/list");
3300
- if (!original) return;
3301
- const schemes = new Map(
3302
- actions.map((a) => [
3303
- a.id,
3304
- [{
3305
- type: "oauth2",
3306
- scopes: [.../* @__PURE__ */ new Set([...a.scopes, ...a.sectionScopes ?? []])].filter((scope) => validateScopesForOAuth([scope]).ok)
3307
- }]
3308
- ])
3309
- );
3310
- inner.setRequestHandler(ListToolsRequestSchema, async (request, extra) => {
3311
- const result = await original(request, extra);
3312
- return {
3313
- ...result,
3314
- tools: result.tools.map((tool) => ({ ...tool, securitySchemes: schemes.get(tool.name) ?? [{ type: "oauth2", scopes: [] }] }))
3315
- };
3316
- });
3317
- }
3318
- function createServer(options) {
3319
- const redactPii = options.identity.type === "oauth_token" && !hasScope(options.identity.scopes, "customer_pii:read");
3320
- const actions = registerableActions(options).filter((a) => !redactPii || OAUTH_PROJECTIONS[a.id] !== void 0);
3321
- const server = new McpServer(
3322
- { name: "throttle", version: VERSION },
3323
- { instructions: buildInstructions(options.identity, actions, options) }
3324
- );
3325
- const ctx = {
3326
- client: options.client,
3327
- identity: options.identity,
3328
- contract: options.contract,
3329
- docs: options.docs
3330
- };
3331
- for (const action of actions) {
3332
- const handler = HANDLERS[action.id];
3333
- server.registerTool(
3334
- action.id,
3335
- {
3336
- title: action.title,
3337
- description: describeForModel(action),
3338
- inputSchema: fieldsToZodShape(action.input),
3339
- // Every hint is an explicit boolean: directory reviews (OpenAI's in
3340
- // particular) read a missing value as "unknown", not as false.
3341
- annotations: {
3342
- title: action.title,
3343
- readOnlyHint: action.kind === "read",
3344
- destructiveHint: action.kind === "write" && Boolean(action.destructive),
3345
- idempotentHint: Boolean(action.idempotent),
3346
- // Every tool is bounded to the connected workspace; none reaches the
3347
- // public internet or an open-ended set of external entities.
3348
- openWorldHint: false
3349
- }
3350
- },
3351
- async (args) => {
3352
- try {
3353
- if (redactPii && action.id === "search_customers" && typeof args?.q === "string" && args.q.trim() !== "") {
3354
- return {
3355
- content: [{ type: "text", text: "Customer text search is not available over this connection, because names, emails, phone numbers and external ids are withheld. List customers by creation date (createdAfter/createdBefore), or open one by its Throttle id from an order, quote or subscription." }],
3356
- isError: true
3357
- };
3358
- }
3359
- const result = stripRawProcessorData(await handler(ctx, args ?? {}));
3360
- const shown = redactPii ? redactShopperPii(project(result, OAUTH_PROJECTIONS[action.id])) : result;
3361
- return { content: [{ type: "text", text: formatResult(shown) }] };
3362
- } catch (error) {
3363
- return {
3364
- content: [{ type: "text", text: formatError(error) }],
3365
- isError: true,
3366
- ...options.authChallenge && isCredentialRejection(error) ? {
3367
- _meta: {
3368
- "mcp/www_authenticate": [
3369
- `${options.authChallenge}, error="invalid_token", error_description="The connected credential was rejected. Sign in again to continue."`
3370
- ]
3371
- }
3372
- } : {}
3373
- };
3374
- }
3375
- }
3376
- );
3377
- }
3378
- if (options.authChallenge) declareSecuritySchemes(server, actions);
3379
- return server;
3380
- }
3381
- function isCredentialRejection(error) {
3382
- return error?.statusCode === 401;
3383
- }
3384
- function describeForModel(action) {
3385
- const parts = [action.description];
3386
- if (action.guardrails && action.guardrails.length > 0) {
3387
- parts.push(`Constraints: ${action.guardrails.join(" ")}`);
3388
- }
3389
- return parts.join(" ");
3390
- }
3391
-
3392
- // src/indexes.ts
3393
- import { readFileSync } from "fs";
3394
- function loadIndex(file, empty, label) {
3395
- try {
3396
- return JSON.parse(readFileSync(new URL(`./${file}`, import.meta.url), "utf8"));
3397
- } catch {
3398
- process.stderr.write(
3399
- `throttle-mcp: ${label} index missing (${file}); that tool will return no results. Run "pnpm --filter @usethrottle/mcp build:indexes".
3400
- `
3401
- );
3402
- return empty;
3403
- }
3404
- }
3405
- function loadDocsIndex() {
3406
- return loadIndex("docs-index.json", { generatedAt: "", entries: [] }, "docs");
3407
- }
3408
- function loadContractIndex() {
3409
- return loadIndex("contract-index.json", { generatedAt: "", operations: [] }, "contract");
3410
- }
3411
-
3412
- // ../money/dist/index.js
3413
- var dist_exports = {};
3414
- __export(dist_exports, {
3415
- CURRENCIES: () => CURRENCIES,
3416
- UNCONFIRMED_EXPONENT_CODES: () => UNCONFIRMED_EXPONENT_CODES,
3417
- UnknownCurrencyError: () => UnknownCurrencyError,
3418
- currencySymbol: () => currencySymbol,
3419
- formatMoney: () => formatMoney,
3420
- isEnableableCurrency: () => isEnableableCurrency,
3421
- isKnownCurrency: () => isKnownCurrency,
3422
- minorUnitsOf: () => minorUnitsOf,
3423
- moneyValue: () => moneyValue,
3424
- parseMoney: () => parseMoney,
3425
- toDecimalString: () => toDecimalString,
3426
- toMinor: () => toMinor
3427
- });
3428
- var CURRENCY_ROWS = [
3429
- ["AED", 2, "AED", false],
3430
- ["AFN", 2, "AFN", false],
3431
- ["ALL", 2, "ALL", false],
3432
- ["AMD", 2, "AMD", false],
3433
- ["AOA", 2, "AOA", false],
3434
- ["ARS", 2, "ARS", false],
3435
- ["AUD", 2, "A$", false],
3436
- ["AWG", 2, "AWG", false],
3437
- ["AZN", 2, "AZN", false],
3438
- ["BAM", 2, "BAM", false],
3439
- ["BBD", 2, "BBD", false],
3440
- ["BDT", 2, "BDT", false],
3441
- ["BHD", 3, "BHD", false],
3442
- ["BIF", 0, "BIF", false],
3443
- ["BMD", 2, "BMD", false],
3444
- ["BND", 2, "BND", false],
3445
- ["BOB", 2, "BOB", false],
3446
- ["BOV", 2, "BOV", true],
3447
- ["BRL", 2, "R$", false],
3448
- ["BSD", 2, "BSD", false],
3449
- ["BTN", 2, "BTN", false],
3450
- ["BWP", 2, "BWP", false],
3451
- ["BYN", 2, "BYN", false],
3452
- ["BZD", 2, "BZD", false],
3453
- ["CAD", 2, "CA$", false],
3454
- ["CDF", 2, "CDF", false],
3455
- ["CHE", 2, "CHE", true],
3456
- ["CHF", 2, "CHF", false],
3457
- ["CHW", 2, "CHW", true],
3458
- ["CLF", 4, "CLF", true],
3459
- ["CLP", 0, "CLP", false],
3460
- ["CNY", 2, "CN\xA5", false],
3461
- ["COP", 2, "COP", false],
3462
- ["COU", 2, "COU", true],
3463
- ["CRC", 2, "CRC", false],
3464
- ["CUP", 2, "CUP", false],
3465
- ["CVE", 2, "CVE", false],
3466
- ["CZK", 2, "CZK", false],
3467
- ["DJF", 0, "DJF", false],
3468
- ["DKK", 2, "DKK", false],
3469
- ["DOP", 2, "DOP", false],
3470
- ["DZD", 2, "DZD", false],
3471
- ["EGP", 2, "EGP", false],
3472
- ["ERN", 2, "ERN", false],
3473
- ["ETB", 2, "ETB", false],
3474
- ["EUR", 2, "\u20AC", false],
3475
- ["FJD", 2, "FJD", false],
3476
- ["FKP", 2, "FKP", false],
3477
- ["GBP", 2, "\xA3", false],
3478
- ["GEL", 2, "GEL", false],
3479
- ["GHS", 2, "GHS", false],
3480
- ["GIP", 2, "GIP", false],
3481
- ["GMD", 2, "GMD", false],
3482
- ["GNF", 0, "GNF", false],
3483
- ["GTQ", 2, "GTQ", false],
3484
- ["GYD", 2, "GYD", false],
3485
- ["HKD", 2, "HK$", false],
3486
- ["HNL", 2, "HNL", false],
3487
- ["HTG", 2, "HTG", false],
3488
- ["HUF", 2, "HUF", false],
3489
- ["IDR", 2, "IDR", false],
3490
- ["ILS", 2, "\u20AA", false],
3491
- ["INR", 2, "\u20B9", false],
3492
- ["IQD", 3, "IQD", false],
3493
- ["IRR", 2, "IRR", false],
3494
- ["ISK", 0, "ISK", false],
3495
- ["JMD", 2, "JMD", false],
3496
- ["JOD", 3, "JOD", false],
3497
- ["JPY", 0, "\xA5", false],
3498
- ["KES", 2, "KES", false],
3499
- ["KGS", 2, "KGS", false],
3500
- ["KHR", 2, "KHR", false],
3501
- ["KMF", 0, "KMF", false],
3502
- ["KPW", 2, "KPW", false],
3503
- ["KRW", 0, "\u20A9", false],
3504
- ["KWD", 3, "KWD", false],
3505
- ["KYD", 2, "KYD", false],
3506
- ["KZT", 2, "KZT", false],
3507
- ["LAK", 2, "LAK", false],
3508
- ["LBP", 2, "LBP", false],
3509
- ["LKR", 2, "LKR", false],
3510
- ["LRD", 2, "LRD", false],
3511
- ["LSL", 2, "LSL", false],
3512
- ["LYD", 3, "LYD", false],
3513
- ["MAD", 2, "MAD", false],
3514
- ["MDL", 2, "MDL", false],
3515
- ["MGA", 2, "MGA", false],
3516
- ["MKD", 2, "MKD", false],
3517
- ["MMK", 2, "MMK", false],
3518
- ["MNT", 2, "MNT", false],
3519
- ["MOP", 2, "MOP", false],
3520
- ["MRU", 2, "MRU", false],
3521
- ["MUR", 2, "MUR", false],
3522
- ["MVR", 2, "MVR", false],
3523
- ["MWK", 2, "MWK", false],
3524
- ["MXN", 2, "MX$", false],
3525
- ["MXV", 2, "MXV", true],
3526
- ["MYR", 2, "MYR", false],
3527
- ["MZN", 2, "MZN", false],
3528
- ["NAD", 2, "NAD", false],
3529
- ["NGN", 2, "NGN", false],
3530
- ["NIO", 2, "NIO", false],
3531
- ["NOK", 2, "NOK", false],
3532
- ["NPR", 2, "NPR", false],
3533
- ["NZD", 2, "NZ$", false],
3534
- ["OMR", 3, "OMR", false],
3535
- ["PAB", 2, "PAB", false],
3536
- ["PEN", 2, "PEN", false],
3537
- ["PGK", 2, "PGK", false],
3538
- ["PHP", 2, "\u20B1", false],
3539
- ["PKR", 2, "PKR", false],
3540
- ["PLN", 2, "PLN", false],
3541
- ["PYG", 0, "PYG", false],
3542
- ["QAR", 2, "QAR", false],
3543
- ["RON", 2, "RON", false],
3544
- ["RSD", 2, "RSD", false],
3545
- ["RUB", 2, "RUB", false],
3546
- ["RWF", 0, "RWF", false],
3547
- ["SAR", 2, "SAR", false],
3548
- ["SBD", 2, "SBD", false],
3549
- ["SCR", 2, "SCR", false],
3550
- ["SDG", 2, "SDG", false],
3551
- ["SEK", 2, "SEK", false],
3552
- ["SGD", 2, "SGD", false],
3553
- ["SHP", 2, "SHP", false],
3554
- ["SLE", 2, "SLE", false],
3555
- ["SOS", 2, "SOS", false],
3556
- ["SRD", 2, "SRD", false],
3557
- ["SSP", 2, "SSP", false],
3558
- ["STN", 2, "STN", false],
3559
- ["SVC", 2, "SVC", false],
3560
- ["SYP", 2, "SYP", false],
3561
- ["SZL", 2, "SZL", false],
3562
- ["THB", 2, "THB", false],
3563
- ["TJS", 2, "TJS", false],
3564
- ["TMT", 2, "TMT", false],
3565
- ["TND", 3, "TND", false],
3566
- ["TOP", 2, "TOP", false],
3567
- ["TRY", 2, "TRY", false],
3568
- ["TTD", 2, "TTD", false],
3569
- ["TWD", 2, "NT$", false],
3570
- ["TZS", 2, "TZS", false],
3571
- ["UAH", 2, "UAH", false],
3572
- ["UGX", 0, "UGX", false],
3573
- ["USD", 2, "$", false],
3574
- ["USN", 2, "USN", true],
3575
- ["UYI", 0, "UYI", true],
3576
- ["UYU", 2, "UYU", false],
3577
- ["UYW", 4, "UYW", true],
3578
- ["UZS", 2, "UZS", false],
3579
- ["VED", 2, "VED", false],
3580
- ["VES", 2, "VES", false],
3581
- ["VND", 0, "\u20AB", false],
3582
- ["VUV", 0, "VUV", false],
3583
- ["WST", 2, "WST", false],
3584
- ["XAD", 2, "XAD", true],
3585
- ["XAF", 0, "FCFA", false],
3586
- ["XCD", 2, "EC$", false],
3587
- ["XCG", 2, "Cg.", false],
3588
- ["XOF", 0, "F\u202FCFA", false],
3589
- ["XPF", 0, "CFPF", false],
3590
- ["YER", 2, "YER", false],
3591
- ["ZAR", 2, "ZAR", false],
3592
- ["ZMW", 2, "ZMW", false],
3593
- ["ZWG", 2, "ZWG", false]
3594
- ];
3595
- var UnknownCurrencyError = class extends Error {
3596
- constructor(currency) {
3597
- super(`Unknown currency code: ${currency}`);
3598
- this.code = "unknown_currency";
3599
- this.name = "UnknownCurrencyError";
3600
- this.currency = currency;
3566
+ recurring: LINE_RECURRING
3567
+ }]
3568
+ }],
3569
+ // Who commented and when, never what they wrote.
3570
+ comments: [{ authorType: S, visibility: S, createdAt: S }],
3571
+ timeline: [{ type: S, actorType: S, createdAt: S }]
3572
+ };
3573
+ var INVOICE2 = {
3574
+ id: S,
3575
+ number: S,
3576
+ status: S,
3577
+ sourceType: S,
3578
+ sourceId: S,
3579
+ customerId: S,
3580
+ currency: S,
3581
+ subtotal: MONEY,
3582
+ discountTotal: MONEY,
3583
+ shippingTotal: MONEY,
3584
+ taxTotal: MONEY,
3585
+ total: MONEY,
3586
+ amountRefunded: MONEY,
3587
+ issuedAt: S,
3588
+ dueAt: S,
3589
+ periodStart: S,
3590
+ periodEnd: S,
3591
+ createdAt: S,
3592
+ billingSnapshot: {
3593
+ planName: T,
3594
+ period: { start: S, end: S },
3595
+ lineItems: [{ quantity: S, unitPrice: MONEY, discountAmount: MONEY, taxAmount: MONEY, total: MONEY }],
3596
+ totals: { currency: S, subtotal: MONEY, discountTotal: MONEY, shippingTotal: MONEY, taxTotal: MONEY, total: MONEY },
3597
+ payment: { method: S, brand: S, status: S }
3601
3598
  }
3602
3599
  };
3603
- var BY_CODE = new Map(
3604
- CURRENCY_ROWS.map(([code, minorUnits, symbol, fund]) => [code, { minorUnits, symbol, fund }])
3605
- );
3606
- var CURRENCIES = Object.freeze(
3607
- CURRENCY_ROWS.map(([code, minorUnits, symbol]) => Object.freeze({ code, minorUnits, symbol }))
3608
- );
3609
- var UNCONFIRMED = /* @__PURE__ */ new Set(["COP", "HUF", "IDR", "ISK", "TWD", "UGX"]);
3610
- var UNCONFIRMED_EXPONENT_CODES = Object.freeze({
3611
- has: (code) => UNCONFIRMED.has(code),
3612
- get size() {
3613
- return UNCONFIRMED.size;
3600
+ var DISCOUNT2 = {
3601
+ id: S,
3602
+ code: T,
3603
+ name: T,
3604
+ type: S,
3605
+ value: S,
3606
+ isActive: S,
3607
+ startsAt: S,
3608
+ endsAt: S,
3609
+ usageCount: S,
3610
+ usageLimit: S,
3611
+ maxRedemptionsPerCustomer: S,
3612
+ createdAt: S,
3613
+ // Per currency, main one included. The decorator drops a fixed discount's legacy `value`
3614
+ // (MC4-R77), so this is where its amount is. A percentage discount's `amounts` hold only
3615
+ // a minimum, so `value` is money whenever it is present.
3616
+ amounts: mapOf({ value: MONEY, minOrder: MONEY })
3617
+ };
3618
+ var EVENT2 = {
3619
+ id: S,
3620
+ type: S,
3621
+ entityType: S,
3622
+ entityId: S,
3623
+ createdAt: S,
3624
+ data: {
3625
+ status: S,
3626
+ previousStatus: S,
3627
+ action: S,
3628
+ amount: MONEY,
3629
+ currency: S,
3630
+ attempt: S,
3631
+ orderId: S,
3632
+ paymentId: S,
3633
+ order: { id: S, orderNumber: S, status: S, paymentStatus: S, currency: S, total: MONEY },
3634
+ payment: { id: S, orderId: S, status: S, method: S, amount: MONEY, currency: S },
3635
+ subscription: { id: S, status: S, planName: T, amount: MONEY, currency: S, interval: S },
3636
+ fulfillment: { id: S, orderId: S, type: S, status: S }
3637
+ }
3638
+ };
3639
+ var DELIVERY2 = {
3640
+ id: S,
3641
+ endpointId: S,
3642
+ eventId: S,
3643
+ eventType: S,
3644
+ status: S,
3645
+ attemptCount: S,
3646
+ lastStatus: S,
3647
+ deliveredAt: S,
3648
+ nextRetryAt: S,
3649
+ createdAt: S,
3650
+ replayOf: S
3651
+ };
3652
+ var COUNT_BY_CURRENCY = { count: S, byCurrency: byCurrency({ count: S }) };
3653
+ var ORDER_PERIOD = {
3654
+ orderCount: S,
3655
+ byCurrency: byCurrency({ orderCount: S, avgOrder: MONEY, refunds: MONEY, net: MONEY })
3656
+ };
3657
+ var OAUTH_PROJECTIONS = {
3658
+ whoami: {
3659
+ type: S,
3660
+ workspace: { name: T, slug: S },
3661
+ application: APPLICATION,
3662
+ environment: { slug: S, kind: S, providerEnvironment: S },
3663
+ note: T
3664
+ },
3665
+ search_docs: PASS,
3666
+ describe_endpoint: PASS,
3667
+ validate_payload: PASS,
3668
+ search_orders: page3(ORDER2),
3669
+ get_order: {
3670
+ order: ORDER2,
3671
+ payments: section([PAYMENT2]),
3672
+ returns: section([RETURN2]),
3673
+ fulfillments: section([FULFILLMENT2])
3674
+ },
3675
+ search_customers: page3(CUSTOMER),
3676
+ get_customer: {
3677
+ customer: CUSTOMER,
3678
+ addresses: section([{ id: S, isDefault: S, ...ADDRESS }]),
3679
+ subscriptions: section([SUBSCRIPTION2])
3680
+ },
3681
+ list_subscriptions: page3(SUBSCRIPTION2),
3682
+ get_subscription: SUBSCRIPTION2,
3683
+ search_quotes: page3(QUOTE_SUMMARY2),
3684
+ get_quote: QUOTE2,
3685
+ list_invoices: page3(INVOICE2),
3686
+ get_invoice: INVOICE2,
3687
+ receivables_aging: {
3688
+ currency: S,
3689
+ buckets: [{ key: S, label: T, count: S, byCurrency: byCurrency({ count: S }) }],
3690
+ total_outstanding_count: S,
3691
+ byCurrency: byCurrency({ count: S })
3692
+ },
3693
+ search_discounts: page3(DISCOUNT2),
3694
+ get_discount: DISCOUNT2,
3695
+ search_payments: page3(PAYMENT2),
3696
+ get_payment: {
3697
+ payment: PAYMENT2,
3698
+ transactions: section([{ id: S, type: S, status: S, amount: MONEY, currency: S, createdAt: S }])
3699
+ },
3700
+ list_abandoned_carts: {
3701
+ carts: section([{
3702
+ id: S,
3703
+ abandonedAt: S,
3704
+ currency: S,
3705
+ itemCount: S,
3706
+ recoveryStatus: S,
3707
+ total: MONEY,
3708
+ customer: { id: S }
3709
+ }]),
3710
+ summary: section({
3711
+ abandonedCount: S,
3712
+ currency: S,
3713
+ byCurrency: byCurrency({ count: S }),
3714
+ recoveryEmailsSent: S,
3715
+ sinceDays: S
3716
+ })
3717
+ },
3718
+ search_events: page3(EVENT2),
3719
+ list_webhook_deliveries: page3(DELIVERY2),
3720
+ get_webhook_delivery: DELIVERY2,
3721
+ explain_checkout_failure: {
3722
+ note: T,
3723
+ hint: T,
3724
+ session: {
3725
+ id: S,
3726
+ status: S,
3727
+ cartId: S,
3728
+ customerId: S,
3729
+ expiresAt: S,
3730
+ completedAt: S,
3731
+ allowedMethods: [S],
3732
+ collect: { shippingAddress: S, billingAddress: S, vatNumber: S },
3733
+ shippingAddress: ADDRESS,
3734
+ billingAddress: ADDRESS,
3735
+ recurringTerms: {
3736
+ interval: S,
3737
+ intervalUnit: S,
3738
+ intervalCount: S,
3739
+ totalPayments: S,
3740
+ taxApplies: S,
3741
+ planChargedToday: S,
3742
+ planName: T,
3743
+ trialDays: S,
3744
+ currency: S,
3745
+ firstChargeAmountMinor: MONEY
3746
+ },
3747
+ hasSubscriptions: S,
3748
+ // One entry per subscription line. No `name`: it is the line's name.
3749
+ subscriptions: [{
3750
+ lineItemId: S,
3751
+ amount: MONEY,
3752
+ quantity: S,
3753
+ interval: S,
3754
+ intervalUnit: S,
3755
+ intervalCount: S,
3756
+ totalPayments: S,
3757
+ trialDays: S,
3758
+ trialEndsAt: S,
3759
+ planChargedToday: S,
3760
+ taxApplies: S,
3761
+ scheduleGapUnits: [S],
3762
+ schedule: [{ net: MONEY, dueAt: S }]
3763
+ }]
3764
+ },
3765
+ cart: section({
3766
+ id: S,
3767
+ status: S,
3768
+ currency: S,
3769
+ subtotal: MONEY,
3770
+ discountTotal: MONEY,
3771
+ shippingTotal: MONEY,
3772
+ taxTotal: MONEY,
3773
+ total: MONEY,
3774
+ itemCount: S,
3775
+ items: [LINE_ITEM2],
3776
+ lineItems: [LINE_ITEM2]
3777
+ }),
3778
+ events: [EVENT2],
3779
+ eventsUnavailable: T,
3780
+ recentWebhookDeliveries: section([DELIVERY2])
3781
+ },
3782
+ list_extension_installations: page3({
3783
+ id: S,
3784
+ extensionId: S,
3785
+ extensionName: T,
3786
+ extensionSlug: S,
3787
+ versionId: S,
3788
+ status: S,
3789
+ environmentSlug: S,
3790
+ installedAt: S,
3791
+ uninstalledAt: S
3792
+ }),
3793
+ get_connector_routing: {
3794
+ paymentRouting: section({
3795
+ defaultCascade: [S],
3796
+ rules: [{ cascade: [S], conditions: [{ type: S, op: S, currency: S, min: S, max: S, values: [S] }] }]
3797
+ }),
3798
+ cardDecline: section({ rules: [{ errorCode: S, conditions: [{ type: S, op: S, values: [S] }] }] }),
3799
+ otherDecline: section({ rules: [{ errorCode: S, conditions: [{ type: S, op: S, values: [S] }] }] }),
3800
+ routingConnectors: section([{ id: S, displayName: T, method: S }])
3801
+ },
3802
+ get_integration_status: {
3803
+ environment: { slug: S, kind: S, providerEnvironment: S },
3804
+ workspace: { name: T, slug: S },
3805
+ applicationId: S,
3806
+ application: APPLICATION,
3807
+ connectors: section([{
3808
+ id: S,
3809
+ displayName: T,
3810
+ method: S,
3811
+ type: S,
3812
+ status: S,
3813
+ active: S,
3814
+ position: S,
3815
+ acceptedCountries: [S],
3816
+ acceptedCurrencies: [S],
3817
+ threeDSecureEnabled: S,
3818
+ createdAt: S
3819
+ }]),
3820
+ webhookEndpoints: section([{ id: S, isActive: S, enabledEvents: [S], createdAt: S }]),
3821
+ unsubscribedEvents: section({ windowDays: S, unsubscribed: [{ type: S, count: S, lastEmittedAt: S }] })
3822
+ },
3823
+ get_workspace_settings: { name: T, slug: S, brandColor: S, logoUrl: T, onboardingCompletedAt: S },
3824
+ // What happened and to which record; not which team member did it.
3825
+ get_audit_log: page3({ id: S, action: S, resourceType: S, resourceId: S, createdAt: S }),
3826
+ list_applications: [{ id: S, name: T, slug: S, currency: S, isActive: S }],
3827
+ // Analytics: computed aggregates, listed field by field all the same.
3828
+ get_business_summary: {
3829
+ period: S,
3830
+ currency: S,
3831
+ range: RANGE,
3832
+ orders: section({
3833
+ current: ORDER_PERIOD,
3834
+ previous: ORDER_PERIOD,
3835
+ deltaByCurrency: [{ currency: S, deltaPct: S }]
3836
+ }),
3837
+ subscriptions: section({
3838
+ mrr: { byCurrency: byCurrency({ periodStart: MONEY, deltaPct: S }) },
3839
+ newSubscriptions: S,
3840
+ cancelledSubscriptions: S,
3841
+ churnRate: S,
3842
+ note: T
3843
+ }),
3844
+ receivables: section({ outstandingCount: S, byCurrency: byCurrency({ count: S }) }),
3845
+ quotes: section({
3846
+ sent: COUNT_BY_CURRENCY,
3847
+ accepted: COUNT_BY_CURRENCY,
3848
+ declined: COUNT_BY_CURRENCY,
3849
+ expired: COUNT_BY_CURRENCY
3850
+ })
3851
+ },
3852
+ get_attention_digest: {
3853
+ currency: S,
3854
+ disputes: section({ open: S, byCurrency: byCurrency({ count: S }) }),
3855
+ subscriptionsInDunning: section(S),
3856
+ overdueInvoices: section(COUNT_BY_CURRENCY),
3857
+ unhealthyWebhooks: section([{ endpointId: S, failureRate: S, attempts7d: S }])
3858
+ },
3859
+ get_sales_timeseries: {
3860
+ application: APPLICATION,
3861
+ range: RANGE,
3862
+ currency: S,
3863
+ days: S,
3864
+ note: T,
3865
+ series: [{ date: S, orders: S, paidOrders: S, byCurrency: byCurrency({ paidOrders: S }) }],
3866
+ totalOrders: S,
3867
+ totalPaidOrders: S,
3868
+ byCurrency: byCurrency({ paidOrders: S })
3869
+ },
3870
+ // get_top_products has no entry, so it is not offered over OAuth: it ranks
3871
+ // products by line-item reference id or name, which a buyer can type.
3872
+ get_customer_growth: {
3873
+ application: APPLICATION,
3874
+ range: RANGE,
3875
+ currency: S,
3876
+ note: T,
3877
+ topBy: S,
3878
+ signups: { total: S, series: [{ date: S, signups: S }] },
3879
+ ordersByCustomerType: { newCustomerOrders: S, returningCustomerOrders: S },
3880
+ // The ranking, by id: a top customer's name and email stay behind.
3881
+ topCustomers: [{ customerId: S, orderCount: S, byCurrency: byCurrency({ orderCount: S }) }],
3882
+ totals: { customerCount: S, orderCount: S, byCurrency: byCurrency({ orderCount: S, customerCount: S }) }
3883
+ },
3884
+ get_revenue_breakdown: {
3885
+ application: APPLICATION,
3886
+ range: RANGE,
3887
+ currency: S,
3888
+ dimension: S,
3889
+ note: T,
3890
+ rows: [{ key: S, orderCount: S, byCurrency: byCurrency({ orderCount: S }) }],
3891
+ totals: { orderCount: S, byCurrency: byCurrency({ orderCount: S }) }
3892
+ },
3893
+ get_funnel_conversion: {
3894
+ application: APPLICATION,
3895
+ range: RANGE,
3896
+ note: T,
3897
+ conversionRate: S,
3898
+ stages: [{ name: S, count: S }],
3899
+ dropOff: [{ from: S, to: S, ratePct: S }]
3900
+ },
3901
+ get_subscription_movement: {
3902
+ application: APPLICATION,
3903
+ range: RANGE,
3904
+ currency: S,
3905
+ note: T,
3906
+ series: [{ date: S, newSubscriptions: S, churnedSubscriptions: S, byCurrency: byCurrency() }],
3907
+ totals: { newSubscriptions: S, churnedSubscriptions: S, byCurrency: byCurrency() }
3614
3908
  },
3615
- forEach: (fn, thisArg) => UNCONFIRMED.forEach((v) => fn.call(thisArg, v, v, UNCONFIRMED_EXPONENT_CODES)),
3616
- keys: () => UNCONFIRMED.keys(),
3617
- values: () => UNCONFIRMED.values(),
3618
- entries: () => UNCONFIRMED.entries(),
3619
- [Symbol.iterator]: () => UNCONFIRMED.values()
3620
- });
3621
- function currencyRow(code) {
3622
- return BY_CODE.get(code);
3623
- }
3624
- function isKnownCurrency(code) {
3625
- return BY_CODE.has(code);
3626
- }
3627
- function minorUnitsOf(code) {
3628
- const row = BY_CODE.get(code);
3629
- if (row === void 0) throw new UnknownCurrencyError(code);
3630
- return row.minorUnits;
3631
- }
3632
- function isEnableableCurrency(code) {
3633
- const row = BY_CODE.get(code);
3634
- return row !== void 0 && row.minorUnits !== 4 && !row.fund && !UNCONFIRMED.has(code);
3635
- }
3636
- var NBSP = "\xA0";
3637
- function normalizeCode(code) {
3638
- return typeof code === "string" ? code.trim().toUpperCase() : "";
3639
- }
3640
- function displayExponent(normalizedCode) {
3641
- return currencyRow(normalizedCode)?.minorUnits ?? 2;
3642
- }
3643
- function roundHalfAwayFromZero(n) {
3644
- return n < 0 ? -Math.round(-n) : Math.round(n);
3645
- }
3646
- function decimalDigits(abs, exponent, grouped) {
3647
- const raw = Number.isSafeInteger(abs) ? String(abs) : BigInt(abs).toString();
3648
- const padded = raw.padStart(exponent + 1, "0");
3649
- const cut = padded.length - exponent;
3650
- let integer = padded.slice(0, cut);
3651
- if (grouped) integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
3652
- return exponent === 0 ? integer : `${integer}.${padded.slice(cut)}`;
3653
- }
3654
- function formatMoney(minor, code, opts) {
3655
- if (typeof minor !== "number" || !Number.isFinite(minor)) return "\u2014";
3656
- const c = normalizeCode(code);
3657
- const row = currencyRow(c);
3658
- const n = roundHalfAwayFromZero(minor);
3659
- const sign = n < 0 ? "-" : "";
3660
- const digits = decimalDigits(Math.abs(n), row?.minorUnits ?? 2, true);
3661
- if (c === "") return sign + digits;
3662
- if (row === void 0) return `${sign}${digits}${NBSP}${c}`;
3663
- const separator = new RegExp("\\p{Sc}$", "u").test(row.symbol) ? "" : NBSP;
3664
- const text = `${sign}${row.symbol}${separator}${digits}`;
3665
- return opts?.display === "symbol-code" && row.symbol !== c ? `${text}${NBSP}${c}` : text;
3666
- }
3667
- function currencySymbol(code) {
3668
- const c = normalizeCode(code);
3669
- return currencyRow(c)?.symbol ?? c;
3909
+ get_discount_performance: {
3910
+ application: APPLICATION,
3911
+ range: RANGE,
3912
+ currency: S,
3913
+ note: T,
3914
+ rows: [{
3915
+ discountId: S,
3916
+ code: T,
3917
+ redemptions: S,
3918
+ byCurrency: byCurrency({ redemptions: S, discountGiven: MONEY })
3919
+ }],
3920
+ totals: { redemptions: S, byCurrency: byCurrency({ redemptions: S, discountGiven: MONEY }) }
3921
+ }
3922
+ };
3923
+
3924
+ // src/server.ts
3925
+ var VERSION = true ? "0.5.0" : "0.0.0-dev";
3926
+ function registerableActions(policy) {
3927
+ const isProduction = policy.identity.environment.providerEnvironment === "production";
3928
+ return actionsForChannel("mcp").filter((action) => {
3929
+ if (!HANDLERS[action.id]) return false;
3930
+ if (action.credentialScoped && policy.allowCredentialScoped === false) return false;
3931
+ if (!canRunAction(policy.identity.scopes, action)) return false;
3932
+ if (action.kind === "read") return true;
3933
+ if (action.sandboxOnly) return !isProduction && (policy.allowSandboxWrites ?? true);
3934
+ if (!policy.allowWrites) return false;
3935
+ return !isProduction || policy.allowLiveWrites;
3936
+ });
3670
3937
  }
3671
- function toDecimalString(minor, code) {
3672
- if (typeof minor !== "number" || !Number.isFinite(minor)) return "";
3673
- const n = roundHalfAwayFromZero(minor);
3674
- const sign = n < 0 ? "-" : "";
3675
- return sign + decimalDigits(Math.abs(n), displayExponent(normalizeCode(code)), false);
3938
+ function buildInstructions(identity, actions, policy) {
3939
+ const isProduction = identity.environment.providerEnvironment === "production";
3940
+ const where = [
3941
+ identity.workspace?.name ?? identity.workspace?.slug ?? "unknown workspace",
3942
+ identity.application?.name ?? identity.application?.slug ?? null
3943
+ ].filter(Boolean).join(" / ");
3944
+ const liveWrites = actions.filter((a) => a.kind === "write" && !a.sandboxOnly);
3945
+ const sandboxWrites = actions.filter((a) => a.kind === "write" && a.sandboxOnly);
3946
+ const lines = [
3947
+ `Throttle MCP ${VERSION}. Connected to ${where}, environment "${identity.environment.slug}" (${isProduction ? "PRODUCTION \u2014 live data" : "non-production \u2014 not live data"}).`,
3948
+ "",
3949
+ "Conventions:",
3950
+ "- The workspace and environment are fixed for this session and cannot be switched from inside a tool call. Call whoami if you need to state where you are.",
3951
+ '- The application can vary per call: pass "applicationId" on a read or analytics tool to reach a different application in this workspace, and call list_applications to see which ones this connection can reach. Omitting applicationId uses the application this connection was authorized for.',
3952
+ "- Every analytics result covers exactly ONE application and names it in `application`. Say which application a figure describes. If the user asks about their business as a whole and this connection reaches more than one application, do not answer from the default alone \u2014 call list_applications, then query each and report each application's figures separately, per currency, or ask which application they mean; never add amounts across applications or currencies.",
3953
+ '- List tools return { data, pagination }. When pagination.hasMore is true, pass pagination.cursor back as "cursor" rather than raising "limit".',
3954
+ "- Money values are `{ amount, currency, display }`: `amount` is integer minor units of `currency` (its ISO 4217 exponent), and `display` is the formatted string to show. Totals come back per currency as arrays; never add amounts in different currencies, and never convert them.",
3955
+ "- Throttle rejects snake_case on public request bodies. Before writing integration code, confirm shapes with describe_endpoint and check bodies with validate_payload instead of guessing field names.",
3956
+ "- API errors come back as text with a stable code. On insufficient_scopes, tell the user which scope to add \u2014 do not retry.",
3957
+ "- Analytics results may mark a section `omitted`. That means UNKNOWN, never zero. When `grantable` is false the data cannot be read over this connection at all \u2014 say so rather than reporting an absence."
3958
+ ];
3959
+ if (liveWrites.length === 0) {
3960
+ lines.push(
3961
+ `- This session is READ-ONLY for real data${policy.allowWrites ? " (no write tools are available to this credential)" : " \u2014 writes were not enabled"}. Say so plainly if asked to change something.`
3962
+ );
3963
+ if (sandboxWrites.length > 0) {
3964
+ lines.push(
3965
+ `- ${sandboxWrites.map((a) => a.id).join(", ")} may create data, but only in this non-production environment.`
3966
+ );
3967
+ }
3968
+ } else {
3969
+ lines.push(
3970
+ `- Write tools are enabled (${liveWrites.map((a) => a.id).join(", ")}). They are irreversible and some are buyer-visible. Confirm with the user before calling one.`
3971
+ );
3972
+ }
3973
+ return lines.join("\n");
3676
3974
  }
3677
- function moneyValue(amount, currency) {
3678
- return { amount, currency: normalizeCode(currency), display: formatMoney(amount, currency) };
3975
+ function declareSecuritySchemes(server, actions) {
3976
+ const inner = server.server;
3977
+ const handlers = inner._requestHandlers;
3978
+ const original = handlers?.get("tools/list");
3979
+ if (!original) return;
3980
+ const schemes = new Map(
3981
+ actions.map((a) => [
3982
+ a.id,
3983
+ [{
3984
+ type: "oauth2",
3985
+ scopes: [.../* @__PURE__ */ new Set([...a.scopes, ...a.sectionScopes ?? []])].filter((scope) => validateScopesForOAuth([scope]).ok)
3986
+ }]
3987
+ ])
3988
+ );
3989
+ inner.setRequestHandler(ListToolsRequestSchema, async (request, extra) => {
3990
+ const result = await original(request, extra);
3991
+ return {
3992
+ ...result,
3993
+ tools: result.tools.map((tool) => ({ ...tool, securitySchemes: schemes.get(tool.name) ?? [{ type: "oauth2", scopes: [] }] }))
3994
+ };
3995
+ });
3679
3996
  }
3680
- function toMinorUnits(negative, integer, fraction, exponent) {
3681
- if (fraction.length > exponent) return null;
3682
- const n = Number(integer + fraction.padEnd(exponent, "0"));
3683
- if (!Number.isSafeInteger(n)) return null;
3684
- return negative && n !== 0 ? -n : n;
3997
+ function createServer(options) {
3998
+ const redactPii = options.identity.type === "oauth_token" && !hasScope(options.identity.scopes, "customer_pii:read");
3999
+ const actions = registerableActions(options).filter((a) => !redactPii || OAUTH_PROJECTIONS[a.id] !== void 0);
4000
+ const server = new McpServer(
4001
+ { name: "throttle", version: VERSION },
4002
+ { instructions: buildInstructions(options.identity, actions, options) }
4003
+ );
4004
+ const ctx = {
4005
+ client: options.client,
4006
+ identity: options.identity,
4007
+ contract: options.contract,
4008
+ docs: options.docs
4009
+ };
4010
+ for (const action of actions) {
4011
+ const handler = HANDLERS[action.id];
4012
+ server.registerTool(
4013
+ action.id,
4014
+ {
4015
+ title: action.title,
4016
+ description: describeForModel(action),
4017
+ inputSchema: fieldsToZodShape(action.input),
4018
+ // Every hint is an explicit boolean: directory reviews (OpenAI's in
4019
+ // particular) read a missing value as "unknown", not as false.
4020
+ annotations: {
4021
+ title: action.title,
4022
+ readOnlyHint: action.kind === "read",
4023
+ destructiveHint: action.kind === "write" && Boolean(action.destructive),
4024
+ idempotentHint: Boolean(action.idempotent),
4025
+ // Every tool is bounded to the connected workspace; none reaches the
4026
+ // public internet or an open-ended set of external entities.
4027
+ openWorldHint: false
4028
+ }
4029
+ },
4030
+ async (args) => {
4031
+ try {
4032
+ if (redactPii && action.id === "search_customers" && typeof args?.q === "string" && args.q.trim() !== "") {
4033
+ return {
4034
+ content: [{ type: "text", text: "Customer text search is not available over this connection, because names, emails, phone numbers and external ids are withheld. List customers by creation date (createdAfter/createdBefore), or open one by its Throttle id from an order, quote or subscription." }],
4035
+ isError: true
4036
+ };
4037
+ }
4038
+ const result = decorateMoney(action.id, stripRawProcessorData(await handler(ctx, args ?? {}))).value;
4039
+ const shown = redactPii ? redactShopperPii(project(result, OAUTH_PROJECTIONS[action.id])) : result;
4040
+ return { content: [{ type: "text", text: formatResult(shown) }] };
4041
+ } catch (error) {
4042
+ return {
4043
+ content: [{ type: "text", text: formatError(error) }],
4044
+ isError: true,
4045
+ ...options.authChallenge && isCredentialRejection(error) ? {
4046
+ _meta: {
4047
+ "mcp/www_authenticate": [
4048
+ `${options.authChallenge}, error="invalid_token", error_description="The connected credential was rejected. Sign in again to continue."`
4049
+ ]
4050
+ }
4051
+ } : {}
4052
+ };
4053
+ }
4054
+ }
4055
+ );
4056
+ }
4057
+ if (options.authChallenge) declareSecuritySchemes(server, actions);
4058
+ return server;
3685
4059
  }
3686
- function toMinor(decimal, code) {
3687
- const text = typeof decimal === "number" ? String(decimal) : typeof decimal === "string" ? decimal : "";
3688
- const m = /^(-?)(\d+)(?:\.(\d+))?$/.exec(text);
3689
- if (m === null) return null;
3690
- return toMinorUnits(m[1] === "-", m[2], m[3] ?? "", displayExponent(normalizeCode(code)));
4060
+ function isCredentialRejection(error) {
4061
+ return error?.statusCode === 401;
3691
4062
  }
3692
- var SPACE = /^[ \u00A0]/;
3693
- var TRAILING_SPACE = /[ \u00A0]$/;
3694
- var AMOUNT = /^([1-9]\d{0,2}(?:,\d{3})+|\d+)(?:\.(\d+))?$/;
3695
- function withoutMarker(text, markers) {
3696
- for (const marker of markers) {
3697
- if (text.startsWith(marker)) return text.slice(marker.length).replace(SPACE, "");
3698
- }
3699
- for (const marker of markers) {
3700
- if (text.endsWith(marker)) return text.slice(0, text.length - marker.length).replace(TRAILING_SPACE, "");
4063
+ function describeForModel(action) {
4064
+ const parts = [action.description];
4065
+ if (action.guardrails && action.guardrails.length > 0) {
4066
+ parts.push(`Constraints: ${action.guardrails.join(" ")}`);
3701
4067
  }
3702
- return text;
4068
+ return parts.join(" ");
3703
4069
  }
3704
- function parseMoney(text, code) {
3705
- if (typeof text !== "string") return null;
3706
- const c = normalizeCode(code);
3707
- let rest = text.trim();
3708
- const negative = rest.startsWith("-");
3709
- if (negative) rest = rest.slice(1);
3710
- if (c !== "") {
3711
- const symbol = currencySymbol(c);
3712
- rest = withoutMarker(rest, symbol === c ? [c] : [symbol, c]);
4070
+
4071
+ // src/indexes.ts
4072
+ import { readFileSync } from "fs";
4073
+ function loadIndex(file, empty, label) {
4074
+ try {
4075
+ return JSON.parse(readFileSync(new URL(`./${file}`, import.meta.url), "utf8"));
4076
+ } catch {
4077
+ process.stderr.write(
4078
+ `throttle-mcp: ${label} index missing (${file}); that tool will return no results. Run "pnpm --filter @usethrottle/mcp build:indexes".
4079
+ `
4080
+ );
4081
+ return empty;
3713
4082
  }
3714
- const m = AMOUNT.exec(rest);
3715
- if (m === null) return null;
3716
- return toMinorUnits(negative, m[1].replace(/,/g, ""), m[2] ?? "", displayExponent(c));
4083
+ }
4084
+ function loadDocsIndex() {
4085
+ return loadIndex("docs-index.json", { generatedAt: "", entries: [] }, "docs");
4086
+ }
4087
+ function loadContractIndex() {
4088
+ return loadIndex("contract-index.json", { generatedAt: "", operations: [] }, "contract");
3717
4089
  }
3718
4090
  export {
3719
4091
  CURRENCIES,