@ar-agents/mercadopago 0.13.0 → 0.15.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.cjs CHANGED
@@ -255,6 +255,12 @@ var MercadoPagoClient = class {
255
255
  circuitBreaker;
256
256
  traceContext;
257
257
  constructor(options) {
258
+ const w = globalThis.window;
259
+ if (typeof w !== "undefined" && !options.__allowBrowser) {
260
+ throw new Error(
261
+ "MercadoPagoClient must NEVER be instantiated in a browser context \u2014 the access token would be exposed in the JavaScript bundle and visible to anyone in DevTools. Use a Server Component, Route Handler, Server Action, or any server-only execution context. If you're running in jsdom for tests and KNOW this is safe, pass `__allowBrowser: true`."
262
+ );
263
+ }
258
264
  if (!options.accessToken) {
259
265
  throw new Error(
260
266
  "MercadoPagoClient requires an accessToken. Get one from https://www.mercadopago.com.ar/developers/panel/credentials"
@@ -453,7 +459,10 @@ var MercadoPagoClient = class {
453
459
  currency_id: params.currency
454
460
  }
455
461
  },
456
- { classifyContext: { payerEmail: params.payerEmail } }
462
+ {
463
+ ...params.idempotencyKey ? { idempotencyKey: params.idempotencyKey } : {},
464
+ classifyContext: { payerEmail: params.payerEmail }
465
+ }
457
466
  );
458
467
  }
459
468
  async getPreapproval(id) {
@@ -649,7 +658,12 @@ var MercadoPagoClient = class {
649
658
  if (params.marketplace) body.marketplace = params.marketplace;
650
659
  if (params.marketplaceFee !== void 0) body.marketplace_fee = params.marketplaceFee;
651
660
  if (params.collectorId !== void 0) body.collector_id = params.collectorId;
652
- return this.request("POST", "/checkout/preferences", body);
661
+ return this.request(
662
+ "POST",
663
+ "/checkout/preferences",
664
+ body,
665
+ params.idempotencyKey ? { idempotencyKey: params.idempotencyKey } : void 0
666
+ );
653
667
  }
654
668
  async getPreference(id) {
655
669
  return this.request("GET", `/checkout/preferences/${id}`);
@@ -3016,7 +3030,8 @@ async function verifyWebhookSignature(params) {
3016
3030
 
3017
3031
  // src/tools.ts
3018
3032
  async function deterministicIdempotencyKey(...parts) {
3019
- const payload = parts.filter((p) => p !== void 0 && p !== null).map(String).join("|");
3033
+ const filtered = parts.filter((p) => p !== void 0 && p !== null).map(String);
3034
+ const payload = filtered.map((p) => `${p.length}:${p}`).join("|");
3020
3035
  return (await sha256Hex(payload)).slice(0, 32);
3021
3036
  }
3022
3037
  var DEFAULT_DESCRIPTIONS = {
@@ -3030,10 +3045,10 @@ var DEFAULT_DESCRIPTIONS = {
3030
3045
  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.",
3031
3046
  get_payment: "Fetch a single payment by ID. Use to confirm status after webhook arrives, or to inspect details (status_detail explains rejections).",
3032
3047
  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.",
3033
- 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.",
3034
- 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.",
3048
+ 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. **IRREVERSIBLE \u2014 confirm with the user before calling. Surface the payment_id, amount, payer_email, and current status, ask 's\xED, cancel\xE1' (or equivalent), then proceed.**",
3049
+ 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. **MOVES MONEY \u2014 confirm the amount with the user before calling.**",
3035
3050
  // ── Refunds ──────────────────────────────────────────────────────────────
3036
- 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.",
3051
+ 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. **IRREVERSIBLE AND MOVES MONEY \u2014 confirm with the user before calling. Restate the payment_id, the refund amount (full vs partial), and ask explicit confirmation. Mercado Pago does not support 'undo refund' \u2014 once issued, the buyer's bank releases the funds.**",
3037
3052
  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.",
3038
3053
  // ── Checkout Pro ─────────────────────────────────────────────────────────
3039
3054
  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.",
@@ -3042,7 +3057,7 @@ var DEFAULT_DESCRIPTIONS = {
3042
3057
  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.",
3043
3058
  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.",
3044
3059
  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.",
3045
- delete_customer_card: "Delete a saved card from a customer. Common use: customer requests removal, or expired card cleanup. Irreversible.",
3060
+ delete_customer_card: "Delete a saved card from a customer. Common use: customer requests removal, or expired card cleanup. **IRREVERSIBLE \u2014 confirm with the user before calling. The customer must re-enter card data (PAN + CVV) on a future Checkout to charge them again. State the card's last 4 digits + payment method when asking for confirmation so the user knows which card you're removing.**",
3046
3061
  // ── Payment Methods + Installments ───────────────────────────────────────
3047
3062
  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.",
3048
3063
  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.",
@@ -3052,7 +3067,7 @@ var DEFAULT_DESCRIPTIONS = {
3052
3067
  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.",
3053
3068
  // ── QR in-store (v0.3) ───────────────────────────────────────────────────
3054
3069
  create_qr_payment: "Generate a dynamic in-store QR for a buyer to scan with any AR wallet (Modo, BNA+, Cuenta DNI, Naranja X, Mercado Pago, etc. \u2014 interop is mandated by Transferencias 3.0). Requires a pre-configured POS external_id (use create_pos to set one up first if needed). Returns the qr_data string + a base64 PNG data URL ready to display. The QR expires in `expires_in_seconds` (default 600). MP fires `point_integration_wh` then `payment` webhooks when scanned.",
3055
- 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.",
3070
+ 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. **IRREVERSIBLE \u2014 but low-stakes since the QR has not been paid yet. Confirm before calling if the user is mid-flow.**",
3056
3071
  // ── Subscription Plans (v0.4) ────────────────────────────────────────────
3057
3072
  create_subscription_plan: "Create a REUSABLE subscription plan (preapproval_plan). Different from create_subscription: a plan defines price + frequency once, then customers subscribe to it via subscribe_to_plan. Use plans for SaaS-style billing (B\xE1sico/Pro/Enterprise tiers). For per-customer custom amounts, use create_subscription directly.",
3058
3073
  list_subscription_plans: "List all subscription plans defined for this MP account. Useful before create_subscription_plan to check if one already exists, or for surfacing options to a customer.",
@@ -3074,7 +3089,7 @@ var DEFAULT_DESCRIPTIONS = {
3074
3089
  list_webhooks: "List all webhook subscriptions configured for this MP application. Use to see what topics + URLs are wired before adding new ones.",
3075
3090
  create_webhook: "Subscribe a webhook URL to a MP topic (payment, subscription_authorized_payment, subscription_preapproval, merchant_order, point_integration_wh). MP will POST to this URL when events of that topic fire.",
3076
3091
  update_webhook: "Update a webhook's URL or topic. Useful when you change deployment URLs without resubscribing from scratch.",
3077
- delete_webhook: "Delete a webhook subscription. MP stops POSTing to it immediately.",
3092
+ delete_webhook: "Delete a webhook subscription. MP stops POSTing to it immediately. **IRREVERSIBLE \u2014 confirm before calling. State the webhook URL + topic so the user knows which subscription is being removed. Re-subscribing requires a new create_webhook call.**",
3078
3093
  // ── Webhook handler combo (v0.5) ─────────────────────────────────────────
3079
3094
  handle_webhook: "Process an incoming MP webhook in ONE call: verify the HMAC-SHA256 signature, parse the event, and (optionally) auto-fetch the underlying resource (Payment, Subscription, Order). Returns the structured event PLUS the full resource. USE THIS in your webhook endpoint INSTEAD of chaining verify_webhook_signature + parse_webhook_event + get_payment manually. Pass the raw request body, x-signature header, x-request-id header, and your MP webhook secret. SAFE: returns { verified: false } when signature mismatches \u2014 caller should respond 401 and stop processing. WHEN auto_fetch is true (default), the resource is fetched as the SAME MP user the client is configured for (so for marketplace integrations, instantiate a per-seller client).",
3080
3095
  // ── OAuth Marketplace (v0.5) ─────────────────────────────────────────────
@@ -3086,7 +3101,7 @@ var DEFAULT_DESCRIPTIONS = {
3086
3101
  get_order: "Fetch an Order by ID. Returns the Order with its lifecycle status and any attached payments/refunds.",
3087
3102
  update_order: "Patch an existing Order before it's captured/canceled. Common use: update items or external_reference.",
3088
3103
  capture_order: "Capture a previously-authorized Order (only for orders created with capture_mode='manual'). Captures up to the originally-authorized amount; pass amount for partial capture. Common use: ride-share marks ride complete \u2192 capture; hotel checks-out guest \u2192 capture.",
3089
- cancel_order: "Cancel an Order. Releases any auth-holds and marks the Order as canceled. For orders that have already been CAPTURED, use refund_payment instead \u2014 cancel only works pre-capture.",
3104
+ cancel_order: "Cancel an Order. Releases any auth-holds and marks the Order as canceled. For orders that have already been CAPTURED, use refund_payment instead \u2014 cancel only works pre-capture. **IRREVERSIBLE \u2014 confirm with the user. State the order_id, total_amount, and current status before asking 's\xED, cancel\xE1'. The buyer's hold is released to their bank within 24-72h depending on issuer.**",
3090
3105
  // ── Account / Balance / Movements / Settlements (v0.6) ───────────────────
3091
3106
  get_account_balance: "Get the seller's current MP wallet balance. Returns { available_balance, unavailable_balance, total_amount, currency_id }. The available balance is what the seller can withdraw or pay with right now; unavailable is in retention (typically 14-21 days for new sellers or risk-flagged transactions). For per-seller marketplace setups, instantiate the client AS THE SELLER first.",
3092
3107
  list_account_movements: "List wallet movements (incoming payments, transfers, refunds, holdings) for the active MP account. Filter by date range with `from`/`to` (ISO 8601). Useful for monthly conciliation or 'show me what came in this month' workflows.",
@@ -3126,7 +3141,7 @@ var DEFAULT_DESCRIPTIONS = {
3126
3141
  update_point_device_mode: "Switch a Point device's operating_mode between 'PDV' (bound to a logical POS, takes payments triggered through that POS) and 'STANDALONE' (works independently, accepts any payment). PDV is for cash-register integrations; STANDALONE is for free-form retail. Affects how payments hit the device.",
3127
3142
  create_point_payment_intent: "Create a payment intent on a physical Point device \u2014 the device prompts the buyer to tap/insert/swipe their card. Returns immediately with intent_id; query state via get_point_payment_intent or wait for point_integration_wh webhook. **AMOUNT IS IN CENTAVOS**, NOT pesos (Point API differs from Payments API): 100 = $1, 1000 = $10, 10000 = $100.",
3128
3143
  get_point_payment_intent: "Get the current state of a Point payment intent (OPEN, PROCESSING, FINISHED, CANCELED, ERROR). USE in polling loops if you can't wait for the webhook. When state=FINISHED, the intent.payment.id is the resulting Payment id usable with get_payment.",
3129
- cancel_point_payment_intent: "Cancel an OPEN point payment intent before the buyer interacts with the device. ONLY WORKS while state='OPEN' \u2014 once the buyer taps, you can't cancel; refund_payment after the fact instead.",
3144
+ cancel_point_payment_intent: "Cancel an OPEN point payment intent before the buyer interacts with the device. ONLY WORKS while state='OPEN' \u2014 once the buyer taps, you can't cancel; refund_payment after the fact instead. **IRREVERSIBLE \u2014 confirm with the cashier/operator before calling. State the device_id and amount.**",
3130
3145
  // ── Pure helpers (v0.7) ──────────────────────────────────────────────────
3131
3146
  compute_marketplace_fee: "PURE HELPER (no network) \u2014 given a transaction amount + fee rule (% or flat ARS, with optional min/max floors), returns the exact `marketplace_fee` value in ARS to pass to create_order or create_payment_preference. USE WHEN your platform takes a commission and you need to compute the exact fee per transaction. Examples: { percent: 5, minArs: 50, maxArs: 5000 } for percentage with floor + cap; { flatArs: 200, percent: 2 } for fixed + percentage.",
3132
3147
  explain_payment_status: "PURE HELPER (no network) \u2014 given a Payment object (from get_payment / create_payment / handle_webhook), returns { summary, recommendedAction, final, paid, retryable } in Spanish. Translates MP's cryptic status_detail codes to plain Spanish + actionable guidance ('reintentar con otra tarjeta' vs 'esperar webhook' vs 'estado final'). USE THIS instead of having to memorize 30+ status_detail codes \u2014 surface summary + recommendedAction directly to the user.",
@@ -3144,6 +3159,10 @@ var DEFAULT_DESCRIPTIONS = {
3144
3159
  };
3145
3160
  function mercadoPagoTools(client, options) {
3146
3161
  const desc = (name) => options.descriptions?.[name] ?? DEFAULT_DESCRIPTIONS[name];
3162
+ const built = buildAllTools(client, options, desc);
3163
+ return options.requireConfirmation ? applyConfirmationGate(built, options.requireConfirmation) : built;
3164
+ }
3165
+ function buildAllTools(client, options, desc) {
3147
3166
  return {
3148
3167
  // ─────────────────────────────────────────────────────────────────────────
3149
3168
  // Subscriptions (v0.1 — kept identical for backward compatibility)
@@ -3158,16 +3177,28 @@ function mercadoPagoTools(client, options) {
3158
3177
  external_reference: zod.z.string().optional().describe("Optional id from your system to track this subscription")
3159
3178
  }),
3160
3179
  execute: async ({ customer_email, amount_ars, frequency_months, reason, external_reference }) => {
3161
- const created = await client.createPreapproval({
3162
- reason,
3163
- payerEmail: customer_email,
3164
- amount: amount_ars,
3165
- currency: "ARS",
3166
- frequency: frequency_months,
3167
- frequencyType: "months",
3168
- backUrl: options.backUrl,
3169
- ...external_reference !== void 0 ? { externalReference: external_reference } : {}
3170
- });
3180
+ const created = await client.createPreapproval(
3181
+ {
3182
+ reason,
3183
+ payerEmail: customer_email,
3184
+ amount: amount_ars,
3185
+ currency: "ARS",
3186
+ frequency: frequency_months,
3187
+ frequencyType: "months",
3188
+ backUrl: options.backUrl,
3189
+ ...external_reference !== void 0 ? { externalReference: external_reference } : {},
3190
+ // Deterministic idempotency — if the LLM retries this tool call
3191
+ // with the same inputs (e.g., timeout + retry), MP returns the
3192
+ // EXISTING subscription instead of creating a duplicate.
3193
+ idempotencyKey: await deterministicIdempotencyKey(
3194
+ "create_subscription",
3195
+ customer_email,
3196
+ amount_ars,
3197
+ frequency_months,
3198
+ external_reference
3199
+ )
3200
+ }
3201
+ );
3171
3202
  await options.state.set(created.id, {
3172
3203
  status: created.status,
3173
3204
  payerEmail: customer_email,
@@ -3374,9 +3405,9 @@ function mercadoPagoTools(client, options) {
3374
3405
  inputSchema: zod.z.object({
3375
3406
  external_reference: zod.z.string().optional(),
3376
3407
  status: zod.z.string().optional().describe("'approved' | 'pending' | 'rejected' | 'cancelled' | 'refunded' etc."),
3377
- payer_email: zod.z.string().optional(),
3378
- begin_date: zod.z.string().optional().describe("ISO 8601, e.g. 2026-01-01T00:00:00Z"),
3379
- end_date: zod.z.string().optional().describe("ISO 8601"),
3408
+ payer_email: zod.z.string().email().optional().describe("Filter by payer email (exact match)."),
3409
+ begin_date: zod.z.string().datetime().optional().describe("ISO 8601, e.g. 2026-01-01T00:00:00Z"),
3410
+ end_date: zod.z.string().datetime().optional().describe("ISO 8601"),
3380
3411
  limit: zod.z.number().int().min(1).max(100).optional().describe("Default 30, max 100"),
3381
3412
  offset: zod.z.number().int().min(0).optional().describe("Pagination offset (default 0)")
3382
3413
  }),
@@ -3494,28 +3525,36 @@ function mercadoPagoTools(client, options) {
3494
3525
  excluded_payment_types: zod.z.array(zod.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")
3495
3526
  }),
3496
3527
  execute: async (input) => {
3497
- const pref = await client.createPreference({
3498
- items: input.items.map((it) => ({
3499
- title: it.title,
3500
- quantity: it.quantity,
3501
- unit_price: it.unit_price,
3502
- currency_id: "ARS",
3503
- ...it.description !== void 0 ? { description: it.description } : {},
3504
- ...it.picture_url !== void 0 ? { picture_url: it.picture_url } : {}
3505
- })),
3506
- ...input.payer_email !== void 0 ? { payer: { email: input.payer_email } } : {},
3507
- ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
3508
- ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
3509
- backUrls: { success: options.backUrl, failure: options.backUrl, pending: options.backUrl },
3510
- autoReturn: "approved",
3511
- ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
3512
- ...input.max_installments !== void 0 || input.excluded_payment_types !== void 0 ? {
3513
- paymentMethods: {
3514
- ...input.max_installments !== void 0 ? { installments: input.max_installments } : {},
3515
- ...input.excluded_payment_types !== void 0 ? { excluded_payment_types: input.excluded_payment_types.map((id) => ({ id })) } : {}
3516
- }
3517
- } : {}
3518
- });
3528
+ const idemKey = await deterministicIdempotencyKey(
3529
+ "create_payment_preference",
3530
+ input.external_reference ?? input.payer_email ?? "",
3531
+ input.items.map((it) => `${it.title}:${it.quantity}:${it.unit_price}`).join("|")
3532
+ );
3533
+ const pref = await client.createPreference(
3534
+ {
3535
+ items: input.items.map((it) => ({
3536
+ title: it.title,
3537
+ quantity: it.quantity,
3538
+ unit_price: it.unit_price,
3539
+ currency_id: "ARS",
3540
+ ...it.description !== void 0 ? { description: it.description } : {},
3541
+ ...it.picture_url !== void 0 ? { picture_url: it.picture_url } : {}
3542
+ })),
3543
+ ...input.payer_email !== void 0 ? { payer: { email: input.payer_email } } : {},
3544
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
3545
+ ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
3546
+ backUrls: { success: options.backUrl, failure: options.backUrl, pending: options.backUrl },
3547
+ autoReturn: "approved",
3548
+ ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
3549
+ ...input.max_installments !== void 0 || input.excluded_payment_types !== void 0 ? {
3550
+ paymentMethods: {
3551
+ ...input.max_installments !== void 0 ? { installments: input.max_installments } : {},
3552
+ ...input.excluded_payment_types !== void 0 ? { excluded_payment_types: input.excluded_payment_types.map((id) => ({ id })) } : {}
3553
+ }
3554
+ } : {},
3555
+ idempotencyKey: idemKey
3556
+ }
3557
+ );
3519
3558
  return {
3520
3559
  preference_id: pref.id,
3521
3560
  init_point_url: pref.init_point ?? null,
@@ -4237,6 +4276,22 @@ function mercadoPagoTools(client, options) {
4237
4276
  resource: null
4238
4277
  };
4239
4278
  }
4279
+ if (options.webhookDedup && request_id_header) {
4280
+ const { shouldProcess } = await options.webhookDedup.check({
4281
+ topic: event.topic,
4282
+ dataId: event.dataId,
4283
+ requestId: request_id_header
4284
+ });
4285
+ if (!shouldProcess) {
4286
+ return {
4287
+ verified: true,
4288
+ deduplicated: true,
4289
+ event,
4290
+ resource: null,
4291
+ resource_error: "Webhook is a duplicate (same topic+dataId+requestId seen recently). Side effects skipped."
4292
+ };
4293
+ }
4294
+ }
4240
4295
  let resource = null;
4241
4296
  let resourceError = null;
4242
4297
  if (auto_fetch) {
@@ -4735,8 +4790,17 @@ function mercadoPagoTools(client, options) {
4735
4790
  update_merchant_order: ai.tool({
4736
4791
  description: desc("update_merchant_order"),
4737
4792
  inputSchema: zod.z.object({
4738
- merchant_order_id: zod.z.string(),
4739
- patch: zod.z.record(zod.z.string(), zod.z.unknown())
4793
+ merchant_order_id: zod.z.string().min(1),
4794
+ // Narrow to MP's documented merchant_order PATCH fields. Previously
4795
+ // this was z.record(z.string(), z.unknown()) which let the LLM pass
4796
+ // arbitrary JSON; MP would silently ignore unknown keys, masking
4797
+ // typos. Strict schema = LLM gets a clear validation error instead.
4798
+ patch: zod.z.object({
4799
+ external_reference: zod.z.string().max(256).optional().describe("Your system's id for this order. Updateable while order is open."),
4800
+ notification_url: zod.z.string().url().optional().describe("Where MP sends webhook notifications for this order."),
4801
+ additional_info: zod.z.string().max(600).optional().describe("Free-form metadata stored alongside the order."),
4802
+ status: zod.z.enum(["opened", "closed", "expired"]).optional().describe("Open orders can be closed (final) or expired (cleanup).")
4803
+ }).strict().describe("Subset of merchant_order fields to update. Unknown keys rejected.")
4740
4804
  }),
4741
4805
  execute: async ({ merchant_order_id, patch }) => {
4742
4806
  return client.updateMerchantOrder(merchant_order_id, patch);
@@ -4955,8 +5019,24 @@ function mercadoPagoTools(client, options) {
4955
5019
  explain_payment_status: ai.tool({
4956
5020
  description: desc("explain_payment_status"),
4957
5021
  inputSchema: zod.z.object({
4958
- payment_id: zod.z.string().optional().describe("If provided, fetches the Payment first."),
4959
- payment: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Alternatively, pass a Payment object directly (saves a network round-trip).")
5022
+ payment_id: zod.z.string().min(1).optional().describe(
5023
+ "If provided, fetches the Payment first. RECOMMENDED PATH for agents \u2014 pass the id and let the lib fetch."
5024
+ ),
5025
+ // Loose object kept for advanced manual callers that have already
5026
+ // fetched a Payment from another path. LLMs should prefer payment_id.
5027
+ // We don't strictly type the Payment shape here because MP's actual
5028
+ // response includes 100+ optional fields; the helper consumes only
5029
+ // status / status_detail / payment_method_id / etc. Exposed loosely
5030
+ // for ergonomic interop, NOT for LLM use.
5031
+ payment: zod.z.object({
5032
+ id: zod.z.union([zod.z.string(), zod.z.number()]).optional(),
5033
+ status: zod.z.string().optional(),
5034
+ status_detail: zod.z.string().optional(),
5035
+ payment_method_id: zod.z.string().optional(),
5036
+ transaction_amount: zod.z.number().optional()
5037
+ }).passthrough().optional().describe(
5038
+ "ADVANCED \u2014 pass a pre-fetched Payment object to skip the network call. LLMs: use payment_id instead."
5039
+ )
4960
5040
  }),
4961
5041
  execute: async ({ payment_id, payment }) => {
4962
5042
  let p;
@@ -5104,6 +5184,43 @@ function mercadoPagoTools(client, options) {
5104
5184
  })
5105
5185
  };
5106
5186
  }
5187
+ var GATED_TOOL_NAMES = [
5188
+ "cancel_payment",
5189
+ "capture_payment",
5190
+ "refund_payment",
5191
+ "delete_customer_card",
5192
+ "cancel_qr_payment",
5193
+ "cancel_order",
5194
+ "cancel_point_payment_intent",
5195
+ "delete_webhook"
5196
+ ];
5197
+ function applyConfirmationGate(tools, requireConfirmation) {
5198
+ const wrapped = { ...tools };
5199
+ for (const name of GATED_TOOL_NAMES) {
5200
+ const original = tools[name];
5201
+ if (!original) continue;
5202
+ wrapped[name] = {
5203
+ ...original,
5204
+ execute: async (input, ctx) => {
5205
+ const args = input ?? {};
5206
+ const approved = await requireConfirmation(name, args);
5207
+ if (!approved) {
5208
+ return {
5209
+ ok: false,
5210
+ reason: "Confirmation declined by requireConfirmation gate.",
5211
+ operation: name,
5212
+ args
5213
+ };
5214
+ }
5215
+ return await original.execute(
5216
+ input,
5217
+ ctx
5218
+ );
5219
+ }
5220
+ };
5221
+ }
5222
+ return wrapped;
5223
+ }
5107
5224
 
5108
5225
  // src/state.ts
5109
5226
  var InMemoryStateAdapter = class {