@ar-agents/mercadopago 0.2.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,58 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Robustness pass + 5 new features across both packages.
8
+
9
+ # `@ar-agents/mercadopago@0.3.0`
10
+
11
+ **Robustness (Section 6 of v0.3 spec)**
12
+
13
+ - Per-request timeout via `AbortSignal` (default 30s, configurable via `requestTimeoutMs`).
14
+ - Auto-retry on 5xx + 429 with exponential backoff (default 1 retry, configurable via `maxRetries`). Honors `Retry-After` header on rate-limit. **Never retries on 4xx** (deterministic user/config errors).
15
+ - New typed errors: `MercadoPagoTimeoutError`, `MercadoPagoOverloadedError` (HTML 503 detection — when MP returns HTML instead of JSON).
16
+ - `onCall` observability hook fires after every request with `{ method, path, durationMs, httpStatus, retried, success }`. Wire into OpenTelemetry / Sentry / Axiom without forking the lib.
17
+ - **Deterministic idempotency keys** — `create_payment` and `refund_payment` now use `sha256(meaningful_fields)` instead of `Date.now()`. Retries dedupe correctly on MP's side.
18
+
19
+ **New tools (3)**
20
+
21
+ - **`charge_saved_card`** — server-side retokenize + charge for returning customers. Requires CVV (AR MP doesn't support CVV-less via public API). Idempotent on (card_id, amount, external_reference).
22
+ - **`create_qr_payment`** — dynamic in-store QR via MP Point. Returns raw `qr_data` (EMVCo) + ready-to-display base64 PNG `qr_data_url`. Compatible with all AR wallets (Modo, BNA+, Cuenta DNI, Naranja X) via Transferencias 3.0 interop.
23
+ - **`cancel_qr_payment`** — clear a pending QR order on a POS so the next `create_qr_payment` doesn't 409.
24
+
25
+ **Total tool count: 24** (was 21 in v0.2). Added `qrcode` as runtime dep for in-store flow.
26
+
27
+ # `@ar-agents/identity-attest@0.2.0`
28
+
29
+ **3 new adapters bringing total to 5**
30
+
31
+ - **`Auth0Adapter`** (trust 0.7, or 0.85 with MFA) — OAuth2 Authorization Code flow with PKCE. Server-side `id_token` verification via `jose` JWKS. Optional MFA step-up via `acr_values` — when MFA is completed, `effective_trust_level` bumps to 0.85.
32
+ - **`MagicLinkSdkAdapter`** (trust 0.7) — Magic.link DIDToken validation via `@magic-sdk/admin` (optional peer dep). Lazy-loaded so users without Magic don't pay cold-start cost. Returns DID + email/phone/wallet claims.
33
+ - **`MercadoPagoIdentityAdapter`** (trust 0.5) — partial KYC via $1 micro-charge. MP doesn't expose a public KYC API, so we use payment-payer attestation: a successful payment proves MP validated the buyer's CUIT/DNI against their internal database. Auto-refunds the $1 by default. Returns `identification_type` + `identification_number` + email + name claims.
34
+
35
+ **New client methods**
36
+
37
+ - `submitOauthCode(requestId, code)` — for OAuth callbacks (Auth0)
38
+ - `submitMagicDidToken(requestId, didToken)` — for Magic.link
39
+ - `submitMercadoPagoPaymentId(requestId, paymentId)` — for MP webhook callbacks
40
+
41
+ **Quality**
42
+
43
+ - 28/28 tests pass (was 15 in v0.1)
44
+ - 12.93 KB ESM brotli'd (jose is treeshakeable; was 4.44 KB without OAuth adapter)
45
+ - publint + arethetypeswrong all 🟢
46
+ - `jose` is a dep (used by Auth0Adapter); `@magic-sdk/admin` is optional peer dep
47
+
48
+ **Trust levels reference (current)**
49
+
50
+ - 0.3 — `WhatsAppOtpAdapter` (phone-owned)
51
+ - 0.5 — `EmailMagicLinkAdapter` (email-owned), `MercadoPagoIdentityAdapter` (partial KYC)
52
+ - 0.7 — `Auth0Adapter` (federated identity), `MagicLinkSdkAdapter` (Magic-managed)
53
+ - 0.85 — `Auth0Adapter` with MFA enforcement
54
+ - 0.95 — gov-verified (planned, blocked on AR SID rollout)
55
+
3
56
  ## 0.2.0
4
57
 
5
58
  ### Minor Changes
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ var crypto = require('crypto');
3
4
  var ai = require('ai');
4
5
  var zod = require('zod');
5
- var crypto = require('crypto');
6
6
 
7
7
  // src/errors.ts
8
8
  var MercadoPagoError = class extends Error {
@@ -100,12 +100,38 @@ var MercadoPagoRateLimitError = class extends MercadoPagoError {
100
100
  }
101
101
  retryAfterSeconds;
102
102
  };
103
+ var MercadoPagoOverloadedError = class extends MercadoPagoError {
104
+ constructor(endpoint, status) {
105
+ super(
106
+ `Mercado Pago appears overloaded \u2014 returned a non-JSON ${status} response for ${endpoint}. Wait a few seconds and retry.`,
107
+ status,
108
+ endpoint
109
+ );
110
+ this.name = "MercadoPagoOverloadedError";
111
+ }
112
+ };
113
+ var MercadoPagoTimeoutError = class extends MercadoPagoError {
114
+ constructor(endpoint, timeoutMs) {
115
+ super(
116
+ `Mercado Pago request timed out after ${timeoutMs}ms on ${endpoint}. Increase requestTimeoutMs or check connectivity.`,
117
+ 0,
118
+ endpoint
119
+ );
120
+ this.timeoutMs = timeoutMs;
121
+ this.name = "MercadoPagoTimeoutError";
122
+ }
123
+ timeoutMs;
124
+ };
103
125
  function classifyError(status, endpoint, body, context) {
104
126
  const bodyText = typeof body === "string" ? body : body && typeof body === "object" ? JSON.stringify(body) : "";
105
127
  const lower = bodyText.toLowerCase();
106
128
  if (status === 401) return new MercadoPagoAuthError(endpoint, body);
107
129
  if (status === 429) {
108
- return new MercadoPagoRateLimitError(endpoint, null, body);
130
+ let retryAfter = null;
131
+ const obj = body;
132
+ if (obj?.retry_after) retryAfter = Number(obj.retry_after);
133
+ else if (obj?.["retry-after"]) retryAfter = Number(obj["retry-after"]);
134
+ return new MercadoPagoRateLimitError(endpoint, retryAfter, body);
109
135
  }
110
136
  if (status === 400) {
111
137
  if (lower.includes("back_url") && lower.includes("not a valid url")) {
@@ -131,10 +157,16 @@ function classifyError(status, endpoint, body, context) {
131
157
 
132
158
  // src/client.ts
133
159
  var DEFAULT_BASE_URL = "https://api.mercadopago.com";
160
+ function sleep(ms) {
161
+ return new Promise((resolve) => setTimeout(resolve, ms));
162
+ }
134
163
  var MercadoPagoClient = class {
135
164
  accessToken;
136
165
  baseUrl;
137
166
  fetchImpl;
167
+ requestTimeoutMs;
168
+ maxRetries;
169
+ onCall;
138
170
  constructor(options) {
139
171
  if (!options.accessToken) {
140
172
  throw new Error(
@@ -144,6 +176,9 @@ var MercadoPagoClient = class {
144
176
  this.accessToken = options.accessToken;
145
177
  this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
146
178
  this.fetchImpl = options.fetch;
179
+ this.requestTimeoutMs = options.requestTimeoutMs ?? 3e4;
180
+ this.maxRetries = Math.max(0, options.maxRetries ?? 1);
181
+ this.onCall = options.onCall;
147
182
  }
148
183
  async request(method, path, body, options) {
149
184
  const headers = {
@@ -153,10 +188,6 @@ var MercadoPagoClient = class {
153
188
  if (options?.idempotencyKey) {
154
189
  headers["X-Idempotency-Key"] = options.idempotencyKey;
155
190
  }
156
- const init = { method, headers };
157
- if (body !== void 0) {
158
- init.body = JSON.stringify(body);
159
- }
160
191
  let url = `${this.baseUrl}${path}`;
161
192
  if (options?.query) {
162
193
  const search = new URLSearchParams();
@@ -169,20 +200,95 @@ var MercadoPagoClient = class {
169
200
  if (qs) url += `?${qs}`;
170
201
  }
171
202
  const fetchFn = this.fetchImpl ?? globalThis.fetch;
172
- const res = await fetchFn(url, init);
173
- if (!res.ok) {
174
- let parsed;
175
- const text2 = await res.text();
203
+ const t0 = Date.now();
204
+ let attempt = 0;
205
+ let lastError;
206
+ let lastStatus = null;
207
+ while (attempt <= this.maxRetries) {
208
+ const controller = new AbortController();
209
+ const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs);
210
+ const init = { method, headers, signal: controller.signal };
211
+ if (body !== void 0) init.body = JSON.stringify(body);
176
212
  try {
177
- parsed = JSON.parse(text2);
178
- } catch {
179
- parsed = text2;
213
+ const res = await fetchFn(url, init);
214
+ clearTimeout(timer);
215
+ lastStatus = res.status;
216
+ if (res.ok) {
217
+ const text2 = await res.text();
218
+ this.onCall?.({
219
+ method,
220
+ path,
221
+ durationMs: Date.now() - t0,
222
+ httpStatus: res.status,
223
+ retried: attempt,
224
+ success: true
225
+ });
226
+ if (!text2) return void 0;
227
+ return JSON.parse(text2);
228
+ }
229
+ const isRetryable = res.status >= 500 || res.status === 429;
230
+ if (isRetryable && attempt < this.maxRetries) {
231
+ const retryAfter = res.headers.get("retry-after");
232
+ const waitMs = retryAfter ? Number(retryAfter) * 1e3 : 250 * Math.pow(2, attempt);
233
+ attempt++;
234
+ await sleep(waitMs);
235
+ continue;
236
+ }
237
+ const contentType = res.headers.get("content-type") ?? "";
238
+ if (res.status >= 500 && !contentType.includes("application/json")) {
239
+ this.onCall?.({
240
+ method,
241
+ path,
242
+ durationMs: Date.now() - t0,
243
+ httpStatus: res.status,
244
+ retried: attempt,
245
+ success: false
246
+ });
247
+ throw new MercadoPagoOverloadedError(path, res.status);
248
+ }
249
+ let parsed;
250
+ const text = await res.text();
251
+ try {
252
+ parsed = JSON.parse(text);
253
+ } catch {
254
+ parsed = text;
255
+ }
256
+ const err = classifyError(res.status, path, parsed, options?.classifyContext);
257
+ this.onCall?.({
258
+ method,
259
+ path,
260
+ durationMs: Date.now() - t0,
261
+ httpStatus: res.status,
262
+ retried: attempt,
263
+ success: false
264
+ });
265
+ throw err;
266
+ } catch (err) {
267
+ clearTimeout(timer);
268
+ if (err instanceof MercadoPagoError) throw err;
269
+ const isAbort = err instanceof Error && err.name === "AbortError";
270
+ const isNetwork = !lastStatus && !isAbort;
271
+ if ((isNetwork || isAbort) && attempt < this.maxRetries) {
272
+ lastError = err;
273
+ attempt++;
274
+ await sleep(250 * Math.pow(2, attempt - 1));
275
+ continue;
276
+ }
277
+ this.onCall?.({
278
+ method,
279
+ path,
280
+ durationMs: Date.now() - t0,
281
+ httpStatus: lastStatus,
282
+ retried: attempt,
283
+ success: false
284
+ });
285
+ if (isAbort) {
286
+ throw new MercadoPagoTimeoutError(path, this.requestTimeoutMs);
287
+ }
288
+ throw err;
180
289
  }
181
- throw classifyError(res.status, path, parsed, options?.classifyContext);
182
290
  }
183
- const text = await res.text();
184
- if (!text) return void 0;
185
- return JSON.parse(text);
291
+ throw lastError ?? new Error(`MercadoPago request failed after ${this.maxRetries} retries`);
186
292
  }
187
293
  // ───────────────────────────────────────────────────────────────────────────
188
294
  // Subscriptions (Preapprovals) — v0.1 surface, kept stable
@@ -500,7 +606,119 @@ var MercadoPagoClient = class {
500
606
  async getMe() {
501
607
  return this.request("GET", "/users/me");
502
608
  }
609
+ // ───────────────────────────────────────────────────────────────────────────
610
+ // Card tokens (server-side, for saved-card retokenization)
611
+ // ───────────────────────────────────────────────────────────────────────────
612
+ /**
613
+ * Create a single-use card token from a saved card. This is the server-side
614
+ * retokenization path (PCI-safe because the card data lives in MP's vault,
615
+ * we only pass the saved card_id + customer_id + the user-supplied CVV).
616
+ *
617
+ * Tokens expire in 7 days but typically burn on first use. AR currently
618
+ * REQUIRES CVV on every charge (MP doesn't store it); skipping CVV requires
619
+ * a private MP product enablement, not a public API.
620
+ */
621
+ async createCardToken(params) {
622
+ return this.request("POST", "/v1/card_tokens", {
623
+ card_id: params.cardId,
624
+ customer_id: params.customerId,
625
+ security_code: params.securityCode
626
+ });
627
+ }
628
+ /**
629
+ * High-level helper: charge a saved card in 3 steps.
630
+ * 1. Mint a card token from {customer_id, card_id, security_code}
631
+ * 2. Lookup card to fill payment_method_id (avoids agent guessing)
632
+ * 3. Create the payment with the token + idempotency key
633
+ *
634
+ * Returns the resulting Payment. Uses deterministic idempotency from
635
+ * (card_id, amount, externalReference) so retries dedupe on MP's side.
636
+ */
637
+ async chargeSavedCard(params) {
638
+ const token = await this.createCardToken({
639
+ cardId: params.cardId,
640
+ customerId: params.customerId,
641
+ securityCode: params.securityCode
642
+ });
643
+ const card = await this.getCustomerCard(params.customerId, params.cardId);
644
+ const paymentMethodId = card.payment_method?.id;
645
+ if (!paymentMethodId) {
646
+ throw new MercadoPagoError(
647
+ `Saved card ${params.cardId} has no payment_method.id. Cannot charge.`,
648
+ 0,
649
+ `/v1/customers/${params.customerId}/cards/${params.cardId}`
650
+ );
651
+ }
652
+ const body = {
653
+ transaction_amount: params.amount,
654
+ token: token.id,
655
+ payment_method_id: paymentMethodId,
656
+ installments: params.installments ?? 1,
657
+ description: params.description,
658
+ payer: { type: "customer", id: params.customerId }
659
+ };
660
+ if (params.externalReference) body.external_reference = params.externalReference;
661
+ if (params.statementDescriptor) body.statement_descriptor = params.statementDescriptor;
662
+ return this.request("POST", "/v1/payments", body, {
663
+ ...params.idempotencyKey !== void 0 ? { idempotencyKey: params.idempotencyKey } : {},
664
+ classifyContext: { customerId: params.customerId }
665
+ });
666
+ }
667
+ // ───────────────────────────────────────────────────────────────────────────
668
+ // QR (in-store dynamic) — Section 2 of v0.3 spec
669
+ // ───────────────────────────────────────────────────────────────────────────
670
+ /**
671
+ * Create a dynamic in-store QR order. Returns `qr_data` (EMVCo TLV string)
672
+ * + `in_store_order_id`. The buyer scans the QR with any AR wallet (Modo,
673
+ * BNA+, Cuenta DNI, Naranja X, etc. — interop is mandated by Transferencias
674
+ * 3.0). On payment, MP fires `point_integration_wh` then `payment` topics.
675
+ *
676
+ * Requires a pre-configured POS (`external_pos_id` from MP dashboard or
677
+ * `POST /pos`). The seller's `user_id` is auto-fetched from `/users/me`.
678
+ *
679
+ * The lib does NOT render the QR image — pass `qr_data` to a QR renderer
680
+ * (e.g., `qrcode` package) to get a data URL. The agent tool layer wraps
681
+ * this and returns both raw + data URL.
682
+ */
683
+ async createQrPayment(userId, params) {
684
+ const body = {
685
+ total_amount: params.totalAmount,
686
+ title: params.title
687
+ };
688
+ if (params.description) body.description = params.description;
689
+ if (params.notificationUrl) body.notification_url = params.notificationUrl;
690
+ if (params.externalReference) body.external_reference = params.externalReference;
691
+ if (params.expirationDate) body.expiration_date = params.expirationDate;
692
+ body.items = params.items ?? [
693
+ {
694
+ title: params.title,
695
+ quantity: 1,
696
+ unit_price: params.totalAmount,
697
+ unit_measure: "unit",
698
+ total_amount: params.totalAmount
699
+ }
700
+ ];
701
+ return this.request(
702
+ "PUT",
703
+ `/instore/orders/qr/seller/collectors/${encodeURIComponent(userId)}/pos/${encodeURIComponent(params.externalPosId)}/qrs`,
704
+ body
705
+ );
706
+ }
707
+ /**
708
+ * Cancel a pending QR order on a POS. Necessary if the buyer never scans
709
+ * — otherwise the next `createQrPayment` on the same POS returns 409.
710
+ */
711
+ async cancelQrPayment(userId, externalPosId) {
712
+ await this.request(
713
+ "DELETE",
714
+ `/instore/orders/qr/seller/collectors/${encodeURIComponent(userId)}/pos/${encodeURIComponent(externalPosId)}/qrs`
715
+ );
716
+ }
503
717
  };
718
+ function deterministicIdempotencyKey(...parts) {
719
+ const payload = parts.filter((p) => p !== void 0 && p !== null).map(String).join("|");
720
+ return crypto.createHash("sha256").update(payload).digest("hex").slice(0, 32);
721
+ }
504
722
  var DEFAULT_DESCRIPTIONS = {
505
723
  // ── Subscriptions ────────────────────────────────────────────────────────
506
724
  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.",
@@ -529,7 +747,12 @@ var DEFAULT_DESCRIPTIONS = {
529
747
  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.",
530
748
  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.",
531
749
  // ── Account ──────────────────────────────────────────────────────────────
532
- 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."
750
+ 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.",
751
+ // ── Saved-card charging (v0.3) ───────────────────────────────────────────
752
+ 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.",
753
+ // ── QR in-store (v0.3) ───────────────────────────────────────────────────
754
+ 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 (one-time setup in MP dashboard). 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.",
755
+ 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."
533
756
  };
534
757
  function mercadoPagoTools(client, options) {
535
758
  const desc = (name) => options.descriptions?.[name] ?? DEFAULT_DESCRIPTIONS[name];
@@ -671,8 +894,15 @@ function mercadoPagoTools(client, options) {
671
894
  ...input.identification !== void 0 ? { identification: input.identification } : {},
672
895
  ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
673
896
  ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
674
- // Auto-generate idempotency key from caller-meaningful fields
675
- idempotencyKey: `${input.external_reference ?? input.payer_email}-${input.amount_ars}-${Date.now()}`
897
+ // Deterministic idempotency key safe to retry, same inputs always
898
+ // produce the same key (MP dedupes on its side).
899
+ idempotencyKey: deterministicIdempotencyKey(
900
+ "create_payment",
901
+ input.external_reference ?? input.payer_email,
902
+ input.amount_ars,
903
+ input.payment_method_id,
904
+ input.token
905
+ )
676
906
  });
677
907
  return {
678
908
  payment_id: payment.id,
@@ -789,7 +1019,7 @@ function mercadoPagoTools(client, options) {
789
1019
  const refund = await client.createRefund({
790
1020
  paymentId: payment_id,
791
1021
  ...amount_ars !== void 0 ? { amount: amount_ars } : {},
792
- idempotencyKey: `refund-${payment_id}-${amount_ars ?? "full"}`
1022
+ idempotencyKey: deterministicIdempotencyKey("refund", payment_id, amount_ars ?? "full")
793
1023
  });
794
1024
  return {
795
1025
  refund_id: refund.id,
@@ -1029,6 +1259,109 @@ function mercadoPagoTools(client, options) {
1029
1259
  user_type: me.user_type
1030
1260
  };
1031
1261
  }
1262
+ }),
1263
+ // ─────────────────────────────────────────────────────────────────────────
1264
+ // Saved-card charging (v0.3)
1265
+ // ─────────────────────────────────────────────────────────────────────────
1266
+ charge_saved_card: ai.tool({
1267
+ description: desc("charge_saved_card"),
1268
+ inputSchema: zod.z.object({
1269
+ customer_id: zod.z.string().describe("MP customer id (from create_customer / find_customer_by_email)"),
1270
+ card_id: zod.z.string().describe("Saved card id (from list_customer_cards)"),
1271
+ security_code: zod.z.string().regex(/^\d{3,4}$/).describe("CVV \u2014 3 digits (Visa/Master) or 4 (Amex). User must provide this each charge in AR."),
1272
+ amount_ars: zod.z.number().positive(),
1273
+ description: zod.z.string().min(1).max(255),
1274
+ installments: zod.z.number().int().min(1).max(24).optional().describe("Default 1. Use calculate_installments first to pick a valid count."),
1275
+ external_reference: zod.z.string().optional(),
1276
+ statement_descriptor: zod.z.string().max(13).optional()
1277
+ }),
1278
+ execute: async (input) => {
1279
+ const payment = await client.chargeSavedCard({
1280
+ customerId: input.customer_id,
1281
+ cardId: input.card_id,
1282
+ securityCode: input.security_code,
1283
+ amount: input.amount_ars,
1284
+ description: input.description,
1285
+ ...input.installments !== void 0 ? { installments: input.installments } : {},
1286
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1287
+ ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
1288
+ idempotencyKey: deterministicIdempotencyKey(
1289
+ "charge_saved_card",
1290
+ input.card_id,
1291
+ input.amount_ars,
1292
+ input.external_reference
1293
+ )
1294
+ });
1295
+ return {
1296
+ payment_id: payment.id,
1297
+ status: payment.status,
1298
+ status_detail: payment.status_detail,
1299
+ amount: payment.transaction_amount,
1300
+ installments: payment.installments,
1301
+ payment_method: payment.payment_method_id,
1302
+ customer_id: input.customer_id,
1303
+ card_id: input.card_id,
1304
+ external_reference: payment.external_reference,
1305
+ date_approved: payment.date_approved
1306
+ };
1307
+ }
1308
+ }),
1309
+ // ─────────────────────────────────────────────────────────────────────────
1310
+ // QR in-store (v0.3)
1311
+ // ─────────────────────────────────────────────────────────────────────────
1312
+ create_qr_payment: ai.tool({
1313
+ description: desc("create_qr_payment"),
1314
+ inputSchema: zod.z.object({
1315
+ external_pos_id: zod.z.string().describe("Pre-configured POS external_id from MP dashboard. Required."),
1316
+ amount_ars: zod.z.number().positive(),
1317
+ title: zod.z.string().min(1).max(80).describe("Display title shown when scanning"),
1318
+ description: zod.z.string().max(255).optional(),
1319
+ external_reference: zod.z.string().optional(),
1320
+ notification_url: zod.z.string().url().optional().describe("Webhook URL \u2014 falls back to dashboard config if omitted"),
1321
+ expires_in_seconds: zod.z.number().int().min(60).max(3600).optional().describe("Default 600 (10 min)")
1322
+ }),
1323
+ execute: async (input) => {
1324
+ const QRCode = (await import('qrcode')).default;
1325
+ const me = await client.getMe();
1326
+ const userId = String(me.id);
1327
+ const expiresAt = new Date(
1328
+ Date.now() + (input.expires_in_seconds ?? 600) * 1e3
1329
+ ).toISOString();
1330
+ const qr = await client.createQrPayment(userId, {
1331
+ externalPosId: input.external_pos_id,
1332
+ totalAmount: input.amount_ars,
1333
+ title: input.title,
1334
+ ...input.description !== void 0 ? { description: input.description } : {},
1335
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1336
+ ...input.notification_url !== void 0 ? { notificationUrl: input.notification_url } : {},
1337
+ expirationDate: expiresAt
1338
+ });
1339
+ const qrDataUrl = await QRCode.toDataURL(qr.qr_data, {
1340
+ errorCorrectionLevel: "M",
1341
+ margin: 1,
1342
+ width: 512
1343
+ });
1344
+ return {
1345
+ in_store_order_id: qr.in_store_order_id,
1346
+ qr_data: qr.qr_data,
1347
+ qr_data_url: qrDataUrl,
1348
+ expires_at: expiresAt,
1349
+ external_pos_id: input.external_pos_id,
1350
+ amount: input.amount_ars,
1351
+ 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."
1352
+ };
1353
+ }
1354
+ }),
1355
+ cancel_qr_payment: ai.tool({
1356
+ description: desc("cancel_qr_payment"),
1357
+ inputSchema: zod.z.object({
1358
+ external_pos_id: zod.z.string()
1359
+ }),
1360
+ execute: async ({ external_pos_id }) => {
1361
+ const me = await client.getMe();
1362
+ await client.cancelQrPayment(String(me.id), external_pos_id);
1363
+ return { external_pos_id, cancelled: true };
1364
+ }
1032
1365
  })
1033
1366
  };
1034
1367
  }
@@ -1229,6 +1562,17 @@ zod.z.object({
1229
1562
  }).passthrough()
1230
1563
  )
1231
1564
  }).passthrough();
1565
+ zod.z.object({
1566
+ in_store_order_id: zod.z.string(),
1567
+ qr_data: zod.z.string()
1568
+ }).passthrough();
1569
+ zod.z.object({
1570
+ id: zod.z.string(),
1571
+ status: zod.z.string().optional(),
1572
+ date_due: zod.z.string().optional(),
1573
+ card_id: zod.z.string().optional(),
1574
+ cardholder: zod.z.unknown().optional()
1575
+ }).passthrough();
1232
1576
  zod.z.object({
1233
1577
  id: zod.z.union([zod.z.string(), zod.z.number()]).transform(String),
1234
1578
  email: zod.z.string().nullable().optional(),
@@ -1276,9 +1620,11 @@ exports.MercadoPagoAuthorizeForbiddenError = MercadoPagoAuthorizeForbiddenError;
1276
1620
  exports.MercadoPagoBackUrlInvalidError = MercadoPagoBackUrlInvalidError;
1277
1621
  exports.MercadoPagoClient = MercadoPagoClient;
1278
1622
  exports.MercadoPagoError = MercadoPagoError;
1623
+ exports.MercadoPagoOverloadedError = MercadoPagoOverloadedError;
1279
1624
  exports.MercadoPagoPaymentRejectedError = MercadoPagoPaymentRejectedError;
1280
1625
  exports.MercadoPagoRateLimitError = MercadoPagoRateLimitError;
1281
1626
  exports.MercadoPagoSelfPaymentError = MercadoPagoSelfPaymentError;
1627
+ exports.MercadoPagoTimeoutError = MercadoPagoTimeoutError;
1282
1628
  exports.classifyError = classifyError;
1283
1629
  exports.mercadoPagoTools = mercadoPagoTools;
1284
1630
  exports.parseWebhookEvent = parseWebhookEvent;