@ar-agents/mercadopago 0.15.1 → 0.15.3
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/AGENTS.md +31 -31
- package/CHANGELOG.md +36 -1
- package/MIGRATION.md +8 -8
- package/README.md +39 -32
- package/README.skeleton.md +22 -22
- package/package.json +18 -17
- package/tools.manifest.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
# @ar-agents/mercadopago
|
|
1
|
+
# @ar-agents/mercadopago: agent guide
|
|
2
2
|
|
|
3
3
|
This file is for AI agents using or recommending this package. Humans should start with [README.md](./README.md). Format follows the [agents.md convention](https://agents.md/).
|
|
4
4
|
|
|
5
|
-
`@ar-agents/mercadopago` is a Mercado Pago Agent Toolkit for the Vercel AI SDK 6. It exposes
|
|
5
|
+
`@ar-agents/mercadopago` is a Mercado Pago Agent Toolkit for the Vercel AI SDK 6. It exposes 89 typed tools spanning the agent-relevant Mercado Pago API surface (Subscriptions, Payments, Checkout Pro, Marketplace OAuth, Order Management, Customers, Cards, Cuotas, QR, 3DS, Point devices, Stores+POS, Account/Balance/Settlements, Webhooks, Disputes, Lookups, Bank Accounts). Opinionated for AR; ships with cross-LATAM tax-id helpers.
|
|
6
6
|
|
|
7
|
-
## Decision tree
|
|
7
|
+
## Decision tree: pick the right tool
|
|
8
8
|
|
|
9
9
|
| User intent | Tool to call |
|
|
10
10
|
|---|---|
|
|
@@ -13,12 +13,12 @@ This file is for AI agents using or recommending this package. Humans should sta
|
|
|
13
13
|
| **"Aceptale $X con account_money / Rapipago / Pago Fácil"** (server-side, no card form) | `create_payment` (omit `token`) |
|
|
14
14
|
| **"Aceptale con tarjeta token X"** (you have a card_token from MP frontend SDK) | `create_payment` (with `token`) |
|
|
15
15
|
| **"¿Pagó ya?"** (check status) | `get_payment` (one-off) or `get_subscription_status` (recurring) |
|
|
16
|
-
| **"Devolvele la plata"** | `refund_payment
|
|
17
|
-
| **"Cuántas cuotas tiene esta tarjeta para $X?"** | `calculate_installments
|
|
16
|
+
| **"Devolvele la plata"** | `refund_payment`: full or partial. Confirm first if amount > 1000 ARS. |
|
|
17
|
+
| **"Cuántas cuotas tiene esta tarjeta para $X?"** | `calculate_installments`: surface the `recommended_message` strings VERBATIM (already in compliant Spanish format) |
|
|
18
18
|
| **"Buscá los pagos de [referencia/email]"** | `search_payments` |
|
|
19
19
|
| **"Cancelá ese pago pendiente"** | `cancel_payment` (only `pending`/`in_process`; for approved use `refund_payment`) |
|
|
20
20
|
| **"Capturá ese pago autorizado"** | `capture_payment` (for capture-later flows with `capture: false`) |
|
|
21
|
-
| **"Buscá / Creá al cliente con email X"** | `find_customer_by_email` then `create_customer` (or call `create_customer` directly
|
|
21
|
+
| **"Buscá / Creá al cliente con email X"** | `find_customer_by_email` then `create_customer` (or call `create_customer` directly: MP is idempotent on email) |
|
|
22
22
|
| **"Listame las tarjetas guardadas de X"** | `list_customer_cards` |
|
|
23
23
|
| **"Borrá esa tarjeta"** | `delete_customer_card` |
|
|
24
24
|
| **"Listame los métodos disponibles"** | `list_payment_methods` |
|
|
@@ -33,7 +33,7 @@ This file is for AI agents using or recommending this package. Humans should sta
|
|
|
33
33
|
| **"Qué bancos emiten Visa?"** | `list_issuers(payment_method_id: "visa")` (pass `bin` for accurate match) |
|
|
34
34
|
| **"Listame los tipos de identificación válidos en AR"** | `list_identification_types` (DNI/CUIT/CUIL/etc) |
|
|
35
35
|
| **"Configurame un webhook para recibir notificaciones de pagos"** | `list_webhooks` first, then `create_webhook(url, topic: "payment")` if not present |
|
|
36
|
-
| **"Procesame este webhook que me llegó de MP"** (v0.5) | `handle_webhook
|
|
36
|
+
| **"Procesame este webhook que me llegó de MP"** (v0.5) | `handle_webhook`: verifica HMAC + parsea + auto-fetch del recurso en una sola call |
|
|
37
37
|
| **"Vincular cuenta MP de un vendedor a mi marketplace"** (v0.5) | `oauth_authorize_url` → vendedor aprueba → `oauth_exchange_code` → persistir token → `oauth_refresh_token` cuando expira |
|
|
38
38
|
| **"Cobrar a través de un seller third-party con fee de marketplace"** (v0.5) | `create_order` con `marketplace_fee` + `collector_id` (o `create_payment_preference` con los mismos campos) |
|
|
39
39
|
| **"Autorizar ahora, capturar después"** (ride-share, hotel, marketplace) (v0.5) | `create_order` con `capture_mode: "manual"` → cuando completás el servicio, `capture_order(order_id)` |
|
|
@@ -45,12 +45,12 @@ This file is for AI agents using or recommending this package. Humans should sta
|
|
|
45
45
|
| **"Listame mis dispositivos Point/Smart"** (v0.7) | `list_point_devices` |
|
|
46
46
|
| **"Cobrá $1000 en el Point que está en la caja"** (v0.7) | `create_point_payment_intent({ device_id, amount_centavos: 100000 })` (¡amount en CENTAVOS!) |
|
|
47
47
|
| **"A qué CBU me deposita MP"** (v0.7) | `list_bank_accounts` (el `is_default: true` es el activo) |
|
|
48
|
-
| **"Calculá el fee del marketplace para este monto"** (v0.7) | `compute_marketplace_fee({ amount_ars, percent, minArs, maxArs })` (PURE
|
|
48
|
+
| **"Calculá el fee del marketplace para este monto"** (v0.7) | `compute_marketplace_fee({ amount_ars, percent, minArs, maxArs })` (PURE: no network) |
|
|
49
49
|
| **"Por qué falló este pago / qué hago ahora"** (v0.7) | `explain_payment_status({ payment_id })` (devuelve `{ summary, recommendedAction, retryable }` en español) |
|
|
50
50
|
|
|
51
51
|
## The two main "take a payment" patterns
|
|
52
52
|
|
|
53
|
-
### Pattern A
|
|
53
|
+
### Pattern A: hosted checkout (recommended for most agent flows)
|
|
54
54
|
|
|
55
55
|
You only have a payer email. You don't want to handle PCI data. You want a URL to send via WhatsApp/email.
|
|
56
56
|
|
|
@@ -63,7 +63,7 @@ MP fires webhook with topic="payment", data.id=<payment_id>
|
|
|
63
63
|
agent: get_payment(payment_id) → confirms status
|
|
64
64
|
```
|
|
65
65
|
|
|
66
|
-
### Pattern B
|
|
66
|
+
### Pattern B: server-side payment (when you have a card_token OR using non-card method)
|
|
67
67
|
|
|
68
68
|
You have a `token` from MP frontend SDK (Cardform/Bricks) OR you're charging account_money / cash.
|
|
69
69
|
|
|
@@ -72,7 +72,7 @@ agent: create_payment({ amount, payment_method_id, payer_email, token?, installm
|
|
|
72
72
|
agent: → returns { payment_id, status: "approved" | "pending" | "rejected", status_detail }
|
|
73
73
|
```
|
|
74
74
|
|
|
75
|
-
**NEVER take raw card data in the agent runtime.** Card tokens come from MP's frontend SDK only. If the user pastes "4509 9535 6623 3704" into chat, REFUSE
|
|
75
|
+
**NEVER take raw card data in the agent runtime.** Card tokens come from MP's frontend SDK only. If the user pastes "4509 9535 6623 3704" into chat, REFUSE: that's a PCI violation. Always direct them to a hosted form via `create_payment_preference`.
|
|
76
76
|
|
|
77
77
|
## Result schemas (memorize)
|
|
78
78
|
|
|
@@ -120,7 +120,7 @@ agent: → returns { payment_id, status: "approved" | "pending" | "rejected", st
|
|
|
120
120
|
}]
|
|
121
121
|
}
|
|
122
122
|
```
|
|
123
|
-
**Surface `recommended_message` verbatim to the user
|
|
123
|
+
**Surface `recommended_message` verbatim to the user**: it's already in compliant Argentine Spanish format with proper currency formatting and includes the total when there's interest. AR's E 51/2017 transparency regulation requires this exact phrasing.
|
|
124
124
|
|
|
125
125
|
### `refund_payment` returns
|
|
126
126
|
```jsonc
|
|
@@ -142,12 +142,12 @@ agent: → returns { payment_id, status: "approved" | "pending" | "rejected", st
|
|
|
142
142
|
| `cc_rejected_bad_filled_security_code` | CVV wrong | "El código de seguridad no coincide" |
|
|
143
143
|
| `cc_rejected_bad_filled_date` | Expiration wrong | "La fecha de vencimiento es incorrecta" |
|
|
144
144
|
| `cc_rejected_call_for_authorize` | Bank wants user to call | "Llamá a tu banco para autorizar el pago, después intentá de nuevo" |
|
|
145
|
-
| `cc_rejected_card_disabled` | Card disabled | "Tu tarjeta está deshabilitada
|
|
146
|
-
| `cc_rejected_insufficient_amount` | Not enough funds | "Saldo insuficiente
|
|
145
|
+
| `cc_rejected_card_disabled` | Card disabled | "Tu tarjeta está deshabilitada: usá otra" |
|
|
146
|
+
| `cc_rejected_insufficient_amount` | Not enough funds | "Saldo insuficiente: usá otra tarjeta o método" |
|
|
147
147
|
| `cc_rejected_high_risk` / `cc_rejected_other_reason` | MP risk engine rejection | "El pago fue rechazado. Probá con otro método (Rapipago / account money)" |
|
|
148
148
|
| `cc_rejected_max_attempts` | Too many tries | "Esperá 24h antes de reintentar" |
|
|
149
|
-
| `cc_rejected_invalid_installments` | Cuotas no allowed for this card | "Probá con menos cuotas"
|
|
150
|
-
| `pending_waiting_payment` | Ticket created (Rapipago/Pago Fácil) | "Pagá el ticket en cualquier sucursal
|
|
149
|
+
| `cc_rejected_invalid_installments` | Cuotas no allowed for this card | "Probá con menos cuotas": re-call `calculate_installments` |
|
|
150
|
+
| `pending_waiting_payment` | Ticket created (Rapipago/Pago Fácil) | "Pagá el ticket en cualquier sucursal: se acredita en 1-3 días" |
|
|
151
151
|
| `pending_contingency` | MP manual review | "Esperá unos minutos, MP está revisando el pago" |
|
|
152
152
|
|
|
153
153
|
## Critical AR-specific gotchas
|
|
@@ -157,25 +157,25 @@ agent: → returns { payment_id, status: "approved" | "pending" | "rejected", st
|
|
|
157
157
|
3. **Sandbox cardholder name selects outcome**: cardholder = `APRO` (approved), `OTHE` (rejected_other), `CONT` (pending_contingency), `CALL` (call_for_authorize), `FUND` (insufficient_amount), `SECU` (bad_filled_security_code), `EXPI` (bad_filled_date), `FORM` (bad_filled_other). DNI = `12345678`. ANY 3-digit CVV in sandbox.
|
|
158
158
|
4. **Test cards (sandbox)**: Visa `4509 9535 6623 3704`, MasterCard `5031 7557 3453 0604`, Amex `3711 803032 57522`, debit Visa `4002 7686 9439 5619`. Expiration any future `MM/YY`.
|
|
159
159
|
5. **`account_money` settles instantly** to seller. Card payments default to T+14 hold for new sellers (drops to T+1 after MP graduates the merchant). Tickets settle 1-3 days after the buyer pays.
|
|
160
|
-
6. **First subscription payment requires CVV
|
|
161
|
-
7. **`back_url` MUST be HTTPS
|
|
162
|
-
8. **`payer.identification
|
|
160
|
+
6. **First subscription payment requires CVV**: there is NO API path that bypasses this. The buyer MUST visit the `init_point_url` and complete the first card+CVV payment.
|
|
161
|
+
7. **`back_url` MUST be HTTPS**: even in sandbox. `http://localhost:3000/done` is rejected.
|
|
162
|
+
8. **`payer.identification`**: use `DNI` for consumers, `CUIT` for B2B (required for monotributo / IVA-discriminated invoicing), `CUIL` for employees.
|
|
163
163
|
9. **CVV required on every saved-card charge** in AR by default. Merchant graduation can lift this for trusted sellers.
|
|
164
164
|
10. **Idempotency-Key is mandatory** for POST since 2023. The lib auto-generates from caller-meaningful fields (external_reference + amount + timestamp); pass `idempotencyKey` explicitly if you want exact-match retry semantics.
|
|
165
|
-
11. **`token` is single-use and expires in 7 days.** If a card payment fails, you can't reuse the token
|
|
165
|
+
11. **`token` is single-use and expires in 7 days.** If a card payment fails, you can't reuse the token: re-tokenize on the frontend.
|
|
166
166
|
|
|
167
|
-
## Cuotas / installments
|
|
167
|
+
## Cuotas / installments: the killer AR feature
|
|
168
168
|
|
|
169
169
|
This is what makes MP unique vs Stripe in any country. Workflow:
|
|
170
170
|
|
|
171
171
|
1. Buyer's card BIN (first 6 digits) hits your frontend (Cardform exposes it before tokenizing).
|
|
172
172
|
2. Agent calls `calculate_installments({ amount_ars, payment_method_id, bin })`.
|
|
173
173
|
3. Receive `payer_costs` array.
|
|
174
|
-
4. **Surface the `recommended_message` strings verbatim
|
|
174
|
+
4. **Surface the `recommended_message` strings verbatim**: they're already in compliant AR format ("3 cuotas sin interés de $X").
|
|
175
175
|
5. User picks installments count.
|
|
176
176
|
6. Agent calls `create_payment({ ..., installments: N })`.
|
|
177
177
|
|
|
178
|
-
**Cuotas Simples** (gov interest-free 3 + 6 mo program) appears automatically as `installment_rate: 0` rows when the merchant category qualifies. Agent doesn't configure
|
|
178
|
+
**Cuotas Simples** (gov interest-free 3 + 6 mo program) appears automatically as `installment_rate: 0` rows when the merchant category qualifies. Agent doesn't configure: just surfaces.
|
|
179
179
|
|
|
180
180
|
**Issuer-specific promos** (Día de la Madre, Hot Sale, Plan Z Naranja X) appear as new `payer_costs` entries when the BIN matches an active promo. Same treatment: surface verbatim.
|
|
181
181
|
|
|
@@ -199,7 +199,7 @@ This is what makes MP unique vs Stripe in any country. Workflow:
|
|
|
199
199
|
| `refund_payment` | 300-800ms | 3s |
|
|
200
200
|
| `create_subscription` | 200-600ms | 2s |
|
|
201
201
|
|
|
202
|
-
Rate limit: ~250 req/min per access token. Lib does not retry
|
|
202
|
+
Rate limit: ~250 req/min per access token. Lib does not retry: wrap with your own backoff if you exceed.
|
|
203
203
|
|
|
204
204
|
## Webhooks (planned for v0.3)
|
|
205
205
|
|
|
@@ -214,9 +214,9 @@ v0.2 ships `parseWebhookEvent()` for the `preapproval` topic (subscription lifec
|
|
|
214
214
|
- Bypass MP's first-payment-CVV requirement for subscriptions (impossible).
|
|
215
215
|
- Reactivate a cancelled subscription or payment (MP doesn't allow).
|
|
216
216
|
- Pay out the seller (transfers + withdrawals are dashboard-only / closed API).
|
|
217
|
-
- Make decisions about pricing or installments
|
|
217
|
+
- Make decisions about pricing or installments: caller's responsibility.
|
|
218
218
|
|
|
219
|
-
## v0.5
|
|
219
|
+
## v0.5: Webhook handler combo
|
|
220
220
|
|
|
221
221
|
Webhooks are how MP tells you a payment cleared, a subscription was authorized,
|
|
222
222
|
a QR was scanned. Without HMAC verification, anyone can POST to your webhook
|
|
@@ -241,15 +241,15 @@ the `MercadoPagoClient` with the SELLER's access_token before calling
|
|
|
241
241
|
needs to look up the seller from the webhook payload's `user_id` and pick
|
|
242
242
|
the right client.
|
|
243
243
|
|
|
244
|
-
## v0.5
|
|
244
|
+
## v0.5: OAuth Marketplace flow
|
|
245
245
|
|
|
246
246
|
For marketplace platforms (Rappi, MercadoLibre, Tienda Nube, etc.) where
|
|
247
247
|
your app cobra a través de cuentas MP de terceros (sellers in your platform).
|
|
248
248
|
|
|
249
249
|
**3 legs**:
|
|
250
|
-
1. `oauth_authorize_url
|
|
251
|
-
2. `oauth_exchange_code
|
|
252
|
-
3. `oauth_refresh_token
|
|
250
|
+
1. `oauth_authorize_url`: pure function, no network. Returns a URL; redirect the seller there.
|
|
251
|
+
2. `oauth_exchange_code`: server-side. Takes the `code` from the OAuth callback, returns `{ user_id, access_token, refresh_token, expires_in }`. **Persist all of it.**
|
|
252
|
+
3. `oauth_refresh_token`: server-side. Use saved `refresh_token` to get a fresh `access_token` before/at expiration.
|
|
253
253
|
|
|
254
254
|
**Token storage shape** (per seller):
|
|
255
255
|
```
|
|
@@ -265,7 +265,7 @@ your app cobra a través de cuentas MP de terceros (sellers in your platform).
|
|
|
265
265
|
|
|
266
266
|
**Marketplace fee**: pass `marketplace_fee` (in ARS) + `collector_id: token.user_id` to `create_order` or `create_payment_preference`. Funds route to the seller, fee goes to your marketplace account.
|
|
267
267
|
|
|
268
|
-
## v0.5
|
|
268
|
+
## v0.5: Order Management vs Preference
|
|
269
269
|
|
|
270
270
|
| When | Use |
|
|
271
271
|
| --------------------------------------- | ------------------------- |
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.15.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [`da49fde`](https://github.com/ar-agents/ar-agents/commit/da49fde136ecea89b4755fe74b3ed91ed9720f46) - Enable [npm provenance attestation](https://docs.npmjs.com/generating-provenance-statements) for all `@ar-agents/*` packages. From this version on, the npm registry includes a verifiable cryptographic record that the package was built from this exact GitHub commit, via the GitHub Actions `release.yml` workflow. Boosts supply-chain audit scores (Socket / Snyk / npm) and lets downstream agents verify package integrity without trusting the publisher.
|
|
8
|
+
|
|
9
|
+
No API or runtime changes.
|
|
10
|
+
|
|
11
|
+
## 0.15.2
|
|
12
|
+
|
|
13
|
+
### Patch — docs: tool-count accuracy (87 → 89)
|
|
14
|
+
|
|
15
|
+
The 0.15.1 docs pass under-counted the public tool surface as 87 due to a
|
|
16
|
+
grep mismatch on `tools.ts`. The actual exported count is 89 (verified by
|
|
17
|
+
`tools.manifest.json` regeneration and the `tools.test.ts` array assertion).
|
|
18
|
+
This patch updates the count everywhere it appears: package.json description
|
|
19
|
+
(npm tagline), README sub-headline, README "At a glance" row, AGENTS.md,
|
|
20
|
+
landing comparison table, layout meta description, OG image, root README.
|
|
21
|
+
|
|
22
|
+
No code changes. No new tools — this is purely a counting correction.
|
|
23
|
+
|
|
24
|
+
The CI manifest-drift gate also caught a stale `tools.manifest.json` version
|
|
25
|
+
field (still pointing at 0.15.0); the regenerated manifest now matches the
|
|
26
|
+
package version.
|
|
27
|
+
|
|
3
28
|
## 0.15.1
|
|
4
29
|
|
|
5
30
|
### Patch — docs: positioning + scope clarity
|
|
@@ -34,7 +59,8 @@ distinguishable from declined confirmations.
|
|
|
34
59
|
|
|
35
60
|
```ts
|
|
36
61
|
mercadoPagoTools(client, {
|
|
37
|
-
state,
|
|
62
|
+
state,
|
|
63
|
+
backUrl,
|
|
38
64
|
requireConfirmation: async (op, args) => {
|
|
39
65
|
return await slack.confirm({
|
|
40
66
|
channel: "#mp-approvals",
|
|
@@ -76,6 +102,7 @@ opt out for jsdom-based tests, pass `__allowBrowser: true`.
|
|
|
76
102
|
|
|
77
103
|
**`z.unknown()` schemas replaced with strict Zod.** Two tools previously
|
|
78
104
|
used `z.record(z.string(), z.unknown())`:
|
|
105
|
+
|
|
79
106
|
- `update_merchant_order.patch` → narrow object with documented MP fields
|
|
80
107
|
(`external_reference`, `notification_url`, `additional_info`, `status`),
|
|
81
108
|
`.strict()` so unknown keys are rejected.
|
|
@@ -84,6 +111,7 @@ used `z.record(z.string(), z.unknown())`:
|
|
|
84
111
|
`payment_id` instead.
|
|
85
112
|
|
|
86
113
|
**Stricter validation on `search_payments`:**
|
|
114
|
+
|
|
87
115
|
- `payer_email` now requires `.email()` (was bare `z.string()`).
|
|
88
116
|
- `begin_date` / `end_date` now require `.datetime()` ISO 8601.
|
|
89
117
|
|
|
@@ -174,6 +202,7 @@ partitions. This makes the safe default: safe.
|
|
|
174
202
|
pause/resume — already deduped by id).
|
|
175
203
|
|
|
176
204
|
6 new tests in `idempotency-default.test.ts` verify:
|
|
205
|
+
|
|
177
206
|
- UUID v4 format on auto-gen
|
|
178
207
|
- Different keys per call
|
|
179
208
|
- Caller-supplied keys honored over auto-gen
|
|
@@ -361,28 +390,34 @@ Architectural features for at-scale deployment.
|
|
|
361
390
|
- MP v0.7: +25 new tools (81 total).
|
|
362
391
|
|
|
363
392
|
**Cierre de gaps obvios (8 tools)**:
|
|
393
|
+
|
|
364
394
|
- `get_customer`, `update_customer`, `create_customer_card`, `get_customer_card`
|
|
365
395
|
- `get_subscription_plan`, `update_subscription`, `search_subscriptions`
|
|
366
396
|
- `get_refund`, `update_payment_preference`
|
|
367
397
|
|
|
368
398
|
**Merchant Orders (3 tools — categoría completa nueva)**:
|
|
399
|
+
|
|
369
400
|
- `get_merchant_order`, `search_merchant_orders`, `update_merchant_order`
|
|
370
401
|
- MerchantOrder agrupa Payments asociados a una Preference — clave para reconciliar webhooks con `topic='merchant_order'`.
|
|
371
402
|
|
|
372
403
|
**Stores + POS CRUD completion (6 tools)**:
|
|
404
|
+
|
|
373
405
|
- `get_store`, `update_store`, `delete_store`
|
|
374
406
|
- `get_pos`, `update_pos`, `delete_pos`
|
|
375
407
|
|
|
376
408
|
**Bank Accounts (2 tools)**:
|
|
409
|
+
|
|
377
410
|
- `list_bank_accounts`, `register_bank_account`
|
|
378
411
|
|
|
379
412
|
**Point Devices físicos (5 tools — categoría nueva)**:
|
|
413
|
+
|
|
380
414
|
- `list_point_devices` (terminales físicas: Smart, Tap to Pay)
|
|
381
415
|
- `update_point_device_mode` (PDV vs STANDALONE)
|
|
382
416
|
- `create_point_payment_intent` (push payment al device — amount en CENTAVOS)
|
|
383
417
|
- `get_point_payment_intent`, `cancel_point_payment_intent`
|
|
384
418
|
|
|
385
419
|
**Pure helpers (2 tools, high-leverage)**:
|
|
420
|
+
|
|
386
421
|
- `compute_marketplace_fee` — given amount + (% o flat ARS, con min/max), returns exact `marketplace_fee`
|
|
387
422
|
- `explain_payment_status` — dado un Payment, traduce los 30+ status_detail codes a `{ summary, recommendedAction, final, paid, retryable }` en español
|
|
388
423
|
|
package/MIGRATION.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
# Migration guide
|
|
1
|
+
# Migration guide: `mercadopago` (official SDK) → `@ar-agents/mercadopago`
|
|
2
2
|
|
|
3
3
|
If you're already using MP's official Node SDK and want to switch to (or
|
|
4
4
|
add on top of) the agent toolkit, this guide shows the side-by-side mapping.
|
|
5
5
|
|
|
6
|
-
The agent toolkit is **not** a drop-in replacement
|
|
6
|
+
The agent toolkit is **not** a drop-in replacement: it's a layer ABOVE
|
|
7
7
|
the underlying API designed for AI agents. You can use both packages in
|
|
8
8
|
the same project: keep `mercadopago` for traditional server flows, add
|
|
9
9
|
`@ar-agents/mercadopago` for the agent layer.
|
|
@@ -47,7 +47,7 @@ const created = await payment.create({
|
|
|
47
47
|
console.log(created.id, created.status);
|
|
48
48
|
```
|
|
49
49
|
|
|
50
|
-
**After (`@ar-agents/mercadopago
|
|
50
|
+
**After (`@ar-agents/mercadopago`: direct client):**
|
|
51
51
|
|
|
52
52
|
```ts
|
|
53
53
|
import { MercadoPagoClient } from "@ar-agents/mercadopago";
|
|
@@ -65,7 +65,7 @@ const created = await client.createPayment({
|
|
|
65
65
|
console.log(created.id, created.status);
|
|
66
66
|
```
|
|
67
67
|
|
|
68
|
-
**After (`@ar-agents/mercadopago
|
|
68
|
+
**After (`@ar-agents/mercadopago`: agent tool):**
|
|
69
69
|
|
|
70
70
|
```ts
|
|
71
71
|
import { MercadoPagoClient, mercadoPagoTools, InMemoryStateAdapter } from "@ar-agents/mercadopago";
|
|
@@ -82,7 +82,7 @@ const tools = mercadoPagoTools(client, {
|
|
|
82
82
|
|
|
83
83
|
## Side-by-side: webhook signature verification
|
|
84
84
|
|
|
85
|
-
**Before (`mercadopago`)**: not provided
|
|
85
|
+
**Before (`mercadopago`)**: not provided: you implement HMAC-SHA256 yourself
|
|
86
86
|
from the docs.
|
|
87
87
|
|
|
88
88
|
**After (`@ar-agents/mercadopago`):**
|
|
@@ -139,7 +139,7 @@ new MercadoPagoClient({
|
|
|
139
139
|
- **Deadline propagation** via parent `AbortSignal`
|
|
140
140
|
- **W3C Trace Context** propagation (OpenTelemetry compat sin peer dep)
|
|
141
141
|
- **Audit logging** with pluggable adapter (`AuditLogger` + `InMemoryAuditLog`)
|
|
142
|
-
- **Webhook idempotency dedup** (`WebhookDedup
|
|
142
|
+
- **Webhook idempotency dedup** (`WebhookDedup`: short-circuits MP retries)
|
|
143
143
|
- **Pagination helpers** (`paginate()` AsyncIterable for 7 endpoints)
|
|
144
144
|
- **Token bucket rate limiter** with adaptive learning from MP headers
|
|
145
145
|
- **AR issuer cuotas catalog** (`AR_ISSUER_PROMOS`, `findApplicablePromos`)
|
|
@@ -147,7 +147,7 @@ new MercadoPagoClient({
|
|
|
147
147
|
- **Tool middleware pattern** (`withAuditLog`, `withRateLimit`, `withMetrics`, `withRetry`)
|
|
148
148
|
- **3DS challenge resolution** (`confirmChallengeAndPoll`)
|
|
149
149
|
- **TaxID validation cross-LATAM** (DNI/CUIT/CPF/CNPJ/RFC/RUT/NIT/RUC)
|
|
150
|
-
- **Status detail explainer** (`explainPaymentStatus
|
|
150
|
+
- **Status detail explainer** (`explainPaymentStatus`: Spanish actionable guidance)
|
|
151
151
|
- **Marketplace fee calculator** (`computeMarketplaceFee`)
|
|
152
152
|
- **Vercel KV state adapters** (subscription state + OAuth tokens + idempotency cache + audit log)
|
|
153
153
|
- **Cookbook** with 8 cookbook recipes
|
|
@@ -173,4 +173,4 @@ new MercadoPagoClient({
|
|
|
173
173
|
- You want **AR-specific knowledge** (cuotas catalog, status_detail explainer in Spanish, AR landmines documented)
|
|
174
174
|
- You want **OpenTelemetry-native** observability without writing instrumentation glue
|
|
175
175
|
|
|
176
|
-
You can use BOTH packages in the same project
|
|
176
|
+
You can use BOTH packages in the same project: they don't conflict.
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> Mercado Pago Agent Toolkit. Built on Vercel.
|
|
4
4
|
>
|
|
5
|
-
>
|
|
5
|
+
> 89 typed tools across the agent-relevant Mercado Pago API surface, for the
|
|
6
6
|
> [Vercel AI SDK](https://ai-sdk.dev/) 6 `Experimental_Agent`.
|
|
7
7
|
>
|
|
8
8
|
> _Payments · Subscriptions · Checkout Pro · Marketplace OAuth · Order Management ·
|
|
@@ -19,24 +19,24 @@ Wraps the Mercado Pago API as a typed tool collection for AI agents. Built for
|
|
|
19
19
|
the Vercel AI SDK 6 `Experimental_Agent`. Compatible with any caller that uses
|
|
20
20
|
`tool()`.
|
|
21
21
|
|
|
22
|
-
> **Reading this as an agent?** Skip to [AGENTS.md](./AGENTS.md)
|
|
22
|
+
> **Reading this as an agent?** Skip to [AGENTS.md](./AGENTS.md): it's targeted at LLM consumption with explicit tool-selection rules and error-recovery patterns.
|
|
23
23
|
|
|
24
24
|
## At a glance
|
|
25
25
|
|
|
26
26
|
| What | Value |
|
|
27
27
|
| --- | --- |
|
|
28
|
-
| Tools shipped | **
|
|
28
|
+
| Tools shipped | **89 tools**: covers the agent-relevant MP API surface. Subscriptions, Payments, Refunds, Checkout Pro, Order Management, Customers, Saved Cards, Cuotas, QR in-store, Subscription Plans, Stores+POS, Point Devices físicos, Merchant Orders, Bank Accounts, Disputes, Lookups, Webhooks management, `handle_webhook` combo, OAuth Marketplace flow, Account/Balance/Settlements, 3DS analyzer, Test cards, `mp_health_check`, plus pure helpers `compute_marketplace_fee` + `explain_payment_status`. |
|
|
29
29
|
| Production hardening | Circuit breaker with state machine + rolling window, deadline propagation via parent AbortSignal, W3C Trace Context propagation (OpenTelemetry-compatible without peer dep), replay-attack protection on webhook signatures (5-min default tolerance), `mp_health_check` endpoint. |
|
|
30
|
-
| Test coverage | **303 tests
|
|
30
|
+
| Test coverage | **303 tests**: unit + property-based (~1400 random scenarios via fast-check) + failure injection (network errors, timeouts, races, malformed responses) + integration vs MP sandbox (gated by env var) + benchmarks (`pnpm bench`). |
|
|
31
31
|
| External dependencies | Mercado Pago access token (TEST or APP_USR), state adapter (Upstash, Redis, Postgres, in-memory, etc.) |
|
|
32
32
|
| Latency | 200–600ms per MP call; <1ms for state ops |
|
|
33
|
-
| Cost | $0
|
|
33
|
+
| Cost | $0: MP API is free; merchant pays per-transaction fees on auto-charges |
|
|
34
34
|
| Side effects | `create_subscription` creates a preapproval. `cancel`/`pause`/`resume` mutate state. `get_status` is read-only. |
|
|
35
35
|
| Agent safety | `cancel_subscription` description triggers confirm-before-call in Claude Sonnet 4.6+ |
|
|
36
36
|
| Sites supported | MLA (Argentina) verified end-to-end. Other LATAM sites should work but aren't exercised by tests. |
|
|
37
|
-
| Runtime | **Edge Runtime + Node 18
|
|
37
|
+
| Runtime | **Edge Runtime + Node 18+**: Web Crypto under the hood, no `node:crypto`. Drops into Vercel Edge Functions, Cloudflare Workers, Deno deploy, or any modern Node. |
|
|
38
38
|
| Vercel KV adapters | Subpath `@ar-agents/mercadopago/vercel-kv` ships adapters for subscription state, OAuth tokens, idempotency cache, audit log, and rate limiter. |
|
|
39
|
-
| Cookbook | 9 recipes shipped in `cookbook
|
|
39
|
+
| Cookbook | 9 recipes shipped in `cookbook/`: checkout, subscriptions, webhook handler, marketplace OAuth, QR in-store, 3DS challenge, auth-only Order, recovery patterns, full OpenTelemetry wiring. |
|
|
40
40
|
|
|
41
41
|
## Why this exists
|
|
42
42
|
|
|
@@ -47,6 +47,13 @@ first time around. This package wraps the agent-relevant surface (subscriptions,
|
|
|
47
47
|
payments, marketplace OAuth, cuotas, QR, 3DS, point devices, webhooks) and turns
|
|
48
48
|
the documented gotchas into typed errors with actionable messages.
|
|
49
49
|
|
|
50
|
+
## Deploy a runnable example
|
|
51
|
+
|
|
52
|
+
[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Far-agents%2Far-agents&root-directory=apps%2Fmp-hello&env=MP_ACCESS_TOKEN%2CANTHROPIC_API_KEY%2CUPSTASH_REDIS_REST_URL%2CUPSTASH_REDIS_REST_TOKEN&envDescription=Mercado%20Pago%20access%20token%2C%20Anthropic%20API%20key%2C%20and%20Upstash%20Redis%20credentials%20for%20subscription%20state.&envLink=https%3A%2F%2Fgithub.com%2Far-agents%2Far-agents%2Ftree%2Fmain%2Fapps%2Fmp-hello%23setup&project-name=mp-hello&repository-name=mp-hello)
|
|
53
|
+
|
|
54
|
+
`apps/mp-hello` ships as a clonable Vercel template: Edge Runtime API routes,
|
|
55
|
+
MP webhook handler with HMAC verify, Upstash-backed subscription state.
|
|
56
|
+
|
|
50
57
|
## Install
|
|
51
58
|
|
|
52
59
|
```bash
|
|
@@ -162,7 +169,7 @@ local development, pass a placeholder valid HTTPS URL like
|
|
|
162
169
|
|
|
163
170
|
The error message is misleading. The actual cause: the seller account
|
|
164
171
|
(whose access token authenticates the request) and the buyer email (`payerEmail`)
|
|
165
|
-
must be the same MP account "type"
|
|
172
|
+
must be the same MP account "type": both real accounts, or both test users
|
|
166
173
|
created via `POST /users/test_user`. Mixing them rejects with this error.
|
|
167
174
|
Throws `MercadoPagoAccountTypeMismatchError`.
|
|
168
175
|
|
|
@@ -246,7 +253,7 @@ has history of normal usage, the engine relaxes.
|
|
|
246
253
|
### 11. Failed first payment auto-cancels the entire preapproval
|
|
247
254
|
|
|
248
255
|
When MP's risk engine rejects the first payment of a preapproval, MP
|
|
249
|
-
automatically marks the WHOLE preapproval as `status: cancelled
|
|
256
|
+
automatically marks the WHOLE preapproval as `status: cancelled`: you cannot
|
|
250
257
|
retry with another card on the same subscription. Create a fresh preapproval
|
|
251
258
|
to retry. Throws `MercadoPagoPaymentRejectedError`, which carries the parent
|
|
252
259
|
`preapprovalId` so the caller knows the parent is dead too.
|
|
@@ -286,9 +293,9 @@ selection guidance. Highlights:
|
|
|
286
293
|
- **In-store QR + POS** (4 tools): create_qr_payment, cancel_qr_payment, create_store, create_pos
|
|
287
294
|
- **Cuotas + lookups** (3 tools): calculate_installments, list_payment_methods, list_issuers
|
|
288
295
|
- **Disputes + Webhooks management** (6 tools): list_payment_disputes, create_webhook, list_webhooks…
|
|
289
|
-
- **v0.5
|
|
290
|
-
- **v0.5
|
|
291
|
-
- **v0.5
|
|
296
|
+
- **v0.5: Webhook handler combo** (1 tool): `handle_webhook`: verify HMAC + parse + auto-fetch in ONE call
|
|
297
|
+
- **v0.5: OAuth Marketplace** (3 tools): `oauth_authorize_url`, `oauth_exchange_code`, `oauth_refresh_token`: wire third-party MP accounts to your platform
|
|
298
|
+
- **v0.5: Order Management API** (5 tools): `create_order`, `get_order`, `update_order`, `capture_order`, `cancel_order`: modern API with auth-only support and marketplace splits
|
|
292
299
|
|
|
293
300
|
Options:
|
|
294
301
|
|
|
@@ -302,7 +309,7 @@ mercadoPagoTools(client, {
|
|
|
302
309
|
});
|
|
303
310
|
```
|
|
304
311
|
|
|
305
|
-
### v0.5
|
|
312
|
+
### v0.5: Webhook handler combo
|
|
306
313
|
|
|
307
314
|
```ts
|
|
308
315
|
// In your /api/mercadopago/webhook handler
|
|
@@ -317,10 +324,10 @@ if (!result.verified) return new Response("unauthorized", { status: 401 });
|
|
|
317
324
|
// Use result.event.topic, result.event.dataId, result.resource (Payment | Preapproval | …)
|
|
318
325
|
```
|
|
319
326
|
|
|
320
|
-
### v0.5
|
|
327
|
+
### v0.5: OAuth Marketplace flow (3 legs)
|
|
321
328
|
|
|
322
329
|
```ts
|
|
323
|
-
// 1. Build authorize URL
|
|
330
|
+
// 1. Build authorize URL: redirect the seller here
|
|
324
331
|
const { url } = await tools.oauth_authorize_url.execute({
|
|
325
332
|
redirect_uri: "https://app.test/oauth/callback",
|
|
326
333
|
state: cryptoRandomToken(), // bind to user's session, verify on redirect
|
|
@@ -342,7 +349,7 @@ const { token } = await tools.oauth_refresh_token.execute({
|
|
|
342
349
|
const sellerClient = new MercadoPagoClient({ accessToken: token.access_token });
|
|
343
350
|
```
|
|
344
351
|
|
|
345
|
-
### v0.5
|
|
352
|
+
### v0.5: Marketplace split payments
|
|
346
353
|
|
|
347
354
|
For two-sided platforms (Rappi-style) where you collect on a seller's behalf
|
|
348
355
|
and take a fee, pass `marketplace`, `marketplace_fee`, `collector_id` to
|
|
@@ -364,20 +371,20 @@ await tools.create_order.execute({
|
|
|
364
371
|
All errors extend `MercadoPagoError` which carries `status`, `endpoint`,
|
|
365
372
|
and `mpResponse` for inspection. Specific subclasses:
|
|
366
373
|
|
|
367
|
-
- `MercadoPagoAuthError
|
|
368
|
-
- `MercadoPagoBackUrlInvalidError
|
|
369
|
-
- `MercadoPagoSelfPaymentError
|
|
370
|
-
- `MercadoPagoAccountTypeMismatchError
|
|
371
|
-
- `MercadoPagoPaymentRejectedError
|
|
372
|
-
- `MercadoPagoAuthorizeForbiddenError
|
|
373
|
-
- `MercadoPagoRateLimitError
|
|
374
|
+
- `MercadoPagoAuthError`: 401 from MP
|
|
375
|
+
- `MercadoPagoBackUrlInvalidError`: see gotcha #1
|
|
376
|
+
- `MercadoPagoSelfPaymentError`: see gotcha #3
|
|
377
|
+
- `MercadoPagoAccountTypeMismatchError`: see gotcha #2
|
|
378
|
+
- `MercadoPagoPaymentRejectedError`: see gotchas #10–11; carries `preapprovalId` and `statusDetail`
|
|
379
|
+
- `MercadoPagoAuthorizeForbiddenError`: see gotcha #6
|
|
380
|
+
- `MercadoPagoRateLimitError`: 429 from MP
|
|
374
381
|
|
|
375
382
|
## Production hardening (v0.9+)
|
|
376
383
|
|
|
377
384
|
### Circuit breaker
|
|
378
385
|
|
|
379
386
|
Protect your app from cascading failures when MP is degraded. The breaker
|
|
380
|
-
observes failures over a rolling window
|
|
387
|
+
observes failures over a rolling window: after enough, it OPENS and fails
|
|
381
388
|
fast (no network round-trip) until cooldown elapses.
|
|
382
389
|
|
|
383
390
|
```ts
|
|
@@ -386,7 +393,7 @@ import { CircuitBreaker, MercadoPagoClient, CircuitOpenError } from "@ar-agents/
|
|
|
386
393
|
const breaker = new CircuitBreaker({
|
|
387
394
|
failureThreshold: 5,
|
|
388
395
|
resetTimeoutMs: 30_000,
|
|
389
|
-
// Don't count 4xx user errors toward circuit opening
|
|
396
|
+
// Don't count 4xx user errors toward circuit opening: only upstream failures
|
|
390
397
|
isFailure: (err) => err instanceof MercadoPagoError && err.status >= 500,
|
|
391
398
|
onStateChange: (e) => metrics.gauge(`mp.circuit.${e.to}`, 1),
|
|
392
399
|
});
|
|
@@ -400,7 +407,7 @@ try {
|
|
|
400
407
|
await client.getPayment("123");
|
|
401
408
|
} catch (err) {
|
|
402
409
|
if (err instanceof CircuitOpenError) {
|
|
403
|
-
// MP is down, breaker tripped
|
|
410
|
+
// MP is down, breaker tripped: fast-fail without network
|
|
404
411
|
return showFallbackUi(err.retryAfterMs);
|
|
405
412
|
}
|
|
406
413
|
throw err;
|
|
@@ -408,11 +415,11 @@ try {
|
|
|
408
415
|
```
|
|
409
416
|
|
|
410
417
|
**Multi-tenant marketplace**: pass the same `CircuitBreaker` instance to all
|
|
411
|
-
per-seller `MercadoPagoClient`s
|
|
418
|
+
per-seller `MercadoPagoClient`s: they share backpressure signal.
|
|
412
419
|
|
|
413
420
|
### Deadline propagation
|
|
414
421
|
|
|
415
|
-
Pass the agent's `AbortSignal` to chain deadlines through to MP
|
|
422
|
+
Pass the agent's `AbortSignal` to chain deadlines through to MP: when the
|
|
416
423
|
agent's budget expires, MP requests cancel cleanly without retrying.
|
|
417
424
|
|
|
418
425
|
```ts
|
|
@@ -460,7 +467,7 @@ Vercel Cron monitoring loops.
|
|
|
460
467
|
| Operation | Throughput |
|
|
461
468
|
|---|---|
|
|
462
469
|
| `hmacSha256Hex` (typical webhook manifest) | 45,932 ops/sec |
|
|
463
|
-
| `sha256Hex` (40-byte input
|
|
470
|
+
| `sha256Hex` (40-byte input: idempotency key) | 92,218 ops/sec |
|
|
464
471
|
| `timingSafeEqualHex` (64 chars) | 3,099,551 ops/sec |
|
|
465
472
|
| `computeMarketplaceFee` | 20,662,947 ops/sec |
|
|
466
473
|
| `explainPaymentStatus` | 21,289,436 ops/sec |
|
|
@@ -472,7 +479,7 @@ Run `pnpm bench` to reproduce.
|
|
|
472
479
|
|
|
473
480
|
The toolkit ships first-class adapters for Vercel infrastructure via the
|
|
474
481
|
`@ar-agents/mercadopago/vercel-kv` subpath. `@vercel/kv` is an **optional**
|
|
475
|
-
peer dep
|
|
482
|
+
peer dep: only install it if you use the subpath.
|
|
476
483
|
|
|
477
484
|
```ts
|
|
478
485
|
import { mercadoPagoTools, MercadoPagoClient } from "@ar-agents/mercadopago";
|
|
@@ -500,7 +507,7 @@ const tools = mercadoPagoTools(
|
|
|
500
507
|
|
|
501
508
|
The toolkit (including HMAC webhook verification) is fully Edge-Runtime
|
|
502
509
|
compatible. Add `export const runtime = "edge"` to any Vercel route handler
|
|
503
|
-
that uses MP tools
|
|
510
|
+
that uses MP tools: sub-100ms global cold starts.
|
|
504
511
|
|
|
505
512
|
### Vercel Cron + Blob + Functions
|
|
506
513
|
|
|
@@ -536,7 +543,7 @@ Each recipe is copy-pasteable into a Next.js route handler.
|
|
|
536
543
|
|
|
537
544
|
## License
|
|
538
545
|
|
|
539
|
-
MIT
|
|
546
|
+
MIT: see [LICENSE](./LICENSE).
|
|
540
547
|
|
|
541
548
|
## Stability
|
|
542
549
|
|
package/README.skeleton.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<!--
|
|
2
|
-
README skeleton
|
|
2
|
+
README skeleton: Vercel-official quality.
|
|
3
3
|
Drop this in as packages/mercadopago/README.md after a final once-over.
|
|
4
4
|
The structure follows the patterns Vercel themselves use on
|
|
5
5
|
https://github.com/vercel/ai-sdk and https://github.com/vercel/next.js
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
Hard rules:
|
|
9
9
|
- Lead with what it is and a 3-line install + first call.
|
|
10
|
-
- Real numbers (latency, bundle size) only
|
|
10
|
+
- Real numbers (latency, bundle size) only: no "fast", "blazing", "robust".
|
|
11
11
|
- Code blocks runnable as-pasted (no `// ...` placeholders that hide work).
|
|
12
12
|
- One-screen scrolling for the top: header → install → first call → core API.
|
|
13
13
|
- Everything below is reference, not pitch.
|
|
@@ -21,9 +21,9 @@
|
|
|
21
21
|
[](https://github.com/ar-agents/ar-agents/actions/workflows/ci.yml)
|
|
22
22
|
[](./LICENSE)
|
|
23
23
|
|
|
24
|
-
Mercado Pago Agent Toolkit. Built on Vercel.
|
|
24
|
+
Mercado Pago Agent Toolkit. Built on Vercel. 89 typed tools across the agent-relevant Mercado Pago API surface (Subscriptions, Payments, Checkout Pro, Marketplace OAuth, Order Management, Customers, Cards, Cuotas, QR, 3DS, Point devices, Stores+POS, Account/Balance/Settlements, Webhooks, Disputes, Lookups, Bank Accounts) for the [Vercel AI SDK](https://ai-sdk.dev/) 6 `Experimental_Agent`. Edge-Runtime-safe.
|
|
25
25
|
|
|
26
|
-
> **Reading this as an agent?** Skip to [AGENTS.md](./AGENTS.md)
|
|
26
|
+
> **Reading this as an agent?** Skip to [AGENTS.md](./AGENTS.md): decision tree, result schemas to memorize, error patterns, latency table.
|
|
27
27
|
|
|
28
28
|
## Quick start
|
|
29
29
|
|
|
@@ -57,16 +57,16 @@ That's it. The agent picks `create_subscription`, returns an `init_point_url` yo
|
|
|
57
57
|
|
|
58
58
|
| | |
|
|
59
59
|
| --- | --- |
|
|
60
|
-
| **Tools** | 30
|
|
60
|
+
| **Tools** | 30: Subscriptions, Payments, Refunds, Checkout Pro, Cuotas, QR in-store, Saved cards, Marketplace OAuth, Order Management, Point devices, 3DS, Webhooks. [Full list](./AGENTS.md#tool-selection). |
|
|
61
61
|
| **Bundle size** | 41 KB ESM brotli'd ([bundlephobia](https://bundlephobia.com/package/@ar-agents/mercadopago)). Tree-shakable subpath exports for `/vercel-kv` + `/otel`. |
|
|
62
|
-
| **Runtime** | Vercel Edge, Node 18+, Cloudflare Workers, Deno
|
|
62
|
+
| **Runtime** | Vercel Edge, Node 18+, Cloudflare Workers, Deno: Web Crypto under the hood. |
|
|
63
63
|
| **Tests** | 290 unit + property + failure-injection + benchmark. `pnpm test`, `pnpm bench`. |
|
|
64
64
|
| **TypeScript** | Strict mode, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`. publint + arethetypeswrong all 🟢. |
|
|
65
65
|
| **AR-specific knowledge** | Cuotas with regulatory text (RG 5286/2023), AR issuer promo catalog, Subscription replay-protection, MLA-verified, ARS default. |
|
|
66
66
|
|
|
67
67
|
## Server-only
|
|
68
68
|
|
|
69
|
-
This package **MUST** run on the server. The constructor throws if instantiated in a browser context
|
|
69
|
+
This package **MUST** run on the server. The constructor throws if instantiated in a browser context: the access token would be exposed in the JavaScript bundle. Use Server Components, Route Handlers, or Server Actions.
|
|
70
70
|
|
|
71
71
|
```ts
|
|
72
72
|
// ❌ Never. Throws at runtime AND would leak the token if it didn't.
|
|
@@ -89,14 +89,14 @@ Server-side MP API client. Edge-Runtime safe.
|
|
|
89
89
|
|
|
90
90
|
| Option | Default | Description |
|
|
91
91
|
| --- | --- | --- |
|
|
92
|
-
| `accessToken` (required) |
|
|
92
|
+
| `accessToken` (required) | no | TEST- prefix for sandbox, APP_USR- for production. |
|
|
93
93
|
| `baseUrl` | `https://api.mercadopago.com` | Override for tests / regional hosts. |
|
|
94
94
|
| `fetch` | `globalThis.fetch` | Custom fetch (e.g., MSW for tests). |
|
|
95
95
|
| `requestTimeoutMs` | `30_000` | Per-request timeout. |
|
|
96
96
|
| `maxRetries` | `1` | 5xx + network retries. 4xx never retried. |
|
|
97
|
-
| `circuitBreaker` |
|
|
98
|
-
| `traceContext` |
|
|
99
|
-
| `onCall` |
|
|
97
|
+
| `circuitBreaker` | no | `new CircuitBreaker({ ... })` to fail fast on cascading failures. |
|
|
98
|
+
| `traceContext` | no | OpenTelemetry context propagator (W3C trace headers). |
|
|
99
|
+
| `onCall` | no | Observability hook fired after every request. |
|
|
100
100
|
|
|
101
101
|
### `mercadoPagoTools(client, options)`
|
|
102
102
|
|
|
@@ -104,7 +104,7 @@ Returns the agent tool set wired to the given client.
|
|
|
104
104
|
|
|
105
105
|
| Option | Required | Description |
|
|
106
106
|
| --- | --- | --- |
|
|
107
|
-
| `state` | yes | `SubscriptionStateAdapter
|
|
107
|
+
| `state` | yes | `SubscriptionStateAdapter`: `InMemoryStateAdapter`, `VercelKVSubscriptionStateAdapter`, or your own. |
|
|
108
108
|
| `backUrl` | yes | HTTPS URL where MP redirects buyers after first payment. localhost rejected. |
|
|
109
109
|
| `notificationUrl` | no | Webhook URL for new payments / status changes. |
|
|
110
110
|
| `oauth` | no | `{ clientId, clientSecret, redirectUri, tokenStore }` for marketplace OAuth flows. |
|
|
@@ -123,7 +123,7 @@ Returns the agent tool set wired to the given client.
|
|
|
123
123
|
|
|
124
124
|
### Idempotency by default
|
|
125
125
|
|
|
126
|
-
Every `POST` request gets an auto-generated UUID idempotency key
|
|
126
|
+
Every `POST` request gets an auto-generated UUID idempotency key: your app survives network blips without double-charging. For LLM-driven retries, `create_payment`, `create_subscription`, `create_payment_preference`, and `refund_payment` use a **deterministic** key derived from the inputs, so a tool retried with the same inputs returns the existing resource instead of creating a duplicate.
|
|
127
127
|
|
|
128
128
|
### Webhook verification
|
|
129
129
|
|
|
@@ -164,22 +164,22 @@ const limiter = new VercelKVRateLimiter({
|
|
|
164
164
|
|
|
165
165
|
### Cookbook
|
|
166
166
|
|
|
167
|
-
9 recipes in [`./cookbook`](./cookbook/)
|
|
167
|
+
9 recipes in [`./cookbook`](./cookbook/): Checkout Pro, SaaS subscription, webhook handler, marketplace split, QR in-store, 3DS challenge, manual capture, recovery patterns, full OpenTelemetry wiring.
|
|
168
168
|
|
|
169
169
|
## Comparison
|
|
170
170
|
|
|
171
171
|
| | `@ar-agents/mercadopago` | `mercadopago` (official SDK) | Hand-rolled |
|
|
172
172
|
| --- | --- | --- | --- |
|
|
173
|
-
| Tools as Vercel AI SDK 6 schemas | ✓ |
|
|
174
|
-
| AR-specific (cuotas, AR issuer promos, AR phone, MLA-verified) | ✓ |
|
|
175
|
-
| `AGENTS.md` per package (LLM-readable) | ✓ |
|
|
176
|
-
| Idempotency-by-default for state mutations | ✓ |
|
|
173
|
+
| Tools as Vercel AI SDK 6 schemas | ✓ | no | build it |
|
|
174
|
+
| AR-specific (cuotas, AR issuer promos, AR phone, MLA-verified) | ✓ | no | weeks |
|
|
175
|
+
| `AGENTS.md` per package (LLM-readable) | ✓ | no |: |
|
|
176
|
+
| Idempotency-by-default for state mutations | ✓ | no | build it |
|
|
177
177
|
| Webhook signature verify + 5-min replay window | ✓ | client only | build it |
|
|
178
178
|
| Edge Runtime support | ✓ | Node-only | build it |
|
|
179
|
-
| Vercel KV adapters via subpath | ✓ |
|
|
180
|
-
| OpenTelemetry instrumentation + recipe | ✓ |
|
|
181
|
-
| Circuit breaker + deadline propagation | ✓ |
|
|
182
|
-
| Tool middleware (compose audit/rate/metrics) | ✓ |
|
|
179
|
+
| Vercel KV adapters via subpath | ✓ | no |: |
|
|
180
|
+
| OpenTelemetry instrumentation + recipe | ✓ | no | build it |
|
|
181
|
+
| Circuit breaker + deadline propagation | ✓ | no | build it |
|
|
182
|
+
| Tool middleware (compose audit/rate/metrics) | ✓ | no |: |
|
|
183
183
|
| Time to first cobro | 30 min | 1+ week | 6-8 weeks |
|
|
184
184
|
|
|
185
185
|
See [`MIGRATION.md`](./MIGRATION.md) for a side-by-side `mercadopago` → `@ar-agents/mercadopago` migration guide.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ar-agents/mercadopago",
|
|
3
|
-
"version": "0.15.
|
|
4
|
-
"description": "Mercado Pago Agent Toolkit for the Vercel AI SDK 6.
|
|
3
|
+
"version": "0.15.3",
|
|
4
|
+
"description": "Mercado Pago Agent Toolkit for the Vercel AI SDK 6. 89 typed tools across the agent-relevant Mercado Pago API surface — Subscriptions, Payments, Checkout Pro, Marketplace OAuth, Order Management, Customers, Cards, Cuotas, QR, 3DS, Point devices, Webhooks, Stores+POS, Account/Balance/Settlements, Disputes, Lookups, Bank Accounts. Edge Runtime. Vercel KV adapters. OpenTelemetry. Deterministic idempotency. Programmatic HITL on irreversible ops.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mercadopago",
|
|
7
7
|
"mp",
|
|
@@ -104,19 +104,6 @@
|
|
|
104
104
|
"LICENSE",
|
|
105
105
|
"tools.manifest.json"
|
|
106
106
|
],
|
|
107
|
-
"scripts": {
|
|
108
|
-
"build": "tsup",
|
|
109
|
-
"test": "vitest run --exclude='test/integration/**'",
|
|
110
|
-
"test:integration": "vitest run test/integration/",
|
|
111
|
-
"bench": "vitest bench --run",
|
|
112
|
-
"test:watch": "vitest",
|
|
113
|
-
"test:coverage": "vitest run --coverage",
|
|
114
|
-
"typecheck": "tsc --noEmit",
|
|
115
|
-
"lint": "echo 'no lint configured yet'",
|
|
116
|
-
"validate": "publint && attw --pack .",
|
|
117
|
-
"size": "size-limit",
|
|
118
|
-
"clean": "rm -rf dist"
|
|
119
|
-
},
|
|
120
107
|
"size-limit": [
|
|
121
108
|
{
|
|
122
109
|
"name": "ESM",
|
|
@@ -166,12 +153,26 @@
|
|
|
166
153
|
"zod": "^4.4.3"
|
|
167
154
|
},
|
|
168
155
|
"publishConfig": {
|
|
169
|
-
"access": "public"
|
|
156
|
+
"access": "public",
|
|
157
|
+
"provenance": true
|
|
170
158
|
},
|
|
171
159
|
"engines": {
|
|
172
160
|
"node": ">=20.0.0"
|
|
173
161
|
},
|
|
174
162
|
"dependencies": {
|
|
175
163
|
"qrcode": "^1.5.4"
|
|
164
|
+
},
|
|
165
|
+
"scripts": {
|
|
166
|
+
"build": "tsup",
|
|
167
|
+
"test": "vitest run --exclude='test/integration/**'",
|
|
168
|
+
"test:integration": "vitest run test/integration/",
|
|
169
|
+
"bench": "vitest bench --run",
|
|
170
|
+
"test:watch": "vitest",
|
|
171
|
+
"test:coverage": "vitest run --coverage",
|
|
172
|
+
"typecheck": "tsc --noEmit",
|
|
173
|
+
"lint": "echo 'no lint configured yet'",
|
|
174
|
+
"validate": "publint && attw --pack .",
|
|
175
|
+
"size": "size-limit",
|
|
176
|
+
"clean": "rm -rf dist"
|
|
176
177
|
}
|
|
177
|
-
}
|
|
178
|
+
}
|