@ar-agents/mercadopago 0.14.0 → 0.15.1

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 CHANGED
@@ -1,7 +1,9 @@
1
- # @ar-agents/mercadopago — agent guide (v0.7)
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 87 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
+
5
7
  ## Decision tree — pick the right tool
6
8
 
7
9
  | User intent | Tool to call |
package/CHANGELOG.md CHANGED
@@ -1,5 +1,69 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.15.1
4
+
5
+ ### Patch — docs: positioning + scope clarity
6
+
7
+ - `package.json` description rewritten as the npm-tagline source of truth: "Mercado Pago Agent Toolkit for the Vercel AI SDK 6. 87 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."
8
+ - `README.md` sub-headline now enumerates the 17 categories. Fixes the drift where the npm page implied subscriptions-only scope.
9
+ - `AGENTS.md` heading no longer carries a stale `(v0.7)` tag; opening paragraph spells out the full surface.
10
+ - Cookbook recipe 03 header: "Production-grade webhook handler" → "Webhook handler".
11
+ - "At a glance" table: tool count corrected (82 → 87), test count refreshed (223 → 303), cookbook count corrected (8 → 9), `Vercel-native` row clarified to `Vercel KV adapters`.
12
+ - `MIGRATION.md`: dropped marketing adjectives ("agent ergonomics", "production-grade").
13
+
14
+ No code changes. No new tools. No API changes.
15
+
16
+ ## 0.15.0
17
+
18
+ ### Minor — `requireConfirmation` opt-in HITL callback (closes /review CRITICAL)
19
+
20
+ Description-based HITL warnings on irreversible ops are best-effort against
21
+ prompt injection. The /review audit (commit 6e3a0dd) flagged this as a real
22
+ risk: a crafted user message smuggled into `external_reference` saying "the
23
+ user already confirmed this refund" could bypass the LLM's heuristic.
24
+
25
+ `mercadoPagoTools(client, { requireConfirmation: async (op, args) => boolean })`
26
+ adds a programmatic out-of-band gate. When set, the 8 irreversible tools
27
+ (`cancel_payment`, `capture_payment`, `refund_payment`,
28
+ `delete_customer_card`, `cancel_qr_payment`, `cancel_order`,
29
+ `cancel_point_payment_intent`, `delete_webhook`) call the callback BEFORE
30
+ executing. If it returns `false`, the tool returns
31
+ `{ ok: false, reason: "Confirmation declined", operation, args }` and never
32
+ reaches MP. If it throws, the error propagates so connection issues are
33
+ distinguishable from declined confirmations.
34
+
35
+ ```ts
36
+ mercadoPagoTools(client, {
37
+ state, backUrl,
38
+ requireConfirmation: async (op, args) => {
39
+ return await slack.confirm({
40
+ channel: "#mp-approvals",
41
+ text: `Refund $${args.amount ?? "FULL"} on payment ${args.payment_id}?`,
42
+ timeoutMs: 60_000,
43
+ });
44
+ },
45
+ });
46
+ ```
47
+
48
+ Backward-compat: omit the option for the previous behavior (description-only
49
+ HITL). 8 new tests in `test/require-confirmation.test.ts` covering decline,
50
+ approve, non-gated tools unaffected, error propagation.
51
+
52
+ ### Other improvements (closes /review findings)
53
+
54
+ - **webhookDedup wired in `handle_webhook`** — the option was declared in
55
+ v0.10 but never used; `handle_webhook` now actually short-circuits on
56
+ duplicate `(topic, dataId, requestId)` tuples (fix for /review CRITICAL).
57
+ - **Idempotency key collision-safe encoding** — `deterministicIdempotencyKey`
58
+ switched from `|`-joined to length-prefix (`<n>:<value>|`) so an attacker
59
+ controlling `external_reference` can no longer craft a colliding key with
60
+ a future legitimate transaction.
61
+ - **VercelKVRateLimiter improvements** — fixed the docstring's fictional
62
+ `MercadoPagoClient({ rateLimiter })` example (now correctly shows
63
+ `withRateLimit` middleware), added randomized jitter (±30%) to the retry
64
+ loop to mitigate thundering herd, capped retries at 8 to fail fast on
65
+ misconfigured buckets.
66
+
3
67
  ## 0.14.0
4
68
 
5
69
  ### Minor Changes — deep-audit hardening pass
@@ -170,8 +234,7 @@ partitions. This makes the safe default: safe.
170
234
 
