@ar-agents/mercadopago 0.17.1 → 0.17.2

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,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.17.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [`9b8e83c`](https://github.com/ar-agents/ar-agents/commit/9b8e83ce6f291a24e00101830a49afceb0102920) - Add 2 cookbook recipes that demonstrate the cross-package thesis:
8
+
9
+ - **16-acp-checkout-with-factura.ts** — the headline ACP-with-factura pattern. A ChatGPT Instant Checkout / Claude / Gemini agent POSTs an ACP `checkout_session`, the bridge mints a Mercado Pago preference, the buyer pays, and the bridge auto-emits an AFIP/ARCA Factura A/B/C/E via the `facturacionHook` — selecting the comprobante type based on the buyer's IVA condition. No other OSS implementation in LATAM ships this end-to-end.
10
+ - **17-usa-llc-companion.ts** — pattern for a USA-LLC agent (ClawBank, doola Agentic, MIDAO) operating in Argentina via an AR-resident facade. The USA agent declares `@ar-agents/mcp` in its MCP host config; all 89+6+2+10+5+6+5 tools become available without the USA agent ever holding AR credentials. Walks through the operator-of-record split + sample agent prompt that drives charge → factura → WhatsApp confirmation.
11
+
12
+ Cookbook is now 17 recipes (was 15).
13
+
3
14
  ## 0.17.1
4
15
 
5
16
  ### Patch Changes
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Recipe 16 — ACP checkout with auto-issued AR factura electrónica.
3
+ *
4
+ * The headline pattern that no other implementation in LATAM ships out of the
5
+ * box: a **Stripe-style hosted checkout where the buyer is an LLM agent**
6
+ * (ChatGPT Instant Checkout / Claude tool calls / Gemini extensions), and your
7
+ * server auto-emits AFIP/ARCA factura electrónica when the payment confirms.
8
+ *
9
+ * # The flow
10
+ *
11
+ * 1. Agent POSTs `/checkout/sessions` with cart + buyer info (ACP spec).
12
+ * 2. Bridge validates the cart, computes totals, generates a session id.
13
+ * 3. Bridge creates a Mercado Pago `preference` and stores the mapping
14
+ * `acp_session → mp_preference` in your KV.
15
+ * 4. Bridge returns the ACP session with the `init_point_url` for the buyer.
16
+ * 5. Buyer pays. MP fires `payment.created` webhook.
17
+ * 6. Bridge's MP webhook handler dispatches to your `facturacionHook`,
18
+ * which calls `@ar-agents/facturacion` to emit Factura A/B/C/E based on
19
+ * the buyer's IVA condition (looked up via @ar-agents/identity).
20
+ * 7. ACP `complete_session` returns the factura PDF URL inside the receipt.
21
+ *
22
+ * # Why this is unique
23
+ *
24
+ * - Stripe's ACP doesn't ship AR factura (Stripe doesn't operate in AR).
25
+ * - Satsuma.ai's "make-my-site-agent-compatible" SaaS handles the agent
26
+ * surface but defers tax to the merchant.
27
+ * - MercadoPago's official MCP exposes payments but no ACP layer.
28
+ * - This recipe is the only OSS path from "agent buys" to "factura emitted"
29
+ * without the merchant writing tax-emission code themselves.
30
+ */
31
+
32
+ import { createDispatcher } from "@ar-agents/agentic-commerce-bridge";
33
+ import {
34
+ createMercadoPagoPaymentProvider,
35
+ mercadoPagoPaymentHandler,
36
+ } from "@ar-agents/agentic-commerce-bridge/mp";
37
+ import {
38
+ createFacturacionHook,
39
+ selectFacturaType,
40
+ } from "@ar-agents/agentic-commerce-bridge/facturacion";
41
+ import { InMemoryStateAdapter } from "@ar-agents/agentic-commerce-bridge";
42
+
43
+ import { MercadoPagoClient } from "@ar-agents/mercadopago";
44
+ import { WsfeClient } from "@ar-agents/facturacion";
45
+
46
+ // ─────────────────────────────────────────────────────────────────────────────
47
+ // Wire the bridge — payment provider + factura emission hook
48
+ // ─────────────────────────────────────────────────────────────────────────────
49
+
50
+ const mp = new MercadoPagoClient({
51
+ accessToken: process.env.MP_ACCESS_TOKEN!,
52
+ });
53
+
54
+ const wsfe = new WsfeClient({
55
+ certPem: process.env.AFIP_CERT_PEM!,
56
+ keyPem: process.env.AFIP_KEY_PEM!,
57
+ cuit: Number(process.env.AFIP_CUIT!),
58
+ env: "prod",
59
+ });
60
+
61
+ // Payment provider: knows how to mint MP preferences from ACP cart payloads.
62
+ const mpProvider = createMercadoPagoPaymentProvider({
63
+ client: mp,
64
+ notificationUrl: "https://yourdomain.com/api/mp/webhook",
65
+ });
66
+
67
+ // Facturacion hook: fires after `payment.approved` from MP webhook.
68
+ const facturacionHook = createFacturacionHook({
69
+ wsfe,
70
+ defaultPtoVta: 1, // your AFIP point-of-sale
71
+ // Agent decides what to bill against — typically a CUIT lookup result
72
+ // for B2B sales, or "consumidor final" for B2C (Factura B).
73
+ selectType: ({ buyer }) =>
74
+ selectFacturaType({
75
+ sellerCondition: "responsable_inscripto", // your IVA condition
76
+ buyerCondition: buyer.taxStatus ?? "consumidor_final",
77
+ }),
78
+ });
79
+
80
+ // Dispatcher: routes the ACP HTTP surface (checkout-session CRUD).
81
+ const dispatcher = createDispatcher({
82
+ state: new InMemoryStateAdapter(), // VercelKVStateAdapter in prod
83
+ payment: mpProvider,
84
+ hooks: { onPaymentApproved: facturacionHook },
85
+ });
86
+
87
+ // ─────────────────────────────────────────────────────────────────────────────
88
+ // Next.js Route Handler — the ACP HTTP surface
89
+ // ─────────────────────────────────────────────────────────────────────────────
90
+
91
+ export async function POST(req: Request, ctx: { params: { route: string[] } }) {
92
+ // Spec endpoints:
93
+ // POST /checkout_sessions → handleCreateSession
94
+ // POST /checkout_sessions/{id} → handleUpdateSession
95
+ // POST /checkout_sessions/{id}/complete → handleCompleteSession
96
+ // POST /checkout_sessions/{id}/cancel → handleCancelSession
97
+ return dispatcher.handle(req);
98
+ }
99
+
100
+ export async function GET(req: Request) {
101
+ // Spec endpoints:
102
+ // GET /checkout_sessions/{id} → handleGetSession
103
+ // GET /.well-known/acp.json → discovery payload
104
+ return dispatcher.handle(req);
105
+ }
106
+
107
+ // ─────────────────────────────────────────────────────────────────────────────
108
+ // Companion MP webhook route — fires the facturacion hook
109
+ // ─────────────────────────────────────────────────────────────────────────────
110
+
111
+ export async function MP_WEBHOOK(req: Request) {
112
+ // The bridge's MP integration verifies HMAC signatures and dispatches
113
+ // to your `onPaymentApproved` hook. The hook receives the ACP session
114
+ // (looked up via the external_reference round-trip) + the MP payment.
115
+ return mercadoPagoPaymentHandler({
116
+ state: dispatcher.state,
117
+ hooks: dispatcher.hooks,
118
+ webhookSecret: process.env.MP_WEBHOOK_SECRET!,
119
+ })(req);
120
+ }
121
+
122
+ // ─────────────────────────────────────────────────────────────────────────────
123
+ // What an agent sees
124
+ // ─────────────────────────────────────────────────────────────────────────────
125
+
126
+ /*
127
+ A ChatGPT Instant Checkout flow (excerpt):
128
+
129
+ 1. Agent calls `POST /checkout_sessions` with:
130
+ {
131
+ "buyer": { "email": "buyer@example.com" },
132
+ "items": [{ "id": "sku-123", "quantity": 1, "amount": 100000 }],
133
+ "totals": { "amount": 100000, "currency": "ars", ... },
134
+ "fulfillment_address": { ... }
135
+ }
136
+
137
+ 2. Bridge returns:
138
+ {
139
+ "id": "cs_abc123",
140
+ "status": "ready_for_payment",
141
+ "payment_method": {
142
+ "type": "redirect",
143
+ "redirect_url": "https://www.mercadopago.com.ar/checkout/v1/redirect?pref_id=…"
144
+ }
145
+ }
146
+
147
+ 3. Buyer pays. MP fires webhook → facturacionHook fires → AFIP returns CAE.
148
+
149
+ 4. Agent calls `POST /checkout_sessions/cs_abc123/complete`:
150
+ {
151
+ "id": "cs_abc123",
152
+ "status": "complete",
153
+ "receipt": {
154
+ "payment_id": "mp-payment-id",
155
+ "factura": {
156
+ "type": "B",
157
+ "cae": "75123456789012",
158
+ "cae_due": "2026-05-18",
159
+ "pdf_url": "https://yourdomain.com/facturas/cs_abc123.pdf",
160
+ "amount": 100000,
161
+ "issued_at": "2026-05-08T19:00:00Z"
162
+ }
163
+ }
164
+ }
165
+
166
+ The agent surfaces the factura URL to the buyer in its receipt rendering.
167
+ The merchant did zero tax-emission code — the bridge handled it.
168
+ */
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Recipe 17 — USA-LLC agent operating in Argentina via @ar-agents/* MCP.
3
+ *
4
+ * Pattern: a USA-incorporated agent (ClawBank-formed Wyoming/Ohio LLC, doola
5
+ * Agentic LLC, Marshall Islands MIDAO entity, etc.) needs to do business in
6
+ * Argentina — invoice AR customers, validate AR taxpayer IDs, accept Mercado
7
+ * Pago, ship via Andreani, monitor regulatory changes. The USA agent doesn't
8
+ * itself have AR tax residency or banking infrastructure; it composes with a
9
+ * thin AR-resident "facade" entity (escribano, contador, or platform partner)
10
+ * for the bits that legally require AR presence.
11
+ *
12
+ * # The split
13
+ *
14
+ * USA-LLC agent AR facade (escribano / contador / platform)
15
+ * ----------------- -------------------------------------------
16
+ * - decides what to do - holds the AFIP/ARCA cert
17
+ * - signs payment intent - emits factura under their CUIT
18
+ * - holds USD escrow - converts USD → ARS for settlement
19
+ * - delegates AR ops - acts as the AR-resident contracting party
20
+ *
21
+ * The USA agent never touches AFIP directly. Instead it calls an AR-resident
22
+ * MCP server that exposes @ar-agents/* tools, and that MCP server's keys belong
23
+ * to the AR facade. This is the legally-clean way to operate cross-border:
24
+ * the AR entity is the principal, the USA agent is the platform.
25
+ *
26
+ * # The MCP host config (USA-LLC side)
27
+ *
28
+ * The USA agent (Claude Desktop / Cursor / a custom MCP host) declares:
29
+ *
30
+ * {
31
+ * "mcpServers": {
32
+ * "ar-ops": {
33
+ * "command": "npx",
34
+ * "args": ["-y", "@ar-agents/mcp"],
35
+ * "env": {
36
+ * // ALL of these belong to the AR facade — never the USA agent.
37
+ * "MP_ACCESS_TOKEN": "APP_USR-…", // facade's MP merchant token
38
+ * "AFIP_CERT_PEM": "-----BEGIN CERTIFICATE-----…",
39
+ * "AFIP_KEY_PEM": "-----BEGIN PRIVATE KEY-----…",
40
+ * "AFIP_CUIT": "30-12345678-9", // facade's CUIT
41
+ * "WHATSAPP_ACCESS_TOKEN": "EAA…" // optional
42
+ * }
43
+ * }
44
+ * }
45
+ * }
46
+ *
47
+ * # What the USA agent can now do
48
+ *
49
+ * - validate_cuit(payerCuit) — algorithm, free, no AR exposure
50
+ * - lookup_cuit_afip(payerCuit) — AR fiscal data, scoped to facade's cert
51
+ * - create_payment(amount, payerEmail, ...) — charges run on facade's MP merchant
52
+ * - emit_factura_b(amount, payerCuit, items) — emitted under facade's CUIT
53
+ * - cotizar_envio_andreani(toCpa, weight) — quote against facade's carrier account
54
+ * - send_whatsapp_text(to, body) — sent from facade's WhatsApp number
55
+ *
56
+ * The USA agent's logic stays in JS; the AR-resident operations stay on the
57
+ * AR side. Both sides see the agreement via signed MCP tool-call records.
58
+ *
59
+ * # Sample agent loop (USA-LLC side, using Vercel AI SDK 6 + MCP client)
60
+ */
61
+
62
+ import { Experimental_Agent as Agent, stepCountIs } from "ai";
63
+ // In a USA agent's project, you'd use the MCP client from `ai` v6 (or `@modelcontextprotocol/sdk`)
64
+ // to connect to the locally-spawned ar-agents MCP server. The agent then sees
65
+ // every @ar-agents/* tool in its tool list.
66
+ //
67
+ // import { experimental_createMCPClient as createMCPClient } from "ai";
68
+
69
+ async function exampleAgentLoop() {
70
+ // ─── Boot the MCP client connection (USA agent → AR facade's MCP server) ─
71
+ // const arOps = await createMCPClient({
72
+ // transport: { type: "stdio", command: "npx", args: ["-y", "@ar-agents/mcp"] },
73
+ // });
74
+ // const tools = await arOps.tools();
75
+ //
76
+ // The 89 + 6 + 2 + 10 + 5 + 6 + 5 = 123 tools across all 7 packages are
77
+ // now available as if they were native to the USA agent.
78
+
79
+ const agent = new Agent({
80
+ model: "anthropic/claude-sonnet-4-6",
81
+ instructions:
82
+ "You are an AI agent incorporated as a Wyoming LLC. To do business in " +
83
+ "Argentina you delegate AR-resident operations to an AR facade via the " +
84
+ "ar-ops MCP server. ALL invoicing, payment collection, taxpayer lookups, " +
85
+ "and shipping in AR go through ar-ops tools. Never store AR credentials " +
86
+ "yourself.",
87
+ // tools, // injected from MCP client
88
+ tools: {} as Record<string, unknown>,
89
+ stopWhen: stepCountIs(10),
90
+ });
91
+
92
+ // What the agent does behind this prompt:
93
+ // 1. validate_cuit("20-12345678-9") via ar-ops
94
+ // 2. lookup_cuit_afip → "Cliente SRL, Responsable Inscripto"
95
+ // 3. cotizar_envio_andreani(B1842, 0.5kg) → AR$ 4.500
96
+ // 4. create_payment(amount=104500, payerEmail) → init_point_url
97
+ // 5. (after payment confirms) emit_factura_a(104500, payerCuit, ["servicio digital"])
98
+ // 6. send_whatsapp_text(payerPhone, "Listo. Factura A: <pdf-url>")
99
+ const { text } = await agent.generate({
100
+ prompt:
101
+ "Cobrale a un cliente AR (CUIT 20-12345678-9, email contacto@ejemplo.com.ar, " +
102
+ "WhatsApp +5491155555555) USD 100 (≈ AR$ 100.000) por un servicio de consultoría " +
103
+ "+ envío Andreani al CP B1842. Si validás que es Responsable Inscripto, emití " +
104
+ "factura A. Si no, factura B. Mandale el link por WhatsApp cuando esté.",
105
+ });
106
+
107
+ console.log(text);
108
+ }
109
+
110
+ if (process.argv[1]?.endsWith("17-usa-llc-companion.ts")) {
111
+ exampleAgentLoop().catch((err: unknown) => {
112
+ console.error(err);
113
+ process.exit(1);
114
+ });
115
+ }
116
+
117
+ export { exampleAgentLoop };
@@ -23,6 +23,8 @@ deploy on Vercel as-is.
23
23
  | 13 | `13-anti-fraud-middleware.ts` | Pre-charge heuristics (CUIT, payer history, velocity, promo abuse) |
24
24
  | 14 | `14-marketplace-onboarding.ts` | End-to-end seller-onboarding: CUIT → AFIP → OAuth → test charge → fee |
25
25
  | 15 | `15-prorated-pause-resume.ts` | Pause with prorated refund, resume with adjusted next-billing date |
26
+ | 16 | `16-acp-checkout-with-factura.ts` | Agentic Commerce Protocol checkout that auto-emits AFIP/ARCA Factura A/B/C/E |
27
+ | 17 | `17-usa-llc-companion.ts` | USA-LLC agent (ClawBank/doola/MIDAO) consuming AR ops via @ar-agents/mcp |
26
28
 
27
29
  ## Conventions
28
30
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ar-agents/mercadopago",
3
- "version": "0.17.1",
3
+ "version": "0.17.2",
4
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",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://github.com/ar-agents/ar-agents/blob/main/tools-manifest.schema.json",
3
3
  "package": "@ar-agents/mercadopago",
4
- "version": "0.17.1",
4
+ "version": "0.17.2",
5
5
  "factory": "mercadoPagoTools",
6
6
  "tools": [
7
7
  {