@ar-agents/mercadopago 0.1.0 → 0.2.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
@@ -143,31 +143,48 @@ var MercadoPagoClient = class {
143
143
  this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
144
144
  this.fetchImpl = options.fetch;
145
145
  }
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
- }
146
+ async request(method, path, body, options) {
147
+ const headers = {
148
+ Authorization: `Bearer ${this.accessToken}`,
149
+ "Content-Type": "application/json"
153
150
  };
151
+ if (options?.idempotencyKey) {
152
+ headers["X-Idempotency-Key"] = options.idempotencyKey;
153
+ }
154
+ const init = { method, headers };
154
155
  if (body !== void 0) {
155
156
  init.body = JSON.stringify(body);
156
157
  }
158
+ let url = `${this.baseUrl}${path}`;
159
+ if (options?.query) {
160
+ const search = new URLSearchParams();
161
+ for (const [k, v] of Object.entries(options.query)) {
162
+ if (v !== void 0 && v !== null && v !== "") {
163
+ search.set(k, String(v));
164
+ }
165
+ }
166
+ const qs = search.toString();
167
+ if (qs) url += `?${qs}`;
168
+ }
157
169
  const fetchFn = this.fetchImpl ?? globalThis.fetch;
158
- const res = await fetchFn(`${this.baseUrl}${path}`, init);
170
+ const res = await fetchFn(url, init);
159
171
  if (!res.ok) {
160
172
  let parsed;
161
- const text = await res.text();
173
+ const text2 = await res.text();
162
174
  try {
163
- parsed = JSON.parse(text);
175
+ parsed = JSON.parse(text2);
164
176
  } catch {
165
- parsed = text;
177
+ parsed = text2;
166
178
  }
167
- throw classifyError(res.status, path, parsed, classifyContext);
179
+ throw classifyError(res.status, path, parsed, options?.classifyContext);
168
180
  }
169
- return await res.json();
181
+ const text = await res.text();
182
+ if (!text) return void 0;
183
+ return JSON.parse(text);
170
184
  }
185
+ // ───────────────────────────────────────────────────────────────────────────
186
+ // Subscriptions (Preapprovals) — v0.1 surface, kept stable
187
+ // ───────────────────────────────────────────────────────────────────────────
171
188
  /**
172
189
  * Create a recurring subscription (preapproval). The returned `init_point`
173
190
  * URL is where the buyer must complete the FIRST payment with their card +
@@ -189,70 +206,335 @@ var MercadoPagoClient = class {
189
206
  currency_id: params.currency
190
207
  }
191
208
  },
192
- { payerEmail: params.payerEmail }
209
+ { classifyContext: { payerEmail: params.payerEmail } }
210
+ );
211
+ }
212
+ async getPreapproval(id) {
213
+ return this.request("GET", `/preapproval/${id}`, void 0, {
214
+ classifyContext: { preapprovalId: id }
215
+ });
216
+ }
217
+ async cancelPreapproval(id) {
218
+ return this.request(
219
+ "PUT",
220
+ `/preapproval/${id}`,
221
+ { status: "cancelled" },
222
+ { classifyContext: { preapprovalId: id } }
193
223
  );
194
224
  }
225
+ async pausePreapproval(id) {
226
+ return this.request(
227
+ "PUT",
228
+ `/preapproval/${id}`,
229
+ { status: "paused" },
230
+ { classifyContext: { preapprovalId: id } }
231
+ );
232
+ }
233
+ async resumePreapproval(id) {
234
+ return this.request(
235
+ "PUT",
236
+ `/preapproval/${id}`,
237
+ { status: "authorized" },
238
+ { classifyContext: { preapprovalId: id } }
239
+ );
240
+ }
241
+ // ───────────────────────────────────────────────────────────────────────────
242
+ // Payments (v0.2)
243
+ // ───────────────────────────────────────────────────────────────────────────
195
244
  /**
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.
245
+ * Create a payment. Two main flows:
246
+ * - **Card payment**: pass `token` (from MP frontend Cardform) + payment_method_id.
247
+ * - **Account money / cash**: omit token, pass payment_method_id like "account_money", "rapipago", "pagofacil".
248
+ *
249
+ * For credit card payments where you don't have a card token (i.e., you only
250
+ * have a payer email and want to send them a payment link), use
251
+ * `createPreference` (Checkout Pro) instead.
252
+ *
253
+ * Idempotency: pass `idempotencyKey` to safely retry. Required for production
254
+ * to dedupe network-failed requests.
199
255
  */
