@ar-agents/mercadopago 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.14.0
4
+
5
+ ### Minor Changes — deep-audit hardening pass
6
+
7
+ **Critical: Browser-context guard in MercadoPagoClient constructor.**
8
+ Throws if instantiated in a context where `window` is defined — prevents
9
+ the access token from being bundled into a client-side JavaScript bundle.
10
+ Edge Runtime, Node, Workers, and any server context pass through. To
11
+ opt out for jsdom-based tests, pass `__allowBrowser: true`.
12
+
13
+ **`z.unknown()` schemas replaced with strict Zod.** Two tools previously
14
+ used `z.record(z.string(), z.unknown())`:
15
+ - `update_merchant_order.patch` → narrow object with documented MP fields
16
+ (`external_reference`, `notification_url`, `additional_info`, `status`),
17
+ `.strict()` so unknown keys are rejected.
18
+ - `explain_payment_status.payment` → typed shape with `.passthrough()` for
19
+ ergonomic interop, marked clearly as ADVANCED — LLMs should use
20
+ `payment_id` instead.
21
+
22
+ **Stricter validation on `search_payments`:**
23
+ - `payer_email` now requires `.email()` (was bare `z.string()`).
24
+ - `begin_date` / `end_date` now require `.datetime()` ISO 8601.
25
+
26
+ **Deterministic idempotency on subscription + preference creation.**
27
+ `create_subscription` and `create_payment_preference` now derive their
28
+ idempotency key from input fields (customer_email + amount + frequency
29
+ for subscriptions; items + payer + external_reference for preferences).
30
+ LLM retries with the same inputs return the EXISTING resource instead
31
+ of creating a duplicate.
32
+
33
+ **Human-in-the-loop warnings on irreversible / money-moving tools.**
34
+ Updated 7 tool descriptions to explicitly tell the LLM to confirm with
35
+ the user before calling: `cancel_payment`, `capture_payment`,
36
+ `refund_payment`, `delete_customer_card`, `cancel_qr_payment`,
37
+ `cancel_order`, `cancel_point_payment_intent`, `delete_webhook`. Each
38
+ description now states what's irreversible, what the user should be
39
+ told before confirmation, and what the post-call state is.
40
+
41
+ `CreatePreapprovalParams` and `CreatePreferenceParams` now accept an
42
+ optional `idempotencyKey` field for callers that want explicit control.
43
+
3
44
  ## 0.13.0
4
45
 
