@ar-agents/mercadopago 0.2.0 → 0.4.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/index.js CHANGED
@@ -1,6 +1,6 @@
1
+ import { createHmac, timingSafeEqual, createHash } from 'crypto';
1
2
  import { tool } from 'ai';
2
3
  import { z } from 'zod';
3
- import { createHmac, timingSafeEqual } from 'crypto';
4
4
 
5
5
  // src/errors.ts
6
6
  var MercadoPagoError = class extends Error {
@@ -98,12 +98,38 @@ var MercadoPagoRateLimitError = class extends MercadoPagoError {
98
98
  }
99
99
  retryAfterSeconds;
100
100
  };
101
+ var MercadoPagoOverloadedError = class extends MercadoPagoError {
102
+ constructor(endpoint, status) {
103
+ super(
104
+ `Mercado Pago appears overloaded \u2014 returned a non-JSON ${status} response for ${endpoint}. Wait a few seconds and retry.`,
105
+ status,
106
+ endpoint
107
+ );
108
+ this.name = "MercadoPagoOverloadedError";
109
+ }
110
+ };
111
+ var MercadoPagoTimeoutError = class extends MercadoPagoError {
112
+ constructor(endpoint, timeoutMs) {
113
+ super(
114
+ `Mercado Pago request timed out after ${timeoutMs}ms on ${endpoint}. Increase requestTimeoutMs or check connectivity.`,
115
+ 0,
116
+ endpoint
117
+ );
118
+ this.timeoutMs = timeoutMs;
119
+ this.name = "MercadoPagoTimeoutError";
120
+ }
121
+ timeoutMs;
122
+ };
101
123
  function classifyError(status, endpoint, body, context) {
102
124
  const bodyText = typeof body === "string" ? body : body && typeof body === "object" ? JSON.stringify(body) : "";
103
125
  const lower = bodyText.toLowerCase();
104
126
  if (status === 401) return new MercadoPagoAuthError(endpoint, body);
105
127
  if (status === 429) {
106
- return new MercadoPagoRateLimitError(endpoint, null, body);
128
+ let retryAfter = null;
129
+ const obj = body;
130
+ if (obj?.retry_after) retryAfter = Number(obj.retry_after);
131
+ else if (obj?.["retry-after"]) retryAfter = Number(obj["retry-after"]);
132
+ return new MercadoPagoRateLimitError(endpoint, retryAfter, body);
107
133
  }
108
134
  if (status === 400) {
109
135
  if (lower.includes("back_url") && lower.includes("not a valid url")) {
@@ -129,10 +155,16 @@ function classifyError(status, endpoint, body, context) {
129
155
 
130
156
  // src/client.ts
131
157
  var DEFAULT_BASE_URL = "https://api.mercadopago.com";
158
+ function sleep(ms) {
159
+ return new Promise((resolve) => setTimeout(resolve, ms));
160
+ }
132
161
  var MercadoPagoClient = class {
133
162
  accessToken;
134
163
  baseUrl;
135
164
  fetchImpl;
165
+ requestTimeoutMs;
166
+ maxRetries;
167
+ onCall;
136
168
  constructor(options) {
137
169
  if (!options.accessToken) {
138
170
  throw new Error(
@@ -142,6 +174,9 @@ var MercadoPagoClient = class {
142
174
  this.accessToken = options.accessToken;
143
175
  this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
144
176
  this.fetchImpl = options.fetch;
177
+ this.requestTimeoutMs = options.requestTimeoutMs ?? 3e4;
178
+ this.maxRetries = Math.max(0, options.maxRetries ?? 1);
179
+ this.onCall = options.onCall;
145
180
  }
146
181
  async request(method, path, body, options) {
147
182
  const headers = {
@@ -151,10 +186,6 @@ var MercadoPagoClient = class {
151
186
  if (options?.idempotencyKey) {
152
187
  headers["X-Idempotency-Key"] = options.idempotencyKey;
153
188
  }
154
- const init = { method, headers };
155
- if (body !== void 0) {
156
- init.body = JSON.stringify(body);
157
- }
158
189
  let url = `${this.baseUrl}${path}`;
159
190
  if (options?.query) {
160
191
  const search = new URLSearchParams();
@@ -167,20 +198,95 @@ var MercadoPagoClient = class {
167
198
  if (qs) url += `?${qs}`;
168
199
  }
169
200
  const fetchFn = this.fetchImpl ?? globalThis.fetch;
170
- const res = await fetchFn(url, init);
171
- if (!res.ok) {
172
- let parsed;
173
- const text2 = await res.text();
201
+ const t0 = Date.now();
202
+ let attempt = 0;
203
+ let lastError;
204
+ let lastStatus = null;
205
+ while (attempt <= this.maxRetries) {
206
+ const controller = new AbortController();
207
+ const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs);
208
+ const init = { method, headers, signal: controller.signal };
209
+ if (body !== void 0) init.body = JSON.stringify(body);
174
210
  try {
175
- parsed = JSON.parse(text2);
176
- } catch {
177
- parsed = text2;
211
+ const res = await fetchFn(url, init);
212
+ clearTimeout(timer);
213
+ lastStatus = res.status;
214
+ if (res.ok) {
215
+ const text2 = await res.text();
216
+ this.onCall?.({
217
+ method,
218
+ path,
219
+ durationMs: Date.now() - t0,
220
+ httpStatus: res.status,
221
+ retried: attempt,
222
+ success: true
223
+ });
224
+ if (!text2) return void 0;
225
+ return JSON.parse(text2);
226
+ }
227
+ const isRetryable = res.status >= 500 || res.status === 429;
228
+ if (isRetryable && attempt < this.maxRetries) {
229
+ const retryAfter = res.headers.get("retry-after");
230
+ const waitMs = retryAfter ? Number(retryAfter) * 1e3 : 250 * Math.pow(2, attempt);
231
+ attempt++;
232
+ await sleep(waitMs);
233
+ continue;
234
+ }
235
+ const contentType = res.headers.get("content-type") ?? "";
236
+ if (res.status >= 500 && !contentType.includes("application/json")) {
237
+ this.onCall?.({
238
+ method,
239
+ path,
240
+ durationMs: Date.now() - t0,
241
+ httpStatus: res.status,
242
+ retried: attempt,
243
+ success: false
244
+ });
245
+ throw new MercadoPagoOverloadedError(path, res.status);
246
+ }
247
+ let parsed;
248
+ const text = await res.text();
249
+ try {
250
+ parsed = JSON.parse(text);
251
+ } catch {
252
+ parsed = text;
253
+ }
254
+ const err = classifyError(res.status, path, parsed, options?.classifyContext);
255
+ this.onCall?.({
256
+ method,
257
+ path,
258
+ durationMs: Date.now() - t0,
259
+ httpStatus: res.status,
260
+ retried: attempt,
261
+ success: false
262
+ });
263
+ throw err;
264
+ } catch (err) {
265
+ clearTimeout(timer);
266
+ if (err instanceof MercadoPagoError) throw err;
267
+ const isAbort = err instanceof Error && err.name === "AbortError";
268
+ const isNetwork = !lastStatus && !isAbort;
269
+ if ((isNetwork || isAbort) && attempt < this.maxRetries) {
270
+ lastError = err;
271
+ attempt++;
272
+ await sleep(250 * Math.pow(2, attempt - 1));
273
+ continue;
274
+ }
275
+ this.onCall?.({
276
+ method,
277
+ path,
278
+ durationMs: Date.now() - t0,
279
+ httpStatus: lastStatus,
280
+ retried: attempt,
281
+ success: false
282
+ });
283
+ if (isAbort) {
284
+ throw new MercadoPagoTimeoutError(path, this.requestTimeoutMs);
285
+ }
286
+ throw err;
178
287
  }
179
- throw classifyError(res.status, path, parsed, options?.classifyContext);
180
288
  }
181
- const text = await res.text();
182
- if (!text) return void 0;
183
- return JSON.parse(text);
289
+ throw lastError ?? new Error(`MercadoPago request failed after ${this.maxRetries} retries`);
184
290
  }
185
291
  // ───────────────────────────────────────────────────────────────────────────
186
292
  // Subscriptions (Preapprovals) — v0.1 surface, kept stable
@@ -498,7 +604,301 @@ var MercadoPagoClient = class {
498
604
  async getMe() {
499
605
  return this.request("GET", "/users/me");
500
606
  }
607
+ // ───────────────────────────────────────────────────────────────────────────
608
+ // Card tokens (server-side, for saved-card retokenization)
609
+ // ───────────────────────────────────────────────────────────────────────────
610
+ /**
611
+ * Create a single-use card token from a saved card. This is the server-side
612
+ * retokenization path (PCI-safe because the card data lives in MP's vault,
613
+ * we only pass the saved card_id + customer_id + the user-supplied CVV).
614
+ *
615
+ * Tokens expire in 7 days but typically burn on first use. AR currently
616
+ * REQUIRES CVV on every charge (MP doesn't store it); skipping CVV requires
617
+ * a private MP product enablement, not a public API.
618
+ */
619
+ async createCardToken(params) {
620
+ return this.request("POST", "/v1/card_tokens", {
621
+ card_id: params.cardId,
622
+ customer_id: params.customerId,
623
+ security_code: params.securityCode
624
+ });
625
+ }
626
+ /**
627
+ * High-level helper: charge a saved card in 3 steps.
628
+ * 1. Mint a card token from {customer_id, card_id, security_code}
629
+ * 2. Lookup card to fill payment_method_id (avoids agent guessing)
630
+ * 3. Create the payment with the token + idempotency key
631
+ *
632
+ * Returns the resulting Payment. Uses deterministic idempotency from
633
+ * (card_id, amount, externalReference) so retries dedupe on MP's side.
634
+ */
635
+ async chargeSavedCard(params) {
636
+ const token = await this.createCardToken({
637
+ cardId: params.cardId,
638
+ customerId: params.customerId,
639
+ securityCode: params.securityCode
640
+ });
641
+ const card = await this.getCustomerCard(params.customerId, params.cardId);
642
+ const paymentMethodId = card.payment_method?.id;
643
+ if (!paymentMethodId) {
644
+ throw new MercadoPagoError(
645
+ `Saved card ${params.cardId} has no payment_method.id. Cannot charge.`,
646
+ 0,
647
+ `/v1/customers/${params.customerId}/cards/${params.cardId}`
648
+ );
649
+ }
650
+ const body = {
651
+ transaction_amount: params.amount,
652
+ token: token.id,
653
+ payment_method_id: paymentMethodId,
654
+ installments: params.installments ?? 1,
655
+ description: params.description,
656
+ payer: { type: "customer", id: params.customerId }
657
+ };
658
+ if (params.externalReference) body.external_reference = params.externalReference;
659
+ if (params.statementDescriptor) body.statement_descriptor = params.statementDescriptor;
660
+ return this.request("POST", "/v1/payments", body, {
661
+ ...params.idempotencyKey !== void 0 ? { idempotencyKey: params.idempotencyKey } : {},
662
+ classifyContext: { customerId: params.customerId }
663
+ });
664
+ }
665
+ // ───────────────────────────────────────────────────────────────────────────
666
+ // QR (in-store dynamic) — Section 2 of v0.3 spec
667
+ // ───────────────────────────────────────────────────────────────────────────
668
+ /**
669
+ * Create a dynamic in-store QR order. Returns `qr_data` (EMVCo TLV string)
670
+ * + `in_store_order_id`. The buyer scans the QR with any AR wallet (Modo,
671
+ * BNA+, Cuenta DNI, Naranja X, etc. — interop is mandated by Transferencias
672
+ * 3.0). On payment, MP fires `point_integration_wh` then `payment` topics.
673
+ *
674
+ * Requires a pre-configured POS (`external_pos_id` from MP dashboard or
675
+ * `POST /pos`). The seller's `user_id` is auto-fetched from `/users/me`.
676
+ *
677
+ * The lib does NOT render the QR image — pass `qr_data` to a QR renderer
678
+ * (e.g., `qrcode` package) to get a data URL. The agent tool layer wraps
679
+ * this and returns both raw + data URL.
680
+ */
681
+ async createQrPayment(userId, params) {
682
+ const body = {
683
+ total_amount: params.totalAmount,
684
+ title: params.title
685
+ };
686
+ if (params.description) body.description = params.description;
687
+ if (params.notificationUrl) body.notification_url = params.notificationUrl;
688
+ if (params.externalReference) body.external_reference = params.externalReference;
689
+ if (params.expirationDate) body.expiration_date = params.expirationDate;
690
+ body.items = params.items ?? [
691
+ {
692
+ title: params.title,
693
+ quantity: 1,
694
+ unit_price: params.totalAmount,
695
+ unit_measure: "unit",
696
+ total_amount: params.totalAmount
697
+ }
698
+ ];
699
+ return this.request(
700
+ "PUT",
701
+ `/instore/orders/qr/seller/collectors/${encodeURIComponent(userId)}/pos/${encodeURIComponent(params.externalPosId)}/qrs`,
702
+ body
703
+ );
704
+ }
705
+ /**
706
+ * Cancel a pending QR order on a POS. Necessary if the buyer never scans
707
+ * — otherwise the next `createQrPayment` on the same POS returns 409.
708
+ */
709
+ async cancelQrPayment(userId, externalPosId) {
710
+ await this.request(
711
+ "DELETE",
712
+ `/instore/orders/qr/seller/collectors/${encodeURIComponent(userId)}/pos/${encodeURIComponent(externalPosId)}/qrs`
713
+ );
714
+ }
715
+ // ───────────────────────────────────────────────────────────────────────────
716
+ // Subscription Plans (preapproval_plan — reusable plans, v0.4)
717
+ // ───────────────────────────────────────────────────────────────────────────
718
+ /**
719
+ * Create a reusable subscription plan. Customers later subscribe to it via
720
+ * `subscribeToPlan` (which creates a preapproval pointing at the plan).
721
+ *
722
+ * Use this when you have fixed tiers (Básico/Pro/Enterprise). For custom
723
+ * per-customer amounts, skip plans and use `createPreapproval` directly.
724
+ */
725
+ async createSubscriptionPlan(params) {
726
+ const body = {
727
+ reason: params.reason,
728
+ back_url: params.backUrl,
729
+ auto_recurring: {
730
+ frequency: params.frequency,
731
+ frequency_type: params.frequencyType,
732
+ transaction_amount: params.amount,
733
+ currency_id: params.currency,
734
+ ...params.freeTrialFrequency !== void 0 && params.freeTrialFrequencyType !== void 0 ? {
735
+ free_trial: {
736
+ frequency: params.freeTrialFrequency,
737
+ frequency_type: params.freeTrialFrequencyType
738
+ }
739
+ } : {}
740
+ }
741
+ };
742
+ if (params.externalReference) body.external_reference = params.externalReference;
743
+ return this.request("POST", "/preapproval_plan", body);
744
+ }
745
+ async getSubscriptionPlan(id) {
746
+ return this.request("GET", `/preapproval_plan/${id}`);
747
+ }
748
+ async listSubscriptionPlans(params = {}) {
749
+ const query = {
750
+ limit: params.limit ?? 30,
751
+ offset: params.offset ?? 0
752
+ };
753
+ if (params.status) query["status"] = params.status;
754
+ return this.request("GET", "/preapproval_plan/search", void 0, { query });
755
+ }
756
+ async updateSubscriptionPlan(id, patch) {
757
+ const body = {};
758
+ if (patch.reason !== void 0) body.reason = patch.reason;
759
+ if (patch.status !== void 0) body.status = patch.status;
760
+ if (patch.backUrl !== void 0) body.back_url = patch.backUrl;
761
+ if (patch.amount !== void 0) {
762
+ body.auto_recurring = { transaction_amount: patch.amount };
763
+ }
764
+ return this.request("PUT", `/preapproval_plan/${id}`, body);
765
+ }
766
+ /**
767
+ * Subscribe a customer to an existing plan. Returns a Preapproval with
768
+ * `init_point` URL where the buyer completes the first payment.
769
+ */
770
+ async subscribeToPlan(params) {
771
+ const body = {
772
+ preapproval_plan_id: params.planId,
773
+ payer_email: params.payerEmail
774
+ };
775
+ if (params.cardTokenId) body.card_token_id = params.cardTokenId;
776
+ if (params.externalReference) body.external_reference = params.externalReference;
777
+ return this.request("POST", "/preapproval", body, {
778
+ classifyContext: { payerEmail: params.payerEmail }
779
+ });
780
+ }
781
+ /**
782
+ * List the auto-charge attempts (authorized_payments) under a preapproval.
783
+ * Useful for "show me the cobros of the last 6 months for this client".
784
+ */
785
+ async listSubscriptionPayments(preapprovalId, params = {}) {
786
+ const query = {
787
+ preapproval_id: preapprovalId,
788
+ limit: params.limit ?? 30,
789
+ offset: params.offset ?? 0
790
+ };
791
+ return this.request(
792
+ "GET",
793
+ `/authorized_payments/search`,
794
+ void 0,
795
+ { query, classifyContext: { preapprovalId } }
796
+ );
797
+ }
798
+ // ───────────────────────────────────────────────────────────────────────────
799
+ // Stores + POS (for QR payments self-serve setup, v0.4)
800
+ // ───────────────────────────────────────────────────────────────────────────
801
+ /** Create a store for the seller. POSes (for QR) live under stores. */
802
+ async createStore(userId, params) {
803
+ const body = {
804
+ name: params.name,
805
+ external_id: params.externalId
806
+ };
807
+ if (params.location) {
808
+ body.location = {
809
+ ...params.location.addressLine ? { address_line: params.location.addressLine } : {},
810
+ ...params.location.cityName ? { city_name: params.location.cityName } : {},
811
+ ...params.location.stateName ? { state_name: params.location.stateName } : {},
812
+ ...params.location.countryId ? { country_id: params.location.countryId } : {},
813
+ ...params.location.latitude !== void 0 ? { latitude: params.location.latitude } : {},
814
+ ...params.location.longitude !== void 0 ? { longitude: params.location.longitude } : {}
815
+ };
816
+ }
817
+ return this.request("POST", `/users/${encodeURIComponent(userId)}/stores`, body);
818
+ }
819
+ async listStores(userId, params = {}) {
820
+ const query = {
821
+ limit: params.limit ?? 50,
822
+ offset: params.offset ?? 0
823
+ };
824
+ return this.request("GET", `/users/${encodeURIComponent(userId)}/stores/search`, void 0, { query });
825
+ }
826
+ /** Create a POS under a store. The POS's `external_id` is what `createQrPayment` uses. */
827
+ async createPos(params) {
828
+ const body = {
829
+ name: params.name,
830
+ external_id: params.externalId,
831
+ store_id: params.storeId,
832
+ category: params.category ?? 621102
833
+ // "Other Food and Beverage Services" — generic default
834
+ };
835
+ if (params.fixedAmount !== void 0) body.fixed_amount = params.fixedAmount;
836
+ return this.request("POST", "/pos", body);
837
+ }
838
+ async listPos(params = {}) {
839
+ const query = {
840
+ limit: params.limit ?? 50,
841
+ offset: params.offset ?? 0
842
+ };
843
+ if (params.storeId !== void 0) query["store_id"] = String(params.storeId);
844
+ return this.request("GET", "/pos", void 0, { query });
845
+ }
846
+ // ───────────────────────────────────────────────────────────────────────────
847
+ // Disputes (read-only, v0.4)
848
+ // ───────────────────────────────────────────────────────────────────────────
849
+ async listPaymentDisputes(paymentId) {
850
+ return this.request("GET", `/v1/payments/${paymentId}/disputes`, void 0, {
851
+ classifyContext: { paymentId }
852
+ });
853
+ }
854
+ async getDispute(paymentId, disputeId) {
855
+ return this.request(
856
+ "GET",
857
+ `/v1/payments/${paymentId}/disputes/${disputeId}`,
858
+ void 0,
859
+ { classifyContext: { paymentId } }
860
+ );
861
+ }
862
+ // ───────────────────────────────────────────────────────────────────────────
863
+ // Identification Types + Issuers (lookup helpers, v0.4)
864
+ // ───────────────────────────────────────────────────────────────────────────
865
+ /** List valid identification types for the seller's site. AR returns DNI/CI/LE/LC/Otro/Pasaporte/CUIT/CUIL. */
866
+ async listIdentificationTypes() {
867
+ return this.request("GET", "/v1/identification_types");
868
+ }
869
+ /** List card issuers for a payment method. Useful with `bin` for installments. */
870
+ async listIssuers(params) {
871
+ const query = {
872
+ payment_method_id: params.paymentMethodId
873
+ };
874
+ if (params.bin) query["bin"] = params.bin;
875
+ return this.request("GET", "/v1/payment_methods/card_issuers", void 0, { query });
876
+ }
877
+ // ───────────────────────────────────────────────────────────────────────────
878
+ // Webhooks management (v0.4)
879
+ // ───────────────────────────────────────────────────────────────────────────
880
+ /** List configured webhook subscriptions. */
881
+ async listWebhooks() {
882
+ return this.request("GET", "/v1/webhooks");
883
+ }
884
+ /** Create a webhook subscription for a topic. */
885
+ async createWebhook(params) {
886
+ return this.request("POST", "/v1/webhooks", {
887
+ url: params.url,
888
+ topic: params.topic
889
+ });
890
+ }
891
+ async updateWebhook(id, patch) {
892
+ return this.request("PUT", `/v1/webhooks/${id}`, patch);
893
+ }
894
+ async deleteWebhook(id) {
895
+ await this.request("DELETE", `/v1/webhooks/${id}`);
896
+ }
501
897
  };
898
+ function deterministicIdempotencyKey(...parts) {
899
+ const payload = parts.filter((p) => p !== void 0 && p !== null).map(String).join("|");
900
+ return createHash("sha256").update(payload).digest("hex").slice(0, 32);
901
+ }
502
902
  var DEFAULT_DESCRIPTIONS = {
503
903
  // ── Subscriptions ────────────────────────────────────────────────────────
504
904
  create_subscription: "Create a Mercado Pago recurring subscription. Returns an init_point URL where the customer must complete the FIRST payment with their card and CVV (this is a hard MP requirement; agents cannot bypass it). After they pay, MP will auto-charge at the configured frequency without further intervention.",
@@ -527,7 +927,34 @@ var DEFAULT_DESCRIPTIONS = {
527
927
  list_payment_methods: "List all payment methods enabled for the seller's MP account (visa, master, naranja, naranja_x, cabal, account_money, rapipago, pagofacil, etc.). Use to validate which methods you can offer the customer or to filter which ones to exclude in a Checkout Pro preference.",
528
928
  calculate_installments: "Calculate cuotas (installments) options for a given amount. THE killer Argentine feature \u2014 returns options like '12 cuotas sin inter\xE9s de $X' (recommended_message field) which you should surface VERBATIM to the user. Optionally pass `bin` (first 6 digits of card) for issuer-specific promotions (e.g., Naranja's interest-free deals). Use before create_payment to let the user pick installments knowingly.",
529
929
  // ── Account ──────────────────────────────────────────────────────────────
530
- get_account_info: "Get info about the Mercado Pago account that owns the access token: site_id (MLA=Argentina), country_id, user_type (registered, partial, etc.). Useful to verify the agent is connected to the right account before taking actions."
930
+ get_account_info: "Get info about the Mercado Pago account that owns the access token: site_id (MLA=Argentina), country_id, user_type (registered, partial, etc.). Useful to verify the agent is connected to the right account before taking actions.",
931
+ // ── Saved-card charging (v0.3) ───────────────────────────────────────────
932
+ charge_saved_card: "Charge a previously-saved card for a returning customer. Requires customer_id + card_id (from list_customer_cards) AND a fresh CVV the user provides this session. AR Mercado Pago does NOT support CVV-less charges via the public API \u2014 every charge needs CVV. Idempotent on (card_id, amount, external_reference): retries dedupe automatically. Returns the resulting Payment.",
933
+ // ── QR in-store (v0.3) ───────────────────────────────────────────────────
934
+ create_qr_payment: "Generate a dynamic in-store QR for a buyer to scan with any AR wallet (Modo, BNA+, Cuenta DNI, Naranja X, Mercado Pago, etc. \u2014 interop is mandated by Transferencias 3.0). Requires a pre-configured POS external_id (use create_pos to set one up first if needed). Returns the qr_data string + a base64 PNG data URL ready to display. The QR expires in `expires_in_seconds` (default 600). MP fires `point_integration_wh` then `payment` webhooks when scanned.",
935
+ cancel_qr_payment: "Cancel a pending QR order on a POS. Necessary if the buyer never scans \u2014 otherwise the next create_qr_payment on the same POS returns 409.",
936
+ // ── Subscription Plans (v0.4) ────────────────────────────────────────────
937
+ create_subscription_plan: "Create a REUSABLE subscription plan (preapproval_plan). Different from create_subscription: a plan defines price + frequency once, then customers subscribe to it via subscribe_to_plan. Use plans for SaaS-style billing (B\xE1sico/Pro/Enterprise tiers). For per-customer custom amounts, use create_subscription directly.",
938
+ list_subscription_plans: "List all subscription plans defined for this MP account. Useful before create_subscription_plan to check if one already exists, or for surfacing options to a customer.",
939
+ update_subscription_plan: "Update a subscription plan's reason / amount / status / back_url. Existing customer subscriptions to the plan are NOT automatically updated \u2014 only NEW subscribers get the new pricing.",
940
+ subscribe_to_plan: "Subscribe a customer to an existing reusable plan. Returns a Preapproval with init_point URL where the customer completes first payment. Cleaner than create_subscription when you have fixed tiers.",
941
+ list_subscription_payments: "List the auto-charge attempts (authorized_payments) under a subscription. Useful for 'show me the cobros del \xFAltimo mes for this client' or to debug a failing recurring charge.",
942
+ // ── Stores + POS (v0.4) ──────────────────────────────────────────────────
943
+ create_store: "Create a store under the seller's MP account. Stores are the parent entity for POSes (which generate QR payments). Required ONE-TIME setup before create_pos. Pass a unique external_id and a display name.",
944
+ list_stores: "List all stores configured for this MP account. Use this to find an existing store_id before create_pos, or to surface store options to the agent.",
945
+ create_pos: "Create a POS (Point of Sale) under a store. The POS's external_id is what create_qr_payment uses. Each physical checkout / counter / agent typically has its own POS. Categories are MP-defined (default 621102 = Other Food and Beverage Services).",
946
+ list_pos: "List all POSes for the seller (or filtered by store_id). Use to find an existing POS before create_qr_payment, or to surface options.",
947
+ // ── Disputes (v0.4 — read-only) ──────────────────────────────────────────
948
+ list_payment_disputes: "List all disputes / chargebacks raised against a payment. Read-only \u2014 resolution is dashboard-only. Surface the dashboard URL `https://www.mercadopago.com.ar/disputes/{dispute_id}` to the user when they need to respond.",
949
+ get_dispute: "Get details of a specific dispute including reason, amount, resolution status. Read-only.",
950
+ // ── Lookup helpers (v0.4) ────────────────────────────────────────────────
951
+ list_identification_types: "List valid identification types for the seller's site. AR returns: DNI, CI, LE, LC, Otro, Pasaporte, CUIT, CUIL with their min/max length. Useful to validate an identification before passing to create_payment.",
952
+ list_issuers: "List card issuers (banks) that support a payment_method_id. Optionally filter by `bin` (first 6 digits of the card) for accurate issuer detection. Useful with calculate_installments \u2014 issuer-specific promos (e.g., Naranja Galicia 6 cuotas sin inter\xE9s) only appear when the issuer is identified.",
953
+ // ── Webhooks management (v0.4) ───────────────────────────────────────────
954
+ list_webhooks: "List all webhook subscriptions configured for this MP application. Use to see what topics + URLs are wired before adding new ones.",
955
+ create_webhook: "Subscribe a webhook URL to a MP topic (payment, subscription_authorized_payment, subscription_preapproval, merchant_order, point_integration_wh). MP will POST to this URL when events of that topic fire.",
956
+ update_webhook: "Update a webhook's URL or topic. Useful when you change deployment URLs without resubscribing from scratch.",
957
+ delete_webhook: "Delete a webhook subscription. MP stops POSTing to it immediately."
531
958
  };
532
959
  function mercadoPagoTools(client, options) {
533
960
  const desc = (name) => options.descriptions?.[name] ?? DEFAULT_DESCRIPTIONS[name];
@@ -669,8 +1096,15 @@ function mercadoPagoTools(client, options) {
669
1096
  ...input.identification !== void 0 ? { identification: input.identification } : {},
670
1097
  ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
671
1098
  ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
672
- // Auto-generate idempotency key from caller-meaningful fields
673
- idempotencyKey: `${input.external_reference ?? input.payer_email}-${input.amount_ars}-${Date.now()}`
1099
+ // Deterministic idempotency key safe to retry, same inputs always
1100
+ // produce the same key (MP dedupes on its side).
1101
+ idempotencyKey: deterministicIdempotencyKey(
1102
+ "create_payment",
1103
+ input.external_reference ?? input.payer_email,
1104
+ input.amount_ars,
1105
+ input.payment_method_id,
1106
+ input.token
1107
+ )
674
1108
  });
675
1109
  return {
676
1110
  payment_id: payment.id,
@@ -787,7 +1221,7 @@ function mercadoPagoTools(client, options) {
787
1221
  const refund = await client.createRefund({
788
1222
  paymentId: payment_id,
789
1223
  ...amount_ars !== void 0 ? { amount: amount_ars } : {},
790
- idempotencyKey: `refund-${payment_id}-${amount_ars ?? "full"}`
1224
+ idempotencyKey: deterministicIdempotencyKey("refund", payment_id, amount_ars ?? "full")
791
1225
  });
792
1226
  return {
793
1227
  refund_id: refund.id,
@@ -1027,6 +1461,493 @@ function mercadoPagoTools(client, options) {
1027
1461
  user_type: me.user_type
1028
1462
  };
1029
1463
  }
1464
+ }),
1465
+ // ─────────────────────────────────────────────────────────────────────────
1466
+ // Saved-card charging (v0.3)
1467
+ // ─────────────────────────────────────────────────────────────────────────
1468
+ charge_saved_card: tool({
1469
+ description: desc("charge_saved_card"),
1470
+ inputSchema: z.object({
1471
+ customer_id: z.string().describe("MP customer id (from create_customer / find_customer_by_email)"),
1472
+ card_id: z.string().describe("Saved card id (from list_customer_cards)"),
1473
+ security_code: z.string().regex(/^\d{3,4}$/).describe("CVV \u2014 3 digits (Visa/Master) or 4 (Amex). User must provide this each charge in AR."),
1474
+ amount_ars: z.number().positive(),
1475
+ description: z.string().min(1).max(255),
1476
+ installments: z.number().int().min(1).max(24).optional().describe("Default 1. Use calculate_installments first to pick a valid count."),
1477
+ external_reference: z.string().optional(),
1478
+ statement_descriptor: z.string().max(13).optional()
1479
+ }),
1480
+ execute: async (input) => {
1481
+ const payment = await client.chargeSavedCard({
1482
+ customerId: input.customer_id,
1483
+ cardId: input.card_id,
1484
+ securityCode: input.security_code,
1485
+ amount: input.amount_ars,
1486
+ description: input.description,
1487
+ ...input.installments !== void 0 ? { installments: input.installments } : {},
1488
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1489
+ ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
1490
+ idempotencyKey: deterministicIdempotencyKey(
1491
+ "charge_saved_card",
1492
+ input.card_id,
1493
+ input.amount_ars,
1494
+ input.external_reference
1495
+ )
1496
+ });
1497
+ return {
1498
+ payment_id: payment.id,
1499
+ status: payment.status,
1500
+ status_detail: payment.status_detail,
1501
+ amount: payment.transaction_amount,
1502
+ installments: payment.installments,
1503
+ payment_method: payment.payment_method_id,
1504
+ customer_id: input.customer_id,
1505
+ card_id: input.card_id,
1506
+ external_reference: payment.external_reference,
1507
+ date_approved: payment.date_approved
1508
+ };
1509
+ }
1510
+ }),
1511
+ // ─────────────────────────────────────────────────────────────────────────
1512
+ // QR in-store (v0.3)
1513
+ // ─────────────────────────────────────────────────────────────────────────
1514
+ create_qr_payment: tool({
1515
+ description: desc("create_qr_payment"),
1516
+ inputSchema: z.object({
1517
+ external_pos_id: z.string().describe("Pre-configured POS external_id from MP dashboard. Required."),
1518
+ amount_ars: z.number().positive(),
1519
+ title: z.string().min(1).max(80).describe("Display title shown when scanning"),
1520
+ description: z.string().max(255).optional(),
1521
+ external_reference: z.string().optional(),
1522
+ notification_url: z.string().url().optional().describe("Webhook URL \u2014 falls back to dashboard config if omitted"),
1523
+ expires_in_seconds: z.number().int().min(60).max(3600).optional().describe("Default 600 (10 min)")
1524
+ }),
1525
+ execute: async (input) => {
1526
+ const QRCode = (await import('qrcode')).default;
1527
+ const me = await client.getMe();
1528
+ const userId = String(me.id);
1529
+ const expiresAt = new Date(
1530
+ Date.now() + (input.expires_in_seconds ?? 600) * 1e3
1531
+ ).toISOString();
1532
+ const qr = await client.createQrPayment(userId, {
1533
+ externalPosId: input.external_pos_id,
1534
+ totalAmount: input.amount_ars,
1535
+ title: input.title,
1536
+ ...input.description !== void 0 ? { description: input.description } : {},
1537
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1538
+ ...input.notification_url !== void 0 ? { notificationUrl: input.notification_url } : {},
1539
+ expirationDate: expiresAt
1540
+ });
1541
+ const qrDataUrl = await QRCode.toDataURL(qr.qr_data, {
1542
+ errorCorrectionLevel: "M",
1543
+ margin: 1,
1544
+ width: 512
1545
+ });
1546
+ return {
1547
+ in_store_order_id: qr.in_store_order_id,
1548
+ qr_data: qr.qr_data,
1549
+ qr_data_url: qrDataUrl,
1550
+ expires_at: expiresAt,
1551
+ external_pos_id: input.external_pos_id,
1552
+ amount: input.amount_ars,
1553
+ next_step: "Display the qr_data_url image to the buyer. Wait for the payment webhook (point_integration_wh fires first, then payment topic). If buyer doesn't scan in time, call cancel_qr_payment to free the POS."
1554
+ };
1555
+ }
1556
+ }),
1557
+ cancel_qr_payment: tool({
1558
+ description: desc("cancel_qr_payment"),
1559
+ inputSchema: z.object({
1560
+ external_pos_id: z.string()
1561
+ }),
1562
+ execute: async ({ external_pos_id }) => {
1563
+ const me = await client.getMe();
1564
+ await client.cancelQrPayment(String(me.id), external_pos_id);
1565
+ return { external_pos_id, cancelled: true };
1566
+ }
1567
+ }),
1568
+ // ─────────────────────────────────────────────────────────────────────────
1569
+ // Subscription Plans (v0.4)
1570
+ // ─────────────────────────────────────────────────────────────────────────
1571
+ create_subscription_plan: tool({
1572
+ description: desc("create_subscription_plan"),
1573
+ inputSchema: z.object({
1574
+ reason: z.string().min(3).max(120).describe("Plan name shown at checkout"),
1575
+ amount_ars: z.number().positive(),
1576
+ frequency_months: z.number().int().min(1).max(12),
1577
+ back_url: z.string().url().describe("HTTPS URL where MP redirects after first payment"),
1578
+ external_reference: z.string().optional(),
1579
+ free_trial_days: z.number().int().min(1).max(60).optional().describe("Free trial period in days before first charge")
1580
+ }),
1581
+ execute: async (input) => {
1582
+ const plan = await client.createSubscriptionPlan({
1583
+ reason: input.reason,
1584
+ amount: input.amount_ars,
1585
+ currency: "ARS",
1586
+ frequency: input.frequency_months,
1587
+ frequencyType: "months",
1588
+ backUrl: input.back_url,
1589
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1590
+ ...input.free_trial_days !== void 0 ? { freeTrialFrequency: input.free_trial_days, freeTrialFrequencyType: "days" } : {}
1591
+ });
1592
+ return {
1593
+ plan_id: plan.id,
1594
+ status: plan.status,
1595
+ reason: plan.reason,
1596
+ amount: plan.auto_recurring.transaction_amount,
1597
+ currency: plan.auto_recurring.currency_id,
1598
+ frequency: `${plan.auto_recurring.frequency} ${plan.auto_recurring.frequency_type}`,
1599
+ external_reference: plan.external_reference,
1600
+ next_step: "Use subscribe_to_plan to enroll customers in this plan, or share its ID for them to subscribe via your frontend."
1601
+ };
1602
+ }
1603
+ }),
1604
+ list_subscription_plans: tool({
1605
+ description: desc("list_subscription_plans"),
1606
+ inputSchema: z.object({
1607
+ status: z.string().optional(),
1608
+ limit: z.number().int().min(1).max(100).optional()
1609
+ }),
1610
+ execute: async (input) => {
1611
+ const result = await client.listSubscriptionPlans({
1612
+ ...input.status !== void 0 ? { status: input.status } : {},
1613
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
1614
+ });
1615
+ return {
1616
+ total: result.paging.total,
1617
+ plans: result.results.map((p) => ({
1618
+ plan_id: p.id,
1619
+ reason: p.reason,
1620
+ status: p.status,
1621
+ amount: p.auto_recurring.transaction_amount,
1622
+ currency: p.auto_recurring.currency_id,
1623
+ frequency: `${p.auto_recurring.frequency} ${p.auto_recurring.frequency_type}`
1624
+ }))
1625
+ };
1626
+ }
1627
+ }),
1628
+ update_subscription_plan: tool({
1629
+ description: desc("update_subscription_plan"),
1630
+ inputSchema: z.object({
1631
+ plan_id: z.string(),
1632
+ reason: z.string().optional(),
1633
+ amount_ars: z.number().positive().optional(),
1634
+ status: z.enum(["active", "cancelled"]).optional(),
1635
+ back_url: z.string().url().optional()
1636
+ }),
1637
+ execute: async (input) => {
1638
+ const updated = await client.updateSubscriptionPlan(input.plan_id, {
1639
+ ...input.reason !== void 0 ? { reason: input.reason } : {},
1640
+ ...input.amount_ars !== void 0 ? { amount: input.amount_ars } : {},
1641
+ ...input.status !== void 0 ? { status: input.status } : {},
1642
+ ...input.back_url !== void 0 ? { backUrl: input.back_url } : {}
1643
+ });
1644
+ return {
1645
+ plan_id: updated.id,
1646
+ status: updated.status,
1647
+ reason: updated.reason,
1648
+ amount: updated.auto_recurring.transaction_amount,
1649
+ message: input.amount_ars !== void 0 ? "Updated. Existing subscribers keep their old amount; only NEW subscribers get the new pricing." : "Plan updated."
1650
+ };
1651
+ }
1652
+ }),
1653
+ subscribe_to_plan: tool({
1654
+ description: desc("subscribe_to_plan"),
1655
+ inputSchema: z.object({
1656
+ plan_id: z.string(),
1657
+ customer_email: z.string().email(),
1658
+ external_reference: z.string().optional()
1659
+ }),
1660
+ execute: async (input) => {
1661
+ const sub = await client.subscribeToPlan({
1662
+ planId: input.plan_id,
1663
+ payerEmail: input.customer_email,
1664
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {}
1665
+ });
1666
+ return {
1667
+ subscription_id: sub.id,
1668
+ status: sub.status,
1669
+ payer_email: sub.payer_email,
1670
+ init_point_url: sub.init_point,
1671
+ next_step: "Send init_point_url to the customer for first payment with card+CVV."
1672
+ };
1673
+ }
1674
+ }),
1675
+ list_subscription_payments: tool({
1676
+ description: desc("list_subscription_payments"),
1677
+ inputSchema: z.object({
1678
+ subscription_id: z.string(),
1679
+ limit: z.number().int().min(1).max(100).optional()
1680
+ }),
1681
+ execute: async (input) => {
1682
+ const result = await client.listSubscriptionPayments(input.subscription_id, {
1683
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
1684
+ });
1685
+ return {
1686
+ subscription_id: input.subscription_id,
1687
+ total: result.paging.total,
1688
+ payments: result.results.map((p) => ({
1689
+ authorized_payment_id: p.id,
1690
+ payment_id: p.payment_id ?? null,
1691
+ status: p.status,
1692
+ amount: p.transaction_amount ?? null,
1693
+ currency: p.currency_id ?? null,
1694
+ debit_date: p.debit_date ?? null,
1695
+ next_retry_date: p.next_retry_date ?? null,
1696
+ retry_attempt: p.retry_attempt ?? 0,
1697
+ reason: p.reason ?? null
1698
+ }))
1699
+ };
1700
+ }
1701
+ }),
1702
+ // ─────────────────────────────────────────────────────────────────────────
1703
+ // Stores + POS (v0.4)
1704
+ // ─────────────────────────────────────────────────────────────────────────
1705
+ create_store: tool({
1706
+ description: desc("create_store"),
1707
+ inputSchema: z.object({
1708
+ name: z.string().min(1).max(80),
1709
+ external_id: z.string().min(1).max(64).describe("Unique within the seller's stores"),
1710
+ address_line: z.string().optional(),
1711
+ city_name: z.string().optional(),
1712
+ state_name: z.string().optional()
1713
+ }),
1714
+ execute: async (input) => {
1715
+ const me = await client.getMe();
1716
+ const store = await client.createStore(String(me.id), {
1717
+ name: input.name,
1718
+ externalId: input.external_id,
1719
+ ...input.address_line || input.city_name || input.state_name ? {
1720
+ location: {
1721
+ ...input.address_line ? { addressLine: input.address_line } : {},
1722
+ ...input.city_name ? { cityName: input.city_name } : {},
1723
+ ...input.state_name ? { stateName: input.state_name } : {},
1724
+ countryId: "AR"
1725
+ }
1726
+ } : {}
1727
+ });
1728
+ return {
1729
+ store_id: store.id,
1730
+ name: store.name,
1731
+ external_id: store.external_id,
1732
+ next_step: "Use create_pos with this store_id to add a Point of Sale where create_qr_payment can issue QRs."
1733
+ };
1734
+ }
1735
+ }),
1736
+ list_stores: tool({
1737
+ description: desc("list_stores"),
1738
+ inputSchema: z.object({
1739
+ limit: z.number().int().min(1).max(100).optional()
1740
+ }),
1741
+ execute: async (input) => {
1742
+ const me = await client.getMe();
1743
+ const result = await client.listStores(String(me.id), {
1744
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
1745
+ });
1746
+ return {
1747
+ total: result.paging.total,
1748
+ stores: result.results.map((s) => ({
1749
+ store_id: s.id,
1750
+ name: s.name ?? null,
1751
+ external_id: s.external_id ?? null
1752
+ }))
1753
+ };
1754
+ }
1755
+ }),
1756
+ create_pos: tool({
1757
+ description: desc("create_pos"),
1758
+ inputSchema: z.object({
1759
+ name: z.string().min(1).max(80),
1760
+ external_id: z.string().min(1).max(64).describe("Unique within the store. This is what create_qr_payment uses."),
1761
+ store_id: z.string().describe("From create_store / list_stores"),
1762
+ category: z.number().int().optional().describe("MP category code, default 621102 (other food/beverage)"),
1763
+ fixed_amount: z.boolean().optional().describe("True for static QR with fixed amount; false (default) for dynamic per-order QR")
1764
+ }),
1765
+ execute: async (input) => {
1766
+ const pos = await client.createPos({
1767
+ name: input.name,
1768
+ externalId: input.external_id,
1769
+ storeId: input.store_id,
1770
+ ...input.category !== void 0 ? { category: input.category } : {},
1771
+ ...input.fixed_amount !== void 0 ? { fixedAmount: input.fixed_amount } : {}
1772
+ });
1773
+ return {
1774
+ pos_id: pos.id,
1775
+ external_id: pos.external_id,
1776
+ store_id: pos.store_id,
1777
+ name: pos.name,
1778
+ next_step: "Use create_qr_payment with this external_id to start issuing dynamic QRs from this POS."
1779
+ };
1780
+ }
1781
+ }),
1782
+ list_pos: tool({
1783
+ description: desc("list_pos"),
1784
+ inputSchema: z.object({
1785
+ store_id: z.string().optional(),
1786
+ limit: z.number().int().min(1).max(100).optional()
1787
+ }),
1788
+ execute: async (input) => {
1789
+ const result = await client.listPos({
1790
+ ...input.store_id !== void 0 ? { storeId: input.store_id } : {},
1791
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
1792
+ });
1793
+ return {
1794
+ total: result.paging.total,
1795
+ pos: result.results.map((p) => ({
1796
+ pos_id: p.id,
1797
+ external_id: p.external_id ?? null,
1798
+ store_id: p.store_id ?? null,
1799
+ name: p.name ?? null
1800
+ }))
1801
+ };
1802
+ }
1803
+ }),
1804
+ // ─────────────────────────────────────────────────────────────────────────
1805
+ // Disputes (v0.4 — read-only)
1806
+ // ─────────────────────────────────────────────────────────────────────────
1807
+ list_payment_disputes: tool({
1808
+ description: desc("list_payment_disputes"),
1809
+ inputSchema: z.object({ payment_id: z.string() }),
1810
+ execute: async ({ payment_id }) => {
1811
+ const disputes = await client.listPaymentDisputes(payment_id);
1812
+ return {
1813
+ payment_id,
1814
+ count: disputes.length,
1815
+ disputes: disputes.map((d) => ({
1816
+ dispute_id: d.id,
1817
+ status: d.status,
1818
+ amount: d.amount ?? null,
1819
+ reason: d.reason ?? null,
1820
+ date_created: d.date_created ?? null,
1821
+ dashboard_url: `https://www.mercadopago.com.ar/disputes/${d.id}`
1822
+ }))
1823
+ };
1824
+ }
1825
+ }),
1826
+ get_dispute: tool({
1827
+ description: desc("get_dispute"),
1828
+ inputSchema: z.object({
1829
+ payment_id: z.string(),
1830
+ dispute_id: z.string()
1831
+ }),
1832
+ execute: async ({ payment_id, dispute_id }) => {
1833
+ const d = await client.getDispute(payment_id, dispute_id);
1834
+ return {
1835
+ dispute_id: d.id,
1836
+ status: d.status,
1837
+ amount: d.amount ?? null,
1838
+ reason: d.reason ?? null,
1839
+ reason_description: d.reason_description ?? null,
1840
+ resolution: d.resolution ?? null,
1841
+ date_created: d.date_created ?? null,
1842
+ dashboard_url: `https://www.mercadopago.com.ar/disputes/${d.id}`
1843
+ };
1844
+ }
1845
+ }),
1846
+ // ─────────────────────────────────────────────────────────────────────────
1847
+ // Lookup helpers (v0.4)
1848
+ // ─────────────────────────────────────────────────────────────────────────
1849
+ list_identification_types: tool({
1850
+ description: desc("list_identification_types"),
1851
+ inputSchema: z.object({}),
1852
+ execute: async () => {
1853
+ const types = await client.listIdentificationTypes();
1854
+ return {
1855
+ count: types.length,
1856
+ types: types.map((t) => ({
1857
+ id: t.id,
1858
+ name: t.name,
1859
+ type: t.type,
1860
+ min_length: t.min_length ?? null,
1861
+ max_length: t.max_length ?? null
1862
+ }))
1863
+ };
1864
+ }
1865
+ }),
1866
+ list_issuers: tool({
1867
+ description: desc("list_issuers"),
1868
+ inputSchema: z.object({
1869
+ payment_method_id: z.string().describe("E.g. 'visa', 'master', 'naranja'"),
1870
+ bin: z.string().min(6).max(8).optional().describe("First 6-8 digits of card for precise issuer detection")
1871
+ }),
1872
+ execute: async (input) => {
1873
+ const issuers = await client.listIssuers({
1874
+ paymentMethodId: input.payment_method_id,
1875
+ ...input.bin !== void 0 ? { bin: input.bin } : {}
1876
+ });
1877
+ return {
1878
+ payment_method_id: input.payment_method_id,
1879
+ count: issuers.length,
1880
+ issuers: issuers.map((i) => ({
1881
+ issuer_id: i.id,
1882
+ name: i.name,
1883
+ status: i.status ?? null
1884
+ }))
1885
+ };
1886
+ }
1887
+ }),
1888
+ // ─────────────────────────────────────────────────────────────────────────
1889
+ // Webhooks management (v0.4)
1890
+ // ─────────────────────────────────────────────────────────────────────────
1891
+ list_webhooks: tool({
1892
+ description: desc("list_webhooks"),
1893
+ inputSchema: z.object({}),
1894
+ execute: async () => {
1895
+ const hooks = await client.listWebhooks();
1896
+ return {
1897
+ count: hooks.length,
1898
+ webhooks: hooks.map((h) => ({
1899
+ webhook_id: h.id,
1900
+ url: h.url ?? null,
1901
+ topic: h.topic ?? null,
1902
+ status: h.status ?? null,
1903
+ date_created: h.date_created ?? null
1904
+ }))
1905
+ };
1906
+ }
1907
+ }),
1908
+ create_webhook: tool({
1909
+ description: desc("create_webhook"),
1910
+ inputSchema: z.object({
1911
+ url: z.string().url(),
1912
+ topic: z.string().describe("E.g. 'payment', 'subscription_authorized_payment', 'subscription_preapproval', 'merchant_order', 'point_integration_wh'")
1913
+ }),
1914
+ execute: async ({ url, topic }) => {
1915
+ const hook = await client.createWebhook({ url, topic });
1916
+ return {
1917
+ webhook_id: hook.id,
1918
+ url: hook.url ?? url,
1919
+ topic: hook.topic ?? topic,
1920
+ status: hook.status ?? null
1921
+ };
1922
+ }
1923
+ }),
1924
+ update_webhook: tool({
1925
+ description: desc("update_webhook"),
1926
+ inputSchema: z.object({
1927
+ webhook_id: z.string(),
1928
+ url: z.string().url().optional(),
1929
+ topic: z.string().optional()
1930
+ }),
1931
+ execute: async (input) => {
1932
+ const hook = await client.updateWebhook(input.webhook_id, {
1933
+ ...input.url !== void 0 ? { url: input.url } : {},
1934
+ ...input.topic !== void 0 ? { topic: input.topic } : {}
1935
+ });
1936
+ return {
1937
+ webhook_id: hook.id,
1938
+ url: hook.url ?? null,
1939
+ topic: hook.topic ?? null,
1940
+ status: hook.status ?? null
1941
+ };
1942
+ }
1943
+ }),
1944
+ delete_webhook: tool({
1945
+ description: desc("delete_webhook"),
1946
+ inputSchema: z.object({ webhook_id: z.string() }),
1947
+ execute: async ({ webhook_id }) => {
1948
+ await client.deleteWebhook(webhook_id);
1949
+ return { webhook_id, deleted: true };
1950
+ }
1030
1951
  })
1031
1952
  };
1032
1953
  }
@@ -1227,6 +2148,17 @@ z.object({
1227
2148
  }).passthrough()
1228
2149
  )
1229
2150
  }).passthrough();
2151
+ z.object({
2152
+ in_store_order_id: z.string(),
2153
+ qr_data: z.string()
2154
+ }).passthrough();
2155
+ z.object({
2156
+ id: z.string(),
2157
+ status: z.string().optional(),
2158
+ date_due: z.string().optional(),
2159
+ card_id: z.string().optional(),
2160
+ cardholder: z.unknown().optional()
2161
+ }).passthrough();
1230
2162
  z.object({
1231
2163
  id: z.union([z.string(), z.number()]).transform(String),
1232
2164
  email: z.string().nullable().optional(),
@@ -1236,6 +2168,105 @@ z.object({
1236
2168
  user_type: z.string().nullable().optional(),
1237
2169
  status: z.object({ user_type: z.string().nullable().optional() }).passthrough().nullable().optional()
1238
2170
  }).passthrough();
2171
+ z.object({
2172
+ id: z.string(),
2173
+ status: z.string(),
2174
+ reason: z.string(),
2175
+ back_url: z.string().url().optional(),
2176
+ external_reference: z.string().nullable().optional(),
2177
+ date_created: z.string(),
2178
+ last_modified: z.string(),
2179
+ auto_recurring: AutoRecurringSchema
2180
+ }).passthrough();
2181
+ z.object({
2182
+ id: z.union([z.string(), z.number()]).transform(String),
2183
+ name: z.string().optional(),
2184
+ external_id: z.string().optional(),
2185
+ date_creation: z.string().optional(),
2186
+ location: z.object({
2187
+ address_line: z.string().optional(),
2188
+ city_name: z.string().optional(),
2189
+ state_name: z.string().optional(),
2190
+ country_id: z.string().optional(),
2191
+ latitude: z.number().optional(),
2192
+ longitude: z.number().optional()
2193
+ }).passthrough().optional()
2194
+ }).passthrough();
2195
+ z.object({
2196
+ id: z.union([z.string(), z.number()]).transform(String),
2197
+ name: z.string().optional(),
2198
+ external_id: z.string().optional(),
2199
+ store_id: z.union([z.string(), z.number()]).optional(),
2200
+ category: z.number().int().optional(),
2201
+ fixed_amount: z.boolean().optional(),
2202
+ qr: z.object({
2203
+ template_image: z.string().optional(),
2204
+ image: z.string().optional()
2205
+ }).passthrough().optional(),
2206
+ date_creation: z.string().optional()
2207
+ }).passthrough();
2208
+ z.object({
2209
+ id: z.union([z.string(), z.number()]).transform(String),
2210
+ status: z.string(),
2211
+ resource: z.string().optional(),
2212
+ resource_id: z.union([z.string(), z.number()]).optional(),
2213
+ amount: z.number().optional(),
2214
+ date_created: z.string().optional(),
2215
+ reason: z.string().optional(),
2216
+ resolution: z.object({
2217
+ reason: z.string().optional(),
2218
+ result: z.string().optional(),
2219
+ date: z.string().optional()
2220
+ }).passthrough().optional(),
2221
+ /** Documents the buyer / seller submitted as evidence. */
2222
+ documents: z.array(z.unknown()).optional(),
2223
+ /** Buyer's stated complaint. */
2224
+ reason_description: z.string().optional()
2225
+ }).passthrough();
2226
+ z.object({
2227
+ id: z.union([z.string(), z.number()]).transform(String),
2228
+ preapproval_id: z.string().optional(),
2229
+ status: z.string(),
2230
+ payment_id: z.union([z.string(), z.number()]).nullable().optional(),
2231
+ transaction_amount: z.number().optional(),
2232
+ currency_id: z.string().optional(),
2233
+ date_created: z.string().optional(),
2234
+ debit_date: z.string().optional(),
2235
+ next_retry_date: z.string().nullable().optional(),
2236
+ retry_attempt: z.number().optional(),
2237
+ reason: z.string().optional()
2238
+ }).passthrough();
2239
+ z.object({
2240
+ id: z.string(),
2241
+ name: z.string(),
2242
+ type: z.string(),
2243
+ min_length: z.number().optional(),
2244
+ max_length: z.number().optional()
2245
+ }).passthrough();
2246
+ z.object({
2247
+ id: z.union([z.string(), z.number()]).transform(String),
2248
+ name: z.string(),
2249
+ secure_thumbnail: z.string().nullable().optional(),
2250
+ thumbnail: z.string().nullable().optional(),
2251
+ processing_mode: z.string().optional(),
2252
+ status: z.string().optional()
2253
+ }).passthrough();
2254
+ z.enum([
2255
+ "payment",
2256
+ "subscription_authorized_payment",
2257
+ "subscription_preapproval",
2258
+ "merchant_order",
2259
+ "point_integration_wh",
2260
+ "stop_delivery_op_wh"
2261
+ ]);
2262
+ z.object({
2263
+ id: z.union([z.string(), z.number()]).transform(String),
2264
+ url: z.string().url().optional(),
2265
+ status: z.string().optional(),
2266
+ topic: z.string().optional(),
2267
+ date_created: z.string().optional(),
2268
+ date_modified: z.string().optional()
2269
+ }).passthrough();
1239
2270
 
1240
2271
  // src/webhook.ts
1241
2272
  function parseWebhookEvent(body, searchParams) {
@@ -1267,6 +2298,6 @@ function verifyWebhookSignature(params) {
1267
2298
  return timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
1268
2299
  }
1269
2300
 
1270
- export { InMemoryStateAdapter, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, MercadoPagoError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, classifyError, mercadoPagoTools, parseWebhookEvent, verifyWebhookSignature };
2301
+ export { InMemoryStateAdapter, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, classifyError, mercadoPagoTools, parseWebhookEvent, verifyWebhookSignature };
1271
2302
  //# sourceMappingURL=index.js.map
1272
2303
  //# sourceMappingURL=index.js.map