171
235
  ### Minor Changes — Production hardening: circuit breaker, deadline propagation, property-based tests, real MP sandbox integration tests, benchmarks
172
236
 
173
- The "100/100, top-1 in the world" upgrade. Architectural production-grade
174
- features that separate a toolkit-with-tests from a toolkit-deployed-at-scale.
237
+ Architectural features for at-scale deployment.
175
238
 
176
239
  **Circuit Breaker (NEW)**
177
240
 
@@ -278,7 +341,7 @@ features that separate a toolkit-with-tests from a toolkit-deployed-at-scale.
278
341
 
279
342
  - `cookbook/01-checkout-pro-basic.ts` — first-time hosted checkout
280
343
  - `cookbook/02-saas-subscription.ts` — reusable plan + first payment + card swap on rejection
281
- - `cookbook/03-webhook-handler.ts` — production-grade Edge handler with HMAC verify
344
+ - `cookbook/03-webhook-handler.ts` — Edge handler with HMAC verify
282
345
  - `cookbook/04-marketplace-split.ts` — OAuth seller link → preference with fee → reconciliation
283
346
  - `cookbook/05-qr-in-store.ts` — QR generation → buyer scan → WhatsApp notify
284
347
  - `cookbook/06-3ds-challenge.ts` — detect → redirect → recover via webhook
@@ -295,7 +358,7 @@ features that separate a toolkit-with-tests from a toolkit-deployed-at-scale.
295
358
 
296
359
  ### Minor Changes
297
360
 
298
- - MP v0.7: completeness máxima — el agente de MP más completo posible. **+25 tools (81 total)**.
361
+ - MP v0.7: +25 new tools (81 total).
299
362
 
300
363
  **Cierre de gaps obvios (8 tools)**:
301
364
  - `get_customer`, `update_customer`, `create_customer_card`, `get_customer_card`