5
46
  ### Minor Changes — Distributed rate limiter via Vercel KV
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}`);
@@ -3030,10 +3044,10 @@ var DEFAULT_DESCRIPTIONS = {
3030
3044
  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
3045
  get_payment: "Fetch a single payment by ID. Use to confirm status after webhook arrives, or to inspect details (status_detail explains rejections).",
3032
3046
  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.",
3047
+ 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.**",
3048
+ 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
3049
  // ── 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.",
3050
+ 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
3051
  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
3052
  // ── Checkout Pro ─────────────────────────────────────────────────────────
3039
3053
  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 +3056,7 @@ var DEFAULT_DESCRIPTIONS = {
3042
3056
  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
3057
  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
3058
  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.",
3059
+ 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
3060
  // ── Payment Methods + Installments ───────────────────────────────────────
3047
3061
  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
3062
  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 +3066,7 @@ var DEFAULT_DESCRIPTIONS = {
3052
3066
  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
3067
  // ── QR in-store (v0.3) ───────────────────────────────────────────────────
3054
3068
  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.",
3069
+ 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
3070
  // ── Subscription Plans (v0.4) ────────────────────────────────────────────
3057
3071
  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
3072
  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 +3088,7 @@ var DEFAULT_DESCRIPTIONS = {
3074
3088
  list_webhooks: "List all webhook subscriptions configured for this MP application. Use to see what topics + URLs are wired before adding new ones.",
3075
3089
  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
3090
  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.",
3091
+ 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
3092
  // ── Webhook handler combo (v0.5) ─────────────────────────────────────────
3079
3093
  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
3094
  // ── OAuth Marketplace (v0.5) ─────────────────────────────────────────────
@@ -3086,7 +3100,7 @@ var DEFAULT_DESCRIPTIONS = {
3086
3100
  get_order: "Fetch an Order by ID. Returns the Order with its lifecycle status and any attached payments/refunds.",
3087
3101
  update_order: "Patch an existing Order before it's captured/canceled. Common use: update items or external_reference.",
3088
3102
  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.",
3103
+ 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
3104
  // ── Account / Balance / Movements / Settlements (v0.6) ───────────────────
3091
3105
  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
3106
  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 +3140,7 @@ var DEFAULT_DESCRIPTIONS = {
3126
3140
  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
3141
  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
3142
  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.",
3143
+ 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
3144
  // ── Pure helpers (v0.7) ──────────────────────────────────────────────────
3131
3145
  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
3146
  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.",
@@ -3158,16 +3172,28 @@ function mercadoPagoTools(client, options) {
3158
3172
  external_reference: zod.z.string().optional().describe("Optional id from your system to track this subscription")
3159
3173
  }),
3160
3174
  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
- });
3175
+ const created = await client.createPreapproval(
3176
+ {
3177
+ reason,
3178
+ payerEmail: customer_email,
3179
+ amount: amount_ars,
3180
+ currency: "ARS",
3181
+ frequency: frequency_months,
3182
+ frequencyType: "months",
3183
+ backUrl: options.backUrl,
3184
+ ...external_reference !== void 0 ? { externalReference: external_reference } : {},
3185
+ // Deterministic idempotency — if the LLM retries this tool call
3186
+ // with the same inputs (e.g., timeout + retry), MP returns the
3187
+ // EXISTING subscription instead of creating a duplicate.
3188
+ idempotencyKey: await deterministicIdempotencyKey(
3189
+ "create_subscription",
3190
+ customer_email,
3191
+ amount_ars,
3192
+ frequency_months,
3193
+ external_reference
3194
+ )
3195
+ }
3196
+ );
3171
3197
  await options.state.set(created.id, {
3172
3198
  status: created.status,
3173
3199
  payerEmail: customer_email,
@@ -3374,9 +3400,9 @@ function mercadoPagoTools(client, options) {
3374
3400
  inputSchema: zod.z.object({
3375
3401
  external_reference: zod.z.string().optional(),
3376
3402
  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"),
3403
+ payer_email: zod.z.string().email().optional().describe("Filter by payer email (exact match)."),
3404
+ begin_date: zod.z.string().datetime().optional().describe("ISO 8601, e.g. 2026-01-01T00:00:00Z"),
3405
+ end_date: zod.z.string().datetime().optional().describe("ISO 8601"),
3380
3406
  limit: zod.z.number().int().min(1).max(100).optional().describe("Default 30, max 100"),
3381
3407
  offset: zod.z.number().int().min(0).optional().describe("Pagination offset (default 0)")
3382
3408
  }),
@@ -3494,28 +3520,36 @@ function mercadoPagoTools(client, options) {
3494
3520
  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
3521
  }),
3496
3522
  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
- });
3523
+ const idemKey = await deterministicIdempotencyKey(
3524
+ "create_payment_preference",
3525
+ input.external_reference ?? input.payer_email ?? "",
3526
+ input.items.map((it) => `${it.title}:${it.quantity}:${it.unit_price}`).join("|")
3527
+ );
3528
+ const pref = await client.createPreference(
3529
+ {
3530
+ items: input.items.map((it) => ({
3531
+ title: it.title,
3532
+ quantity: it.quantity,
3533
+ unit_price: it.unit_price,
3534
+ currency_id: "ARS",
3535
+ ...it.description !== void 0 ? { description: it.description } : {},
3536
+ ...it.picture_url !== void 0 ? { picture_url: it.picture_url } : {}
3537
+ })),
3538
+ ...input.payer_email !== void 0 ? { payer: { email: input.payer_email } } : {},
3539
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
3540
+ ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
3541
+ backUrls: { success: options.backUrl, failure: options.backUrl, pending: options.backUrl },
3542
+ autoReturn: "approved",
3543
+ ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
3544
+ ...input.max_installments !== void 0 || input.excluded_payment_types !== void 0 ? {
3545
+ paymentMethods: {
3546
+ ...input.max_installments !== void 0 ? { installments: input.max_installments } : {},
3547
+ ...input.excluded_payment_types !== void 0 ? { excluded_payment_types: input.excluded_payment_types.map((id) => ({ id })) } : {}
3548
+ }
3549
+ } : {},
3550
+ idempotencyKey: idemKey
3551
+ }
3552
+ );
3519
3553
  return {
3520
3554
  preference_id: pref.id,
3521
3555
  init_point_url: pref.init_point ?? null,
@@ -4735,8 +4769,17 @@ function mercadoPagoTools(client, options) {
4735
4769
  update_merchant_order: ai.tool({
4736
4770
  description: desc("update_merchant_order"),
4737
4771
  inputSchema: zod.z.object({
4738
- merchant_order_id: zod.z.string(),
4739
- patch: zod.z.record(zod.z.string(), zod.z.unknown())
4772
+ merchant_order_id: zod.z.string().min(1),
4773
+ // Narrow to MP's documented merchant_order PATCH fields. Previously
4774
+ // this was z.record(z.string(), z.unknown()) which let the LLM pass
4775
+ // arbitrary JSON; MP would silently ignore unknown keys, masking
4776
+ // typos. Strict schema = LLM gets a clear validation error instead.
4777
+ patch: zod.z.object({
4778
+ external_reference: zod.z.string().max(256).optional().describe("Your system's id for this order. Updateable while order is open."),
4779
+ notification_url: zod.z.string().url().optional().describe("Where MP sends webhook notifications for this order."),
4780
+ additional_info: zod.z.string().max(600).optional().describe("Free-form metadata stored alongside the order."),
4781
+ status: zod.z.enum(["opened", "closed", "expired"]).optional().describe("Open orders can be closed (final) or expired (cleanup).")
4782
+ }).strict().describe("Subset of merchant_order fields to update. Unknown keys rejected.")
4740
4783
  }),
4741
4784
  execute: async ({ merchant_order_id, patch }) => {
4742
4785
  return client.updateMerchantOrder(merchant_order_id, patch);
@@ -4955,8 +4998,24 @@ function mercadoPagoTools(client, options) {
4955
4998
  explain_payment_status: ai.tool({
4956
4999
  description: desc("explain_payment_status"),
4957
5000
  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).")
5001
+ payment_id: zod.z.string().min(1).optional().describe(
5002
+ "If provided, fetches the Payment first. RECOMMENDED PATH for agents \u2014 pass the id and let the lib fetch."
5003
+ ),
5004
+ // Loose object kept for advanced manual callers that have already
5005
+ // fetched a Payment from another path. LLMs should prefer payment_id.
5006
+ // We don't strictly type the Payment shape here because MP's actual
5007
+ // response includes 100+ optional fields; the helper consumes only
5008
+ // status / status_detail / payment_method_id / etc. Exposed loosely
5009
+ // for ergonomic interop, NOT for LLM use.
5010
+ payment: zod.z.object({
5011
+ id: zod.z.union([zod.z.string(), zod.z.number()]).optional(),
5012
+ status: zod.z.string().optional(),
5013
+ status_detail: zod.z.string().optional(),
5014
+ payment_method_id: zod.z.string().optional(),
5015
+ transaction_amount: zod.z.number().optional()
5016
+ }).passthrough().optional().describe(
5017
+ "ADVANCED \u2014 pass a pre-fetched Payment object to skip the network call. LLMs: use payment_id instead."
5018
+ )
4960
5019
  }),
4961
5020
  execute: async ({ payment_id, payment }) => {
4962
5021
  let p;