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