package/MIGRATION.md CHANGED
@@ -150,7 +150,7 @@ new MercadoPagoClient({
150
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
- - **Cookbook** with 8 production-grade recipes
153
+ - **Cookbook** with 8 cookbook recipes
154
154
  - **Edge Runtime support** (Web Crypto, no `node:crypto`)
155
155
  - **Property-based testing** with fast-check (~1500 random scenarios)
156
156
  - **Failure injection tests** + integration tests vs MP sandbox
@@ -160,14 +160,14 @@ new MercadoPagoClient({
160
160
 
161
161
  - Your codebase is already deeply integrated with the official SDK
162
162
  - You don't need the agent layer (no Vercel AI SDK)
163
- - You operate primarily server-side with cron jobs and don't care about
164
- agent ergonomics, audit logs, circuit breakers, or status explainers
163
+ - You operate primarily server-side with cron jobs and don't need
164
+ AI-SDK-shaped tool schemas, audit logs, circuit breakers, or status explainers
165
165
 
166
166
  ## When to add `@ar-agents/mercadopago`
167
167
 
168
168
  - You're building anything with an AI agent (Claude, GPT, Gemini)
169
169
  - You're deploying to Vercel and want first-class KV adapters
170
- - You need **production-grade webhook handling** (HMAC + dedup + replay protection)
170
+ - You need **cookbook webhook handling** (HMAC + dedup + replay protection)
171
171
  - You operate a **marketplace** with per-seller OAuth flows
172
172
  - You need **compliance-grade audit logging** for refunds/payments
173
173
  - You want **AR-specific knowledge** (cuotas catalog, status_detail explainer in Spanish, AR landmines documented)
package/README.md CHANGED
@@ -1,6 +1,13 @@
1
1
  # @ar-agents/mercadopago
2
2
 
3
- > Mercado Pago Subscriptions as drop-in tools for the [Vercel AI SDK](https://ai-sdk.dev/). Argentine-focused, agent-ready.
3
+ > Mercado Pago Agent Toolkit. Built on Vercel.
4
+ >
5
+ > 87 typed tools across the agent-relevant Mercado Pago API surface, for the
6
+ > [Vercel AI SDK](https://ai-sdk.dev/) 6 `Experimental_Agent`.
7
+ >
8
+ > _Payments · Subscriptions · Checkout Pro · Marketplace OAuth · Order Management ·
9
+ > Customers · Cards · Cuotas · QR · 3DS · Point devices · Stores+POS ·
10
+ > Account/Balance/Settlements · Webhooks · Disputes · Lookups · Bank Accounts_
4
11
 
5
12
  [![npm version](https://img.shields.io/npm/v/@ar-agents/mercadopago.svg)](https://www.npmjs.com/package/@ar-agents/mercadopago)
6
13
  [![npm downloads](https://img.shields.io/npm/dm/@ar-agents/mercadopago.svg)](https://www.npmjs.com/package/@ar-agents/mercadopago)
@@ -8,9 +15,9 @@
8
15
  [![CI](https://github.com/ar-agents/ar-agents/actions/workflows/ci.yml/badge.svg)](https://github.com/ar-agents/ar-agents/actions/workflows/ci.yml)
9
16
  [![bundle size](https://img.shields.io/bundlephobia/minzip/@ar-agents/mercadopago.svg)](https://bundlephobia.com/package/@ar-agents/mercadopago)
10
17
 
11
- Exposes Mercado Pago's recurring-billing API to AI agents through a typed,
12
- opinionated tool collection. Built for the Vercel AI SDK 6 `Experimental_Agent`.
13
- Compatible with any caller that uses `tool()`.
18
+ Wraps the Mercado Pago API as a typed tool collection for AI agents. Built for
19
+ the Vercel AI SDK 6 `Experimental_Agent`. Compatible with any caller that uses
20
+ `tool()`.
14
21
 
15
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.
16
23
 
@@ -18,9 +25,9 @@ Compatible with any caller that uses `tool()`.
18
25
 
19
26
  | What | Value |
20
27
  | --- | --- |
21
- | Tools shipped | **82 tools** — covers the full 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`. |
22
- | Production hardening (v0.9) | **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), **health check** endpoint. |
23
- | Test coverage | **223 unit tests** + **14 property-based tests** (~1400 random scenarios via fast-check) + **11 failure injection tests** (network errors, timeouts, races, malformed responses) + **integration tests vs MP sandbox** (gated by env var) + **benchmarks** (`pnpm bench`). |
28
+ | Tools shipped | **87 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
+ | 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** — 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`). |
24
31
  | External dependencies | Mercado Pago access token (TEST or APP_USR), state adapter (Upstash, Redis, Postgres, in-memory, etc.) |
25
32
  | Latency | 200–600ms per MP call; <1ms for state ops |
26
33
  | Cost | $0 — MP API is free; merchant pays per-transaction fees on auto-charges |
@@ -28,18 +35,17 @@ Compatible with any caller that uses `tool()`.
28
35
  | Agent safety | `cancel_subscription` description triggers confirm-before-call in Claude Sonnet 4.6+ |
29
36
  | Sites supported | MLA (Argentina) verified end-to-end. Other LATAM sites should work but aren't exercised by tests. |
30
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. |
31
- | Vercel-native | First-class adapters for **Vercel KV** (subscription state, OAuth tokens, idempotency cache) via `@ar-agents/mercadopago/vercel-kv` subpath. |
32
- | Cookbook | 8 production-grade recipes shipped in `cookbook/` — checkout, subscriptions, webhook handler, marketplace OAuth, QR in-store, 3DS challenge, auth-only Order, recovery patterns. |
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/` — checkout, subscriptions, webhook handler, marketplace OAuth, QR in-store, 3DS challenge, auth-only Order, recovery patterns, full OpenTelemetry wiring. |
33
40
 
34
41
  ## Why this exists
35
42
 
36
- Building an agent that operates a real Argentine business means integrating
37
- Mercado Pago. MP's API has a surface area of dozens of endpoints, a docs site
38
- that is partially translated to Spanish-from-the-90s, and at least 11
39
- non-obvious landmines that take days each to discover. This package encapsulates
40
- the subset of MP that an agent typically needs (recurring subscriptions: create,
41
- check status, pause/resume, cancel) and turns the documented gotchas into typed
42
- errors with actionable messages.
43
+ Building an agent that operates an Argentine business means integrating Mercado
44
+ Pago. The API surface is dozens of endpoints, the docs are partially translated,
45
+ and there are 11+ non-obvious landmines that take days each to discover the
46
+ first time around. This package wraps the agent-relevant surface (subscriptions,
47
+ payments, marketplace OAuth, cuotas, QR, 3DS, point devices, webhooks) and turns
48
+ the documented gotchas into typed errors with actionable messages.
43
49
 
44
50
  ## Install
45
51
 
@@ -531,3 +537,14 @@ Each recipe is copy-pasteable into a Next.js route handler.
531
537
  ## License
532
538
 
533
539
  MIT — see [LICENSE](./LICENSE).
540
+
541
+ ## Stability
542
+
543
+ This package is **pre-1.0**. Per [npm convention](https://docs.npmjs.com/about-semantic-versioning), **0.x minor versions may include breaking changes**. We document every breaking change in `CHANGELOG.md` under the corresponding minor bump and flag it explicitly. To avoid surprises:
544
+
545
+ ```bash
546
+ # Pin to exact version (recommended for production):
547
+ pnpm add @ar-agents/<package>@<exact-version>
548
+ ```
549
+
550
+ We commit to **no breaking changes within a patch version**, and we publish `1.0.0` once the public API has stabilized across at least two consecutive minor releases.
@@ -0,0 +1,200 @@
1
+ <!--
2
+ README skeleton — Vercel-official quality.
3
+ Drop this in as packages/mercadopago/README.md after a final once-over.
4
+ The structure follows the patterns Vercel themselves use on
5
+ https://github.com/vercel/ai-sdk and https://github.com/vercel/next.js
6
+ for their public OSS repos.
7
+
8
+ Hard rules:
9
+ - Lead with what it is and a 3-line install + first call.
10
+ - Real numbers (latency, bundle size) only — no "fast", "blazing", "robust".
11
+ - Code blocks runnable as-pasted (no `// ...` placeholders that hide work).
12
+ - One-screen scrolling for the top: header → install → first call → core API.
13
+ - Everything below is reference, not pitch.
14
+ -->
15
+
16
+ # `@ar-agents/mercadopago`
17
+
18
+ [![npm version](https://img.shields.io/npm/v/@ar-agents/mercadopago.svg?label=npm)](https://www.npmjs.com/package/@ar-agents/mercadopago)
19
+ [![bundle size](https://img.shields.io/bundlephobia/minzip/@ar-agents/mercadopago.svg)](https://bundlephobia.com/package/@ar-agents/mercadopago)
20
+ [![types](https://img.shields.io/npm/types/@ar-agents/mercadopago.svg)](https://arethetypeswrong.github.io/?p=@ar-agents/mercadopago)
21
+ [![CI](https://github.com/ar-agents/ar-agents/actions/workflows/ci.yml/badge.svg)](https://github.com/ar-agents/ar-agents/actions/workflows/ci.yml)
22
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
23
+
24
+ Mercado Pago Agent Toolkit. Built on Vercel. 87 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
+
26
+ > **Reading this as an agent?** Skip to [AGENTS.md](./AGENTS.md) — decision tree, result schemas to memorize, error patterns, latency table.
27
+
28
+ ## Quick start
29
+
30
+ ```bash
31
+ pnpm add @ar-agents/mercadopago ai zod
32
+ ```
33
+
34
+ ```ts
35
+ import { Experimental_Agent as Agent, stepCountIs } from "ai";
36
+ import { MercadoPagoClient, mercadoPagoTools, InMemoryStateAdapter } from "@ar-agents/mercadopago";
37
+
38
+ const mp = new MercadoPagoClient({ accessToken: process.env.MP_ACCESS_TOKEN! });
39
+
40
+ export const agent = new Agent({
41
+ model: "anthropic/claude-sonnet-4-6",
42
+ instructions: "Sos un asistente de billing para una SaaS argentina.",
43
+ tools: mercadoPagoTools(mp, { state: new InMemoryStateAdapter(), backUrl: "https://example.com/done" }),
44
+ stopWhen: stepCountIs(8),
45
+ });
46
+ ```
47
+
48
+ ```ts
49
+ const { text } = await agent.generate({
50
+ prompt: "Cobrale $25.000 mensual a juan@example.com con razón 'Plan Pro'."
51
+ });
52
+ ```
53
+
54
+ That's it. The agent picks `create_subscription`, returns an `init_point_url` you send to the customer, and the rest of the flow (first payment confirmation, recurring charges, webhooks) just works.
55
+
56
+ ## At a glance
57
+
58
+ | | |
59
+ | --- | --- |
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
+ | **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 — Web Crypto under the hood. |
63
+ | **Tests** | 290 unit + property + failure-injection + benchmark. `pnpm test`, `pnpm bench`. |
64
+ | **TypeScript** | Strict mode, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`. publint + arethetypeswrong all 🟢. |
65
+ | **AR-specific knowledge** | Cuotas with regulatory text (RG 5286/2023), AR issuer promo catalog, Subscription replay-protection, MLA-verified, ARS default. |
66
+
67
+ ## Server-only
68
+
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
+
71
+ ```ts
72
+ // ❌ Never. Throws at runtime AND would leak the token if it didn't.
73
+ "use client";
74
+ const mp = new MercadoPagoClient({ accessToken: ... });
75
+
76
+ // ✅ Server Component / Route Handler / Server Action.
77
+ import { MercadoPagoClient } from "@ar-agents/mercadopago";
78
+ export async function POST(req: Request) {
79
+ const mp = new MercadoPagoClient({ accessToken: process.env.MP_ACCESS_TOKEN! });
80
+ // ...
81
+ }
82
+ ```
83
+
84
+ ## API reference
85
+
86
+ ### `new MercadoPagoClient(options)`
87
+
88
+ Server-side MP API client. Edge-Runtime safe.
89
+
90
+ | Option | Default | Description |
91
+ | --- | --- | --- |
92
+ | `accessToken` (required) | — | TEST- prefix for sandbox, APP_USR- for production. |
93
+ | `baseUrl` | `https://api.mercadopago.com` | Override for tests / regional hosts. |
94
+ | `fetch` | `globalThis.fetch` | Custom fetch (e.g., MSW for tests). |
95
+ | `requestTimeoutMs` | `30_000` | Per-request timeout. |
96
+ | `maxRetries` | `1` | 5xx + network retries. 4xx never retried. |
97
+ | `circuitBreaker` | — | `new CircuitBreaker({ ... })` to fail fast on cascading failures. |
98
+ | `traceContext` | — | OpenTelemetry context propagator (W3C trace headers). |
99
+ | `onCall` | — | Observability hook fired after every request. |
100
+
101
+ ### `mercadoPagoTools(client, options)`
102
+
103
+ Returns the agent tool set wired to the given client.
104
+
105
+ | Option | Required | Description |
106
+ | --- | --- | --- |
107
+ | `state` | yes | `SubscriptionStateAdapter` — `InMemoryStateAdapter`, `VercelKVSubscriptionStateAdapter`, or your own. |
108
+ | `backUrl` | yes | HTTPS URL where MP redirects buyers after first payment. localhost rejected. |
109
+ | `notificationUrl` | no | Webhook URL for new payments / status changes. |
110
+ | `oauth` | no | `{ clientId, clientSecret, redirectUri, tokenStore }` for marketplace OAuth flows. |
111
+ | `webhookSecret` | no | HMAC secret for `handle_webhook` (paste from MP dev panel). |
112
+ | `descriptions` | no | Override individual tool descriptions for fine-tuning the LLM. |
113
+
114
+ ### Subpath exports
115
+
116
+ | Subpath | When to use |
117
+ | --- | --- |
118
+ | `@ar-agents/mercadopago` | The 30 tools + client. Always-on. |
119
+ | `@ar-agents/mercadopago/vercel-kv` | Vercel KV–backed adapters: `VercelKVSubscriptionStateAdapter`, `VercelKVOAuthTokenStore`, `VercelKVIdempotencyCache`, `VercelKVAuditLog`, `VercelKVRateLimiter` (distributed). Pulls in `@vercel/kv` peer dep. |
120
+ | `@ar-agents/mercadopago/otel` | `instrumentMercadoPagoClient` + `instrumentMercadoPagoTools` for OpenTelemetry spans + metrics. Pulls in `@opentelemetry/api` peer dep. |
121
+
122
+ ## Production patterns
123
+
124
+ ### Idempotency by default
125
+
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
+
128
+ ### Webhook verification
129
+
130
+ ```ts
131
+ import { verifyWebhookSignature, parseWebhookEvent } from "@ar-agents/mercadopago";
132
+
133
+ export async function POST(req: Request) {
134
+ const url = new URL(req.url);
135
+ const rawBody = await req.text();
136
+ const event = parseWebhookEvent(JSON.parse(rawBody), url.searchParams);
137
+
138
+ const ok = await verifyWebhookSignature({
139
+ requestId: req.headers.get("x-request-id"),
140
+ dataId: event!.dataId,
141
+ signatureHeader: req.headers.get("x-signature"),
142
+ secret: process.env.MP_WEBHOOK_SECRET!,
143
+ });
144
+ if (!ok) return new Response("Invalid signature", { status: 401 });
145
+ // process event...
146
+ }
147
+ ```
148
+
149
+ 5-minute replay-tolerance window built in. Constant-time HMAC comparison.
150
+
151
+ ### Distributed rate limiting
152
+
153
+ For multi-region or marketplace deploys where serverless instances would each get their own per-process bucket:
154
+
155
+ ```ts
156
+ import { VercelKVRateLimiter } from "@ar-agents/mercadopago/vercel-kv";
157
+
158
+ const limiter = new VercelKVRateLimiter({
159
+ key: "mp-account-prod",
160
+ capacity: 50,
161
+ refillPerSecond: 25,
162
+ });
163
+ ```
164
+
165
+ ### Cookbook
166
+
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
+
169
+ ## Comparison
170
+
171
+ | | `@ar-agents/mercadopago` | `mercadopago` (official SDK) | Hand-rolled |
172
+ | --- | --- | --- | --- |
173
+ | Tools as Vercel AI SDK 6 schemas | ✓ | — | build it |
174
+ | AR-specific (cuotas, AR issuer promos, AR phone, MLA-verified) | ✓ | — | weeks |
175
+ | `AGENTS.md` per package (LLM-readable) | ✓ | — | — |
176
+ | Idempotency-by-default for state mutations | ✓ | — | build it |
177
+ | Webhook signature verify + 5-min replay window | ✓ | client only | build it |
178
+ | Edge Runtime support | ✓ | Node-only | build it |
179
+ | Vercel KV adapters via subpath | ✓ | — | — |
180
+ | OpenTelemetry instrumentation + recipe | ✓ | — | build it |
181
+ | Circuit breaker + deadline propagation | ✓ | — | build it |
182
+ | Tool middleware (compose audit/rate/metrics) | ✓ | — | — |
183
+ | Time to first cobro | 30 min | 1+ week | 6-8 weeks |
184
+
185
+ See [`MIGRATION.md`](./MIGRATION.md) for a side-by-side `mercadopago` → `@ar-agents/mercadopago` migration guide.
186
+
187
+ ## Security
188
+
189
+ This package handles money. Read [SECURITY.md](../../SECURITY.md) before deploying:
190
+
191
+ - The constructor refuses to instantiate in a browser context (token leak prevention).
192
+ - Every webhook handler MUST call `verifyWebhookSignature` before trusting payload contents.
193
+ - Irreversible tools (`refund_payment`, `cancel_*`, `delete_customer_card`) include explicit confirm-with-user instructions in their descriptions; the LLM should ask before calling.
194
+ - Report vulnerabilities privately per [SECURITY.md](../../SECURITY.md).
195
+
196
+ ## License
197
+
198
+ [MIT](./LICENSE) · © Nazareno Clemente
199
+
200
+ If this saves your team weeks of MP integration work, consider [sponsoring](https://github.com/sponsors/naza00000).
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Recipe 03 — Production-grade webhook handler.
2
+ * Recipe 03 — Webhook handler.
3
3
  *
4
4
  * # The 3-line summary
5
5
  *
package/dist/index.cjs CHANGED
@@ -3030,7 +3030,8 @@ async function verifyWebhookSignature(params) {
3030
3030
 
3031
3031
  // src/tools.ts
3032
3032
  async function deterministicIdempotencyKey(...parts) {
3033
- 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("|");
3034
3035
  return (await sha256Hex(payload)).slice(0, 32);
3035
3036
  }
3036
3037
  var DEFAULT_DESCRIPTIONS = {
@@ -3158,6 +3159,10 @@ var DEFAULT_DESCRIPTIONS = {
3158
3159
  };
3159
3160
  function mercadoPagoTools(client, options) {
3160
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) {
3161
3166
  return {
3162
3167
  // ─────────────────────────────────────────────────────────────────────────
3163
3168
  // Subscriptions (v0.1 — kept identical for backward compatibility)
@@ -4271,6 +4276,22 @@ function mercadoPagoTools(client, options) {
4271
4276
  resource: null
4272
4277
  };
4273
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
+ }
4274
4295
  let resource = null;
4275
4296
  let resourceError = null;
4276
4297
  if (auto_fetch) {
@@ -5163,6 +5184,43 @@ function mercadoPagoTools(client, options) {
5163
5184
  })
5164
5185
  };
5165
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
+ }
5166
5224
 
5167
5225
  // src/state.ts
5168
5226
  var InMemoryStateAdapter = class {