@ar-agents/mercadopago 0.1.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/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,32 +174,123 @@ 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
- async request(method, path, body, classifyContext) {
147
- const init = {
148
- method,
149
- headers: {
150
- Authorization: `Bearer ${this.accessToken}`,
151
- "Content-Type": "application/json"
152
- }
181
+ async request(method, path, body, options) {
182
+ const headers = {
183
+ Authorization: `Bearer ${this.accessToken}`,
184
+ "Content-Type": "application/json"
153
185
  };
154
- if (body !== void 0) {
155
- init.body = JSON.stringify(body);
186
+ if (options?.idempotencyKey) {
187
+ headers["X-Idempotency-Key"] = options.idempotencyKey;
188
+ }
189
+ let url = `${this.baseUrl}${path}`;
190
+ if (options?.query) {
191
+ const search = new URLSearchParams();
192
+ for (const [k, v] of Object.entries(options.query)) {
193
+ if (v !== void 0 && v !== null && v !== "") {
194
+ search.set(k, String(v));
195
+ }
196
+ }
197
+ const qs = search.toString();
198
+ if (qs) url += `?${qs}`;
156
199
  }
157
200
  const fetchFn = this.fetchImpl ?? globalThis.fetch;
158
- const res = await fetchFn(`${this.baseUrl}${path}`, init);
159
- if (!res.ok) {
160
- let parsed;
161
- const text = 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);
162
210
  try {
163
- parsed = JSON.parse(text);
164
- } catch {
165
- parsed = text;
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;
166
287
  }
167
- throw classifyError(res.status, path, parsed, classifyContext);
168
288
  }
169
- return await res.json();
289
+ throw lastError ?? new Error(`MercadoPago request failed after ${this.maxRetries} retries`);
170
290
  }
291
+ // ───────────────────────────────────────────────────────────────────────────
292
+ // Subscriptions (Preapprovals) — v0.1 surface, kept stable
293
+ // ───────────────────────────────────────────────────────────────────────────
171
294
  /**
172
295
  * Create a recurring subscription (preapproval). The returned `init_point`
173
296
  * URL is where the buyer must complete the FIRST payment with their card +
@@ -189,70 +312,452 @@ var MercadoPagoClient = class {
189
312
  currency_id: params.currency
190
313
  }
191
314
  },
192
- { payerEmail: params.payerEmail }
315
+ { classifyContext: { payerEmail: params.payerEmail } }
193
316
  );
194
317
  }
318
+ async getPreapproval(id) {
319
+ return this.request("GET", `/preapproval/${id}`, void 0, {
320
+ classifyContext: { preapprovalId: id }
321
+ });
322
+ }
323
+ async cancelPreapproval(id) {
324
+ return this.request(
325
+ "PUT",
326
+ `/preapproval/${id}`,
327
+ { status: "cancelled" },
328
+ { classifyContext: { preapprovalId: id } }
329
+ );
330
+ }
331
+ async pausePreapproval(id) {
332
+ return this.request(
333
+ "PUT",
334
+ `/preapproval/${id}`,
335
+ { status: "paused" },
336
+ { classifyContext: { preapprovalId: id } }
337
+ );
338
+ }
339
+ async resumePreapproval(id) {
340
+ return this.request(
341
+ "PUT",
342
+ `/preapproval/${id}`,
343
+ { status: "authorized" },
344
+ { classifyContext: { preapprovalId: id } }
345
+ );
346
+ }
347
+ // ───────────────────────────────────────────────────────────────────────────
348
+ // Payments (v0.2)
349
+ // ───────────────────────────────────────────────────────────────────────────
195
350
  /**
196
- * Fetch the current state of a preapproval. Useful to confirm whether the
197
- * buyer has completed the first payment (`status: 'authorized'`) or whether
198
- * the subscription was cancelled.
351
+ * Create a payment. Two main flows:
352
+ * - **Card payment**: pass `token` (from MP frontend Cardform) + payment_method_id.
353
+ * - **Account money / cash**: omit token, pass payment_method_id like "account_money", "rapipago", "pagofacil".
354
+ *
355
+ * For credit card payments where you don't have a card token (i.e., you only
356
+ * have a payer email and want to send them a payment link), use
357
+ * `createPreference` (Checkout Pro) instead.
358
+ *
359
+ * Idempotency: pass `idempotencyKey` to safely retry. Required for production
360
+ * to dedupe network-failed requests.
199
361
  */
200
- async getPreapproval(id) {
362
+ async createPayment(params) {
363
+ const body = {
364
+ transaction_amount: params.transactionAmount,
365
+ payment_method_id: params.paymentMethodId,
366
+ payer: {
367
+ email: params.payerEmail,
368
+ ...params.identification ? { identification: params.identification } : {}
369
+ }
370
+ };
371
+ if (params.installments !== void 0) body.installments = params.installments;
372
+ if (params.token !== void 0) body.token = params.token;
373
+ if (params.description !== void 0) body.description = params.description;
374
+ if (params.externalReference !== void 0) body.external_reference = params.externalReference;
375
+ if (params.notificationUrl !== void 0) body.notification_url = params.notificationUrl;
376
+ if (params.statementDescriptor !== void 0)
377
+ body.statement_descriptor = params.statementDescriptor;
378
+ if (params.capture !== void 0) body.capture = params.capture;
379
+ if (params.additionalInfo !== void 0) body.additional_info = params.additionalInfo;
380
+ return this.request("POST", "/v1/payments", body, {
381
+ ...params.idempotencyKey ? { idempotencyKey: params.idempotencyKey } : {},
382
+ classifyContext: { payerEmail: params.payerEmail }
383
+ });
384
+ }
385
+ /** Fetch a payment by ID. */
386
+ async getPayment(id) {
387
+ return this.request("GET", `/v1/payments/${id}`, void 0, {
388
+ classifyContext: { paymentId: id }
389
+ });
390
+ }
391
+ /**
392
+ * Search payments with filters. Common: by external_reference (your-system
393
+ * id), by status, by date range. Pagination via offset + limit (max 100).
394
+ */
395
+ async searchPayments(params = {}) {
396
+ const query = {
397
+ limit: params.limit ?? 30,
398
+ offset: params.offset ?? 0
399
+ };
400
+ if (params.externalReference) query["external_reference"] = params.externalReference;
401
+ if (params.status) query["status"] = params.status;
402
+ if (params.payerEmail) query["payer.email"] = params.payerEmail;
403
+ if (params.beginDate) query["begin_date"] = params.beginDate;
404
+ if (params.endDate) query["end_date"] = params.endDate;
405
+ if (params.sort) query["sort"] = params.sort;
406
+ if (params.criteria) query["criteria"] = params.criteria;
201
407
  return this.request(
202
408
  "GET",
203
- `/preapproval/${id}`,
409
+ "/v1/payments/search",
204
410
  void 0,
205
- { preapprovalId: id }
411
+ { query }
206
412
  );
207
413
  }
208
414
  /**
209
- * Cancel an active preapproval. Irreversible: MP will not charge the buyer
210
- * again and the subscription cannot be reactivated.
415
+ * Capture a previously authorized payment. Only works for credit-card
416
+ * payments created with `capture: false`. Optional partial capture amount.
211
417
  */
212
- async cancelPreapproval(id) {
418
+ async capturePayment(id, amount) {
213
419
  return this.request(
214
420
  "PUT",
215
- `/preapproval/${id}`,
216
- { status: "cancelled" },
217
- { preapprovalId: id }
421
+ `/v1/payments/${id}`,
422
+ amount !== void 0 ? { capture: true, transaction_amount: amount } : { capture: true },
423
+ { classifyContext: { paymentId: id } }
218
424
  );
219
425
  }
220
426
  /**
221
- * Pause an authorized preapproval. The subscription stops auto-charging but
222
- * can be re-activated. Note: MP only allows pausing subs that are currently
223
- * `authorized` — pending/cancelled subs reject this.
427
+ * Cancel a pending or in_process payment. Once approved, you must use
428
+ * `createRefund` instead.
224
429
  */
225
- async pausePreapproval(id) {
430
+ async cancelPayment(id) {
226
431
  return this.request(
227
432
  "PUT",
228
- `/preapproval/${id}`,
229
- { status: "paused" },
230
- { preapprovalId: id }
433
+ `/v1/payments/${id}`,
434
+ { status: "cancelled" },
435
+ { classifyContext: { paymentId: id } }
231
436
  );
232
437
  }
438
+ // ───────────────────────────────────────────────────────────────────────────
439
+ // Refunds
440
+ // ───────────────────────────────────────────────────────────────────────────
233
441
  /**
234
- * Re-activate a paused preapproval. Charges resume on the next scheduled
235
- * date.
442
+ * Refund a payment fully (omit `amount`) or partially. Idempotency key
443
+ * recommended — refunds can fail mid-flight and you don't want double-refunds
444
+ * on retry.
236
445
  */
237
- async resumePreapproval(id) {
446
+ async createRefund(params) {
447
+ const body = params.amount !== void 0 ? { amount: params.amount } : void 0;
448
+ return this.request(
449
+ "POST",
450
+ `/v1/payments/${params.paymentId}/refunds`,
451
+ body,
452
+ {
453
+ ...params.idempotencyKey ? { idempotencyKey: params.idempotencyKey } : {},
454
+ classifyContext: { paymentId: params.paymentId }
455
+ }
456
+ );
457
+ }
458
+ async listRefunds(paymentId) {
459
+ const res = await this.request(
460
+ "GET",
461
+ `/v1/payments/${paymentId}/refunds`,
462
+ void 0,
463
+ { classifyContext: { paymentId } }
464
+ );
465
+ return Array.isArray(res) ? res : res.refunds ?? [];
466
+ }
467
+ async getRefund(paymentId, refundId) {
468
+ return this.request(
469
+ "GET",
470
+ `/v1/payments/${paymentId}/refunds/${refundId}`,
471
+ void 0,
472
+ { classifyContext: { paymentId } }
473
+ );
474
+ }
475
+ // ───────────────────────────────────────────────────────────────────────────
476
+ // Checkout Pro (Preferences)
477
+ // ───────────────────────────────────────────────────────────────────────────
478
+ /**
479
+ * Create a payment preference for Checkout Pro. Returns `init_point` URL
480
+ * where the buyer completes payment on MP-hosted form. This is the
481
+ * recommended flow when you don't have a card token (most common path for
482
+ * agents — you don't want to handle PCI data).
483
+ *
484
+ * Sandbox: use `sandbox_init_point` instead of `init_point`.
485
+ */
486
+ async createPreference(params) {
487
+ const body = {
488
+ items: params.items.map((it) => ({
489
+ title: it.title,
490
+ quantity: it.quantity,
491
+ unit_price: it.unit_price,
492
+ currency_id: it.currency_id ?? "ARS",
493
+ ...it.description ? { description: it.description } : {},
494
+ ...it.picture_url ? { picture_url: it.picture_url } : {}
495
+ }))
496
+ };
497
+ if (params.payer) body.payer = params.payer;
498
+ if (params.backUrls) body.back_urls = params.backUrls;
499
+ if (params.autoReturn) body.auto_return = params.autoReturn;
500
+ if (params.notificationUrl) body.notification_url = params.notificationUrl;
501
+ if (params.externalReference) body.external_reference = params.externalReference;
502
+ if (params.paymentMethods) body.payment_methods = params.paymentMethods;
503
+ if (params.statementDescriptor)
504
+ body.statement_descriptor = params.statementDescriptor;
505
+ if (params.expires !== void 0) body.expires = params.expires;
506
+ if (params.expirationDateFrom) body.expiration_date_from = params.expirationDateFrom;
507
+ if (params.expirationDateTo) body.expiration_date_to = params.expirationDateTo;
508
+ return this.request("POST", "/checkout/preferences", body);
509
+ }
510
+ async getPreference(id) {
511
+ return this.request("GET", `/checkout/preferences/${id}`);
512
+ }
513
+ async updatePreference(id, patch) {
514
+ return this.request("PUT", `/checkout/preferences/${id}`, patch);
515
+ }
516
+ // ───────────────────────────────────────────────────────────────────────────
517
+ // Customers + Saved Cards
518
+ // ───────────────────────────────────────────────────────────────────────────
519
+ async createCustomer(params) {
520
+ const body = { email: params.email };
521
+ if (params.firstName) body.first_name = params.firstName;
522
+ if (params.lastName) body.last_name = params.lastName;
523
+ if (params.phone) body.phone = { area_code: params.phone.areaCode, number: params.phone.number };
524
+ if (params.identification) body.identification = params.identification;
525
+ if (params.description) body.description = params.description;
526
+ return this.request("POST", "/v1/customers", body, {
527
+ classifyContext: { payerEmail: params.email }
528
+ });
529
+ }
530
+ async getCustomer(id) {
531
+ return this.request("GET", `/v1/customers/${id}`, void 0, {
532
+ classifyContext: { customerId: id }
533
+ });
534
+ }
535
+ /**
536
+ * Search customers. Most common: by email (returns 0 or 1 result).
537
+ * Note: MP's `/v1/customers/search` returns a paginated wrapper, not a flat array.
538
+ */
539
+ async searchCustomers(params = {}) {
540
+ const query = {
541
+ limit: params.limit ?? 10,
542
+ offset: params.offset ?? 0
543
+ };
544
+ if (params.email) query["email"] = params.email;
545
+ return this.request("GET", "/v1/customers/search", void 0, { query });
546
+ }
547
+ async listCustomerCards(customerId) {
548
+ return this.request(
549
+ "GET",
550
+ `/v1/customers/${customerId}/cards`,
551
+ void 0,
552
+ { classifyContext: { customerId } }
553
+ );
554
+ }
555
+ async getCustomerCard(customerId, cardId) {
556
+ return this.request(
557
+ "GET",
558
+ `/v1/customers/${customerId}/cards/${cardId}`,
559
+ void 0,
560
+ { classifyContext: { customerId } }
561
+ );
562
+ }
563
+ async deleteCustomerCard(customerId, cardId) {
564
+ await this.request(
565
+ "DELETE",
566
+ `/v1/customers/${customerId}/cards/${cardId}`,
567
+ void 0,
568
+ { classifyContext: { customerId } }
569
+ );
570
+ }
571
+ // ───────────────────────────────────────────────────────────────────────────
572
+ // Payment Methods + Installments
573
+ // ───────────────────────────────────────────────────────────────────────────
574
+ /** List all payment methods enabled for the account's site (MLA = Argentina). */
575
+ async listPaymentMethods() {
576
+ return this.request("GET", "/v1/payment_methods");
577
+ }
578
+ /**
579
+ * Get installment options for an amount. THE killer AR feature — returns
580
+ * `payer_costs` with `recommended_message` strings like "12 cuotas sin
581
+ * interés de $X" that you should surface verbatim to the user.
582
+ *
583
+ * Pass `bin` (first 6 digits of card) for issuer-specific offers (e.g.,
584
+ * Naranja's interest-free promotions). Without bin, returns generic offers.
585
+ */
586
+ async getInstallments(params) {
587
+ const query = {
588
+ amount: params.amount
589
+ };
590
+ if (params.paymentMethodId) query["payment_method_id"] = params.paymentMethodId;
591
+ if (params.bin) query["bin"] = params.bin;
592
+ if (params.issuerId) query["issuer.id"] = params.issuerId;
593
+ return this.request(
594
+ "GET",
595
+ "/v1/payment_methods/installments",
596
+ void 0,
597
+ { query }
598
+ );
599
+ }
600
+ // ───────────────────────────────────────────────────────────────────────────
601
+ // Account
602
+ // ───────────────────────────────────────────────────────────────────────────
603
+ /** Get info about the account that owns this access token. */
604
+ async getMe() {
605
+ return this.request("GET", "/users/me");
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
+ ];
238
699
  return this.request(
239
700
  "PUT",
240
- `/preapproval/${id}`,
241
- { status: "authorized" },
242
- { preapprovalId: id }
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`
243
713
  );
244
714
  }
245
715
  };
716
+ function deterministicIdempotencyKey(...parts) {
717
+ const payload = parts.filter((p) => p !== void 0 && p !== null).map(String).join("|");
718
+ return createHash("sha256").update(payload).digest("hex").slice(0, 32);
719
+ }
246
720
  var DEFAULT_DESCRIPTIONS = {
721
+ // ── Subscriptions ────────────────────────────────────────────────────────
247
722
  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.",
248
723
  get_subscription_status: "Check the current status of a Mercado Pago subscription. Use this to confirm the customer completed the first payment (status becomes 'authorized') or to inspect the next charge date.",
249
724
  cancel_subscription: "Cancel an active Mercado Pago subscription. After cancellation, MP will not charge the customer again. This action is irreversible \u2014 confirm with the user before calling.",
250
725
  pause_subscription: "Pause an authorized Mercado Pago subscription. Charges stop until resumed. Only works on subscriptions in 'authorized' status.",
251
- resume_subscription: "Resume a paused Mercado Pago subscription. Charges resume on the next scheduled date. Only works on subscriptions in 'paused' status."
726
+ resume_subscription: "Resume a paused Mercado Pago subscription. Charges resume on the next scheduled date. Only works on subscriptions in 'paused' status.",
727
+ // ── Payments ─────────────────────────────────────────────────────────────
728
+ create_payment: "Create a one-time payment. Two flows: (a) with a card token from MP frontend Cardform \u2014 for transparent checkout; (b) without token, for non-card methods like 'account_money', 'rapipago', 'pagofacil'. For most agent flows where you only have a payer email and want to send them a payment link, use create_payment_preference instead (Checkout Pro hosted form). Returns the Payment object with status \u2014 typically 'approved' for account_money and 'pending' for tickets.",
729
+ get_payment: "Fetch a single payment by ID. Use to confirm status after webhook arrives, or to inspect details (status_detail explains rejections).",
730
+ search_payments: "Search payments with filters. Most common: by external_reference (your-system identifier) to find all payments for an order, or by status='approved' to list successful charges in a date range. Returns paginated results.",
731
+ cancel_payment: "Cancel a pending or in_process payment (only works before approval). Once approved, use refund_payment instead. Common use: cancel an unpaid ticket payment that's still pending.",
732
+ capture_payment: "Capture an authorized credit-card payment that was created with capture=false. Use for hold-then-capture flows (e.g., authorize on order, capture on shipment). Optional partial amount.",
733
+ // ── Refunds ──────────────────────────────────────────────────────────────
734
+ refund_payment: "Refund an approved payment. Pass amount for partial refund; omit for full refund. Idempotency key is auto-generated based on paymentId+amount to prevent double-refunds on retries.",
735
+ list_refunds: "List all refunds for a given payment. Returns array of Refund objects. Useful to confirm a refund was processed or to inspect partial-refund history.",
736
+ // ── Checkout Pro ─────────────────────────────────────────────────────────
737
+ create_payment_preference: "Create a Mercado Pago Checkout Pro preference and get back a payment URL (init_point) to send to the customer. THIS is the recommended way for an agent to take a payment when you only have a payer email \u2014 the buyer enters card data on MP's hosted form (no PCI scope needed). Supports cuotas configuration, payment method exclusions, back URLs after success/failure/pending. In sandbox, use sandbox_init_point from the response.",
738
+ get_payment_preference: "Fetch a Checkout Pro preference by ID. Returns the preference config and current init_point URLs. Use to inspect a previously-created link.",
739
+ // ── Customers + Cards ────────────────────────────────────────────────────
740
+ create_customer: "Create a Mercado Pago customer record so the buyer can save cards for future charges. Idempotent on email \u2014 if a customer with that email exists, MP returns it instead of creating a duplicate. Use find_customer_by_email first if you're unsure.",
741
+ find_customer_by_email: "Find an existing customer by email address. Returns the customer object if found, or null. Use before create_customer to avoid duplicate records.",
742
+ list_customer_cards: "List the saved cards for a customer. Returns array with last 4 digits, expiration, payment method (visa, master, naranja, etc.). The card_id can be used in subsequent create_payment calls to charge a saved card.",
743
+ delete_customer_card: "Delete a saved card from a customer. Common use: customer requests removal, or expired card cleanup. Irreversible.",
744
+ // ── Payment Methods + Installments ───────────────────────────────────────
745
+ 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.",
746
+ 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.",
747
+ // ── Account ──────────────────────────────────────────────────────────────
748
+ 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.",
749
+ // ── Saved-card charging (v0.3) ───────────────────────────────────────────
750
+ 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.",
751
+ // ── QR in-store (v0.3) ───────────────────────────────────────────────────
752
+ 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.",
753
+ 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."
252
754
  };
253
755
  function mercadoPagoTools(client, options) {
254
756
  const desc = (name) => options.descriptions?.[name] ?? DEFAULT_DESCRIPTIONS[name];
255
757
  return {
758
+ // ─────────────────────────────────────────────────────────────────────────
759
+ // Subscriptions (v0.1 — kept identical for backward compatibility)
760
+ // ─────────────────────────────────────────────────────────────────────────
256
761
  create_subscription: tool({
257
762
  description: desc("create_subscription"),
258
763
  inputSchema: z.object({
@@ -262,13 +767,7 @@ function mercadoPagoTools(client, options) {
262
767
  reason: z.string().min(3).max(120).describe("Short description shown to the customer at checkout"),
263
768
  external_reference: z.string().optional().describe("Optional id from your system to track this subscription")
264
769
  }),
265
- execute: async ({
266
- customer_email,
267
- amount_ars,
268
- frequency_months,
269
- reason,
270
- external_reference
271
- }) => {
770
+ execute: async ({ customer_email, amount_ars, frequency_months, reason, external_reference }) => {
272
771
  const created = await client.createPreapproval({
273
772
  reason,
274
773
  payerEmail: customer_email,
@@ -338,9 +837,7 @@ function mercadoPagoTools(client, options) {
338
837
  }),
339
838
  pause_subscription: tool({
340
839
  description: desc("pause_subscription"),
341
- inputSchema: z.object({
342
- subscription_id: z.string()
343
- }),
840
+ inputSchema: z.object({ subscription_id: z.string() }),
344
841
  execute: async ({ subscription_id }) => {
345
842
  const paused = await client.pausePreapproval(subscription_id);
346
843
  await options.state.set(subscription_id, { status: paused.status });
@@ -353,9 +850,7 @@ function mercadoPagoTools(client, options) {
353
850
  }),
354
851
  resume_subscription: tool({
355
852
  description: desc("resume_subscription"),
356
- inputSchema: z.object({
357
- subscription_id: z.string()
358
- }),
853
+ inputSchema: z.object({ subscription_id: z.string() }),
359
854
  execute: async ({ subscription_id }) => {
360
855
  const resumed = await client.resumePreapproval(subscription_id);
361
856
  await options.state.set(subscription_id, { status: resumed.status });
@@ -365,6 +860,506 @@ function mercadoPagoTools(client, options) {
365
860
  message: "Subscription resumed. Charges will continue on next scheduled date."
366
861
  };
367
862
  }
863
+ }),
864
+ // ─────────────────────────────────────────────────────────────────────────
865
+ // Payments (v0.2)
866
+ // ─────────────────────────────────────────────────────────────────────────
867
+ create_payment: tool({
868
+ description: desc("create_payment"),
869
+ inputSchema: z.object({
870
+ amount_ars: z.number().positive().describe("Amount in ARS"),
871
+ payment_method_id: z.string().describe("MP payment method id (e.g. 'account_money', 'rapipago', 'visa', 'master', 'naranja')"),
872
+ payer_email: z.string().email().describe("Email of the payer. Cannot equal seller email."),
873
+ token: z.string().optional().describe("Card token from MP frontend Cardform. Required for credit/debit; omit for cash/account_money."),
874
+ installments: z.number().int().min(1).max(24).optional().describe("Number of installments (cuotas). Default 1. Use calculate_installments first to see options."),
875
+ description: z.string().max(255).optional().describe("Short description"),
876
+ external_reference: z.string().optional().describe("Your-system identifier"),
877
+ identification: z.object({
878
+ type: z.enum(["DNI", "CUIT", "CUIL"]),
879
+ number: z.string()
880
+ }).optional().describe("Payer identification \u2014 required for some payment types in AR"),
881
+ statement_descriptor: z.string().max(13).optional().describe("Shows on buyer's card statement (max 13 chars)")
882
+ }),
883
+ execute: async (input) => {
884
+ const payment = await client.createPayment({
885
+ transactionAmount: input.amount_ars,
886
+ paymentMethodId: input.payment_method_id,
887
+ payerEmail: input.payer_email,
888
+ ...input.token !== void 0 ? { token: input.token } : {},
889
+ ...input.installments !== void 0 ? { installments: input.installments } : {},
890
+ ...input.description !== void 0 ? { description: input.description } : {},
891
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
892
+ ...input.identification !== void 0 ? { identification: input.identification } : {},
893
+ ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
894
+ ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
895
+ // Deterministic idempotency key — safe to retry, same inputs always
896
+ // produce the same key (MP dedupes on its side).
897
+ idempotencyKey: deterministicIdempotencyKey(
898
+ "create_payment",
899
+ input.external_reference ?? input.payer_email,
900
+ input.amount_ars,
901
+ input.payment_method_id,
902
+ input.token
903
+ )
904
+ });
905
+ return {
906
+ payment_id: payment.id,
907
+ status: payment.status,
908
+ status_detail: payment.status_detail,
909
+ amount: payment.transaction_amount,
910
+ currency: payment.currency_id,
911
+ installments: payment.installments,
912
+ payment_method: payment.payment_method_id,
913
+ payer_email: payment.payer?.email ?? null,
914
+ external_reference: payment.external_reference,
915
+ date_created: payment.date_created,
916
+ date_approved: payment.date_approved
917
+ };
918
+ }
919
+ }),
920
+ get_payment: tool({
921
+ description: desc("get_payment"),
922
+ inputSchema: z.object({
923
+ payment_id: z.string().describe("The MP payment ID")
924
+ }),
925
+ execute: async ({ payment_id }) => {
926
+ const p = await client.getPayment(payment_id);
927
+ return {
928
+ payment_id: p.id,
929
+ status: p.status,
930
+ status_detail: p.status_detail,
931
+ amount: p.transaction_amount,
932
+ currency: p.currency_id,
933
+ payment_method: p.payment_method_id,
934
+ installments: p.installments,
935
+ payer_email: p.payer?.email ?? null,
936
+ external_reference: p.external_reference,
937
+ date_created: p.date_created,
938
+ date_approved: p.date_approved,
939
+ net_received: p.transaction_details?.net_received_amount ?? null
940
+ };
941
+ }
942
+ }),
943
+ search_payments: tool({
944
+ description: desc("search_payments"),
945
+ inputSchema: z.object({
946
+ external_reference: z.string().optional(),
947
+ status: z.string().optional().describe("'approved' | 'pending' | 'rejected' | 'cancelled' | 'refunded' etc."),
948
+ payer_email: z.string().optional(),
949
+ begin_date: z.string().optional().describe("ISO 8601, e.g. 2026-01-01T00:00:00Z"),
950
+ end_date: z.string().optional().describe("ISO 8601"),
951
+ limit: z.number().int().min(1).max(100).optional().describe("Default 30, max 100"),
952
+ offset: z.number().int().min(0).optional().describe("Pagination offset (default 0)")
953
+ }),
954
+ execute: async (input) => {
955
+ const result = await client.searchPayments({
956
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
957
+ ...input.status !== void 0 ? { status: input.status } : {},
958
+ ...input.payer_email !== void 0 ? { payerEmail: input.payer_email } : {},
959
+ ...input.begin_date !== void 0 ? { beginDate: input.begin_date } : {},
960
+ ...input.end_date !== void 0 ? { endDate: input.end_date } : {},
961
+ ...input.limit !== void 0 ? { limit: input.limit } : {},
962
+ ...input.offset !== void 0 ? { offset: input.offset } : {}
963
+ });
964
+ return {
965
+ total: result.paging.total,
966
+ returned: result.results.length,
967
+ offset: result.paging.offset,
968
+ payments: result.results.map((p) => ({
969
+ payment_id: p.id,
970
+ status: p.status,
971
+ amount: p.transaction_amount,
972
+ currency: p.currency_id,
973
+ payer_email: p.payer?.email ?? null,
974
+ external_reference: p.external_reference,
975
+ date_created: p.date_created
976
+ }))
977
+ };
978
+ }
979
+ }),
980
+ cancel_payment: tool({
981
+ description: desc("cancel_payment"),
982
+ inputSchema: z.object({ payment_id: z.string() }),
983
+ execute: async ({ payment_id }) => {
984
+ const cancelled = await client.cancelPayment(payment_id);
985
+ return {
986
+ payment_id: cancelled.id,
987
+ status: cancelled.status,
988
+ message: "Payment cancelled. If it was already approved, use refund_payment instead."
989
+ };
990
+ }
991
+ }),
992
+ capture_payment: tool({
993
+ description: desc("capture_payment"),
994
+ inputSchema: z.object({
995
+ payment_id: z.string(),
996
+ amount_ars: z.number().positive().optional().describe("Optional partial-capture amount. Omit to capture full authorized amount.")
997
+ }),
998
+ execute: async ({ payment_id, amount_ars }) => {
999
+ const captured = await client.capturePayment(payment_id, amount_ars);
1000
+ return {
1001
+ payment_id: captured.id,
1002
+ status: captured.status,
1003
+ amount: captured.transaction_amount
1004
+ };
1005
+ }
1006
+ }),
1007
+ // ─────────────────────────────────────────────────────────────────────────
1008
+ // Refunds
1009
+ // ─────────────────────────────────────────────────────────────────────────
1010
+ refund_payment: tool({
1011
+ description: desc("refund_payment"),
1012
+ inputSchema: z.object({
1013
+ payment_id: z.string(),
1014
+ amount_ars: z.number().positive().optional().describe("Partial-refund amount in ARS. Omit for full refund.")
1015
+ }),
1016
+ execute: async ({ payment_id, amount_ars }) => {
1017
+ const refund = await client.createRefund({
1018
+ paymentId: payment_id,
1019
+ ...amount_ars !== void 0 ? { amount: amount_ars } : {},
1020
+ idempotencyKey: deterministicIdempotencyKey("refund", payment_id, amount_ars ?? "full")
1021
+ });
1022
+ return {
1023
+ refund_id: refund.id,
1024
+ payment_id: refund.payment_id,
1025
+ amount: refund.amount,
1026
+ status: refund.status,
1027
+ message: amount_ars === void 0 ? "Full refund issued. Funds return to the buyer in 3-10 business days." : `Partial refund of ${amount_ars} ARS issued.`
1028
+ };
1029
+ }
1030
+ }),
1031
+ list_refunds: tool({
1032
+ description: desc("list_refunds"),
1033
+ inputSchema: z.object({ payment_id: z.string() }),
1034
+ execute: async ({ payment_id }) => {
1035
+ const refunds = await client.listRefunds(payment_id);
1036
+ return {
1037
+ payment_id,
1038
+ count: refunds.length,
1039
+ refunds: refunds.map((r) => ({
1040
+ refund_id: r.id,
1041
+ amount: r.amount,
1042
+ status: r.status,
1043
+ date_created: r.date_created
1044
+ }))
1045
+ };
1046
+ }
1047
+ }),
1048
+ // ─────────────────────────────────────────────────────────────────────────
1049
+ // Checkout Pro
1050
+ // ─────────────────────────────────────────────────────────────────────────
1051
+ create_payment_preference: tool({
1052
+ description: desc("create_payment_preference"),
1053
+ inputSchema: z.object({
1054
+ items: z.array(z.object({
1055
+ title: z.string().min(1).max(256),
1056
+ quantity: z.number().int().positive(),
1057
+ unit_price: z.number().positive(),
1058
+ description: z.string().optional(),
1059
+ picture_url: z.string().url().optional()
1060
+ })).min(1).describe("Items being charged. At least one required."),
1061
+ payer_email: z.string().email().optional().describe("Pre-fill the payer email on Checkout Pro form"),
1062
+ external_reference: z.string().optional(),
1063
+ max_installments: z.number().int().min(1).max(24).optional().describe("Limit max cuotas offered. Defaults to MP account config."),
1064
+ statement_descriptor: z.string().max(13).optional(),
1065
+ excluded_payment_types: z.array(z.enum(["credit_card", "debit_card", "ticket", "atm", "bank_transfer"])).optional().describe("Block payment types \u2014 e.g., ['ticket'] to disable Rapipago/Pago F\xE1cil")
1066
+ }),
1067
+ execute: async (input) => {
1068
+ const pref = await client.createPreference({
1069
+ items: input.items.map((it) => ({
1070
+ title: it.title,
1071
+ quantity: it.quantity,
1072
+ unit_price: it.unit_price,
1073
+ currency_id: "ARS",
1074
+ ...it.description !== void 0 ? { description: it.description } : {},
1075
+ ...it.picture_url !== void 0 ? { picture_url: it.picture_url } : {}
1076
+ })),
1077
+ ...input.payer_email !== void 0 ? { payer: { email: input.payer_email } } : {},
1078
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1079
+ ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
1080
+ backUrls: { success: options.backUrl, failure: options.backUrl, pending: options.backUrl },
1081
+ autoReturn: "approved",
1082
+ ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
1083
+ ...input.max_installments !== void 0 || input.excluded_payment_types !== void 0 ? {
1084
+ paymentMethods: {
1085
+ ...input.max_installments !== void 0 ? { installments: input.max_installments } : {},
1086
+ ...input.excluded_payment_types !== void 0 ? { excluded_payment_types: input.excluded_payment_types.map((id) => ({ id })) } : {}
1087
+ }
1088
+ } : {}
1089
+ });
1090
+ return {
1091
+ preference_id: pref.id,
1092
+ init_point_url: pref.init_point ?? null,
1093
+ sandbox_init_point_url: pref.sandbox_init_point ?? null,
1094
+ external_reference: pref.external_reference,
1095
+ date_created: pref.date_created,
1096
+ next_step: "Send init_point_url (or sandbox_init_point_url in sandbox) to the customer. After they pay, MP fires a webhook with the payment_id; use get_payment to confirm status."
1097
+ };
1098
+ }
1099
+ }),
1100
+ get_payment_preference: tool({
1101
+ description: desc("get_payment_preference"),
1102
+ inputSchema: z.object({ preference_id: z.string() }),
1103
+ execute: async ({ preference_id }) => {
1104
+ const pref = await client.getPreference(preference_id);
1105
+ return {
1106
+ preference_id: pref.id,
1107
+ init_point_url: pref.init_point ?? null,
1108
+ sandbox_init_point_url: pref.sandbox_init_point ?? null,
1109
+ external_reference: pref.external_reference,
1110
+ items: pref.items,
1111
+ date_created: pref.date_created
1112
+ };
1113
+ }
1114
+ }),
1115
+ // ─────────────────────────────────────────────────────────────────────────
1116
+ // Customers + Saved Cards
1117
+ // ─────────────────────────────────────────────────────────────────────────
1118
+ create_customer: tool({
1119
+ description: desc("create_customer"),
1120
+ inputSchema: z.object({
1121
+ email: z.string().email(),
1122
+ first_name: z.string().optional(),
1123
+ last_name: z.string().optional(),
1124
+ identification: z.object({
1125
+ type: z.enum(["DNI", "CUIT", "CUIL"]),
1126
+ number: z.string()
1127
+ }).optional(),
1128
+ description: z.string().optional()
1129
+ }),
1130
+ execute: async (input) => {
1131
+ const customer = await client.createCustomer({
1132
+ email: input.email,
1133
+ ...input.first_name !== void 0 ? { firstName: input.first_name } : {},
1134
+ ...input.last_name !== void 0 ? { lastName: input.last_name } : {},
1135
+ ...input.identification !== void 0 ? { identification: input.identification } : {},
1136
+ ...input.description !== void 0 ? { description: input.description } : {}
1137
+ });
1138
+ return {
1139
+ customer_id: customer.id,
1140
+ email: customer.email,
1141
+ first_name: customer.first_name,
1142
+ last_name: customer.last_name,
1143
+ date_created: customer.date_created
1144
+ };
1145
+ }
1146
+ }),
1147
+ find_customer_by_email: tool({
1148
+ description: desc("find_customer_by_email"),
1149
+ inputSchema: z.object({ email: z.string().email() }),
1150
+ execute: async ({ email }) => {
1151
+ const result = await client.searchCustomers({ email, limit: 1 });
1152
+ const customer = result.results[0] ?? null;
1153
+ return customer ? {
1154
+ found: true,
1155
+ customer_id: customer.id,
1156
+ email: customer.email,
1157
+ first_name: customer.first_name,
1158
+ last_name: customer.last_name
1159
+ } : { found: false, customer_id: null };
1160
+ }
1161
+ }),
1162
+ list_customer_cards: tool({
1163
+ description: desc("list_customer_cards"),
1164
+ inputSchema: z.object({ customer_id: z.string() }),
1165
+ execute: async ({ customer_id }) => {
1166
+ const cards = await client.listCustomerCards(customer_id);
1167
+ return {
1168
+ customer_id,
1169
+ count: cards.length,
1170
+ cards: cards.map((c) => ({
1171
+ card_id: c.id,
1172
+ last_four_digits: c.last_four_digits,
1173
+ expiration_month: c.expiration_month,
1174
+ expiration_year: c.expiration_year,
1175
+ payment_method: c.payment_method?.id ?? null,
1176
+ payment_method_name: c.payment_method?.name ?? null
1177
+ }))
1178
+ };
1179
+ }
1180
+ }),
1181
+ delete_customer_card: tool({
1182
+ description: desc("delete_customer_card"),
1183
+ inputSchema: z.object({
1184
+ customer_id: z.string(),
1185
+ card_id: z.string()
1186
+ }),
1187
+ execute: async ({ customer_id, card_id }) => {
1188
+ await client.deleteCustomerCard(customer_id, card_id);
1189
+ return { customer_id, card_id, deleted: true };
1190
+ }
1191
+ }),
1192
+ // ─────────────────────────────────────────────────────────────────────────
1193
+ // Payment Methods + Installments
1194
+ // ─────────────────────────────────────────────────────────────────────────
1195
+ list_payment_methods: tool({
1196
+ description: desc("list_payment_methods"),
1197
+ inputSchema: z.object({}),
1198
+ execute: async () => {
1199
+ const methods = await client.listPaymentMethods();
1200
+ return {
1201
+ count: methods.length,
1202
+ methods: methods.map((m) => ({
1203
+ id: m.id,
1204
+ name: m.name,
1205
+ payment_type: m.payment_type_id,
1206
+ status: m.status,
1207
+ min_amount: m.min_allowed_amount,
1208
+ max_amount: m.max_allowed_amount
1209
+ }))
1210
+ };
1211
+ }
1212
+ }),
1213
+ calculate_installments: tool({
1214
+ description: desc("calculate_installments"),
1215
+ inputSchema: z.object({
1216
+ amount_ars: z.number().positive(),
1217
+ payment_method_id: z.string().optional().describe("E.g. 'visa', 'master', 'naranja'. Omit for all available methods."),
1218
+ bin: z.string().min(6).max(8).optional().describe("First 6-8 digits of card for issuer-specific offers (e.g., Naranja interest-free promotions)")
1219
+ }),
1220
+ execute: async (input) => {
1221
+ const offers = await client.getInstallments({
1222
+ amount: input.amount_ars,
1223
+ ...input.payment_method_id !== void 0 ? { paymentMethodId: input.payment_method_id } : {},
1224
+ ...input.bin !== void 0 ? { bin: input.bin } : {}
1225
+ });
1226
+ return {
1227
+ amount: input.amount_ars,
1228
+ offers: offers.map((o) => ({
1229
+ payment_method_id: o.payment_method_id,
1230
+ payment_type_id: o.payment_type_id,
1231
+ issuer_name: o.issuer?.name ?? null,
1232
+ options: o.payer_costs.map((pc) => ({
1233
+ installments: pc.installments,
1234
+ installment_amount: pc.installment_amount,
1235
+ total_amount: pc.total_amount,
1236
+ installment_rate: pc.installment_rate,
1237
+ recommended_message: pc.recommended_message
1238
+ }))
1239
+ }))
1240
+ };
1241
+ }
1242
+ }),
1243
+ // ─────────────────────────────────────────────────────────────────────────
1244
+ // Account
1245
+ // ─────────────────────────────────────────────────────────────────────────
1246
+ get_account_info: tool({
1247
+ description: desc("get_account_info"),
1248
+ inputSchema: z.object({}),
1249
+ execute: async () => {
1250
+ const me = await client.getMe();
1251
+ return {
1252
+ account_id: me.id,
1253
+ email: me.email,
1254
+ nickname: me.nickname,
1255
+ country_id: me.country_id,
1256
+ site_id: me.site_id,
1257
+ user_type: me.user_type
1258
+ };
1259
+ }
1260
+ }),
1261
+ // ─────────────────────────────────────────────────────────────────────────
1262
+ // Saved-card charging (v0.3)
1263
+ // ─────────────────────────────────────────────────────────────────────────
1264
+ charge_saved_card: tool({
1265
+ description: desc("charge_saved_card"),
1266
+ inputSchema: z.object({
1267
+ customer_id: z.string().describe("MP customer id (from create_customer / find_customer_by_email)"),
1268
+ card_id: z.string().describe("Saved card id (from list_customer_cards)"),
1269
+ 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."),
1270
+ amount_ars: z.number().positive(),
1271
+ description: z.string().min(1).max(255),
1272
+ installments: z.number().int().min(1).max(24).optional().describe("Default 1. Use calculate_installments first to pick a valid count."),
1273
+ external_reference: z.string().optional(),
1274
+ statement_descriptor: z.string().max(13).optional()
1275
+ }),
1276
+ execute: async (input) => {
1277
+ const payment = await client.chargeSavedCard({
1278
+ customerId: input.customer_id,
1279
+ cardId: input.card_id,
1280
+ securityCode: input.security_code,
1281
+ amount: input.amount_ars,
1282
+ description: input.description,
1283
+ ...input.installments !== void 0 ? { installments: input.installments } : {},
1284
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1285
+ ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
1286
+ idempotencyKey: deterministicIdempotencyKey(
1287
+ "charge_saved_card",
1288
+ input.card_id,
1289
+ input.amount_ars,
1290
+ input.external_reference
1291
+ )
1292
+ });
1293
+ return {
1294
+ payment_id: payment.id,
1295
+ status: payment.status,
1296
+ status_detail: payment.status_detail,
1297
+ amount: payment.transaction_amount,
1298
+ installments: payment.installments,
1299
+ payment_method: payment.payment_method_id,
1300
+ customer_id: input.customer_id,
1301
+ card_id: input.card_id,
1302
+ external_reference: payment.external_reference,
1303
+ date_approved: payment.date_approved
1304
+ };
1305
+ }
1306
+ }),
1307
+ // ─────────────────────────────────────────────────────────────────────────
1308
+ // QR in-store (v0.3)
1309
+ // ─────────────────────────────────────────────────────────────────────────
1310
+ create_qr_payment: tool({
1311
+ description: desc("create_qr_payment"),
1312
+ inputSchema: z.object({
1313
+ external_pos_id: z.string().describe("Pre-configured POS external_id from MP dashboard. Required."),
1314
+ amount_ars: z.number().positive(),
1315
+ title: z.string().min(1).max(80).describe("Display title shown when scanning"),
1316
+ description: z.string().max(255).optional(),
1317
+ external_reference: z.string().optional(),
1318
+ notification_url: z.string().url().optional().describe("Webhook URL \u2014 falls back to dashboard config if omitted"),
1319
+ expires_in_seconds: z.number().int().min(60).max(3600).optional().describe("Default 600 (10 min)")
1320
+ }),
1321
+ execute: async (input) => {
1322
+ const QRCode = (await import('qrcode')).default;
1323
+ const me = await client.getMe();
1324
+ const userId = String(me.id);
1325
+ const expiresAt = new Date(
1326
+ Date.now() + (input.expires_in_seconds ?? 600) * 1e3
1327
+ ).toISOString();
1328
+ const qr = await client.createQrPayment(userId, {
1329
+ externalPosId: input.external_pos_id,
1330
+ totalAmount: input.amount_ars,
1331
+ title: input.title,
1332
+ ...input.description !== void 0 ? { description: input.description } : {},
1333
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1334
+ ...input.notification_url !== void 0 ? { notificationUrl: input.notification_url } : {},
1335
+ expirationDate: expiresAt
1336
+ });
1337
+ const qrDataUrl = await QRCode.toDataURL(qr.qr_data, {
1338
+ errorCorrectionLevel: "M",
1339
+ margin: 1,
1340
+ width: 512
1341
+ });
1342
+ return {
1343
+ in_store_order_id: qr.in_store_order_id,
1344
+ qr_data: qr.qr_data,
1345
+ qr_data_url: qrDataUrl,
1346
+ expires_at: expiresAt,
1347
+ external_pos_id: input.external_pos_id,
1348
+ amount: input.amount_ars,
1349
+ 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."
1350
+ };
1351
+ }
1352
+ }),
1353
+ cancel_qr_payment: tool({
1354
+ description: desc("cancel_qr_payment"),
1355
+ inputSchema: z.object({
1356
+ external_pos_id: z.string()
1357
+ }),
1358
+ execute: async ({ external_pos_id }) => {
1359
+ const me = await client.getMe();
1360
+ await client.cancelQrPayment(String(me.id), external_pos_id);
1361
+ return { external_pos_id, cancelled: true };
1362
+ }
368
1363
  })
369
1364
  };
370
1365
  }
@@ -429,6 +1424,162 @@ var WebhookBodySchema = z.object({
429
1424
  id: z.union([z.string(), z.number()]).optional(),
430
1425
  live_mode: z.boolean().optional()
431
1426
  }).passthrough();
1427
+ var PaymentStatusSchema = z.union([
1428
+ z.literal("pending"),
1429
+ z.literal("approved"),
1430
+ z.literal("authorized"),
1431
+ z.literal("in_process"),
1432
+ z.literal("in_mediation"),
1433
+ z.literal("rejected"),
1434
+ z.literal("cancelled"),
1435
+ z.literal("refunded"),
1436
+ z.literal("charged_back"),
1437
+ z.string()
1438
+ ]);
1439
+ var PaymentSchema = z.object({
1440
+ id: z.union([z.string(), z.number()]).transform(String),
1441
+ status: PaymentStatusSchema,
1442
+ status_detail: z.string().nullable().optional(),
1443
+ date_created: z.string().nullable().optional(),
1444
+ date_approved: z.string().nullable().optional(),
1445
+ date_last_updated: z.string().nullable().optional(),
1446
+ transaction_amount: z.number(),
1447
+ currency_id: z.string(),
1448
+ installments: z.number().int().nullable().optional(),
1449
+ payment_method_id: z.string().nullable().optional(),
1450
+ payment_type_id: z.string().nullable().optional(),
1451
+ external_reference: z.string().nullable().optional(),
1452
+ description: z.string().nullable().optional(),
1453
+ payer: z.object({
1454
+ id: z.union([z.string(), z.number()]).optional(),
1455
+ email: z.string().nullable().optional(),
1456
+ identification: z.object({
1457
+ type: z.string().nullable().optional(),
1458
+ number: z.string().nullable().optional()
1459
+ }).nullable().optional()
1460
+ }).passthrough().optional(),
1461
+ transaction_details: z.object({
1462
+ net_received_amount: z.number().nullable().optional(),
1463
+ total_paid_amount: z.number().nullable().optional(),
1464
+ installment_amount: z.number().nullable().optional()
1465
+ }).passthrough().optional()
1466
+ }).passthrough();
1467
+ z.object({
1468
+ paging: z.object({
1469
+ total: z.number(),
1470
+ limit: z.number(),
1471
+ offset: z.number()
1472
+ }),
1473
+ results: z.array(PaymentSchema)
1474
+ });
1475
+ z.object({
1476
+ id: z.union([z.string(), z.number()]).transform(String),
1477
+ payment_id: z.union([z.string(), z.number()]).transform(String),
1478
+ amount: z.number(),
1479
+ source: z.object({
1480
+ id: z.string().nullable().optional(),
1481
+ name: z.string().nullable().optional(),
1482
+ type: z.string().nullable().optional()
1483
+ }).nullable().optional(),
1484
+ date_created: z.string().nullable().optional(),
1485
+ status: z.string().nullable().optional()
1486
+ }).passthrough();
1487
+ var PreferenceItemSchema = z.object({
1488
+ id: z.string().optional(),
1489
+ title: z.string(),
1490
+ description: z.string().optional(),
1491
+ picture_url: z.string().url().optional(),
1492
+ category_id: z.string().optional(),
1493
+ quantity: z.number().int().positive(),
1494
+ unit_price: z.number().positive(),
1495
+ currency_id: CurrencyIdSchema.optional()
1496
+ });
1497
+ z.object({
1498
+ id: z.string(),
1499
+ init_point: z.string().url().optional(),
1500
+ sandbox_init_point: z.string().url().optional(),
1501
+ client_id: z.union([z.string(), z.number()]).optional(),
1502
+ collector_id: z.union([z.string(), z.number()]).optional(),
1503
+ items: z.array(PreferenceItemSchema).optional(),
1504
+ external_reference: z.string().nullable().optional(),
1505
+ date_created: z.string().nullable().optional(),
1506
+ expires: z.boolean().optional(),
1507
+ expiration_date_from: z.string().nullable().optional(),
1508
+ expiration_date_to: z.string().nullable().optional()
1509
+ }).passthrough();
1510
+ z.object({
1511
+ id: z.string(),
1512
+ email: z.string(),
1513
+ first_name: z.string().nullable().optional(),
1514
+ last_name: z.string().nullable().optional(),
1515
+ phone: z.object({ area_code: z.string().nullable().optional(), number: z.string().nullable().optional() }).nullable().optional(),
1516
+ identification: z.object({ type: z.string().nullable().optional(), number: z.string().nullable().optional() }).nullable().optional(),
1517
+ date_created: z.string().nullable().optional(),
1518
+ date_last_updated: z.string().nullable().optional(),
1519
+ description: z.string().nullable().optional()
1520
+ }).passthrough();
1521
+ z.object({
1522
+ id: z.string(),
1523
+ customer_id: z.string(),
1524
+ expiration_month: z.number().int().nullable().optional(),
1525
+ expiration_year: z.number().int().nullable().optional(),
1526
+ first_six_digits: z.string().nullable().optional(),
1527
+ last_four_digits: z.string().nullable().optional(),
1528
+ payment_method: z.object({
1529
+ id: z.string().nullable().optional(),
1530
+ name: z.string().nullable().optional(),
1531
+ payment_type_id: z.string().nullable().optional()
1532
+ }).nullable().optional(),
1533
+ date_created: z.string().nullable().optional()
1534
+ }).passthrough();
1535
+ z.object({
1536
+ id: z.string(),
1537
+ name: z.string(),
1538
+ payment_type_id: z.string(),
1539
+ status: z.string(),
1540
+ thumbnail: z.string().nullable().optional(),
1541
+ secure_thumbnail: z.string().nullable().optional(),
1542
+ min_allowed_amount: z.number().nullable().optional(),
1543
+ max_allowed_amount: z.number().nullable().optional()
1544
+ }).passthrough();
1545
+ z.object({
1546
+ payment_method_id: z.string(),
1547
+ payment_type_id: z.string(),
1548
+ issuer: z.object({
1549
+ id: z.union([z.string(), z.number()]).optional(),
1550
+ name: z.string().nullable().optional()
1551
+ }).nullable().optional(),
1552
+ payer_costs: z.array(
1553
+ z.object({
1554
+ installments: z.number().int(),
1555
+ installment_rate: z.number(),
1556
+ discount_rate: z.number().nullable().optional(),
1557
+ installment_amount: z.number(),
1558
+ total_amount: z.number(),
1559
+ recommended_message: z.string().nullable().optional()
1560
+ }).passthrough()
1561
+ )
1562
+ }).passthrough();
1563
+ z.object({
1564
+ in_store_order_id: z.string(),
1565
+ qr_data: z.string()
1566
+ }).passthrough();
1567
+ z.object({
1568
+ id: z.string(),
1569
+ status: z.string().optional(),
1570
+ date_due: z.string().optional(),
1571
+ card_id: z.string().optional(),
1572
+ cardholder: z.unknown().optional()
1573
+ }).passthrough();
1574
+ z.object({
1575
+ id: z.union([z.string(), z.number()]).transform(String),
1576
+ email: z.string().nullable().optional(),
1577
+ nickname: z.string().nullable().optional(),
1578
+ country_id: z.string().nullable().optional(),
1579
+ site_id: z.string().nullable().optional(),
1580
+ user_type: z.string().nullable().optional(),
1581
+ status: z.object({ user_type: z.string().nullable().optional() }).passthrough().nullable().optional()
1582
+ }).passthrough();
432
1583
 
433
1584
  // src/webhook.ts
434
1585
  function parseWebhookEvent(body, searchParams) {
@@ -460,6 +1611,6 @@ function verifyWebhookSignature(params) {
460
1611
  return timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
461
1612
  }
462
1613
 
463
- export { InMemoryStateAdapter, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, MercadoPagoError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, classifyError, mercadoPagoTools, parseWebhookEvent, verifyWebhookSignature };
1614
+ export { InMemoryStateAdapter, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, classifyError, mercadoPagoTools, parseWebhookEvent, verifyWebhookSignature };
464
1615
  //# sourceMappingURL=index.js.map
465
1616
  //# sourceMappingURL=index.js.map