200
- async getPreapproval(id) {
256
+ async createPayment(params) {
257
+ const body = {
258
+ transaction_amount: params.transactionAmount,
259
+ payment_method_id: params.paymentMethodId,
260
+ payer: {
261
+ email: params.payerEmail,
262
+ ...params.identification ? { identification: params.identification } : {}
263
+ }
264
+ };
265
+ if (params.installments !== void 0) body.installments = params.installments;
266
+ if (params.token !== void 0) body.token = params.token;
267
+ if (params.description !== void 0) body.description = params.description;
268
+ if (params.externalReference !== void 0) body.external_reference = params.externalReference;
269
+ if (params.notificationUrl !== void 0) body.notification_url = params.notificationUrl;
270
+ if (params.statementDescriptor !== void 0)
271
+ body.statement_descriptor = params.statementDescriptor;
272
+ if (params.capture !== void 0) body.capture = params.capture;
273
+ if (params.additionalInfo !== void 0) body.additional_info = params.additionalInfo;
274
+ return this.request("POST", "/v1/payments", body, {
275
+ ...params.idempotencyKey ? { idempotencyKey: params.idempotencyKey } : {},
276
+ classifyContext: { payerEmail: params.payerEmail }
277
+ });
278
+ }
279
+ /** Fetch a payment by ID. */
280
+ async getPayment(id) {
281
+ return this.request("GET", `/v1/payments/${id}`, void 0, {
282
+ classifyContext: { paymentId: id }
283
+ });
284
+ }
285
+ /**
286
+ * Search payments with filters. Common: by external_reference (your-system
287
+ * id), by status, by date range. Pagination via offset + limit (max 100).
288
+ */
289
+ async searchPayments(params = {}) {
290
+ const query = {
291
+ limit: params.limit ?? 30,
292
+ offset: params.offset ?? 0
293
+ };
294
+ if (params.externalReference) query["external_reference"] = params.externalReference;
295
+ if (params.status) query["status"] = params.status;
296
+ if (params.payerEmail) query["payer.email"] = params.payerEmail;
297
+ if (params.beginDate) query["begin_date"] = params.beginDate;
298
+ if (params.endDate) query["end_date"] = params.endDate;
299
+ if (params.sort) query["sort"] = params.sort;
300
+ if (params.criteria) query["criteria"] = params.criteria;
201
301
  return this.request(
202
302
  "GET",
203
- `/preapproval/${id}`,
303
+ "/v1/payments/search",
204
304
  void 0,
205
- { preapprovalId: id }
305
+ { query }
206
306
  );
207
307
  }
208
308
  /**
209
- * Cancel an active preapproval. Irreversible: MP will not charge the buyer
210
- * again and the subscription cannot be reactivated.
309
+ * Capture a previously authorized payment. Only works for credit-card
310
+ * payments created with `capture: false`. Optional partial capture amount.
211
311
  */
212
- async cancelPreapproval(id) {
312
+ async capturePayment(id, amount) {
213
313
  return this.request(
214
314
  "PUT",
215
- `/preapproval/${id}`,
216
- { status: "cancelled" },
217
- { preapprovalId: id }
315
+ `/v1/payments/${id}`,
316
+ amount !== void 0 ? { capture: true, transaction_amount: amount } : { capture: true },
317
+ { classifyContext: { paymentId: id } }
218
318
  );
219
319
  }
220
320
  /**
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.
321
+ * Cancel a pending or in_process payment. Once approved, you must use
322
+ * `createRefund` instead.
224
323
  */
225
- async pausePreapproval(id) {
324
+ async cancelPayment(id) {
226
325
  return this.request(
227
326
  "PUT",
228
- `/preapproval/${id}`,
229
- { status: "paused" },
230
- { preapprovalId: id }
327
+ `/v1/payments/${id}`,
328
+ { status: "cancelled" },
329
+ { classifyContext: { paymentId: id } }
231
330
  );
232
331
  }
332
+ // ───────────────────────────────────────────────────────────────────────────
333
+ // Refunds
334
+ // ───────────────────────────────────────────────────────────────────────────
233
335
  /**
234
- * Re-activate a paused preapproval. Charges resume on the next scheduled
235
- * date.
336
+ * Refund a payment fully (omit `amount`) or partially. Idempotency key
337
+ * recommended — refunds can fail mid-flight and you don't want double-refunds
338
+ * on retry.
236
339
  */
237
- async resumePreapproval(id) {
340
+ async createRefund(params) {
341
+ const body = params.amount !== void 0 ? { amount: params.amount } : void 0;
238
342
  return this.request(
239
- "PUT",
240
- `/preapproval/${id}`,
241
- { status: "authorized" },
242
- { preapprovalId: id }
343
+ "POST",
344
+ `/v1/payments/${params.paymentId}/refunds`,
345
+ body,
346
+ {
347
+ ...params.idempotencyKey ? { idempotencyKey: params.idempotencyKey } : {},
348
+ classifyContext: { paymentId: params.paymentId }
349
+ }
350
+ );
351
+ }
352
+ async listRefunds(paymentId) {
353
+ const res = await this.request(
354
+ "GET",
355
+ `/v1/payments/${paymentId}/refunds`,
356
+ void 0,
357
+ { classifyContext: { paymentId } }
358
+ );
359
+ return Array.isArray(res) ? res : res.refunds ?? [];
360
+ }
361
+ async getRefund(paymentId, refundId) {
362
+ return this.request(
363
+ "GET",
364
+ `/v1/payments/${paymentId}/refunds/${refundId}`,
365
+ void 0,
366
+ { classifyContext: { paymentId } }
243
367
  );
244
368
  }
369
+ // ───────────────────────────────────────────────────────────────────────────
370
+ // Checkout Pro (Preferences)
371
+ // ───────────────────────────────────────────────────────────────────────────
372
+ /**
373
+ * Create a payment preference for Checkout Pro. Returns `init_point` URL
374
+ * where the buyer completes payment on MP-hosted form. This is the
375
+ * recommended flow when you don't have a card token (most common path for
376
+ * agents — you don't want to handle PCI data).
377
+ *
378
+ * Sandbox: use `sandbox_init_point` instead of `init_point`.
379
+ */
380
+ async createPreference(params) {
381
+ const body = {
382
+ items: params.items.map((it) => ({
383
+ title: it.title,
384
+ quantity: it.quantity,
385
+ unit_price: it.unit_price,
386
+ currency_id: it.currency_id ?? "ARS",
387
+ ...it.description ? { description: it.description } : {},
388
+ ...it.picture_url ? { picture_url: it.picture_url } : {}
389
+ }))
390
+ };
391
+ if (params.payer) body.payer = params.payer;
392
+ if (params.backUrls) body.back_urls = params.backUrls;
393
+ if (params.autoReturn) body.auto_return = params.autoReturn;
394
+ if (params.notificationUrl) body.notification_url = params.notificationUrl;
395
+ if (params.externalReference) body.external_reference = params.externalReference;
396
+ if (params.paymentMethods) body.payment_methods = params.paymentMethods;
397
+ if (params.statementDescriptor)
398
+ body.statement_descriptor = params.statementDescriptor;
399
+ if (params.expires !== void 0) body.expires = params.expires;
400
+ if (params.expirationDateFrom) body.expiration_date_from = params.expirationDateFrom;
401
+ if (params.expirationDateTo) body.expiration_date_to = params.expirationDateTo;
402
+ return this.request("POST", "/checkout/preferences", body);
403
+ }
404
+ async getPreference(id) {
405
+ return this.request("GET", `/checkout/preferences/${id}`);
406
+ }
407
+ async updatePreference(id, patch) {
408
+ return this.request("PUT", `/checkout/preferences/${id}`, patch);
409
+ }
410
+ // ───────────────────────────────────────────────────────────────────────────
411
+ // Customers + Saved Cards
412
+ // ───────────────────────────────────────────────────────────────────────────
413
+ async createCustomer(params) {
414
+ const body = { email: params.email };
415
+ if (params.firstName) body.first_name = params.firstName;
416
+ if (params.lastName) body.last_name = params.lastName;
417
+ if (params.phone) body.phone = { area_code: params.phone.areaCode, number: params.phone.number };
418
+ if (params.identification) body.identification = params.identification;
419
+ if (params.description) body.description = params.description;
420
+ return this.request("POST", "/v1/customers", body, {
421
+ classifyContext: { payerEmail: params.email }
422
+ });
423
+ }
424
+ async getCustomer(id) {
425
+ return this.request("GET", `/v1/customers/${id}`, void 0, {
426
+ classifyContext: { customerId: id }
427
+ });
428
+ }
429
+ /**
430
+ * Search customers. Most common: by email (returns 0 or 1 result).
431
+ * Note: MP's `/v1/customers/search` returns a paginated wrapper, not a flat array.
432
+ */
433
+ async searchCustomers(params = {}) {
434
+ const query = {
435
+ limit: params.limit ?? 10,
436
+ offset: params.offset ?? 0
437
+ };
438
+ if (params.email) query["email"] = params.email;
439
+ return this.request("GET", "/v1/customers/search", void 0, { query });
440
+ }
441
+ async listCustomerCards(customerId) {
442
+ return this.request(
443
+ "GET",
444
+ `/v1/customers/${customerId}/cards`,
445
+ void 0,
446
+ { classifyContext: { customerId } }
447
+ );
448
+ }
449
+ async getCustomerCard(customerId, cardId) {
450
+ return this.request(
451
+ "GET",
452
+ `/v1/customers/${customerId}/cards/${cardId}`,
453
+ void 0,
454
+ { classifyContext: { customerId } }
455
+ );
456
+ }
457
+ async deleteCustomerCard(customerId, cardId) {
458
+ await this.request(
459
+ "DELETE",
460
+ `/v1/customers/${customerId}/cards/${cardId}`,
461
+ void 0,
462
+ { classifyContext: { customerId } }
463
+ );
464
+ }
465
+ // ───────────────────────────────────────────────────────────────────────────
466
+ // Payment Methods + Installments
467
+ // ───────────────────────────────────────────────────────────────────────────
468
+ /** List all payment methods enabled for the account's site (MLA = Argentina). */
469
+ async listPaymentMethods() {
470
+ return this.request("GET", "/v1/payment_methods");
471
+ }
472
+ /**
473
+ * Get installment options for an amount. THE killer AR feature — returns
474
+ * `payer_costs` with `recommended_message` strings like "12 cuotas sin
475
+ * interés de $X" that you should surface verbatim to the user.
476
+ *
477
+ * Pass `bin` (first 6 digits of card) for issuer-specific offers (e.g.,
478
+ * Naranja's interest-free promotions). Without bin, returns generic offers.
479
+ */
480
+ async getInstallments(params) {
481
+ const query = {
482
+ amount: params.amount
483
+ };
484
+ if (params.paymentMethodId) query["payment_method_id"] = params.paymentMethodId;
485
+ if (params.bin) query["bin"] = params.bin;
486
+ if (params.issuerId) query["issuer.id"] = params.issuerId;
487
+ return this.request(
488
+ "GET",
489
+ "/v1/payment_methods/installments",
490
+ void 0,
491
+ { query }
492
+ );
493
+ }
494
+ // ───────────────────────────────────────────────────────────────────────────
495
+ // Account
496
+ // ───────────────────────────────────────────────────────────────────────────
497
+ /** Get info about the account that owns this access token. */
498
+ async getMe() {
499
+ return this.request("GET", "/users/me");
500
+ }
245
501
  };
246
502
  var DEFAULT_DESCRIPTIONS = {
503
+ // ── Subscriptions ────────────────────────────────────────────────────────
247
504
  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
505
  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
506
  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
507
  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."
508
+ resume_subscription: "Resume a paused Mercado Pago subscription. Charges resume on the next scheduled date. Only works on subscriptions in 'paused' status.",
509
+ // ── Payments ─────────────────────────────────────────────────────────────
510
+ 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.",
511
+ get_payment: "Fetch a single payment by ID. Use to confirm status after webhook arrives, or to inspect details (status_detail explains rejections).",
512
+ 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.",
513
+ 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.",
514
+ 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.",
515
+ // ── Refunds ──────────────────────────────────────────────────────────────
516
+ 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.",
517
+ 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.",
518
+ // ── Checkout Pro ─────────────────────────────────────────────────────────
519
+ 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.",
520
+ 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.",
521
+ // ── Customers + Cards ────────────────────────────────────────────────────
522
+ 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.",
523
+ 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.",
524
+ 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.",
525
+ delete_customer_card: "Delete a saved card from a customer. Common use: customer requests removal, or expired card cleanup. Irreversible.",
526
+ // ── Payment Methods + Installments ───────────────────────────────────────
527
+ list_payment_methods: "List all payment methods enabled for the seller's MP account (visa, master, naranja, naranja_x, cabal, account_money, rapipago, pagofacil, etc.). Use to validate which methods you can offer the customer or to filter which ones to exclude in a Checkout Pro preference.",
528
+ calculate_installments: "Calculate cuotas (installments) options for a given amount. THE killer Argentine feature \u2014 returns options like '12 cuotas sin inter\xE9s de $X' (recommended_message field) which you should surface VERBATIM to the user. Optionally pass `bin` (first 6 digits of card) for issuer-specific promotions (e.g., Naranja's interest-free deals). Use before create_payment to let the user pick installments knowingly.",
529
+ // ── Account ──────────────────────────────────────────────────────────────
530
+ get_account_info: "Get info about the Mercado Pago account that owns the access token: site_id (MLA=Argentina), country_id, user_type (registered, partial, etc.). Useful to verify the agent is connected to the right account before taking actions."
252
531
  };
253
532
  function mercadoPagoTools(client, options) {
254
533
  const desc = (name) => options.descriptions?.[name] ?? DEFAULT_DESCRIPTIONS[name];
255
534
  return {
535
+ // ─────────────────────────────────────────────────────────────────────────
536
+ // Subscriptions (v0.1 — kept identical for backward compatibility)
537
+ // ─────────────────────────────────────────────────────────────────────────
256
538
  create_subscription: tool({
257
539
  description: desc("create_subscription"),
258
540
  inputSchema: z.object({
@@ -262,13 +544,7 @@ function mercadoPagoTools(client, options) {
262
544
  reason: z.string().min(3).max(120).describe("Short description shown to the customer at checkout"),
263
545
  external_reference: z.string().optional().describe("Optional id from your system to track this subscription")
264
546
  }),
265
- execute: async ({
266
- customer_email,
267
- amount_ars,
268
- frequency_months,
269
- reason,
270
- external_reference
271
- }) => {
547
+ execute: async ({ customer_email, amount_ars, frequency_months, reason, external_reference }) => {
272
548
  const created = await client.createPreapproval({
273
549
  reason,
274
550
  payerEmail: customer_email,
@@ -338,9 +614,7 @@ function mercadoPagoTools(client, options) {
338
614
  }),
339
615
  pause_subscription: tool({
340
616
  description: desc("pause_subscription"),
341
- inputSchema: z.object({
342
- subscription_id: z.string()
343
- }),
617
+ inputSchema: z.object({ subscription_id: z.string() }),
344
618
  execute: async ({ subscription_id }) => {
345
619
  const paused = await client.pausePreapproval(subscription_id);
346
620
  await options.state.set(subscription_id, { status: paused.status });
@@ -353,9 +627,7 @@ function mercadoPagoTools(client, options) {
353
627
  }),
354
628
  resume_subscription: tool({
355
629
  description: desc("resume_subscription"),
356
- inputSchema: z.object({
357
- subscription_id: z.string()
358
- }),
630
+ inputSchema: z.object({ subscription_id: z.string() }),
359
631
  execute: async ({ subscription_id }) => {
360
632
  const resumed = await client.resumePreapproval(subscription_id);
361
633
  await options.state.set(subscription_id, { status: resumed.status });
@@ -365,6 +637,396 @@ function mercadoPagoTools(client, options) {
365
637
  message: "Subscription resumed. Charges will continue on next scheduled date."
366
638
  };
367
639
  }
640
+ }),
641
+ // ─────────────────────────────────────────────────────────────────────────
642
+ // Payments (v0.2)
643
+ // ─────────────────────────────────────────────────────────────────────────
644
+ create_payment: tool({
645
+ description: desc("create_payment"),
646
+ inputSchema: z.object({
647
+ amount_ars: z.number().positive().describe("Amount in ARS"),
648
+ payment_method_id: z.string().describe("MP payment method id (e.g. 'account_money', 'rapipago', 'visa', 'master', 'naranja')"),
649
+ payer_email: z.string().email().describe("Email of the payer. Cannot equal seller email."),
650
+ token: z.string().optional().describe("Card token from MP frontend Cardform. Required for credit/debit; omit for cash/account_money."),
651
+ installments: z.number().int().min(1).max(24).optional().describe("Number of installments (cuotas). Default 1. Use calculate_installments first to see options."),
652
+ description: z.string().max(255).optional().describe("Short description"),
653
+ external_reference: z.string().optional().describe("Your-system identifier"),
654
+ identification: z.object({
655
+ type: z.enum(["DNI", "CUIT", "CUIL"]),
656
+ number: z.string()
657
+ }).optional().describe("Payer identification \u2014 required for some payment types in AR"),
658
+ statement_descriptor: z.string().max(13).optional().describe("Shows on buyer's card statement (max 13 chars)")
659
+ }),
660
+ execute: async (input) => {
661
+ const payment = await client.createPayment({
662
+ transactionAmount: input.amount_ars,
663
+ paymentMethodId: input.payment_method_id,
664
+ payerEmail: input.payer_email,
665
+ ...input.token !== void 0 ? { token: input.token } : {},
666
+ ...input.installments !== void 0 ? { installments: input.installments } : {},
667
+ ...input.description !== void 0 ? { description: input.description } : {},
668
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
669
+ ...input.identification !== void 0 ? { identification: input.identification } : {},
670
+ ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
671
+ ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
672
+ // Auto-generate idempotency key from caller-meaningful fields
673
+ idempotencyKey: `${input.external_reference ?? input.payer_email}-${input.amount_ars}-${Date.now()}`
674
+ });
675
+ return {
676
+ payment_id: payment.id,
677
+ status: payment.status,
678
+ status_detail: payment.status_detail,
679
+ amount: payment.transaction_amount,
680
+ currency: payment.currency_id,
681
+ installments: payment.installments,
682
+ payment_method: payment.payment_method_id,
683
+ payer_email: payment.payer?.email ?? null,
684
+ external_reference: payment.external_reference,
685
+ date_created: payment.date_created,
686
+ date_approved: payment.date_approved
687
+ };
688
+ }
689
+ }),
690
+ get_payment: tool({
691
+ description: desc("get_payment"),
692
+ inputSchema: z.object({
693
+ payment_id: z.string().describe("The MP payment ID")
694
+ }),
695
+ execute: async ({ payment_id }) => {
696
+ const p = await client.getPayment(payment_id);
697
+ return {
698
+ payment_id: p.id,
699
+ status: p.status,
700
+ status_detail: p.status_detail,
701
+ amount: p.transaction_amount,
702
+ currency: p.currency_id,
703
+ payment_method: p.payment_method_id,
704
+ installments: p.installments,
705
+ payer_email: p.payer?.email ?? null,
706
+ external_reference: p.external_reference,
707
+ date_created: p.date_created,
708
+ date_approved: p.date_approved,
709
+ net_received: p.transaction_details?.net_received_amount ?? null
710
+ };
711
+ }
712
+ }),
713
+ search_payments: tool({
714
+ description: desc("search_payments"),
715
+ inputSchema: z.object({
716
+ external_reference: z.string().optional(),
717
+ status: z.string().optional().describe("'approved' | 'pending' | 'rejected' | 'cancelled' | 'refunded' etc."),
718
+ payer_email: z.string().optional(),
719
+ begin_date: z.string().optional().describe("ISO 8601, e.g. 2026-01-01T00:00:00Z"),
720
+ end_date: z.string().optional().describe("ISO 8601"),
721
+ limit: z.number().int().min(1).max(100).optional().describe("Default 30, max 100"),
722
+ offset: z.number().int().min(0).optional().describe("Pagination offset (default 0)")
723
+ }),
724
+ execute: async (input) => {
725
+ const result = await client.searchPayments({
726
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
727
+ ...input.status !== void 0 ? { status: input.status } : {},
728
+ ...input.payer_email !== void 0 ? { payerEmail: input.payer_email } : {},
729
+ ...input.begin_date !== void 0 ? { beginDate: input.begin_date } : {},
730
+ ...input.end_date !== void 0 ? { endDate: input.end_date } : {},
731
+ ...input.limit !== void 0 ? { limit: input.limit } : {},
732
+ ...input.offset !== void 0 ? { offset: input.offset } : {}
733
+ });
734
+ return {
735
+ total: result.paging.total,
736
+ returned: result.results.length,
737
+ offset: result.paging.offset,
738
+ payments: result.results.map((p) => ({
739
+ payment_id: p.id,
740
+ status: p.status,
741
+ amount: p.transaction_amount,
742
+ currency: p.currency_id,
743
+ payer_email: p.payer?.email ?? null,
744
+ external_reference: p.external_reference,
745
+ date_created: p.date_created
746
+ }))
747
+ };
748
+ }
749
+ }),
750
+ cancel_payment: tool({
751
+ description: desc("cancel_payment"),
752
+ inputSchema: z.object({ payment_id: z.string() }),
753
+ execute: async ({ payment_id }) => {
754
+ const cancelled = await client.cancelPayment(payment_id);
755
+ return {
756
+ payment_id: cancelled.id,
757
+ status: cancelled.status,
758
+ message: "Payment cancelled. If it was already approved, use refund_payment instead."
759
+ };
760
+ }
761
+ }),
762
+ capture_payment: tool({
763
+ description: desc("capture_payment"),
764
+ inputSchema: z.object({
765
+ payment_id: z.string(),
766
+ amount_ars: z.number().positive().optional().describe("Optional partial-capture amount. Omit to capture full authorized amount.")
767
+ }),
768
+ execute: async ({ payment_id, amount_ars }) => {
769
+ const captured = await client.capturePayment(payment_id, amount_ars);
770
+ return {
771
+ payment_id: captured.id,
772
+ status: captured.status,
773
+ amount: captured.transaction_amount
774
+ };
775
+ }
776
+ }),
777
+ // ─────────────────────────────────────────────────────────────────────────
778
+ // Refunds
779
+ // ─────────────────────────────────────────────────────────────────────────
780
+ refund_payment: tool({
781
+ description: desc("refund_payment"),
782
+ inputSchema: z.object({
783
+ payment_id: z.string(),
784
+ amount_ars: z.number().positive().optional().describe("Partial-refund amount in ARS. Omit for full refund.")
785
+ }),
786
+ execute: async ({ payment_id, amount_ars }) => {
787
+ const refund = await client.createRefund({
788
+ paymentId: payment_id,
789
+ ...amount_ars !== void 0 ? { amount: amount_ars } : {},
790
+ idempotencyKey: `refund-${payment_id}-${amount_ars ?? "full"}`
791
+ });
792
+ return {
793
+ refund_id: refund.id,
794
+ payment_id: refund.payment_id,
795
+ amount: refund.amount,
796
+ status: refund.status,
797
+ 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.`
798
+ };
799
+ }
800
+ }),
801
+ list_refunds: tool({
802
+ description: desc("list_refunds"),
803
+ inputSchema: z.object({ payment_id: z.string() }),
804
+ execute: async ({ payment_id }) => {
805
+ const refunds = await client.listRefunds(payment_id);
806
+ return {
807
+ payment_id,
808
+ count: refunds.length,
809
+ refunds: refunds.map((r) => ({
810
+ refund_id: r.id,
811
+ amount: r.amount,
812
+ status: r.status,
813
+ date_created: r.date_created
814
+ }))
815
+ };
816
+ }
817
+ }),
818
+ // ─────────────────────────────────────────────────────────────────────────
819
+ // Checkout Pro
820
+ // ─────────────────────────────────────────────────────────────────────────
821
+ create_payment_preference: tool({
822
+ description: desc("create_payment_preference"),
823
+ inputSchema: z.object({
824
+ items: z.array(z.object({
825
+ title: z.string().min(1).max(256),
826
+ quantity: z.number().int().positive(),
827
+ unit_price: z.number().positive(),
828
+ description: z.string().optional(),
829
+ picture_url: z.string().url().optional()
830
+ })).min(1).describe("Items being charged. At least one required."),
831
+ payer_email: z.string().email().optional().describe("Pre-fill the payer email on Checkout Pro form"),
832
+ external_reference: z.string().optional(),
833
+ max_installments: z.number().int().min(1).max(24).optional().describe("Limit max cuotas offered. Defaults to MP account config."),
834
+ statement_descriptor: z.string().max(13).optional(),
835
+ 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")
836
+ }),
837
+ execute: async (input) => {
838
+ const pref = await client.createPreference({
839
+ items: input.items.map((it) => ({
840
+ title: it.title,
841
+ quantity: it.quantity,
842
+ unit_price: it.unit_price,
843
+ currency_id: "ARS",
844
+ ...it.description !== void 0 ? { description: it.description } : {},
845
+ ...it.picture_url !== void 0 ? { picture_url: it.picture_url } : {}
846
+ })),
847
+ ...input.payer_email !== void 0 ? { payer: { email: input.payer_email } } : {},
848
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
849
+ ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
850
+ backUrls: { success: options.backUrl, failure: options.backUrl, pending: options.backUrl },
851
+ autoReturn: "approved",
852
+ ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
853
+ ...input.max_installments !== void 0 || input.excluded_payment_types !== void 0 ? {
854
+ paymentMethods: {
855
+ ...input.max_installments !== void 0 ? { installments: input.max_installments } : {},
856
+ ...input.excluded_payment_types !== void 0 ? { excluded_payment_types: input.excluded_payment_types.map((id) => ({ id })) } : {}
857
+ }
858
+ } : {}
859
+ });
860
+ return {
861
+ preference_id: pref.id,
862
+ init_point_url: pref.init_point ?? null,
863
+ sandbox_init_point_url: pref.sandbox_init_point ?? null,
864
+ external_reference: pref.external_reference,
865
+ date_created: pref.date_created,
866
+ 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."
867
+ };
868
+ }
869
+ }),
870
+ get_payment_preference: tool({
871
+ description: desc("get_payment_preference"),
872
+ inputSchema: z.object({ preference_id: z.string() }),
873
+ execute: async ({ preference_id }) => {
874
+ const pref = await client.getPreference(preference_id);
875
+ return {
876
+ preference_id: pref.id,
877
+ init_point_url: pref.init_point ?? null,
878
+ sandbox_init_point_url: pref.sandbox_init_point ?? null,
879
+ external_reference: pref.external_reference,
880
+ items: pref.items,
881
+ date_created: pref.date_created
882
+ };
883
+ }
884
+ }),
885
+ // ─────────────────────────────────────────────────────────────────────────
886
+ // Customers + Saved Cards
887
+ // ─────────────────────────────────────────────────────────────────────────
888
+ create_customer: tool({
889
+ description: desc("create_customer"),
890
+ inputSchema: z.object({
891
+ email: z.string().email(),
892
+ first_name: z.string().optional(),
893
+ last_name: z.string().optional(),
894
+ identification: z.object({
895
+ type: z.enum(["DNI", "CUIT", "CUIL"]),
896
+ number: z.string()
897
+ }).optional(),
898
+ description: z.string().optional()
899
+ }),
900
+ execute: async (input) => {
901
+ const customer = await client.createCustomer({
902
+ email: input.email,
903
+ ...input.first_name !== void 0 ? { firstName: input.first_name } : {},
904
+ ...input.last_name !== void 0 ? { lastName: input.last_name } : {},
905
+ ...input.identification !== void 0 ? { identification: input.identification } : {},
906
+ ...input.description !== void 0 ? { description: input.description } : {}
907
+ });
908
+ return {
909
+ customer_id: customer.id,
910
+ email: customer.email,
911
+ first_name: customer.first_name,
912
+ last_name: customer.last_name,
913
+ date_created: customer.date_created
914
+ };
915
+ }
916
+ }),
917
+ find_customer_by_email: tool({
918
+ description: desc("find_customer_by_email"),
919
+ inputSchema: z.object({ email: z.string().email() }),
920
+ execute: async ({ email }) => {
921
+ const result = await client.searchCustomers({ email, limit: 1 });
922
+ const customer = result.results[0] ?? null;
923
+ return customer ? {
924
+ found: true,
925
+ customer_id: customer.id,
926
+ email: customer.email,
927
+ first_name: customer.first_name,
928
+ last_name: customer.last_name
929
+ } : { found: false, customer_id: null };
930
+ }
931
+ }),
932
+ list_customer_cards: tool({
933
+ description: desc("list_customer_cards"),
934
+ inputSchema: z.object({ customer_id: z.string() }),
935
+ execute: async ({ customer_id }) => {
936
+ const cards = await client.listCustomerCards(customer_id);
937
+ return {
938
+ customer_id,
939
+ count: cards.length,
940
+ cards: cards.map((c) => ({
941
+ card_id: c.id,
942
+ last_four_digits: c.last_four_digits,
943
+ expiration_month: c.expiration_month,
944
+ expiration_year: c.expiration_year,
945
+ payment_method: c.payment_method?.id ?? null,
946
+ payment_method_name: c.payment_method?.name ?? null
947
+ }))
948
+ };
949
+ }
950
+ }),
951
+ delete_customer_card: tool({
952
+ description: desc("delete_customer_card"),
953
+ inputSchema: z.object({
954
+ customer_id: z.string(),
955
+ card_id: z.string()
956
+ }),
957
+ execute: async ({ customer_id, card_id }) => {
958
+ await client.deleteCustomerCard(customer_id, card_id);
959
+ return { customer_id, card_id, deleted: true };
960
+ }
961
+ }),
962
+ // ─────────────────────────────────────────────────────────────────────────
963
+ // Payment Methods + Installments
964
+ // ─────────────────────────────────────────────────────────────────────────
965
+ list_payment_methods: tool({
966
+ description: desc("list_payment_methods"),
967
+ inputSchema: z.object({}),
968
+ execute: async () => {
969
+ const methods = await client.listPaymentMethods();
970
+ return {
971
+ count: methods.length,
972
+ methods: methods.map((m) => ({
973
+ id: m.id,
974
+ name: m.name,
975
+ payment_type: m.payment_type_id,
976
+ status: m.status,
977
+ min_amount: m.min_allowed_amount,
978
+ max_amount: m.max_allowed_amount
979
+ }))
980
+ };
981
+ }
982
+ }),
983
+ calculate_installments: tool({
984
+ description: desc("calculate_installments"),
985
+ inputSchema: z.object({
986
+ amount_ars: z.number().positive(),
987
+ payment_method_id: z.string().optional().describe("E.g. 'visa', 'master', 'naranja'. Omit for all available methods."),
988
+ 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)")
989
+ }),
990
+ execute: async (input) => {
991
+ const offers = await client.getInstallments({
992
+ amount: input.amount_ars,
993
+ ...input.payment_method_id !== void 0 ? { paymentMethodId: input.payment_method_id } : {},
994
+ ...input.bin !== void 0 ? { bin: input.bin } : {}
995
+ });
996
+ return {
997
+ amount: input.amount_ars,
998
+ offers: offers.map((o) => ({
999
+ payment_method_id: o.payment_method_id,
1000
+ payment_type_id: o.payment_type_id,
1001
+ issuer_name: o.issuer?.name ?? null,
1002
+ options: o.payer_costs.map((pc) => ({
1003
+ installments: pc.installments,
1004
+ installment_amount: pc.installment_amount,
1005
+ total_amount: pc.total_amount,
1006
+ installment_rate: pc.installment_rate,
1007
+ recommended_message: pc.recommended_message
1008
+ }))
1009
+ }))
1010
+ };
1011
+ }
1012
+ }),
1013
+ // ─────────────────────────────────────────────────────────────────────────
1014
+ // Account
1015
+ // ─────────────────────────────────────────────────────────────────────────
1016
+ get_account_info: tool({
1017
+ description: desc("get_account_info"),
1018
+ inputSchema: z.object({}),
1019
+ execute: async () => {
1020
+ const me = await client.getMe();
1021
+ return {
1022
+ account_id: me.id,
1023
+ email: me.email,
1024
+ nickname: me.nickname,
1025
+ country_id: me.country_id,
1026
+ site_id: me.site_id,
1027
+ user_type: me.user_type
1028
+ };
1029
+ }
368
1030
  })
369
1031
  };
370
1032
  }
@@ -429,6 +1091,151 @@ var WebhookBodySchema = z.object({
429
1091
  id: z.union([z.string(), z.number()]).optional(),
430
1092
  live_mode: z.boolean().optional()
431
1093
  }).passthrough();
1094
+ var PaymentStatusSchema = z.union([
1095
+ z.literal("pending"),
1096
+ z.literal("approved"),
1097
+ z.literal("authorized"),
1098
+ z.literal("in_process"),
1099
+ z.literal("in_mediation"),
1100
+ z.literal("rejected"),
1101
+ z.literal("cancelled"),
1102
+ z.literal("refunded"),
1103
+ z.literal("charged_back"),
1104
+ z.string()
1105
+ ]);
1106
+ var PaymentSchema = z.object({
1107
+ id: z.union([z.string(), z.number()]).transform(String),
1108
+ status: PaymentStatusSchema,
1109
+ status_detail: z.string().nullable().optional(),
1110
+ date_created: z.string().nullable().optional(),
1111
+ date_approved: z.string().nullable().optional(),
1112
+ date_last_updated: z.string().nullable().optional(),
1113
+ transaction_amount: z.number(),
1114
+ currency_id: z.string(),
1115
+ installments: z.number().int().nullable().optional(),
1116
+ payment_method_id: z.string().nullable().optional(),
1117
+ payment_type_id: z.string().nullable().optional(),
1118
+ external_reference: z.string().nullable().optional(),
1119
+ description: z.string().nullable().optional(),
1120
+ payer: z.object({
1121
+ id: z.union([z.string(), z.number()]).optional(),
1122
+ email: z.string().nullable().optional(),
1123
+ identification: z.object({
1124
+ type: z.string().nullable().optional(),
1125
+ number: z.string().nullable().optional()
1126
+ }).nullable().optional()
1127
+ }).passthrough().optional(),
1128
+ transaction_details: z.object({
1129
+ net_received_amount: z.number().nullable().optional(),
1130
+ total_paid_amount: z.number().nullable().optional(),
1131
+ installment_amount: z.number().nullable().optional()
1132
+ }).passthrough().optional()
1133
+ }).passthrough();
1134
+ z.object({
1135
+ paging: z.object({
1136
+ total: z.number(),
1137
+ limit: z.number(),
1138
+ offset: z.number()
1139
+ }),
1140
+ results: z.array(PaymentSchema)
1141
+ });
1142
+ z.object({
1143
+ id: z.union([z.string(), z.number()]).transform(String),
1144
+ payment_id: z.union([z.string(), z.number()]).transform(String),
1145
+ amount: z.number(),
1146
+ source: z.object({
1147
+ id: z.string().nullable().optional(),
1148
+ name: z.string().nullable().optional(),
1149
+ type: z.string().nullable().optional()
1150
+ }).nullable().optional(),
1151
+ date_created: z.string().nullable().optional(),
1152
+ status: z.string().nullable().optional()
1153
+ }).passthrough();
1154
+ var PreferenceItemSchema = z.object({
1155
+ id: z.string().optional(),
1156
+ title: z.string(),
1157
+ description: z.string().optional(),
1158
+ picture_url: z.string().url().optional(),
1159
+ category_id: z.string().optional(),
1160
+ quantity: z.number().int().positive(),
1161
+ unit_price: z.number().positive(),
1162
+ currency_id: CurrencyIdSchema.optional()
1163
+ });
1164
+ z.object({
1165
+ id: z.string(),
1166
+ init_point: z.string().url().optional(),
1167
+ sandbox_init_point: z.string().url().optional(),
1168
+ client_id: z.union([z.string(), z.number()]).optional(),
1169
+ collector_id: z.union([z.string(), z.number()]).optional(),
1170
+ items: z.array(PreferenceItemSchema).optional(),
1171
+ external_reference: z.string().nullable().optional(),
1172
+ date_created: z.string().nullable().optional(),
1173
+ expires: z.boolean().optional(),
1174
+ expiration_date_from: z.string().nullable().optional(),
1175
+ expiration_date_to: z.string().nullable().optional()
1176
+ }).passthrough();
1177
+ z.object({
1178
+ id: z.string(),
1179
+ email: z.string(),
1180
+ first_name: z.string().nullable().optional(),
1181
+ last_name: z.string().nullable().optional(),
1182
+ phone: z.object({ area_code: z.string().nullable().optional(), number: z.string().nullable().optional() }).nullable().optional(),
1183
+ identification: z.object({ type: z.string().nullable().optional(), number: z.string().nullable().optional() }).nullable().optional(),
1184
+ date_created: z.string().nullable().optional(),
1185
+ date_last_updated: z.string().nullable().optional(),
1186
+ description: z.string().nullable().optional()
1187
+ }).passthrough();
1188
+ z.object({
1189
+ id: z.string(),
1190
+ customer_id: z.string(),
1191
+ expiration_month: z.number().int().nullable().optional(),
1192
+ expiration_year: z.number().int().nullable().optional(),
1193
+ first_six_digits: z.string().nullable().optional(),
1194
+ last_four_digits: z.string().nullable().optional(),
1195
+ payment_method: z.object({
1196
+ id: z.string().nullable().optional(),
1197
+ name: z.string().nullable().optional(),
1198
+ payment_type_id: z.string().nullable().optional()
1199
+ }).nullable().optional(),
1200
+ date_created: z.string().nullable().optional()
1201
+ }).passthrough();
1202
+ z.object({
1203
+ id: z.string(),
1204
+ name: z.string(),
1205
+ payment_type_id: z.string(),
1206
+ status: z.string(),
1207
+ thumbnail: z.string().nullable().optional(),
1208
+ secure_thumbnail: z.string().nullable().optional(),
1209
+ min_allowed_amount: z.number().nullable().optional(),
1210
+ max_allowed_amount: z.number().nullable().optional()
1211
+ }).passthrough();
1212
+ z.object({
1213
+ payment_method_id: z.string(),
1214
+ payment_type_id: z.string(),
1215
+ issuer: z.object({
1216
+ id: z.union([z.string(), z.number()]).optional(),
1217
+ name: z.string().nullable().optional()
1218
+ }).nullable().optional(),
1219
+ payer_costs: z.array(
1220
+ z.object({
1221
+ installments: z.number().int(),
1222
+ installment_rate: z.number(),
1223
+ discount_rate: z.number().nullable().optional(),
1224
+ installment_amount: z.number(),
1225
+ total_amount: z.number(),
1226
+ recommended_message: z.string().nullable().optional()
1227
+ }).passthrough()
1228
+ )
1229
+ }).passthrough();
1230
+ z.object({
1231
+ id: z.union([z.string(), z.number()]).transform(String),
1232
+ email: z.string().nullable().optional(),
1233
+ nickname: z.string().nullable().optional(),
1234
+ country_id: z.string().nullable().optional(),
1235
+ site_id: z.string().nullable().optional(),
1236
+ user_type: z.string().nullable().optional(),
1237
+ status: z.object({ user_type: z.string().nullable().optional() }).passthrough().nullable().optional()
1238
+ }).passthrough();
432
1239
 
433
1240
  // src/webhook.ts
434
1241
  function parseWebhookEvent(body, searchParams) {