@ar-agents/mercadopago 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -507,6 +507,9 @@ var MercadoPagoClient = class {
507
507
  if (params.expires !== void 0) body.expires = params.expires;
508
508
  if (params.expirationDateFrom) body.expiration_date_from = params.expirationDateFrom;
509
509
  if (params.expirationDateTo) body.expiration_date_to = params.expirationDateTo;
510
+ if (params.marketplace) body.marketplace = params.marketplace;
511
+ if (params.marketplaceFee !== void 0) body.marketplace_fee = params.marketplaceFee;
512
+ if (params.collectorId !== void 0) body.collector_id = params.collectorId;
510
513
  return this.request("POST", "/checkout/preferences", body);
511
514
  }
512
515
  async getPreference(id) {
@@ -896,1081 +899,67 @@ var MercadoPagoClient = class {
896
899
  async deleteWebhook(id) {
897
900
  await this.request("DELETE", `/v1/webhooks/${id}`);
898
901
  }
899
- };
900
- function deterministicIdempotencyKey(...parts) {
901
- const payload = parts.filter((p) => p !== void 0 && p !== null).map(String).join("|");
902
- return crypto.createHash("sha256").update(payload).digest("hex").slice(0, 32);
903
- }
904
- var DEFAULT_DESCRIPTIONS = {
905
- // ── Subscriptions ────────────────────────────────────────────────────────
906
- create_subscription: "Create a Mercado Pago recurring subscription. Returns an init_point URL where the customer must complete the FIRST payment with their card and CVV (this is a hard MP requirement; agents cannot bypass it). After they pay, MP will auto-charge at the configured frequency without further intervention.",
907
- get_subscription_status: "Check the current status of a Mercado Pago subscription. Use this to confirm the customer completed the first payment (status becomes 'authorized') or to inspect the next charge date.",
908
- cancel_subscription: "Cancel an active Mercado Pago subscription. After cancellation, MP will not charge the customer again. This action is irreversible \u2014 confirm with the user before calling.",
909
- pause_subscription: "Pause an authorized Mercado Pago subscription. Charges stop until resumed. Only works on subscriptions in 'authorized' status.",
910
- resume_subscription: "Resume a paused Mercado Pago subscription. Charges resume on the next scheduled date. Only works on subscriptions in 'paused' status.",
911
- // ── Payments ─────────────────────────────────────────────────────────────
912
- create_payment: "Create a one-time payment. Two flows: (a) with a card token from MP frontend Cardform \u2014 for transparent checkout; (b) without token, for non-card methods like 'account_money', 'rapipago', 'pagofacil'. For most agent flows where you only have a payer email and want to send them a payment link, use create_payment_preference instead (Checkout Pro hosted form). Returns the Payment object with status \u2014 typically 'approved' for account_money and 'pending' for tickets.",
913
- get_payment: "Fetch a single payment by ID. Use to confirm status after webhook arrives, or to inspect details (status_detail explains rejections).",
914
- search_payments: "Search payments with filters. Most common: by external_reference (your-system identifier) to find all payments for an order, or by status='approved' to list successful charges in a date range. Returns paginated results.",
915
- cancel_payment: "Cancel a pending or in_process payment (only works before approval). Once approved, use refund_payment instead. Common use: cancel an unpaid ticket payment that's still pending.",
916
- capture_payment: "Capture an authorized credit-card payment that was created with capture=false. Use for hold-then-capture flows (e.g., authorize on order, capture on shipment). Optional partial amount.",
917
- // ── Refunds ──────────────────────────────────────────────────────────────
918
- refund_payment: "Refund an approved payment. Pass amount for partial refund; omit for full refund. Idempotency key is auto-generated based on paymentId+amount to prevent double-refunds on retries.",
919
- list_refunds: "List all refunds for a given payment. Returns array of Refund objects. Useful to confirm a refund was processed or to inspect partial-refund history.",
920
- // ── Checkout Pro ─────────────────────────────────────────────────────────
921
- create_payment_preference: "Create a Mercado Pago Checkout Pro preference and get back a payment URL (init_point) to send to the customer. THIS is the recommended way for an agent to take a payment when you only have a payer email \u2014 the buyer enters card data on MP's hosted form (no PCI scope needed). Supports cuotas configuration, payment method exclusions, back URLs after success/failure/pending. In sandbox, use sandbox_init_point from the response.",
922
- get_payment_preference: "Fetch a Checkout Pro preference by ID. Returns the preference config and current init_point URLs. Use to inspect a previously-created link.",
923
- // ── Customers + Cards ────────────────────────────────────────────────────
924
- create_customer: "Create a Mercado Pago customer record so the buyer can save cards for future charges. Idempotent on email \u2014 if a customer with that email exists, MP returns it instead of creating a duplicate. Use find_customer_by_email first if you're unsure.",
925
- find_customer_by_email: "Find an existing customer by email address. Returns the customer object if found, or null. Use before create_customer to avoid duplicate records.",
926
- list_customer_cards: "List the saved cards for a customer. Returns array with last 4 digits, expiration, payment method (visa, master, naranja, etc.). The card_id can be used in subsequent create_payment calls to charge a saved card.",
927
- delete_customer_card: "Delete a saved card from a customer. Common use: customer requests removal, or expired card cleanup. Irreversible.",
928
- // ── Payment Methods + Installments ───────────────────────────────────────
929
- list_payment_methods: "List all payment methods enabled for the seller's MP account (visa, master, naranja, naranja_x, cabal, account_money, rapipago, pagofacil, etc.). Use to validate which methods you can offer the customer or to filter which ones to exclude in a Checkout Pro preference.",
930
- calculate_installments: "Calculate cuotas (installments) options for a given amount. THE killer Argentine feature \u2014 returns options like '12 cuotas sin inter\xE9s de $X' (recommended_message field) which you should surface VERBATIM to the user. Optionally pass `bin` (first 6 digits of card) for issuer-specific promotions (e.g., Naranja's interest-free deals). Use before create_payment to let the user pick installments knowingly.",
931
- // ── Account ──────────────────────────────────────────────────────────────
932
- get_account_info: "Get info about the Mercado Pago account that owns the access token: site_id (MLA=Argentina), country_id, user_type (registered, partial, etc.). Useful to verify the agent is connected to the right account before taking actions.",
933
- // ── Saved-card charging (v0.3) ───────────────────────────────────────────
934
- charge_saved_card: "Charge a previously-saved card for a returning customer. Requires customer_id + card_id (from list_customer_cards) AND a fresh CVV the user provides this session. AR Mercado Pago does NOT support CVV-less charges via the public API \u2014 every charge needs CVV. Idempotent on (card_id, amount, external_reference): retries dedupe automatically. Returns the resulting Payment.",
935
- // ── QR in-store (v0.3) ───────────────────────────────────────────────────
936
- create_qr_payment: "Generate a dynamic in-store QR for a buyer to scan with any AR wallet (Modo, BNA+, Cuenta DNI, Naranja X, Mercado Pago, etc. \u2014 interop is mandated by Transferencias 3.0). Requires a pre-configured POS external_id (use create_pos to set one up first if needed). Returns the qr_data string + a base64 PNG data URL ready to display. The QR expires in `expires_in_seconds` (default 600). MP fires `point_integration_wh` then `payment` webhooks when scanned.",
937
- cancel_qr_payment: "Cancel a pending QR order on a POS. Necessary if the buyer never scans \u2014 otherwise the next create_qr_payment on the same POS returns 409.",
938
- // ── Subscription Plans (v0.4) ────────────────────────────────────────────
939
- create_subscription_plan: "Create a REUSABLE subscription plan (preapproval_plan). Different from create_subscription: a plan defines price + frequency once, then customers subscribe to it via subscribe_to_plan. Use plans for SaaS-style billing (B\xE1sico/Pro/Enterprise tiers). For per-customer custom amounts, use create_subscription directly.",
940
- list_subscription_plans: "List all subscription plans defined for this MP account. Useful before create_subscription_plan to check if one already exists, or for surfacing options to a customer.",
941
- update_subscription_plan: "Update a subscription plan's reason / amount / status / back_url. Existing customer subscriptions to the plan are NOT automatically updated \u2014 only NEW subscribers get the new pricing.",
942
- subscribe_to_plan: "Subscribe a customer to an existing reusable plan. Returns a Preapproval with init_point URL where the customer completes first payment. Cleaner than create_subscription when you have fixed tiers.",
943
- list_subscription_payments: "List the auto-charge attempts (authorized_payments) under a subscription. Useful for 'show me the cobros del \xFAltimo mes for this client' or to debug a failing recurring charge.",
944
- // ── Stores + POS (v0.4) ──────────────────────────────────────────────────
945
- create_store: "Create a store under the seller's MP account. Stores are the parent entity for POSes (which generate QR payments). Required ONE-TIME setup before create_pos. Pass a unique external_id and a display name.",
946
- list_stores: "List all stores configured for this MP account. Use this to find an existing store_id before create_pos, or to surface store options to the agent.",
947
- create_pos: "Create a POS (Point of Sale) under a store. The POS's external_id is what create_qr_payment uses. Each physical checkout / counter / agent typically has its own POS. Categories are MP-defined (default 621102 = Other Food and Beverage Services).",
948
- list_pos: "List all POSes for the seller (or filtered by store_id). Use to find an existing POS before create_qr_payment, or to surface options.",
949
- // ── Disputes (v0.4 — read-only) ──────────────────────────────────────────
950
- list_payment_disputes: "List all disputes / chargebacks raised against a payment. Read-only \u2014 resolution is dashboard-only. Surface the dashboard URL `https://www.mercadopago.com.ar/disputes/{dispute_id}` to the user when they need to respond.",
951
- get_dispute: "Get details of a specific dispute including reason, amount, resolution status. Read-only.",
952
- // ── Lookup helpers (v0.4) ────────────────────────────────────────────────
953
- list_identification_types: "List valid identification types for the seller's site. AR returns: DNI, CI, LE, LC, Otro, Pasaporte, CUIT, CUIL with their min/max length. Useful to validate an identification before passing to create_payment.",
954
- list_issuers: "List card issuers (banks) that support a payment_method_id. Optionally filter by `bin` (first 6 digits of the card) for accurate issuer detection. Useful with calculate_installments \u2014 issuer-specific promos (e.g., Naranja Galicia 6 cuotas sin inter\xE9s) only appear when the issuer is identified.",
955
- // ── Webhooks management (v0.4) ───────────────────────────────────────────
956
- list_webhooks: "List all webhook subscriptions configured for this MP application. Use to see what topics + URLs are wired before adding new ones.",
957
- create_webhook: "Subscribe a webhook URL to a MP topic (payment, subscription_authorized_payment, subscription_preapproval, merchant_order, point_integration_wh). MP will POST to this URL when events of that topic fire.",
958
- update_webhook: "Update a webhook's URL or topic. Useful when you change deployment URLs without resubscribing from scratch.",
959
- delete_webhook: "Delete a webhook subscription. MP stops POSTing to it immediately."
960
- };
961
- function mercadoPagoTools(client, options) {
962
- const desc = (name) => options.descriptions?.[name] ?? DEFAULT_DESCRIPTIONS[name];
963
- return {
964
- // ─────────────────────────────────────────────────────────────────────────
965
- // Subscriptions (v0.1 — kept identical for backward compatibility)
966
- // ─────────────────────────────────────────────────────────────────────────
967
- create_subscription: ai.tool({
968
- description: desc("create_subscription"),
969
- inputSchema: zod.z.object({
970
- customer_email: zod.z.string().email().describe("Email of the customer who will be charged"),
971
- amount_ars: zod.z.number().positive().describe("Amount in Argentine Pesos per recurring charge"),
972
- frequency_months: zod.z.number().int().positive().max(12).describe("Frequency in months (1=monthly, 3=quarterly, 12=yearly)"),
973
- reason: zod.z.string().min(3).max(120).describe("Short description shown to the customer at checkout"),
974
- external_reference: zod.z.string().optional().describe("Optional id from your system to track this subscription")
975
- }),
976
- execute: async ({ customer_email, amount_ars, frequency_months, reason, external_reference }) => {
977
- const created = await client.createPreapproval({
978
- reason,
979
- payerEmail: customer_email,
980
- amount: amount_ars,
981
- currency: "ARS",
982
- frequency: frequency_months,
983
- frequencyType: "months",
984
- backUrl: options.backUrl,
985
- ...external_reference !== void 0 ? { externalReference: external_reference } : {}
986
- });
987
- await options.state.set(created.id, {
988
- status: created.status,
989
- payerEmail: customer_email,
990
- amount: amount_ars,
991
- currency: "ARS",
992
- frequency: frequency_months,
993
- frequencyType: "months",
994
- initPoint: created.init_point,
995
- ...external_reference !== void 0 ? { externalReference: external_reference } : {},
996
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
997
- });
998
- return {
999
- subscription_id: created.id,
1000
- status: created.status,
1001
- init_point_url: created.init_point,
1002
- next_step: "Send init_point_url to the customer. They must complete the first payment with card+CVV. Use get_subscription_status to confirm activation after they pay."
1003
- };
1004
- }
1005
- }),
1006
- get_subscription_status: ai.tool({
1007
- description: desc("get_subscription_status"),
1008
- inputSchema: zod.z.object({
1009
- subscription_id: zod.z.string().describe("The Mercado Pago subscription/preapproval ID")
1010
- }),
1011
- execute: async ({ subscription_id }) => {
1012
- const fresh = await client.getPreapproval(subscription_id);
1013
- const cached = await options.state.get(subscription_id);
1014
- return {
1015
- subscription_id: fresh.id,
1016
- status: fresh.status,
1017
- payer_email: fresh.payer_email,
1018
- amount: fresh.auto_recurring.transaction_amount,
1019
- currency: fresh.auto_recurring.currency_id,
1020
- next_payment_date: fresh.next_payment_date ?? null,
1021
- last_webhook_status: cached?.lastWebhookStatus ?? null,
1022
- last_webhook_at: cached?.lastWebhookAt ?? null
1023
- };
1024
- }
1025
- }),
1026
- cancel_subscription: ai.tool({
1027
- description: desc("cancel_subscription"),
1028
- inputSchema: zod.z.object({
1029
- subscription_id: zod.z.string().describe("The Mercado Pago subscription/preapproval ID to cancel")
1030
- }),
1031
- execute: async ({ subscription_id }) => {
1032
- const cancelled = await client.cancelPreapproval(subscription_id);
1033
- await options.state.set(subscription_id, {
1034
- status: cancelled.status,
1035
- cancelledAt: (/* @__PURE__ */ new Date()).toISOString()
1036
- });
1037
- return {
1038
- subscription_id: cancelled.id,
1039
- status: cancelled.status,
1040
- message: "Subscription cancelled. No further charges will occur."
1041
- };
1042
- }
1043
- }),
1044
- pause_subscription: ai.tool({
1045
- description: desc("pause_subscription"),
1046
- inputSchema: zod.z.object({ subscription_id: zod.z.string() }),
1047
- execute: async ({ subscription_id }) => {
1048
- const paused = await client.pausePreapproval(subscription_id);
1049
- await options.state.set(subscription_id, { status: paused.status });
1050
- return {
1051
- subscription_id: paused.id,
1052
- status: paused.status,
1053
- message: "Subscription paused. Use resume_subscription to reactivate."
1054
- };
1055
- }
1056
- }),
1057
- resume_subscription: ai.tool({
1058
- description: desc("resume_subscription"),
1059
- inputSchema: zod.z.object({ subscription_id: zod.z.string() }),
1060
- execute: async ({ subscription_id }) => {
1061
- const resumed = await client.resumePreapproval(subscription_id);
1062
- await options.state.set(subscription_id, { status: resumed.status });
1063
- return {
1064
- subscription_id: resumed.id,
1065
- status: resumed.status,
1066
- message: "Subscription resumed. Charges will continue on next scheduled date."
1067
- };
1068
- }
1069
- }),
1070
- // ─────────────────────────────────────────────────────────────────────────
1071
- // Payments (v0.2)
1072
- // ─────────────────────────────────────────────────────────────────────────
1073
- create_payment: ai.tool({
1074
- description: desc("create_payment"),
1075
- inputSchema: zod.z.object({
1076
- amount_ars: zod.z.number().positive().describe("Amount in ARS"),
1077
- payment_method_id: zod.z.string().describe("MP payment method id (e.g. 'account_money', 'rapipago', 'visa', 'master', 'naranja')"),
1078
- payer_email: zod.z.string().email().describe("Email of the payer. Cannot equal seller email."),
1079
- token: zod.z.string().optional().describe("Card token from MP frontend Cardform. Required for credit/debit; omit for cash/account_money."),
1080
- installments: zod.z.number().int().min(1).max(24).optional().describe("Number of installments (cuotas). Default 1. Use calculate_installments first to see options."),
1081
- description: zod.z.string().max(255).optional().describe("Short description"),
1082
- external_reference: zod.z.string().optional().describe("Your-system identifier"),
1083
- identification: zod.z.object({
1084
- type: zod.z.enum(["DNI", "CUIT", "CUIL"]),
1085
- number: zod.z.string()
1086
- }).optional().describe("Payer identification \u2014 required for some payment types in AR"),
1087
- statement_descriptor: zod.z.string().max(13).optional().describe("Shows on buyer's card statement (max 13 chars)")
1088
- }),
1089
- execute: async (input) => {
1090
- const payment = await client.createPayment({
1091
- transactionAmount: input.amount_ars,
1092
- paymentMethodId: input.payment_method_id,
1093
- payerEmail: input.payer_email,
1094
- ...input.token !== void 0 ? { token: input.token } : {},
1095
- ...input.installments !== void 0 ? { installments: input.installments } : {},
1096
- ...input.description !== void 0 ? { description: input.description } : {},
1097
- ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1098
- ...input.identification !== void 0 ? { identification: input.identification } : {},
1099
- ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
1100
- ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
1101
- // Deterministic idempotency key — safe to retry, same inputs always
1102
- // produce the same key (MP dedupes on its side).
1103
- idempotencyKey: deterministicIdempotencyKey(
1104
- "create_payment",
1105
- input.external_reference ?? input.payer_email,
1106
- input.amount_ars,
1107
- input.payment_method_id,
1108
- input.token
1109
- )
1110
- });
1111
- return {
1112
- payment_id: payment.id,
1113
- status: payment.status,
1114
- status_detail: payment.status_detail,
1115
- amount: payment.transaction_amount,
1116
- currency: payment.currency_id,
1117
- installments: payment.installments,
1118
- payment_method: payment.payment_method_id,
1119
- payer_email: payment.payer?.email ?? null,
1120
- external_reference: payment.external_reference,
1121
- date_created: payment.date_created,
1122
- date_approved: payment.date_approved
1123
- };
1124
- }
1125
- }),
1126
- get_payment: ai.tool({
1127
- description: desc("get_payment"),
1128
- inputSchema: zod.z.object({
1129
- payment_id: zod.z.string().describe("The MP payment ID")
1130
- }),
1131
- execute: async ({ payment_id }) => {
1132
- const p = await client.getPayment(payment_id);
1133
- return {
1134
- payment_id: p.id,
1135
- status: p.status,
1136
- status_detail: p.status_detail,
1137
- amount: p.transaction_amount,
1138
- currency: p.currency_id,
1139
- payment_method: p.payment_method_id,
1140
- installments: p.installments,
1141
- payer_email: p.payer?.email ?? null,
1142
- external_reference: p.external_reference,
1143
- date_created: p.date_created,
1144
- date_approved: p.date_approved,
1145
- net_received: p.transaction_details?.net_received_amount ?? null
1146
- };
1147
- }
1148
- }),
1149
- search_payments: ai.tool({
1150
- description: desc("search_payments"),
1151
- inputSchema: zod.z.object({
1152
- external_reference: zod.z.string().optional(),
1153
- status: zod.z.string().optional().describe("'approved' | 'pending' | 'rejected' | 'cancelled' | 'refunded' etc."),
1154
- payer_email: zod.z.string().optional(),
1155
- begin_date: zod.z.string().optional().describe("ISO 8601, e.g. 2026-01-01T00:00:00Z"),
1156
- end_date: zod.z.string().optional().describe("ISO 8601"),
1157
- limit: zod.z.number().int().min(1).max(100).optional().describe("Default 30, max 100"),
1158
- offset: zod.z.number().int().min(0).optional().describe("Pagination offset (default 0)")
1159
- }),
1160
- execute: async (input) => {
1161
- const result = await client.searchPayments({
1162
- ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1163
- ...input.status !== void 0 ? { status: input.status } : {},
1164
- ...input.payer_email !== void 0 ? { payerEmail: input.payer_email } : {},
1165
- ...input.begin_date !== void 0 ? { beginDate: input.begin_date } : {},
1166
- ...input.end_date !== void 0 ? { endDate: input.end_date } : {},
1167
- ...input.limit !== void 0 ? { limit: input.limit } : {},
1168
- ...input.offset !== void 0 ? { offset: input.offset } : {}
1169
- });
1170
- return {
1171
- total: result.paging.total,
1172
- returned: result.results.length,
1173
- offset: result.paging.offset,
1174
- payments: result.results.map((p) => ({
1175
- payment_id: p.id,
1176
- status: p.status,
1177
- amount: p.transaction_amount,
1178
- currency: p.currency_id,
1179
- payer_email: p.payer?.email ?? null,
1180
- external_reference: p.external_reference,
1181
- date_created: p.date_created
1182
- }))
1183
- };
1184
- }
1185
- }),
1186
- cancel_payment: ai.tool({
1187
- description: desc("cancel_payment"),
1188
- inputSchema: zod.z.object({ payment_id: zod.z.string() }),
1189
- execute: async ({ payment_id }) => {
1190
- const cancelled = await client.cancelPayment(payment_id);
1191
- return {
1192
- payment_id: cancelled.id,
1193
- status: cancelled.status,
1194
- message: "Payment cancelled. If it was already approved, use refund_payment instead."
1195
- };
1196
- }
1197
- }),
1198
- capture_payment: ai.tool({
1199
- description: desc("capture_payment"),
1200
- inputSchema: zod.z.object({
1201
- payment_id: zod.z.string(),
1202
- amount_ars: zod.z.number().positive().optional().describe("Optional partial-capture amount. Omit to capture full authorized amount.")
1203
- }),
1204
- execute: async ({ payment_id, amount_ars }) => {
1205
- const captured = await client.capturePayment(payment_id, amount_ars);
1206
- return {
1207
- payment_id: captured.id,
1208
- status: captured.status,
1209
- amount: captured.transaction_amount
1210
- };
1211
- }
1212
- }),
1213
- // ─────────────────────────────────────────────────────────────────────────
1214
- // Refunds
1215
- // ─────────────────────────────────────────────────────────────────────────
1216
- refund_payment: ai.tool({
1217
- description: desc("refund_payment"),
1218
- inputSchema: zod.z.object({
1219
- payment_id: zod.z.string(),
1220
- amount_ars: zod.z.number().positive().optional().describe("Partial-refund amount in ARS. Omit for full refund.")
1221
- }),
1222
- execute: async ({ payment_id, amount_ars }) => {
1223
- const refund = await client.createRefund({
1224
- paymentId: payment_id,
1225
- ...amount_ars !== void 0 ? { amount: amount_ars } : {},
1226
- idempotencyKey: deterministicIdempotencyKey("refund", payment_id, amount_ars ?? "full")
1227
- });
1228
- return {
1229
- refund_id: refund.id,
1230
- payment_id: refund.payment_id,
1231
- amount: refund.amount,
1232
- status: refund.status,
1233
- message: amount_ars === void 0 ? "Full refund issued. Funds return to the buyer in 3-10 business days." : `Partial refund of ${amount_ars} ARS issued.`
1234
- };
1235
- }
1236
- }),
1237
- list_refunds: ai.tool({
1238
- description: desc("list_refunds"),
1239
- inputSchema: zod.z.object({ payment_id: zod.z.string() }),
1240
- execute: async ({ payment_id }) => {
1241
- const refunds = await client.listRefunds(payment_id);
1242
- return {
1243
- payment_id,
1244
- count: refunds.length,
1245
- refunds: refunds.map((r) => ({
1246
- refund_id: r.id,
1247
- amount: r.amount,
1248
- status: r.status,
1249
- date_created: r.date_created
1250
- }))
1251
- };
1252
- }
1253
- }),
1254
- // ─────────────────────────────────────────────────────────────────────────
1255
- // Checkout Pro
1256
- // ─────────────────────────────────────────────────────────────────────────
1257
- create_payment_preference: ai.tool({
1258
- description: desc("create_payment_preference"),
1259
- inputSchema: zod.z.object({
1260
- items: zod.z.array(zod.z.object({
1261
- title: zod.z.string().min(1).max(256),
1262
- quantity: zod.z.number().int().positive(),
1263
- unit_price: zod.z.number().positive(),
1264
- description: zod.z.string().optional(),
1265
- picture_url: zod.z.string().url().optional()
1266
- })).min(1).describe("Items being charged. At least one required."),
1267
- payer_email: zod.z.string().email().optional().describe("Pre-fill the payer email on Checkout Pro form"),
1268
- external_reference: zod.z.string().optional(),
1269
- max_installments: zod.z.number().int().min(1).max(24).optional().describe("Limit max cuotas offered. Defaults to MP account config."),
1270
- statement_descriptor: zod.z.string().max(13).optional(),
1271
- excluded_payment_types: zod.z.array(zod.z.enum(["credit_card", "debit_card", "ticket", "atm", "bank_transfer"])).optional().describe("Block payment types \u2014 e.g., ['ticket'] to disable Rapipago/Pago F\xE1cil")
1272
- }),
1273
- execute: async (input) => {
1274
- const pref = await client.createPreference({
1275
- items: input.items.map((it) => ({
1276
- title: it.title,
1277
- quantity: it.quantity,
1278
- unit_price: it.unit_price,
1279
- currency_id: "ARS",
1280
- ...it.description !== void 0 ? { description: it.description } : {},
1281
- ...it.picture_url !== void 0 ? { picture_url: it.picture_url } : {}
1282
- })),
1283
- ...input.payer_email !== void 0 ? { payer: { email: input.payer_email } } : {},
1284
- ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1285
- ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
1286
- backUrls: { success: options.backUrl, failure: options.backUrl, pending: options.backUrl },
1287
- autoReturn: "approved",
1288
- ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
1289
- ...input.max_installments !== void 0 || input.excluded_payment_types !== void 0 ? {
1290
- paymentMethods: {
1291
- ...input.max_installments !== void 0 ? { installments: input.max_installments } : {},
1292
- ...input.excluded_payment_types !== void 0 ? { excluded_payment_types: input.excluded_payment_types.map((id) => ({ id })) } : {}
1293
- }
1294
- } : {}
1295
- });
1296
- return {
1297
- preference_id: pref.id,
1298
- init_point_url: pref.init_point ?? null,
1299
- sandbox_init_point_url: pref.sandbox_init_point ?? null,
1300
- external_reference: pref.external_reference,
1301
- date_created: pref.date_created,
1302
- next_step: "Send init_point_url (or sandbox_init_point_url in sandbox) to the customer. After they pay, MP fires a webhook with the payment_id; use get_payment to confirm status."
1303
- };
1304
- }
1305
- }),
1306
- get_payment_preference: ai.tool({
1307
- description: desc("get_payment_preference"),
1308
- inputSchema: zod.z.object({ preference_id: zod.z.string() }),
1309
- execute: async ({ preference_id }) => {
1310
- const pref = await client.getPreference(preference_id);
1311
- return {
1312
- preference_id: pref.id,
1313
- init_point_url: pref.init_point ?? null,
1314
- sandbox_init_point_url: pref.sandbox_init_point ?? null,
1315
- external_reference: pref.external_reference,
1316
- items: pref.items,
1317
- date_created: pref.date_created
1318
- };
1319
- }
1320
- }),
1321
- // ─────────────────────────────────────────────────────────────────────────
1322
- // Customers + Saved Cards
1323
- // ─────────────────────────────────────────────────────────────────────────
1324
- create_customer: ai.tool({
1325
- description: desc("create_customer"),
1326
- inputSchema: zod.z.object({
1327
- email: zod.z.string().email(),
1328
- first_name: zod.z.string().optional(),
1329
- last_name: zod.z.string().optional(),
1330
- identification: zod.z.object({
1331
- type: zod.z.enum(["DNI", "CUIT", "CUIL"]),
1332
- number: zod.z.string()
1333
- }).optional(),
1334
- description: zod.z.string().optional()
1335
- }),
1336
- execute: async (input) => {
1337
- const customer = await client.createCustomer({
1338
- email: input.email,
1339
- ...input.first_name !== void 0 ? { firstName: input.first_name } : {},
1340
- ...input.last_name !== void 0 ? { lastName: input.last_name } : {},
1341
- ...input.identification !== void 0 ? { identification: input.identification } : {},
1342
- ...input.description !== void 0 ? { description: input.description } : {}
1343
- });
1344
- return {
1345
- customer_id: customer.id,
1346
- email: customer.email,
1347
- first_name: customer.first_name,
1348
- last_name: customer.last_name,
1349
- date_created: customer.date_created
1350
- };
1351
- }
1352
- }),
1353
- find_customer_by_email: ai.tool({
1354
- description: desc("find_customer_by_email"),
1355
- inputSchema: zod.z.object({ email: zod.z.string().email() }),
1356
- execute: async ({ email }) => {
1357
- const result = await client.searchCustomers({ email, limit: 1 });
1358
- const customer = result.results[0] ?? null;
1359
- return customer ? {
1360
- found: true,
1361
- customer_id: customer.id,
1362
- email: customer.email,
1363
- first_name: customer.first_name,
1364
- last_name: customer.last_name
1365
- } : { found: false, customer_id: null };
1366
- }
1367
- }),
1368
- list_customer_cards: ai.tool({
1369
- description: desc("list_customer_cards"),
1370
- inputSchema: zod.z.object({ customer_id: zod.z.string() }),
1371
- execute: async ({ customer_id }) => {
1372
- const cards = await client.listCustomerCards(customer_id);
1373
- return {
1374
- customer_id,
1375
- count: cards.length,
1376
- cards: cards.map((c) => ({
1377
- card_id: c.id,
1378
- last_four_digits: c.last_four_digits,
1379
- expiration_month: c.expiration_month,
1380
- expiration_year: c.expiration_year,
1381
- payment_method: c.payment_method?.id ?? null,
1382
- payment_method_name: c.payment_method?.name ?? null
1383
- }))
1384
- };
1385
- }
1386
- }),
1387
- delete_customer_card: ai.tool({
1388
- description: desc("delete_customer_card"),
1389
- inputSchema: zod.z.object({
1390
- customer_id: zod.z.string(),
1391
- card_id: zod.z.string()
1392
- }),
1393
- execute: async ({ customer_id, card_id }) => {
1394
- await client.deleteCustomerCard(customer_id, card_id);
1395
- return { customer_id, card_id, deleted: true };
1396
- }
1397
- }),
1398
- // ─────────────────────────────────────────────────────────────────────────
1399
- // Payment Methods + Installments
1400
- // ─────────────────────────────────────────────────────────────────────────
1401
- list_payment_methods: ai.tool({
1402
- description: desc("list_payment_methods"),
1403
- inputSchema: zod.z.object({}),
1404
- execute: async () => {
1405
- const methods = await client.listPaymentMethods();
1406
- return {
1407
- count: methods.length,
1408
- methods: methods.map((m) => ({
1409
- id: m.id,
1410
- name: m.name,
1411
- payment_type: m.payment_type_id,
1412
- status: m.status,
1413
- min_amount: m.min_allowed_amount,
1414
- max_amount: m.max_allowed_amount
1415
- }))
1416
- };
1417
- }
1418
- }),
1419
- calculate_installments: ai.tool({
1420
- description: desc("calculate_installments"),
1421
- inputSchema: zod.z.object({
1422
- amount_ars: zod.z.number().positive(),
1423
- payment_method_id: zod.z.string().optional().describe("E.g. 'visa', 'master', 'naranja'. Omit for all available methods."),
1424
- bin: zod.z.string().min(6).max(8).optional().describe("First 6-8 digits of card for issuer-specific offers (e.g., Naranja interest-free promotions)")
1425
- }),
1426
- execute: async (input) => {
1427
- const offers = await client.getInstallments({
1428
- amount: input.amount_ars,
1429
- ...input.payment_method_id !== void 0 ? { paymentMethodId: input.payment_method_id } : {},
1430
- ...input.bin !== void 0 ? { bin: input.bin } : {}
1431
- });
1432
- return {
1433
- amount: input.amount_ars,
1434
- offers: offers.map((o) => ({
1435
- payment_method_id: o.payment_method_id,
1436
- payment_type_id: o.payment_type_id,
1437
- issuer_name: o.issuer?.name ?? null,
1438
- options: o.payer_costs.map((pc) => ({
1439
- installments: pc.installments,
1440
- installment_amount: pc.installment_amount,
1441
- total_amount: pc.total_amount,
1442
- installment_rate: pc.installment_rate,
1443
- recommended_message: pc.recommended_message
1444
- }))
1445
- }))
1446
- };
1447
- }
1448
- }),
1449
- // ─────────────────────────────────────────────────────────────────────────
1450
- // Account
1451
- // ─────────────────────────────────────────────────────────────────────────
1452
- get_account_info: ai.tool({
1453
- description: desc("get_account_info"),
1454
- inputSchema: zod.z.object({}),
1455
- execute: async () => {
1456
- const me = await client.getMe();
1457
- return {
1458
- account_id: me.id,
1459
- email: me.email,
1460
- nickname: me.nickname,
1461
- country_id: me.country_id,
1462
- site_id: me.site_id,
1463
- user_type: me.user_type
1464
- };
1465
- }
1466
- }),
1467
- // ─────────────────────────────────────────────────────────────────────────
1468
- // Saved-card charging (v0.3)
1469
- // ─────────────────────────────────────────────────────────────────────────
1470
- charge_saved_card: ai.tool({
1471
- description: desc("charge_saved_card"),
1472
- inputSchema: zod.z.object({
1473
- customer_id: zod.z.string().describe("MP customer id (from create_customer / find_customer_by_email)"),
1474
- card_id: zod.z.string().describe("Saved card id (from list_customer_cards)"),
1475
- security_code: zod.z.string().regex(/^\d{3,4}$/).describe("CVV \u2014 3 digits (Visa/Master) or 4 (Amex). User must provide this each charge in AR."),
1476
- amount_ars: zod.z.number().positive(),
1477
- description: zod.z.string().min(1).max(255),
1478
- installments: zod.z.number().int().min(1).max(24).optional().describe("Default 1. Use calculate_installments first to pick a valid count."),
1479
- external_reference: zod.z.string().optional(),
1480
- statement_descriptor: zod.z.string().max(13).optional()
1481
- }),
1482
- execute: async (input) => {
1483
- const payment = await client.chargeSavedCard({
1484
- customerId: input.customer_id,
1485
- cardId: input.card_id,
1486
- securityCode: input.security_code,
1487
- amount: input.amount_ars,
1488
- description: input.description,
1489
- ...input.installments !== void 0 ? { installments: input.installments } : {},
1490
- ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1491
- ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
1492
- idempotencyKey: deterministicIdempotencyKey(
1493
- "charge_saved_card",
1494
- input.card_id,
1495
- input.amount_ars,
1496
- input.external_reference
1497
- )
1498
- });
1499
- return {
1500
- payment_id: payment.id,
1501
- status: payment.status,
1502
- status_detail: payment.status_detail,
1503
- amount: payment.transaction_amount,
1504
- installments: payment.installments,
1505
- payment_method: payment.payment_method_id,
1506
- customer_id: input.customer_id,
1507
- card_id: input.card_id,
1508
- external_reference: payment.external_reference,
1509
- date_approved: payment.date_approved
1510
- };
1511
- }
1512
- }),
1513
- // ─────────────────────────────────────────────────────────────────────────
1514
- // QR in-store (v0.3)
1515
- // ─────────────────────────────────────────────────────────────────────────
1516
- create_qr_payment: ai.tool({
1517
- description: desc("create_qr_payment"),
1518
- inputSchema: zod.z.object({
1519
- external_pos_id: zod.z.string().describe("Pre-configured POS external_id from MP dashboard. Required."),
1520
- amount_ars: zod.z.number().positive(),
1521
- title: zod.z.string().min(1).max(80).describe("Display title shown when scanning"),
1522
- description: zod.z.string().max(255).optional(),
1523
- external_reference: zod.z.string().optional(),
1524
- notification_url: zod.z.string().url().optional().describe("Webhook URL \u2014 falls back to dashboard config if omitted"),
1525
- expires_in_seconds: zod.z.number().int().min(60).max(3600).optional().describe("Default 600 (10 min)")
1526
- }),
1527
- execute: async (input) => {
1528
- const QRCode = (await import('qrcode')).default;
1529
- const me = await client.getMe();
1530
- const userId = String(me.id);
1531
- const expiresAt = new Date(
1532
- Date.now() + (input.expires_in_seconds ?? 600) * 1e3
1533
- ).toISOString();
1534
- const qr = await client.createQrPayment(userId, {
1535
- externalPosId: input.external_pos_id,
1536
- totalAmount: input.amount_ars,
1537
- title: input.title,
1538
- ...input.description !== void 0 ? { description: input.description } : {},
1539
- ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1540
- ...input.notification_url !== void 0 ? { notificationUrl: input.notification_url } : {},
1541
- expirationDate: expiresAt
1542
- });
1543
- const qrDataUrl = await QRCode.toDataURL(qr.qr_data, {
1544
- errorCorrectionLevel: "M",
1545
- margin: 1,
1546
- width: 512
1547
- });
1548
- return {
1549
- in_store_order_id: qr.in_store_order_id,
1550
- qr_data: qr.qr_data,
1551
- qr_data_url: qrDataUrl,
1552
- expires_at: expiresAt,
1553
- external_pos_id: input.external_pos_id,
1554
- amount: input.amount_ars,
1555
- next_step: "Display the qr_data_url image to the buyer. Wait for the payment webhook (point_integration_wh fires first, then payment topic). If buyer doesn't scan in time, call cancel_qr_payment to free the POS."
1556
- };
1557
- }
1558
- }),
1559
- cancel_qr_payment: ai.tool({
1560
- description: desc("cancel_qr_payment"),
1561
- inputSchema: zod.z.object({
1562
- external_pos_id: zod.z.string()
1563
- }),
1564
- execute: async ({ external_pos_id }) => {
1565
- const me = await client.getMe();
1566
- await client.cancelQrPayment(String(me.id), external_pos_id);
1567
- return { external_pos_id, cancelled: true };
1568
- }
1569
- }),
1570
- // ─────────────────────────────────────────────────────────────────────────
1571
- // Subscription Plans (v0.4)
1572
- // ─────────────────────────────────────────────────────────────────────────
1573
- create_subscription_plan: ai.tool({
1574
- description: desc("create_subscription_plan"),
1575
- inputSchema: zod.z.object({
1576
- reason: zod.z.string().min(3).max(120).describe("Plan name shown at checkout"),
1577
- amount_ars: zod.z.number().positive(),
1578
- frequency_months: zod.z.number().int().min(1).max(12),
1579
- back_url: zod.z.string().url().describe("HTTPS URL where MP redirects after first payment"),
1580
- external_reference: zod.z.string().optional(),
1581
- free_trial_days: zod.z.number().int().min(1).max(60).optional().describe("Free trial period in days before first charge")
1582
- }),
1583
- execute: async (input) => {
1584
- const plan = await client.createSubscriptionPlan({
1585
- reason: input.reason,
1586
- amount: input.amount_ars,
1587
- currency: "ARS",
1588
- frequency: input.frequency_months,
1589
- frequencyType: "months",
1590
- backUrl: input.back_url,
1591
- ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1592
- ...input.free_trial_days !== void 0 ? { freeTrialFrequency: input.free_trial_days, freeTrialFrequencyType: "days" } : {}
1593
- });
1594
- return {
1595
- plan_id: plan.id,
1596
- status: plan.status,
1597
- reason: plan.reason,
1598
- amount: plan.auto_recurring.transaction_amount,
1599
- currency: plan.auto_recurring.currency_id,
1600
- frequency: `${plan.auto_recurring.frequency} ${plan.auto_recurring.frequency_type}`,
1601
- external_reference: plan.external_reference,
1602
- next_step: "Use subscribe_to_plan to enroll customers in this plan, or share its ID for them to subscribe via your frontend."
1603
- };
1604
- }
1605
- }),
1606
- list_subscription_plans: ai.tool({
1607
- description: desc("list_subscription_plans"),
1608
- inputSchema: zod.z.object({
1609
- status: zod.z.string().optional(),
1610
- limit: zod.z.number().int().min(1).max(100).optional()
1611
- }),
1612
- execute: async (input) => {
1613
- const result = await client.listSubscriptionPlans({
1614
- ...input.status !== void 0 ? { status: input.status } : {},
1615
- ...input.limit !== void 0 ? { limit: input.limit } : {}
1616
- });
1617
- return {
1618
- total: result.paging.total,
1619
- plans: result.results.map((p) => ({
1620
- plan_id: p.id,
1621
- reason: p.reason,
1622
- status: p.status,
1623
- amount: p.auto_recurring.transaction_amount,
1624
- currency: p.auto_recurring.currency_id,
1625
- frequency: `${p.auto_recurring.frequency} ${p.auto_recurring.frequency_type}`
1626
- }))
1627
- };
1628
- }
1629
- }),
1630
- update_subscription_plan: ai.tool({
1631
- description: desc("update_subscription_plan"),
1632
- inputSchema: zod.z.object({
1633
- plan_id: zod.z.string(),
1634
- reason: zod.z.string().optional(),
1635
- amount_ars: zod.z.number().positive().optional(),
1636
- status: zod.z.enum(["active", "cancelled"]).optional(),
1637
- back_url: zod.z.string().url().optional()
1638
- }),
1639
- execute: async (input) => {
1640
- const updated = await client.updateSubscriptionPlan(input.plan_id, {
1641
- ...input.reason !== void 0 ? { reason: input.reason } : {},
1642
- ...input.amount_ars !== void 0 ? { amount: input.amount_ars } : {},
1643
- ...input.status !== void 0 ? { status: input.status } : {},
1644
- ...input.back_url !== void 0 ? { backUrl: input.back_url } : {}
1645
- });
1646
- return {
1647
- plan_id: updated.id,
1648
- status: updated.status,
1649
- reason: updated.reason,
1650
- amount: updated.auto_recurring.transaction_amount,
1651
- message: input.amount_ars !== void 0 ? "Updated. Existing subscribers keep their old amount; only NEW subscribers get the new pricing." : "Plan updated."
1652
- };
1653
- }
1654
- }),
1655
- subscribe_to_plan: ai.tool({
1656
- description: desc("subscribe_to_plan"),
1657
- inputSchema: zod.z.object({
1658
- plan_id: zod.z.string(),
1659
- customer_email: zod.z.string().email(),
1660
- external_reference: zod.z.string().optional()
1661
- }),
1662
- execute: async (input) => {
1663
- const sub = await client.subscribeToPlan({
1664
- planId: input.plan_id,
1665
- payerEmail: input.customer_email,
1666
- ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {}
1667
- });
1668
- return {
1669
- subscription_id: sub.id,
1670
- status: sub.status,
1671
- payer_email: sub.payer_email,
1672
- init_point_url: sub.init_point,
1673
- next_step: "Send init_point_url to the customer for first payment with card+CVV."
1674
- };
1675
- }
1676
- }),
1677
- list_subscription_payments: ai.tool({
1678
- description: desc("list_subscription_payments"),
1679
- inputSchema: zod.z.object({
1680
- subscription_id: zod.z.string(),
1681
- limit: zod.z.number().int().min(1).max(100).optional()
1682
- }),
1683
- execute: async (input) => {
1684
- const result = await client.listSubscriptionPayments(input.subscription_id, {
1685
- ...input.limit !== void 0 ? { limit: input.limit } : {}
1686
- });
1687
- return {
1688
- subscription_id: input.subscription_id,
1689
- total: result.paging.total,
1690
- payments: result.results.map((p) => ({
1691
- authorized_payment_id: p.id,
1692
- payment_id: p.payment_id ?? null,
1693
- status: p.status,
1694
- amount: p.transaction_amount ?? null,
1695
- currency: p.currency_id ?? null,
1696
- debit_date: p.debit_date ?? null,
1697
- next_retry_date: p.next_retry_date ?? null,
1698
- retry_attempt: p.retry_attempt ?? 0,
1699
- reason: p.reason ?? null
1700
- }))
1701
- };
1702
- }
1703
- }),
1704
- // ─────────────────────────────────────────────────────────────────────────
1705
- // Stores + POS (v0.4)
1706
- // ─────────────────────────────────────────────────────────────────────────
1707
- create_store: ai.tool({
1708
- description: desc("create_store"),
1709
- inputSchema: zod.z.object({
1710
- name: zod.z.string().min(1).max(80),
1711
- external_id: zod.z.string().min(1).max(64).describe("Unique within the seller's stores"),
1712
- address_line: zod.z.string().optional(),
1713
- city_name: zod.z.string().optional(),
1714
- state_name: zod.z.string().optional()
1715
- }),
1716
- execute: async (input) => {
1717
- const me = await client.getMe();
1718
- const store = await client.createStore(String(me.id), {
1719
- name: input.name,
1720
- externalId: input.external_id,
1721
- ...input.address_line || input.city_name || input.state_name ? {
1722
- location: {
1723
- ...input.address_line ? { addressLine: input.address_line } : {},
1724
- ...input.city_name ? { cityName: input.city_name } : {},
1725
- ...input.state_name ? { stateName: input.state_name } : {},
1726
- countryId: "AR"
1727
- }
1728
- } : {}
1729
- });
1730
- return {
1731
- store_id: store.id,
1732
- name: store.name,
1733
- external_id: store.external_id,
1734
- next_step: "Use create_pos with this store_id to add a Point of Sale where create_qr_payment can issue QRs."
1735
- };
1736
- }
1737
- }),
1738
- list_stores: ai.tool({
1739
- description: desc("list_stores"),
1740
- inputSchema: zod.z.object({
1741
- limit: zod.z.number().int().min(1).max(100).optional()
1742
- }),
1743
- execute: async (input) => {
1744
- const me = await client.getMe();
1745
- const result = await client.listStores(String(me.id), {
1746
- ...input.limit !== void 0 ? { limit: input.limit } : {}
1747
- });
1748
- return {
1749
- total: result.paging.total,
1750
- stores: result.results.map((s) => ({
1751
- store_id: s.id,
1752
- name: s.name ?? null,
1753
- external_id: s.external_id ?? null
1754
- }))
1755
- };
1756
- }
1757
- }),
1758
- create_pos: ai.tool({
1759
- description: desc("create_pos"),
1760
- inputSchema: zod.z.object({
1761
- name: zod.z.string().min(1).max(80),
1762
- external_id: zod.z.string().min(1).max(64).describe("Unique within the store. This is what create_qr_payment uses."),
1763
- store_id: zod.z.string().describe("From create_store / list_stores"),
1764
- category: zod.z.number().int().optional().describe("MP category code, default 621102 (other food/beverage)"),
1765
- fixed_amount: zod.z.boolean().optional().describe("True for static QR with fixed amount; false (default) for dynamic per-order QR")
1766
- }),
1767
- execute: async (input) => {
1768
- const pos = await client.createPos({
1769
- name: input.name,
1770
- externalId: input.external_id,
1771
- storeId: input.store_id,
1772
- ...input.category !== void 0 ? { category: input.category } : {},
1773
- ...input.fixed_amount !== void 0 ? { fixedAmount: input.fixed_amount } : {}
1774
- });
1775
- return {
1776
- pos_id: pos.id,
1777
- external_id: pos.external_id,
1778
- store_id: pos.store_id,
1779
- name: pos.name,
1780
- next_step: "Use create_qr_payment with this external_id to start issuing dynamic QRs from this POS."
1781
- };
1782
- }
1783
- }),
1784
- list_pos: ai.tool({
1785
- description: desc("list_pos"),
1786
- inputSchema: zod.z.object({
1787
- store_id: zod.z.string().optional(),
1788
- limit: zod.z.number().int().min(1).max(100).optional()
1789
- }),
1790
- execute: async (input) => {
1791
- const result = await client.listPos({
1792
- ...input.store_id !== void 0 ? { storeId: input.store_id } : {},
1793
- ...input.limit !== void 0 ? { limit: input.limit } : {}
1794
- });
1795
- return {
1796
- total: result.paging.total,
1797
- pos: result.results.map((p) => ({
1798
- pos_id: p.id,
1799
- external_id: p.external_id ?? null,
1800
- store_id: p.store_id ?? null,
1801
- name: p.name ?? null
1802
- }))
1803
- };
1804
- }
1805
- }),
1806
- // ─────────────────────────────────────────────────────────────────────────
1807
- // Disputes (v0.4 — read-only)
1808
- // ─────────────────────────────────────────────────────────────────────────
1809
- list_payment_disputes: ai.tool({
1810
- description: desc("list_payment_disputes"),
1811
- inputSchema: zod.z.object({ payment_id: zod.z.string() }),
1812
- execute: async ({ payment_id }) => {
1813
- const disputes = await client.listPaymentDisputes(payment_id);
1814
- return {
1815
- payment_id,
1816
- count: disputes.length,
1817
- disputes: disputes.map((d) => ({
1818
- dispute_id: d.id,
1819
- status: d.status,
1820
- amount: d.amount ?? null,
1821
- reason: d.reason ?? null,
1822
- date_created: d.date_created ?? null,
1823
- dashboard_url: `https://www.mercadopago.com.ar/disputes/${d.id}`
1824
- }))
1825
- };
1826
- }
1827
- }),
1828
- get_dispute: ai.tool({
1829
- description: desc("get_dispute"),
1830
- inputSchema: zod.z.object({
1831
- payment_id: zod.z.string(),
1832
- dispute_id: zod.z.string()
1833
- }),
1834
- execute: async ({ payment_id, dispute_id }) => {
1835
- const d = await client.getDispute(payment_id, dispute_id);
1836
- return {
1837
- dispute_id: d.id,
1838
- status: d.status,
1839
- amount: d.amount ?? null,
1840
- reason: d.reason ?? null,
1841
- reason_description: d.reason_description ?? null,
1842
- resolution: d.resolution ?? null,
1843
- date_created: d.date_created ?? null,
1844
- dashboard_url: `https://www.mercadopago.com.ar/disputes/${d.id}`
1845
- };
1846
- }
1847
- }),
1848
- // ─────────────────────────────────────────────────────────────────────────
1849
- // Lookup helpers (v0.4)
1850
- // ─────────────────────────────────────────────────────────────────────────
1851
- list_identification_types: ai.tool({
1852
- description: desc("list_identification_types"),
1853
- inputSchema: zod.z.object({}),
1854
- execute: async () => {
1855
- const types = await client.listIdentificationTypes();
1856
- return {
1857
- count: types.length,
1858
- types: types.map((t) => ({
1859
- id: t.id,
1860
- name: t.name,
1861
- type: t.type,
1862
- min_length: t.min_length ?? null,
1863
- max_length: t.max_length ?? null
1864
- }))
1865
- };
1866
- }
1867
- }),
1868
- list_issuers: ai.tool({
1869
- description: desc("list_issuers"),
1870
- inputSchema: zod.z.object({
1871
- payment_method_id: zod.z.string().describe("E.g. 'visa', 'master', 'naranja'"),
1872
- bin: zod.z.string().min(6).max(8).optional().describe("First 6-8 digits of card for precise issuer detection")
1873
- }),
1874
- execute: async (input) => {
1875
- const issuers = await client.listIssuers({
1876
- paymentMethodId: input.payment_method_id,
1877
- ...input.bin !== void 0 ? { bin: input.bin } : {}
1878
- });
1879
- return {
1880
- payment_method_id: input.payment_method_id,
1881
- count: issuers.length,
1882
- issuers: issuers.map((i) => ({
1883
- issuer_id: i.id,
1884
- name: i.name,
1885
- status: i.status ?? null
1886
- }))
1887
- };
1888
- }
1889
- }),
1890
- // ─────────────────────────────────────────────────────────────────────────
1891
- // Webhooks management (v0.4)
1892
- // ─────────────────────────────────────────────────────────────────────────
1893
- list_webhooks: ai.tool({
1894
- description: desc("list_webhooks"),
1895
- inputSchema: zod.z.object({}),
1896
- execute: async () => {
1897
- const hooks = await client.listWebhooks();
1898
- return {
1899
- count: hooks.length,
1900
- webhooks: hooks.map((h) => ({
1901
- webhook_id: h.id,
1902
- url: h.url ?? null,
1903
- topic: h.topic ?? null,
1904
- status: h.status ?? null,
1905
- date_created: h.date_created ?? null
1906
- }))
1907
- };
1908
- }
1909
- }),
1910
- create_webhook: ai.tool({
1911
- description: desc("create_webhook"),
1912
- inputSchema: zod.z.object({
1913
- url: zod.z.string().url(),
1914
- topic: zod.z.string().describe("E.g. 'payment', 'subscription_authorized_payment', 'subscription_preapproval', 'merchant_order', 'point_integration_wh'")
1915
- }),
1916
- execute: async ({ url, topic }) => {
1917
- const hook = await client.createWebhook({ url, topic });
1918
- return {
1919
- webhook_id: hook.id,
1920
- url: hook.url ?? url,
1921
- topic: hook.topic ?? topic,
1922
- status: hook.status ?? null
1923
- };
1924
- }
1925
- }),
1926
- update_webhook: ai.tool({
1927
- description: desc("update_webhook"),
1928
- inputSchema: zod.z.object({
1929
- webhook_id: zod.z.string(),
1930
- url: zod.z.string().url().optional(),
1931
- topic: zod.z.string().optional()
1932
- }),
1933
- execute: async (input) => {
1934
- const hook = await client.updateWebhook(input.webhook_id, {
1935
- ...input.url !== void 0 ? { url: input.url } : {},
1936
- ...input.topic !== void 0 ? { topic: input.topic } : {}
1937
- });
1938
- return {
1939
- webhook_id: hook.id,
1940
- url: hook.url ?? null,
1941
- topic: hook.topic ?? null,
1942
- status: hook.status ?? null
1943
- };
1944
- }
1945
- }),
1946
- delete_webhook: ai.tool({
1947
- description: desc("delete_webhook"),
1948
- inputSchema: zod.z.object({ webhook_id: zod.z.string() }),
1949
- execute: async ({ webhook_id }) => {
1950
- await client.deleteWebhook(webhook_id);
1951
- return { webhook_id, deleted: true };
1952
- }
1953
- })
1954
- };
1955
- }
1956
-
1957
- // src/state.ts
1958
- var InMemoryStateAdapter = class {
1959
- store = /* @__PURE__ */ new Map();
1960
- async set(id, state) {
1961
- const existing = this.store.get(id) ?? {};
1962
- this.store.set(id, { ...existing, ...state });
1963
- }
1964
- async get(id) {
1965
- return this.store.get(id) ?? null;
1966
- }
1967
- async list() {
1968
- return Array.from(this.store.keys());
1969
- }
1970
- /** Test helper: drop everything. Not part of the adapter interface. */
1971
- reset() {
1972
- this.store.clear();
1973
- }
902
+ // ──────────────────────────────────────────────────────────────────────────
903
+ // v0.5 — Order Management API
904
+ //
905
+ // The Order API is MP's newer abstraction for purchases, replacing some
906
+ // Preference flows. Distinct from Preference: Order is a transactional
907
+ // entity with explicit lifecycle (created → processed → captured/canceled),
908
+ // supports manual capture (auth-only, capture later), and can attach
909
+ // multiple payments to a single Order.
910
+ //
911
+ // Use Order when you need:
912
+ // - Auth-only flow (capture later, e.g. ride-share, hotels)
913
+ // - Multi-payment aggregation (one Order = N partial payments)
914
+ // - In-store + online unified status
915
+ //
916
+ // Stick with Preference (Checkout Pro) when you just need a hosted pay-link.
917
+ // ──────────────────────────────────────────────────────────────────────────
918
+ /**
919
+ * Create a new Order. Use `capture_mode: "manual"` for auth-only flows
920
+ * where you want to capture funds later (ride-share, hotels, marketplaces).
921
+ *
922
+ * For marketplace splits, set `marketplace`, `marketplace_fee`,
923
+ * `collector_id` see `MarketplaceParams`.
924
+ */
925
+ async createOrder(params, options) {
926
+ const body = {
927
+ type: params.type
928
+ };
929
+ if (params.currency_id) body.currency_id = params.currency_id;
930
+ if (params.external_reference) body.external_reference = params.external_reference;
931
+ if (params.items) body.items = params.items;
932
+ if (params.total_amount !== void 0) body.total_amount = params.total_amount;
933
+ if (params.payer) body.payer = params.payer;
934
+ if (params.capture_mode) body.capture_mode = params.capture_mode;
935
+ if (params.notification_url) body.notification_url = params.notification_url;
936
+ if (params.marketplace) body.marketplace = params.marketplace;
937
+ if (params.marketplace_fee !== void 0) body.marketplace_fee = params.marketplace_fee;
938
+ if (params.collector_id !== void 0) body.collector_id = params.collector_id;
939
+ return this.request("POST", "/v1/orders", body, options);
940
+ }
941
+ async getOrder(id) {
942
+ return this.request("GET", `/v1/orders/${id}`);
943
+ }
944
+ async updateOrder(id, patch) {
945
+ return this.request("PUT", `/v1/orders/${id}`, patch);
946
+ }
947
+ /**
948
+ * Capture a previously-authorized Order (only for orders created with
949
+ * `capture_mode: "manual"`). Captures up to the originally-authorized
950
+ * amount; pass `amount` for partial capture.
951
+ */
952
+ async captureOrder(id, amount) {
953
+ const body = amount !== void 0 ? { amount } : {};
954
+ return this.request("POST", `/v1/orders/${id}/capture`, body);
955
+ }
956
+ /**
957
+ * Cancel an Order. Releases any auth-holds; marks the Order as canceled.
958
+ * For orders that have already been captured, use `createRefund` instead.
959
+ */
960
+ async cancelOrder(id) {
961
+ return this.request("POST", `/v1/orders/${id}/cancel`);
962
+ }
1974
963
  };
1975
964
  zod.z.enum(["MLA", "MLB", "MLM", "MCO", "MLC", "MLU"]);
1976
965
  var CurrencyIdSchema = zod.z.enum(["ARS", "USD", "BRL", "MXN"]);
@@ -2269,8 +1258,122 @@ zod.z.object({
2269
1258
  date_created: zod.z.string().optional(),
2270
1259
  date_modified: zod.z.string().optional()
2271
1260
  }).passthrough();
1261
+ var OAuthTokenSchema = zod.z.object({
1262
+ access_token: zod.z.string(),
1263
+ token_type: zod.z.string().optional(),
1264
+ /** Seconds until access_token expires. Typically 21600 (6h). */
1265
+ expires_in: zod.z.number().optional(),
1266
+ scope: zod.z.string().optional(),
1267
+ /** The MP user_id of the seller who authorized your app. */
1268
+ user_id: zod.z.union([zod.z.string(), zod.z.number()]).transform(String),
1269
+ refresh_token: zod.z.string().optional(),
1270
+ public_key: zod.z.string().optional(),
1271
+ live_mode: zod.z.boolean().optional()
1272
+ }).passthrough();
1273
+ var OrderStatusSchema = zod.z.union([
1274
+ zod.z.literal("created"),
1275
+ zod.z.literal("processed"),
1276
+ zod.z.literal("action_required"),
1277
+ zod.z.literal("canceled"),
1278
+ zod.z.literal("expired"),
1279
+ zod.z.literal("refunded"),
1280
+ zod.z.string()
1281
+ ]);
1282
+ var OrderItemSchema = zod.z.object({
1283
+ title: zod.z.string(),
1284
+ unit_price: zod.z.number(),
1285
+ quantity: zod.z.number(),
1286
+ description: zod.z.string().optional(),
1287
+ id: zod.z.string().optional(),
1288
+ category_id: zod.z.string().optional(),
1289
+ picture_url: zod.z.string().optional()
1290
+ }).passthrough();
1291
+ zod.z.object({
1292
+ id: zod.z.union([zod.z.string(), zod.z.number()]).transform(String),
1293
+ type: zod.z.string().optional(),
1294
+ status: OrderStatusSchema.optional(),
1295
+ status_detail: zod.z.string().optional(),
1296
+ external_reference: zod.z.string().optional(),
1297
+ total_amount: zod.z.union([zod.z.number(), zod.z.string()]).optional(),
1298
+ /** Currency for this Order (e.g. "ARS"). */
1299
+ currency_id: zod.z.string().optional(),
1300
+ date_created: zod.z.string().optional(),
1301
+ date_last_updated: zod.z.string().optional(),
1302
+ items: zod.z.array(OrderItemSchema).optional(),
1303
+ /** Underlying transactions (payments) attached to this Order. */
1304
+ transactions: zod.z.object({
1305
+ payments: zod.z.array(zod.z.unknown()).optional(),
1306
+ refunds: zod.z.array(zod.z.unknown()).optional()
1307
+ }).passthrough().optional(),
1308
+ /** Capture mode: "automatic" (charges immediately) or "manual" (auth-only). */
1309
+ capture_mode: zod.z.string().optional()
1310
+ }).passthrough();
2272
1311
 
2273
- // src/webhook.ts
1312
+ // src/oauth.ts
1313
+ var DEFAULT_AUTHORIZE_URL = "https://auth.mercadopago.com.ar/authorization";
1314
+ var DEFAULT_TOKEN_URL = "https://api.mercadopago.com/oauth/token";
1315
+ function buildAuthorizeUrl(params) {
1316
+ const url = new URL(params.authorizeUrl ?? DEFAULT_AUTHORIZE_URL);
1317
+ url.searchParams.set("client_id", params.clientId);
1318
+ url.searchParams.set("response_type", "code");
1319
+ url.searchParams.set("platform_id", "mp");
1320
+ url.searchParams.set("redirect_uri", params.redirectUri);
1321
+ if (params.state) url.searchParams.set("state", params.state);
1322
+ return url.toString();
1323
+ }
1324
+ async function exchangeCodeForToken(params) {
1325
+ const url = params.tokenUrl ?? DEFAULT_TOKEN_URL;
1326
+ const fetchFn = params.fetchImpl ?? globalThis.fetch;
1327
+ const res = await fetchFn(url, {
1328
+ method: "POST",
1329
+ headers: {
1330
+ "Content-Type": "application/x-www-form-urlencoded",
1331
+ Accept: "application/json"
1332
+ },
1333
+ body: new URLSearchParams({
1334
+ grant_type: "authorization_code",
1335
+ client_id: params.clientId,
1336
+ client_secret: params.clientSecret,
1337
+ code: params.code,
1338
+ redirect_uri: params.redirectUri
1339
+ }).toString()
1340
+ });
1341
+ return parseTokenResponse(res);
1342
+ }
1343
+ async function refreshAccessToken(params) {
1344
+ const url = params.tokenUrl ?? DEFAULT_TOKEN_URL;
1345
+ const fetchFn = params.fetchImpl ?? globalThis.fetch;
1346
+ const res = await fetchFn(url, {
1347
+ method: "POST",
1348
+ headers: {
1349
+ "Content-Type": "application/x-www-form-urlencoded",
1350
+ Accept: "application/json"
1351
+ },
1352
+ body: new URLSearchParams({
1353
+ grant_type: "refresh_token",
1354
+ client_id: params.clientId,
1355
+ client_secret: params.clientSecret,
1356
+ refresh_token: params.refreshToken
1357
+ }).toString()
1358
+ });
1359
+ return parseTokenResponse(res);
1360
+ }
1361
+ async function parseTokenResponse(res) {
1362
+ const text = await res.text();
1363
+ if (!res.ok) {
1364
+ throw new Error(
1365
+ `MP OAuth ${res.status}: ${text.slice(0, 300)}`
1366
+ );
1367
+ }
1368
+ const json = JSON.parse(text);
1369
+ return OAuthTokenSchema.parse(json);
1370
+ }
1371
+ function expirationTimeMs(issuedAtMs, expiresInSeconds) {
1372
+ return issuedAtMs + (expiresInSeconds ?? 21600) * 1e3;
1373
+ }
1374
+ function isExpiringSoon(expirationMs, skewSeconds = 300) {
1375
+ return Date.now() + skewSeconds * 1e3 >= expirationMs;
1376
+ }
2274
1377
  function parseWebhookEvent(body, searchParams) {
2275
1378
  const parseResult = WebhookBodySchema.safeParse(body ?? {});
2276
1379
  const parsedBody = parseResult.success ? parseResult.data : {};
@@ -2286,19 +1389,1421 @@ function parseWebhookEvent(body, searchParams) {
2286
1389
  raw: parsedBody
2287
1390
  };
2288
1391
  }
2289
- function verifyWebhookSignature(params) {
2290
- if (!params.signatureHeader || !params.requestId) return false;
2291
- const parts = Object.fromEntries(
2292
- params.signatureHeader.split(",").map((segment) => segment.trim().split("="))
2293
- );
2294
- const ts = parts.ts;
2295
- const v1 = parts.v1;
2296
- if (!ts || !v1) return false;
2297
- const manifest = `id:${params.dataId};request-id:${params.requestId};ts:${ts};`;
2298
- const expected = crypto.createHmac("sha256", params.secret).update(manifest).digest("hex");
2299
- if (expected.length !== v1.length) return false;
2300
- return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
2301
- }
1392
+ function verifyWebhookSignature(params) {
1393
+ if (!params.signatureHeader || !params.requestId) return false;
1394
+ const parts = Object.fromEntries(
1395
+ params.signatureHeader.split(",").map((segment) => segment.trim().split("="))
1396
+ );
1397
+ const ts = parts.ts;
1398
+ const v1 = parts.v1;
1399
+ if (!ts || !v1) return false;
1400
+ const manifest = `id:${params.dataId};request-id:${params.requestId};ts:${ts};`;
1401
+ const expected = crypto.createHmac("sha256", params.secret).update(manifest).digest("hex");
1402
+ if (expected.length !== v1.length) return false;
1403
+ return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
1404
+ }
1405
+
1406
+ // src/tools.ts
1407
+ function deterministicIdempotencyKey(...parts) {
1408
+ const payload = parts.filter((p) => p !== void 0 && p !== null).map(String).join("|");
1409
+ return crypto.createHash("sha256").update(payload).digest("hex").slice(0, 32);
1410
+ }
1411
+ var DEFAULT_DESCRIPTIONS = {
1412
+ // ── Subscriptions ────────────────────────────────────────────────────────
1413
+ create_subscription: "Create a Mercado Pago recurring subscription. Returns an init_point URL where the customer must complete the FIRST payment with their card and CVV (this is a hard MP requirement; agents cannot bypass it). After they pay, MP will auto-charge at the configured frequency without further intervention.",
1414
+ get_subscription_status: "Check the current status of a Mercado Pago subscription. Use this to confirm the customer completed the first payment (status becomes 'authorized') or to inspect the next charge date.",
1415
+ cancel_subscription: "Cancel an active Mercado Pago subscription. After cancellation, MP will not charge the customer again. This action is irreversible \u2014 confirm with the user before calling.",
1416
+ pause_subscription: "Pause an authorized Mercado Pago subscription. Charges stop until resumed. Only works on subscriptions in 'authorized' status.",
1417
+ resume_subscription: "Resume a paused Mercado Pago subscription. Charges resume on the next scheduled date. Only works on subscriptions in 'paused' status.",
1418
+ // ── Payments ─────────────────────────────────────────────────────────────
1419
+ create_payment: "Create a one-time payment. Two flows: (a) with a card token from MP frontend Cardform \u2014 for transparent checkout; (b) without token, for non-card methods like 'account_money', 'rapipago', 'pagofacil'. For most agent flows where you only have a payer email and want to send them a payment link, use create_payment_preference instead (Checkout Pro hosted form). Returns the Payment object with status \u2014 typically 'approved' for account_money and 'pending' for tickets.",
1420
+ get_payment: "Fetch a single payment by ID. Use to confirm status after webhook arrives, or to inspect details (status_detail explains rejections).",
1421
+ search_payments: "Search payments with filters. Most common: by external_reference (your-system identifier) to find all payments for an order, or by status='approved' to list successful charges in a date range. Returns paginated results.",
1422
+ cancel_payment: "Cancel a pending or in_process payment (only works before approval). Once approved, use refund_payment instead. Common use: cancel an unpaid ticket payment that's still pending.",
1423
+ capture_payment: "Capture an authorized credit-card payment that was created with capture=false. Use for hold-then-capture flows (e.g., authorize on order, capture on shipment). Optional partial amount.",
1424
+ // ── Refunds ──────────────────────────────────────────────────────────────
1425
+ refund_payment: "Refund an approved payment. Pass amount for partial refund; omit for full refund. Idempotency key is auto-generated based on paymentId+amount to prevent double-refunds on retries.",
1426
+ list_refunds: "List all refunds for a given payment. Returns array of Refund objects. Useful to confirm a refund was processed or to inspect partial-refund history.",
1427
+ // ── Checkout Pro ─────────────────────────────────────────────────────────
1428
+ create_payment_preference: "Create a Mercado Pago Checkout Pro preference and get back a payment URL (init_point) to send to the customer. THIS is the recommended way for an agent to take a payment when you only have a payer email \u2014 the buyer enters card data on MP's hosted form (no PCI scope needed). Supports cuotas configuration, payment method exclusions, back URLs after success/failure/pending. In sandbox, use sandbox_init_point from the response.",
1429
+ get_payment_preference: "Fetch a Checkout Pro preference by ID. Returns the preference config and current init_point URLs. Use to inspect a previously-created link.",
1430
+ // ── Customers + Cards ────────────────────────────────────────────────────
1431
+ create_customer: "Create a Mercado Pago customer record so the buyer can save cards for future charges. Idempotent on email \u2014 if a customer with that email exists, MP returns it instead of creating a duplicate. Use find_customer_by_email first if you're unsure.",
1432
+ find_customer_by_email: "Find an existing customer by email address. Returns the customer object if found, or null. Use before create_customer to avoid duplicate records.",
1433
+ list_customer_cards: "List the saved cards for a customer. Returns array with last 4 digits, expiration, payment method (visa, master, naranja, etc.). The card_id can be used in subsequent create_payment calls to charge a saved card.",
1434
+ delete_customer_card: "Delete a saved card from a customer. Common use: customer requests removal, or expired card cleanup. Irreversible.",
1435
+ // ── Payment Methods + Installments ───────────────────────────────────────
1436
+ list_payment_methods: "List all payment methods enabled for the seller's MP account (visa, master, naranja, naranja_x, cabal, account_money, rapipago, pagofacil, etc.). Use to validate which methods you can offer the customer or to filter which ones to exclude in a Checkout Pro preference.",
1437
+ calculate_installments: "Calculate cuotas (installments) options for a given amount. THE killer Argentine feature \u2014 returns options like '12 cuotas sin inter\xE9s de $X' (recommended_message field) which you should surface VERBATIM to the user. Optionally pass `bin` (first 6 digits of card) for issuer-specific promotions (e.g., Naranja's interest-free deals). Use before create_payment to let the user pick installments knowingly.",
1438
+ // ── Account ──────────────────────────────────────────────────────────────
1439
+ get_account_info: "Get info about the Mercado Pago account that owns the access token: site_id (MLA=Argentina), country_id, user_type (registered, partial, etc.). Useful to verify the agent is connected to the right account before taking actions.",
1440
+ // ── Saved-card charging (v0.3) ───────────────────────────────────────────
1441
+ charge_saved_card: "Charge a previously-saved card for a returning customer. Requires customer_id + card_id (from list_customer_cards) AND a fresh CVV the user provides this session. AR Mercado Pago does NOT support CVV-less charges via the public API \u2014 every charge needs CVV. Idempotent on (card_id, amount, external_reference): retries dedupe automatically. Returns the resulting Payment.",
1442
+ // ── QR in-store (v0.3) ───────────────────────────────────────────────────
1443
+ create_qr_payment: "Generate a dynamic in-store QR for a buyer to scan with any AR wallet (Modo, BNA+, Cuenta DNI, Naranja X, Mercado Pago, etc. \u2014 interop is mandated by Transferencias 3.0). Requires a pre-configured POS external_id (use create_pos to set one up first if needed). Returns the qr_data string + a base64 PNG data URL ready to display. The QR expires in `expires_in_seconds` (default 600). MP fires `point_integration_wh` then `payment` webhooks when scanned.",
1444
+ cancel_qr_payment: "Cancel a pending QR order on a POS. Necessary if the buyer never scans \u2014 otherwise the next create_qr_payment on the same POS returns 409.",
1445
+ // ── Subscription Plans (v0.4) ────────────────────────────────────────────
1446
+ create_subscription_plan: "Create a REUSABLE subscription plan (preapproval_plan). Different from create_subscription: a plan defines price + frequency once, then customers subscribe to it via subscribe_to_plan. Use plans for SaaS-style billing (B\xE1sico/Pro/Enterprise tiers). For per-customer custom amounts, use create_subscription directly.",
1447
+ list_subscription_plans: "List all subscription plans defined for this MP account. Useful before create_subscription_plan to check if one already exists, or for surfacing options to a customer.",
1448
+ update_subscription_plan: "Update a subscription plan's reason / amount / status / back_url. Existing customer subscriptions to the plan are NOT automatically updated \u2014 only NEW subscribers get the new pricing.",
1449
+ subscribe_to_plan: "Subscribe a customer to an existing reusable plan. Returns a Preapproval with init_point URL where the customer completes first payment. Cleaner than create_subscription when you have fixed tiers.",
1450
+ list_subscription_payments: "List the auto-charge attempts (authorized_payments) under a subscription. Useful for 'show me the cobros del \xFAltimo mes for this client' or to debug a failing recurring charge.",
1451
+ // ── Stores + POS (v0.4) ──────────────────────────────────────────────────
1452
+ create_store: "Create a store under the seller's MP account. Stores are the parent entity for POSes (which generate QR payments). Required ONE-TIME setup before create_pos. Pass a unique external_id and a display name.",
1453
+ list_stores: "List all stores configured for this MP account. Use this to find an existing store_id before create_pos, or to surface store options to the agent.",
1454
+ create_pos: "Create a POS (Point of Sale) under a store. The POS's external_id is what create_qr_payment uses. Each physical checkout / counter / agent typically has its own POS. Categories are MP-defined (default 621102 = Other Food and Beverage Services).",
1455
+ list_pos: "List all POSes for the seller (or filtered by store_id). Use to find an existing POS before create_qr_payment, or to surface options.",
1456
+ // ── Disputes (v0.4 — read-only) ──────────────────────────────────────────
1457
+ list_payment_disputes: "List all disputes / chargebacks raised against a payment. Read-only \u2014 resolution is dashboard-only. Surface the dashboard URL `https://www.mercadopago.com.ar/disputes/{dispute_id}` to the user when they need to respond.",
1458
+ get_dispute: "Get details of a specific dispute including reason, amount, resolution status. Read-only.",
1459
+ // ── Lookup helpers (v0.4) ────────────────────────────────────────────────
1460
+ list_identification_types: "List valid identification types for the seller's site. AR returns: DNI, CI, LE, LC, Otro, Pasaporte, CUIT, CUIL with their min/max length. Useful to validate an identification before passing to create_payment.",
1461
+ list_issuers: "List card issuers (banks) that support a payment_method_id. Optionally filter by `bin` (first 6 digits of the card) for accurate issuer detection. Useful with calculate_installments \u2014 issuer-specific promos (e.g., Naranja Galicia 6 cuotas sin inter\xE9s) only appear when the issuer is identified.",
1462
+ // ── Webhooks management (v0.4) ───────────────────────────────────────────
1463
+ list_webhooks: "List all webhook subscriptions configured for this MP application. Use to see what topics + URLs are wired before adding new ones.",
1464
+ create_webhook: "Subscribe a webhook URL to a MP topic (payment, subscription_authorized_payment, subscription_preapproval, merchant_order, point_integration_wh). MP will POST to this URL when events of that topic fire.",
1465
+ update_webhook: "Update a webhook's URL or topic. Useful when you change deployment URLs without resubscribing from scratch.",
1466
+ delete_webhook: "Delete a webhook subscription. MP stops POSTing to it immediately.",
1467
+ // ── Webhook handler combo (v0.5) ─────────────────────────────────────────
1468
+ handle_webhook: "Process an incoming MP webhook in ONE call: verify the HMAC-SHA256 signature, parse the event, and (optionally) auto-fetch the underlying resource (Payment, Subscription, Order). Returns the structured event PLUS the full resource. USE THIS in your webhook endpoint INSTEAD of chaining verify_webhook_signature + parse_webhook_event + get_payment manually. Pass the raw request body, x-signature header, x-request-id header, and your MP webhook secret. SAFE: returns { verified: false } when signature mismatches \u2014 caller should respond 401 and stop processing. WHEN auto_fetch is true (default), the resource is fetched as the SAME MP user the client is configured for (so for marketplace integrations, instantiate a per-seller client).",
1469
+ // ── OAuth Marketplace (v0.5) ─────────────────────────────────────────────
1470
+ oauth_authorize_url: "Build the URL the SELLER (third-party MP account) visits to authorize your marketplace app. Pass the seller's redirect uri (must be whitelisted in MP dev panel) and an opaque state token (CSRF protection \u2014 bind it to the user's session). PURE FUNCTION: no network. The seller approves, MP redirects them to your `redirect_uri?code=...&state=...`. Then call oauth_exchange_code with the code.",
1471
+ oauth_exchange_code: "Exchange the authorization code (from the OAuth redirect) for an `OAuthToken`. Returns access_token, refresh_token, user_id, and expires_in. **PERSIST the entire response** \u2014 refresh_token is long-lived and the only way to keep the integration alive past 6h. Use the access_token to instantiate a per-seller MercadoPagoClient for marketplace flows.",
1472
+ oauth_refresh_token: "Refresh a per-seller access_token using the saved refresh_token. Call PROACTIVELY before expires_in elapses, or REACTIVELY on a 401 from a per-seller MercadoPagoClient. Returns a fresh OAuthToken \u2014 persist the new refresh_token (MP often returns the same value, but always replace).",
1473
+ // ── Order Management API (v0.5 — modern Order API) ───────────────────────
1474
+ create_order: "Create a new Order via MP's modern Order Management API. DIFFERENT from create_payment_preference: Order is a transactional entity with explicit lifecycle (created \u2192 processed \u2192 captured/canceled), supports MANUAL CAPTURE (auth-only, capture later \u2014 for ride-share, hotels, marketplaces) and aggregates multiple payments into one Order. Use Preference (Checkout Pro) for simple hosted pay-links; use Order when you need auth-only or multi-payment-per-order semantics. For marketplace splits, set marketplace + marketplace_fee + collector_id (the SELLER's MP user_id from oauth_exchange_code).",
1475
+ get_order: "Fetch an Order by ID. Returns the Order with its lifecycle status and any attached payments/refunds.",
1476
+ update_order: "Patch an existing Order before it's captured/canceled. Common use: update items or external_reference.",
1477
+ capture_order: "Capture a previously-authorized Order (only for orders created with capture_mode='manual'). Captures up to the originally-authorized amount; pass amount for partial capture. Common use: ride-share marks ride complete \u2192 capture; hotel checks-out guest \u2192 capture.",
1478
+ cancel_order: "Cancel an Order. Releases any auth-holds and marks the Order as canceled. For orders that have already been CAPTURED, use refund_payment instead \u2014 cancel only works pre-capture."
1479
+ };
1480
+ function mercadoPagoTools(client, options) {
1481
+ const desc = (name) => options.descriptions?.[name] ?? DEFAULT_DESCRIPTIONS[name];
1482
+ return {
1483
+ // ─────────────────────────────────────────────────────────────────────────
1484
+ // Subscriptions (v0.1 — kept identical for backward compatibility)
1485
+ // ─────────────────────────────────────────────────────────────────────────
1486
+ create_subscription: ai.tool({
1487
+ description: desc("create_subscription"),
1488
+ inputSchema: zod.z.object({
1489
+ customer_email: zod.z.string().email().describe("Email of the customer who will be charged"),
1490
+ amount_ars: zod.z.number().positive().describe("Amount in Argentine Pesos per recurring charge"),
1491
+ frequency_months: zod.z.number().int().positive().max(12).describe("Frequency in months (1=monthly, 3=quarterly, 12=yearly)"),
1492
+ reason: zod.z.string().min(3).max(120).describe("Short description shown to the customer at checkout"),
1493
+ external_reference: zod.z.string().optional().describe("Optional id from your system to track this subscription")
1494
+ }),
1495
+ execute: async ({ customer_email, amount_ars, frequency_months, reason, external_reference }) => {
1496
+ const created = await client.createPreapproval({
1497
+ reason,
1498
+ payerEmail: customer_email,
1499
+ amount: amount_ars,
1500
+ currency: "ARS",
1501
+ frequency: frequency_months,
1502
+ frequencyType: "months",
1503
+ backUrl: options.backUrl,
1504
+ ...external_reference !== void 0 ? { externalReference: external_reference } : {}
1505
+ });
1506
+ await options.state.set(created.id, {
1507
+ status: created.status,
1508
+ payerEmail: customer_email,
1509
+ amount: amount_ars,
1510
+ currency: "ARS",
1511
+ frequency: frequency_months,
1512
+ frequencyType: "months",
1513
+ initPoint: created.init_point,
1514
+ ...external_reference !== void 0 ? { externalReference: external_reference } : {},
1515
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1516
+ });
1517
+ return {
1518
+ subscription_id: created.id,
1519
+ status: created.status,
1520
+ init_point_url: created.init_point,
1521
+ next_step: "Send init_point_url to the customer. They must complete the first payment with card+CVV. Use get_subscription_status to confirm activation after they pay."
1522
+ };
1523
+ }
1524
+ }),
1525
+ get_subscription_status: ai.tool({
1526
+ description: desc("get_subscription_status"),
1527
+ inputSchema: zod.z.object({
1528
+ subscription_id: zod.z.string().describe("The Mercado Pago subscription/preapproval ID")
1529
+ }),
1530
+ execute: async ({ subscription_id }) => {
1531
+ const fresh = await client.getPreapproval(subscription_id);
1532
+ const cached = await options.state.get(subscription_id);
1533
+ return {
1534
+ subscription_id: fresh.id,
1535
+ status: fresh.status,
1536
+ payer_email: fresh.payer_email,
1537
+ amount: fresh.auto_recurring.transaction_amount,
1538
+ currency: fresh.auto_recurring.currency_id,
1539
+ next_payment_date: fresh.next_payment_date ?? null,
1540
+ last_webhook_status: cached?.lastWebhookStatus ?? null,
1541
+ last_webhook_at: cached?.lastWebhookAt ?? null
1542
+ };
1543
+ }
1544
+ }),
1545
+ cancel_subscription: ai.tool({
1546
+ description: desc("cancel_subscription"),
1547
+ inputSchema: zod.z.object({
1548
+ subscription_id: zod.z.string().describe("The Mercado Pago subscription/preapproval ID to cancel")
1549
+ }),
1550
+ execute: async ({ subscription_id }) => {
1551
+ const cancelled = await client.cancelPreapproval(subscription_id);
1552
+ await options.state.set(subscription_id, {
1553
+ status: cancelled.status,
1554
+ cancelledAt: (/* @__PURE__ */ new Date()).toISOString()
1555
+ });
1556
+ return {
1557
+ subscription_id: cancelled.id,
1558
+ status: cancelled.status,
1559
+ message: "Subscription cancelled. No further charges will occur."
1560
+ };
1561
+ }
1562
+ }),
1563
+ pause_subscription: ai.tool({
1564
+ description: desc("pause_subscription"),
1565
+ inputSchema: zod.z.object({ subscription_id: zod.z.string() }),
1566
+ execute: async ({ subscription_id }) => {
1567
+ const paused = await client.pausePreapproval(subscription_id);
1568
+ await options.state.set(subscription_id, { status: paused.status });
1569
+ return {
1570
+ subscription_id: paused.id,
1571
+ status: paused.status,
1572
+ message: "Subscription paused. Use resume_subscription to reactivate."
1573
+ };
1574
+ }
1575
+ }),
1576
+ resume_subscription: ai.tool({
1577
+ description: desc("resume_subscription"),
1578
+ inputSchema: zod.z.object({ subscription_id: zod.z.string() }),
1579
+ execute: async ({ subscription_id }) => {
1580
+ const resumed = await client.resumePreapproval(subscription_id);
1581
+ await options.state.set(subscription_id, { status: resumed.status });
1582
+ return {
1583
+ subscription_id: resumed.id,
1584
+ status: resumed.status,
1585
+ message: "Subscription resumed. Charges will continue on next scheduled date."
1586
+ };
1587
+ }
1588
+ }),
1589
+ // ─────────────────────────────────────────────────────────────────────────
1590
+ // Payments (v0.2)
1591
+ // ─────────────────────────────────────────────────────────────────────────
1592
+ create_payment: ai.tool({
1593
+ description: desc("create_payment"),
1594
+ inputSchema: zod.z.object({
1595
+ amount_ars: zod.z.number().positive().describe("Amount in ARS"),
1596
+ payment_method_id: zod.z.string().describe("MP payment method id (e.g. 'account_money', 'rapipago', 'visa', 'master', 'naranja')"),
1597
+ payer_email: zod.z.string().email().describe("Email of the payer. Cannot equal seller email."),
1598
+ token: zod.z.string().optional().describe("Card token from MP frontend Cardform. Required for credit/debit; omit for cash/account_money."),
1599
+ installments: zod.z.number().int().min(1).max(24).optional().describe("Number of installments (cuotas). Default 1. Use calculate_installments first to see options."),
1600
+ description: zod.z.string().max(255).optional().describe("Short description"),
1601
+ external_reference: zod.z.string().optional().describe("Your-system identifier"),
1602
+ identification: zod.z.object({
1603
+ type: zod.z.enum(["DNI", "CUIT", "CUIL"]),
1604
+ number: zod.z.string()
1605
+ }).optional().describe("Payer identification \u2014 required for some payment types in AR"),
1606
+ statement_descriptor: zod.z.string().max(13).optional().describe("Shows on buyer's card statement (max 13 chars)")
1607
+ }),
1608
+ execute: async (input) => {
1609
+ const payment = await client.createPayment({
1610
+ transactionAmount: input.amount_ars,
1611
+ paymentMethodId: input.payment_method_id,
1612
+ payerEmail: input.payer_email,
1613
+ ...input.token !== void 0 ? { token: input.token } : {},
1614
+ ...input.installments !== void 0 ? { installments: input.installments } : {},
1615
+ ...input.description !== void 0 ? { description: input.description } : {},
1616
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1617
+ ...input.identification !== void 0 ? { identification: input.identification } : {},
1618
+ ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
1619
+ ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
1620
+ // Deterministic idempotency key — safe to retry, same inputs always
1621
+ // produce the same key (MP dedupes on its side).
1622
+ idempotencyKey: deterministicIdempotencyKey(
1623
+ "create_payment",
1624
+ input.external_reference ?? input.payer_email,
1625
+ input.amount_ars,
1626
+ input.payment_method_id,
1627
+ input.token
1628
+ )
1629
+ });
1630
+ return {
1631
+ payment_id: payment.id,
1632
+ status: payment.status,
1633
+ status_detail: payment.status_detail,
1634
+ amount: payment.transaction_amount,
1635
+ currency: payment.currency_id,
1636
+ installments: payment.installments,
1637
+ payment_method: payment.payment_method_id,
1638
+ payer_email: payment.payer?.email ?? null,
1639
+ external_reference: payment.external_reference,
1640
+ date_created: payment.date_created,
1641
+ date_approved: payment.date_approved
1642
+ };
1643
+ }
1644
+ }),
1645
+ get_payment: ai.tool({
1646
+ description: desc("get_payment"),
1647
+ inputSchema: zod.z.object({
1648
+ payment_id: zod.z.string().describe("The MP payment ID")
1649
+ }),
1650
+ execute: async ({ payment_id }) => {
1651
+ const p = await client.getPayment(payment_id);
1652
+ return {
1653
+ payment_id: p.id,
1654
+ status: p.status,
1655
+ status_detail: p.status_detail,
1656
+ amount: p.transaction_amount,
1657
+ currency: p.currency_id,
1658
+ payment_method: p.payment_method_id,
1659
+ installments: p.installments,
1660
+ payer_email: p.payer?.email ?? null,
1661
+ external_reference: p.external_reference,
1662
+ date_created: p.date_created,
1663
+ date_approved: p.date_approved,
1664
+ net_received: p.transaction_details?.net_received_amount ?? null
1665
+ };
1666
+ }
1667
+ }),
1668
+ search_payments: ai.tool({
1669
+ description: desc("search_payments"),
1670
+ inputSchema: zod.z.object({
1671
+ external_reference: zod.z.string().optional(),
1672
+ status: zod.z.string().optional().describe("'approved' | 'pending' | 'rejected' | 'cancelled' | 'refunded' etc."),
1673
+ payer_email: zod.z.string().optional(),
1674
+ begin_date: zod.z.string().optional().describe("ISO 8601, e.g. 2026-01-01T00:00:00Z"),
1675
+ end_date: zod.z.string().optional().describe("ISO 8601"),
1676
+ limit: zod.z.number().int().min(1).max(100).optional().describe("Default 30, max 100"),
1677
+ offset: zod.z.number().int().min(0).optional().describe("Pagination offset (default 0)")
1678
+ }),
1679
+ execute: async (input) => {
1680
+ const result = await client.searchPayments({
1681
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1682
+ ...input.status !== void 0 ? { status: input.status } : {},
1683
+ ...input.payer_email !== void 0 ? { payerEmail: input.payer_email } : {},
1684
+ ...input.begin_date !== void 0 ? { beginDate: input.begin_date } : {},
1685
+ ...input.end_date !== void 0 ? { endDate: input.end_date } : {},
1686
+ ...input.limit !== void 0 ? { limit: input.limit } : {},
1687
+ ...input.offset !== void 0 ? { offset: input.offset } : {}
1688
+ });
1689
+ return {
1690
+ total: result.paging.total,
1691
+ returned: result.results.length,
1692
+ offset: result.paging.offset,
1693
+ payments: result.results.map((p) => ({
1694
+ payment_id: p.id,
1695
+ status: p.status,
1696
+ amount: p.transaction_amount,
1697
+ currency: p.currency_id,
1698
+ payer_email: p.payer?.email ?? null,
1699
+ external_reference: p.external_reference,
1700
+ date_created: p.date_created
1701
+ }))
1702
+ };
1703
+ }
1704
+ }),
1705
+ cancel_payment: ai.tool({
1706
+ description: desc("cancel_payment"),
1707
+ inputSchema: zod.z.object({ payment_id: zod.z.string() }),
1708
+ execute: async ({ payment_id }) => {
1709
+ const cancelled = await client.cancelPayment(payment_id);
1710
+ return {
1711
+ payment_id: cancelled.id,
1712
+ status: cancelled.status,
1713
+ message: "Payment cancelled. If it was already approved, use refund_payment instead."
1714
+ };
1715
+ }
1716
+ }),
1717
+ capture_payment: ai.tool({
1718
+ description: desc("capture_payment"),
1719
+ inputSchema: zod.z.object({
1720
+ payment_id: zod.z.string(),
1721
+ amount_ars: zod.z.number().positive().optional().describe("Optional partial-capture amount. Omit to capture full authorized amount.")
1722
+ }),
1723
+ execute: async ({ payment_id, amount_ars }) => {
1724
+ const captured = await client.capturePayment(payment_id, amount_ars);
1725
+ return {
1726
+ payment_id: captured.id,
1727
+ status: captured.status,
1728
+ amount: captured.transaction_amount
1729
+ };
1730
+ }
1731
+ }),
1732
+ // ─────────────────────────────────────────────────────────────────────────
1733
+ // Refunds
1734
+ // ─────────────────────────────────────────────────────────────────────────
1735
+ refund_payment: ai.tool({
1736
+ description: desc("refund_payment"),
1737
+ inputSchema: zod.z.object({
1738
+ payment_id: zod.z.string(),
1739
+ amount_ars: zod.z.number().positive().optional().describe("Partial-refund amount in ARS. Omit for full refund.")
1740
+ }),
1741
+ execute: async ({ payment_id, amount_ars }) => {
1742
+ const refund = await client.createRefund({
1743
+ paymentId: payment_id,
1744
+ ...amount_ars !== void 0 ? { amount: amount_ars } : {},
1745
+ idempotencyKey: deterministicIdempotencyKey("refund", payment_id, amount_ars ?? "full")
1746
+ });
1747
+ return {
1748
+ refund_id: refund.id,
1749
+ payment_id: refund.payment_id,
1750
+ amount: refund.amount,
1751
+ status: refund.status,
1752
+ message: amount_ars === void 0 ? "Full refund issued. Funds return to the buyer in 3-10 business days." : `Partial refund of ${amount_ars} ARS issued.`
1753
+ };
1754
+ }
1755
+ }),
1756
+ list_refunds: ai.tool({
1757
+ description: desc("list_refunds"),
1758
+ inputSchema: zod.z.object({ payment_id: zod.z.string() }),
1759
+ execute: async ({ payment_id }) => {
1760
+ const refunds = await client.listRefunds(payment_id);
1761
+ return {
1762
+ payment_id,
1763
+ count: refunds.length,
1764
+ refunds: refunds.map((r) => ({
1765
+ refund_id: r.id,
1766
+ amount: r.amount,
1767
+ status: r.status,
1768
+ date_created: r.date_created
1769
+ }))
1770
+ };
1771
+ }
1772
+ }),
1773
+ // ─────────────────────────────────────────────────────────────────────────
1774
+ // Checkout Pro
1775
+ // ─────────────────────────────────────────────────────────────────────────
1776
+ create_payment_preference: ai.tool({
1777
+ description: desc("create_payment_preference"),
1778
+ inputSchema: zod.z.object({
1779
+ items: zod.z.array(zod.z.object({
1780
+ title: zod.z.string().min(1).max(256),
1781
+ quantity: zod.z.number().int().positive(),
1782
+ unit_price: zod.z.number().positive(),
1783
+ description: zod.z.string().optional(),
1784
+ picture_url: zod.z.string().url().optional()
1785
+ })).min(1).describe("Items being charged. At least one required."),
1786
+ payer_email: zod.z.string().email().optional().describe("Pre-fill the payer email on Checkout Pro form"),
1787
+ external_reference: zod.z.string().optional(),
1788
+ max_installments: zod.z.number().int().min(1).max(24).optional().describe("Limit max cuotas offered. Defaults to MP account config."),
1789
+ statement_descriptor: zod.z.string().max(13).optional(),
1790
+ excluded_payment_types: zod.z.array(zod.z.enum(["credit_card", "debit_card", "ticket", "atm", "bank_transfer"])).optional().describe("Block payment types \u2014 e.g., ['ticket'] to disable Rapipago/Pago F\xE1cil")
1791
+ }),
1792
+ execute: async (input) => {
1793
+ const pref = await client.createPreference({
1794
+ items: input.items.map((it) => ({
1795
+ title: it.title,
1796
+ quantity: it.quantity,
1797
+ unit_price: it.unit_price,
1798
+ currency_id: "ARS",
1799
+ ...it.description !== void 0 ? { description: it.description } : {},
1800
+ ...it.picture_url !== void 0 ? { picture_url: it.picture_url } : {}
1801
+ })),
1802
+ ...input.payer_email !== void 0 ? { payer: { email: input.payer_email } } : {},
1803
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
1804
+ ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
1805
+ backUrls: { success: options.backUrl, failure: options.backUrl, pending: options.backUrl },
1806
+ autoReturn: "approved",
1807
+ ...options.notificationUrl !== void 0 ? { notificationUrl: options.notificationUrl } : {},
1808
+ ...input.max_installments !== void 0 || input.excluded_payment_types !== void 0 ? {
1809
+ paymentMethods: {
1810
+ ...input.max_installments !== void 0 ? { installments: input.max_installments } : {},
1811
+ ...input.excluded_payment_types !== void 0 ? { excluded_payment_types: input.excluded_payment_types.map((id) => ({ id })) } : {}
1812
+ }
1813
+ } : {}
1814
+ });
1815
+ return {
1816
+ preference_id: pref.id,
1817
+ init_point_url: pref.init_point ?? null,
1818
+ sandbox_init_point_url: pref.sandbox_init_point ?? null,
1819
+ external_reference: pref.external_reference,
1820
+ date_created: pref.date_created,
1821
+ next_step: "Send init_point_url (or sandbox_init_point_url in sandbox) to the customer. After they pay, MP fires a webhook with the payment_id; use get_payment to confirm status."
1822
+ };
1823
+ }
1824
+ }),
1825
+ get_payment_preference: ai.tool({
1826
+ description: desc("get_payment_preference"),
1827
+ inputSchema: zod.z.object({ preference_id: zod.z.string() }),
1828
+ execute: async ({ preference_id }) => {
1829
+ const pref = await client.getPreference(preference_id);
1830
+ return {
1831
+ preference_id: pref.id,
1832
+ init_point_url: pref.init_point ?? null,
1833
+ sandbox_init_point_url: pref.sandbox_init_point ?? null,
1834
+ external_reference: pref.external_reference,
1835
+ items: pref.items,
1836
+ date_created: pref.date_created
1837
+ };
1838
+ }
1839
+ }),
1840
+ // ─────────────────────────────────────────────────────────────────────────
1841
+ // Customers + Saved Cards
1842
+ // ─────────────────────────────────────────────────────────────────────────
1843
+ create_customer: ai.tool({
1844
+ description: desc("create_customer"),
1845
+ inputSchema: zod.z.object({
1846
+ email: zod.z.string().email(),
1847
+ first_name: zod.z.string().optional(),
1848
+ last_name: zod.z.string().optional(),
1849
+ identification: zod.z.object({
1850
+ type: zod.z.enum(["DNI", "CUIT", "CUIL"]),
1851
+ number: zod.z.string()
1852
+ }).optional(),
1853
+ description: zod.z.string().optional()
1854
+ }),
1855
+ execute: async (input) => {
1856
+ const customer = await client.createCustomer({
1857
+ email: input.email,
1858
+ ...input.first_name !== void 0 ? { firstName: input.first_name } : {},
1859
+ ...input.last_name !== void 0 ? { lastName: input.last_name } : {},
1860
+ ...input.identification !== void 0 ? { identification: input.identification } : {},
1861
+ ...input.description !== void 0 ? { description: input.description } : {}
1862
+ });
1863
+ return {
1864
+ customer_id: customer.id,
1865
+ email: customer.email,
1866
+ first_name: customer.first_name,
1867
+ last_name: customer.last_name,
1868
+ date_created: customer.date_created
1869
+ };
1870
+ }
1871
+ }),
1872
+ find_customer_by_email: ai.tool({
1873
+ description: desc("find_customer_by_email"),
1874
+ inputSchema: zod.z.object({ email: zod.z.string().email() }),
1875
+ execute: async ({ email }) => {
1876
+ const result = await client.searchCustomers({ email, limit: 1 });
1877
+ const customer = result.results[0] ?? null;
1878
+ return customer ? {
1879
+ found: true,
1880
+ customer_id: customer.id,
1881
+ email: customer.email,
1882
+ first_name: customer.first_name,
1883
+ last_name: customer.last_name
1884
+ } : { found: false, customer_id: null };
1885
+ }
1886
+ }),
1887
+ list_customer_cards: ai.tool({
1888
+ description: desc("list_customer_cards"),
1889
+ inputSchema: zod.z.object({ customer_id: zod.z.string() }),
1890
+ execute: async ({ customer_id }) => {
1891
+ const cards = await client.listCustomerCards(customer_id);
1892
+ return {
1893
+ customer_id,
1894
+ count: cards.length,
1895
+ cards: cards.map((c) => ({
1896
+ card_id: c.id,
1897
+ last_four_digits: c.last_four_digits,
1898
+ expiration_month: c.expiration_month,
1899
+ expiration_year: c.expiration_year,
1900
+ payment_method: c.payment_method?.id ?? null,
1901
+ payment_method_name: c.payment_method?.name ?? null
1902
+ }))
1903
+ };
1904
+ }
1905
+ }),
1906
+ delete_customer_card: ai.tool({
1907
+ description: desc("delete_customer_card"),
1908
+ inputSchema: zod.z.object({
1909
+ customer_id: zod.z.string(),
1910
+ card_id: zod.z.string()
1911
+ }),
1912
+ execute: async ({ customer_id, card_id }) => {
1913
+ await client.deleteCustomerCard(customer_id, card_id);
1914
+ return { customer_id, card_id, deleted: true };
1915
+ }
1916
+ }),
1917
+ // ─────────────────────────────────────────────────────────────────────────
1918
+ // Payment Methods + Installments
1919
+ // ─────────────────────────────────────────────────────────────────────────
1920
+ list_payment_methods: ai.tool({
1921
+ description: desc("list_payment_methods"),
1922
+ inputSchema: zod.z.object({}),
1923
+ execute: async () => {
1924
+ const methods = await client.listPaymentMethods();
1925
+ return {
1926
+ count: methods.length,
1927
+ methods: methods.map((m) => ({
1928
+ id: m.id,
1929
+ name: m.name,
1930
+ payment_type: m.payment_type_id,
1931
+ status: m.status,
1932
+ min_amount: m.min_allowed_amount,
1933
+ max_amount: m.max_allowed_amount
1934
+ }))
1935
+ };
1936
+ }
1937
+ }),
1938
+ calculate_installments: ai.tool({
1939
+ description: desc("calculate_installments"),
1940
+ inputSchema: zod.z.object({
1941
+ amount_ars: zod.z.number().positive(),
1942
+ payment_method_id: zod.z.string().optional().describe("E.g. 'visa', 'master', 'naranja'. Omit for all available methods."),
1943
+ bin: zod.z.string().min(6).max(8).optional().describe("First 6-8 digits of card for issuer-specific offers (e.g., Naranja interest-free promotions)")
1944
+ }),
1945
+ execute: async (input) => {
1946
+ const offers = await client.getInstallments({
1947
+ amount: input.amount_ars,
1948
+ ...input.payment_method_id !== void 0 ? { paymentMethodId: input.payment_method_id } : {},
1949
+ ...input.bin !== void 0 ? { bin: input.bin } : {}
1950
+ });
1951
+ return {
1952
+ amount: input.amount_ars,
1953
+ offers: offers.map((o) => ({
1954
+ payment_method_id: o.payment_method_id,
1955
+ payment_type_id: o.payment_type_id,
1956
+ issuer_name: o.issuer?.name ?? null,
1957
+ options: o.payer_costs.map((pc) => ({
1958
+ installments: pc.installments,
1959
+ installment_amount: pc.installment_amount,
1960
+ total_amount: pc.total_amount,
1961
+ installment_rate: pc.installment_rate,
1962
+ recommended_message: pc.recommended_message
1963
+ }))
1964
+ }))
1965
+ };
1966
+ }
1967
+ }),
1968
+ // ─────────────────────────────────────────────────────────────────────────
1969
+ // Account
1970
+ // ─────────────────────────────────────────────────────────────────────────
1971
+ get_account_info: ai.tool({
1972
+ description: desc("get_account_info"),
1973
+ inputSchema: zod.z.object({}),
1974
+ execute: async () => {
1975
+ const me = await client.getMe();
1976
+ return {
1977
+ account_id: me.id,
1978
+ email: me.email,
1979
+ nickname: me.nickname,
1980
+ country_id: me.country_id,
1981
+ site_id: me.site_id,
1982
+ user_type: me.user_type
1983
+ };
1984
+ }
1985
+ }),
1986
+ // ─────────────────────────────────────────────────────────────────────────
1987
+ // Saved-card charging (v0.3)
1988
+ // ─────────────────────────────────────────────────────────────────────────
1989
+ charge_saved_card: ai.tool({
1990
+ description: desc("charge_saved_card"),
1991
+ inputSchema: zod.z.object({
1992
+ customer_id: zod.z.string().describe("MP customer id (from create_customer / find_customer_by_email)"),
1993
+ card_id: zod.z.string().describe("Saved card id (from list_customer_cards)"),
1994
+ security_code: zod.z.string().regex(/^\d{3,4}$/).describe("CVV \u2014 3 digits (Visa/Master) or 4 (Amex). User must provide this each charge in AR."),
1995
+ amount_ars: zod.z.number().positive(),
1996
+ description: zod.z.string().min(1).max(255),
1997
+ installments: zod.z.number().int().min(1).max(24).optional().describe("Default 1. Use calculate_installments first to pick a valid count."),
1998
+ external_reference: zod.z.string().optional(),
1999
+ statement_descriptor: zod.z.string().max(13).optional()
2000
+ }),
2001
+ execute: async (input) => {
2002
+ const payment = await client.chargeSavedCard({
2003
+ customerId: input.customer_id,
2004
+ cardId: input.card_id,
2005
+ securityCode: input.security_code,
2006
+ amount: input.amount_ars,
2007
+ description: input.description,
2008
+ ...input.installments !== void 0 ? { installments: input.installments } : {},
2009
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
2010
+ ...input.statement_descriptor !== void 0 ? { statementDescriptor: input.statement_descriptor } : {},
2011
+ idempotencyKey: deterministicIdempotencyKey(
2012
+ "charge_saved_card",
2013
+ input.card_id,
2014
+ input.amount_ars,
2015
+ input.external_reference
2016
+ )
2017
+ });
2018
+ return {
2019
+ payment_id: payment.id,
2020
+ status: payment.status,
2021
+ status_detail: payment.status_detail,
2022
+ amount: payment.transaction_amount,
2023
+ installments: payment.installments,
2024
+ payment_method: payment.payment_method_id,
2025
+ customer_id: input.customer_id,
2026
+ card_id: input.card_id,
2027
+ external_reference: payment.external_reference,
2028
+ date_approved: payment.date_approved
2029
+ };
2030
+ }
2031
+ }),
2032
+ // ─────────────────────────────────────────────────────────────────────────
2033
+ // QR in-store (v0.3)
2034
+ // ─────────────────────────────────────────────────────────────────────────
2035
+ create_qr_payment: ai.tool({
2036
+ description: desc("create_qr_payment"),
2037
+ inputSchema: zod.z.object({
2038
+ external_pos_id: zod.z.string().describe("Pre-configured POS external_id from MP dashboard. Required."),
2039
+ amount_ars: zod.z.number().positive(),
2040
+ title: zod.z.string().min(1).max(80).describe("Display title shown when scanning"),
2041
+ description: zod.z.string().max(255).optional(),
2042
+ external_reference: zod.z.string().optional(),
2043
+ notification_url: zod.z.string().url().optional().describe("Webhook URL \u2014 falls back to dashboard config if omitted"),
2044
+ expires_in_seconds: zod.z.number().int().min(60).max(3600).optional().describe("Default 600 (10 min)")
2045
+ }),
2046
+ execute: async (input) => {
2047
+ const QRCode = (await import('qrcode')).default;
2048
+ const me = await client.getMe();
2049
+ const userId = String(me.id);
2050
+ const expiresAt = new Date(
2051
+ Date.now() + (input.expires_in_seconds ?? 600) * 1e3
2052
+ ).toISOString();
2053
+ const qr = await client.createQrPayment(userId, {
2054
+ externalPosId: input.external_pos_id,
2055
+ totalAmount: input.amount_ars,
2056
+ title: input.title,
2057
+ ...input.description !== void 0 ? { description: input.description } : {},
2058
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
2059
+ ...input.notification_url !== void 0 ? { notificationUrl: input.notification_url } : {},
2060
+ expirationDate: expiresAt
2061
+ });
2062
+ const qrDataUrl = await QRCode.toDataURL(qr.qr_data, {
2063
+ errorCorrectionLevel: "M",
2064
+ margin: 1,
2065
+ width: 512
2066
+ });
2067
+ return {
2068
+ in_store_order_id: qr.in_store_order_id,
2069
+ qr_data: qr.qr_data,
2070
+ qr_data_url: qrDataUrl,
2071
+ expires_at: expiresAt,
2072
+ external_pos_id: input.external_pos_id,
2073
+ amount: input.amount_ars,
2074
+ next_step: "Display the qr_data_url image to the buyer. Wait for the payment webhook (point_integration_wh fires first, then payment topic). If buyer doesn't scan in time, call cancel_qr_payment to free the POS."
2075
+ };
2076
+ }
2077
+ }),
2078
+ cancel_qr_payment: ai.tool({
2079
+ description: desc("cancel_qr_payment"),
2080
+ inputSchema: zod.z.object({
2081
+ external_pos_id: zod.z.string()
2082
+ }),
2083
+ execute: async ({ external_pos_id }) => {
2084
+ const me = await client.getMe();
2085
+ await client.cancelQrPayment(String(me.id), external_pos_id);
2086
+ return { external_pos_id, cancelled: true };
2087
+ }
2088
+ }),
2089
+ // ─────────────────────────────────────────────────────────────────────────
2090
+ // Subscription Plans (v0.4)
2091
+ // ─────────────────────────────────────────────────────────────────────────
2092
+ create_subscription_plan: ai.tool({
2093
+ description: desc("create_subscription_plan"),
2094
+ inputSchema: zod.z.object({
2095
+ reason: zod.z.string().min(3).max(120).describe("Plan name shown at checkout"),
2096
+ amount_ars: zod.z.number().positive(),
2097
+ frequency_months: zod.z.number().int().min(1).max(12),
2098
+ back_url: zod.z.string().url().describe("HTTPS URL where MP redirects after first payment"),
2099
+ external_reference: zod.z.string().optional(),
2100
+ free_trial_days: zod.z.number().int().min(1).max(60).optional().describe("Free trial period in days before first charge")
2101
+ }),
2102
+ execute: async (input) => {
2103
+ const plan = await client.createSubscriptionPlan({
2104
+ reason: input.reason,
2105
+ amount: input.amount_ars,
2106
+ currency: "ARS",
2107
+ frequency: input.frequency_months,
2108
+ frequencyType: "months",
2109
+ backUrl: input.back_url,
2110
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {},
2111
+ ...input.free_trial_days !== void 0 ? { freeTrialFrequency: input.free_trial_days, freeTrialFrequencyType: "days" } : {}
2112
+ });
2113
+ return {
2114
+ plan_id: plan.id,
2115
+ status: plan.status,
2116
+ reason: plan.reason,
2117
+ amount: plan.auto_recurring.transaction_amount,
2118
+ currency: plan.auto_recurring.currency_id,
2119
+ frequency: `${plan.auto_recurring.frequency} ${plan.auto_recurring.frequency_type}`,
2120
+ external_reference: plan.external_reference,
2121
+ next_step: "Use subscribe_to_plan to enroll customers in this plan, or share its ID for them to subscribe via your frontend."
2122
+ };
2123
+ }
2124
+ }),
2125
+ list_subscription_plans: ai.tool({
2126
+ description: desc("list_subscription_plans"),
2127
+ inputSchema: zod.z.object({
2128
+ status: zod.z.string().optional(),
2129
+ limit: zod.z.number().int().min(1).max(100).optional()
2130
+ }),
2131
+ execute: async (input) => {
2132
+ const result = await client.listSubscriptionPlans({
2133
+ ...input.status !== void 0 ? { status: input.status } : {},
2134
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
2135
+ });
2136
+ return {
2137
+ total: result.paging.total,
2138
+ plans: result.results.map((p) => ({
2139
+ plan_id: p.id,
2140
+ reason: p.reason,
2141
+ status: p.status,
2142
+ amount: p.auto_recurring.transaction_amount,
2143
+ currency: p.auto_recurring.currency_id,
2144
+ frequency: `${p.auto_recurring.frequency} ${p.auto_recurring.frequency_type}`
2145
+ }))
2146
+ };
2147
+ }
2148
+ }),
2149
+ update_subscription_plan: ai.tool({
2150
+ description: desc("update_subscription_plan"),
2151
+ inputSchema: zod.z.object({
2152
+ plan_id: zod.z.string(),
2153
+ reason: zod.z.string().optional(),
2154
+ amount_ars: zod.z.number().positive().optional(),
2155
+ status: zod.z.enum(["active", "cancelled"]).optional(),
2156
+ back_url: zod.z.string().url().optional()
2157
+ }),
2158
+ execute: async (input) => {
2159
+ const updated = await client.updateSubscriptionPlan(input.plan_id, {
2160
+ ...input.reason !== void 0 ? { reason: input.reason } : {},
2161
+ ...input.amount_ars !== void 0 ? { amount: input.amount_ars } : {},
2162
+ ...input.status !== void 0 ? { status: input.status } : {},
2163
+ ...input.back_url !== void 0 ? { backUrl: input.back_url } : {}
2164
+ });
2165
+ return {
2166
+ plan_id: updated.id,
2167
+ status: updated.status,
2168
+ reason: updated.reason,
2169
+ amount: updated.auto_recurring.transaction_amount,
2170
+ message: input.amount_ars !== void 0 ? "Updated. Existing subscribers keep their old amount; only NEW subscribers get the new pricing." : "Plan updated."
2171
+ };
2172
+ }
2173
+ }),
2174
+ subscribe_to_plan: ai.tool({
2175
+ description: desc("subscribe_to_plan"),
2176
+ inputSchema: zod.z.object({
2177
+ plan_id: zod.z.string(),
2178
+ customer_email: zod.z.string().email(),
2179
+ external_reference: zod.z.string().optional()
2180
+ }),
2181
+ execute: async (input) => {
2182
+ const sub = await client.subscribeToPlan({
2183
+ planId: input.plan_id,
2184
+ payerEmail: input.customer_email,
2185
+ ...input.external_reference !== void 0 ? { externalReference: input.external_reference } : {}
2186
+ });
2187
+ return {
2188
+ subscription_id: sub.id,
2189
+ status: sub.status,
2190
+ payer_email: sub.payer_email,
2191
+ init_point_url: sub.init_point,
2192
+ next_step: "Send init_point_url to the customer for first payment with card+CVV."
2193
+ };
2194
+ }
2195
+ }),
2196
+ list_subscription_payments: ai.tool({
2197
+ description: desc("list_subscription_payments"),
2198
+ inputSchema: zod.z.object({
2199
+ subscription_id: zod.z.string(),
2200
+ limit: zod.z.number().int().min(1).max(100).optional()
2201
+ }),
2202
+ execute: async (input) => {
2203
+ const result = await client.listSubscriptionPayments(input.subscription_id, {
2204
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
2205
+ });
2206
+ return {
2207
+ subscription_id: input.subscription_id,
2208
+ total: result.paging.total,
2209
+ payments: result.results.map((p) => ({
2210
+ authorized_payment_id: p.id,
2211
+ payment_id: p.payment_id ?? null,
2212
+ status: p.status,
2213
+ amount: p.transaction_amount ?? null,
2214
+ currency: p.currency_id ?? null,
2215
+ debit_date: p.debit_date ?? null,
2216
+ next_retry_date: p.next_retry_date ?? null,
2217
+ retry_attempt: p.retry_attempt ?? 0,
2218
+ reason: p.reason ?? null
2219
+ }))
2220
+ };
2221
+ }
2222
+ }),
2223
+ // ─────────────────────────────────────────────────────────────────────────
2224
+ // Stores + POS (v0.4)
2225
+ // ─────────────────────────────────────────────────────────────────────────
2226
+ create_store: ai.tool({
2227
+ description: desc("create_store"),
2228
+ inputSchema: zod.z.object({
2229
+ name: zod.z.string().min(1).max(80),
2230
+ external_id: zod.z.string().min(1).max(64).describe("Unique within the seller's stores"),
2231
+ address_line: zod.z.string().optional(),
2232
+ city_name: zod.z.string().optional(),
2233
+ state_name: zod.z.string().optional()
2234
+ }),
2235
+ execute: async (input) => {
2236
+ const me = await client.getMe();
2237
+ const store = await client.createStore(String(me.id), {
2238
+ name: input.name,
2239
+ externalId: input.external_id,
2240
+ ...input.address_line || input.city_name || input.state_name ? {
2241
+ location: {
2242
+ ...input.address_line ? { addressLine: input.address_line } : {},
2243
+ ...input.city_name ? { cityName: input.city_name } : {},
2244
+ ...input.state_name ? { stateName: input.state_name } : {},
2245
+ countryId: "AR"
2246
+ }
2247
+ } : {}
2248
+ });
2249
+ return {
2250
+ store_id: store.id,
2251
+ name: store.name,
2252
+ external_id: store.external_id,
2253
+ next_step: "Use create_pos with this store_id to add a Point of Sale where create_qr_payment can issue QRs."
2254
+ };
2255
+ }
2256
+ }),
2257
+ list_stores: ai.tool({
2258
+ description: desc("list_stores"),
2259
+ inputSchema: zod.z.object({
2260
+ limit: zod.z.number().int().min(1).max(100).optional()
2261
+ }),
2262
+ execute: async (input) => {
2263
+ const me = await client.getMe();
2264
+ const result = await client.listStores(String(me.id), {
2265
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
2266
+ });
2267
+ return {
2268
+ total: result.paging.total,
2269
+ stores: result.results.map((s) => ({
2270
+ store_id: s.id,
2271
+ name: s.name ?? null,
2272
+ external_id: s.external_id ?? null
2273
+ }))
2274
+ };
2275
+ }
2276
+ }),
2277
+ create_pos: ai.tool({
2278
+ description: desc("create_pos"),
2279
+ inputSchema: zod.z.object({
2280
+ name: zod.z.string().min(1).max(80),
2281
+ external_id: zod.z.string().min(1).max(64).describe("Unique within the store. This is what create_qr_payment uses."),
2282
+ store_id: zod.z.string().describe("From create_store / list_stores"),
2283
+ category: zod.z.number().int().optional().describe("MP category code, default 621102 (other food/beverage)"),
2284
+ fixed_amount: zod.z.boolean().optional().describe("True for static QR with fixed amount; false (default) for dynamic per-order QR")
2285
+ }),
2286
+ execute: async (input) => {
2287
+ const pos = await client.createPos({
2288
+ name: input.name,
2289
+ externalId: input.external_id,
2290
+ storeId: input.store_id,
2291
+ ...input.category !== void 0 ? { category: input.category } : {},
2292
+ ...input.fixed_amount !== void 0 ? { fixedAmount: input.fixed_amount } : {}
2293
+ });
2294
+ return {
2295
+ pos_id: pos.id,
2296
+ external_id: pos.external_id,
2297
+ store_id: pos.store_id,
2298
+ name: pos.name,
2299
+ next_step: "Use create_qr_payment with this external_id to start issuing dynamic QRs from this POS."
2300
+ };
2301
+ }
2302
+ }),
2303
+ list_pos: ai.tool({
2304
+ description: desc("list_pos"),
2305
+ inputSchema: zod.z.object({
2306
+ store_id: zod.z.string().optional(),
2307
+ limit: zod.z.number().int().min(1).max(100).optional()
2308
+ }),
2309
+ execute: async (input) => {
2310
+ const result = await client.listPos({
2311
+ ...input.store_id !== void 0 ? { storeId: input.store_id } : {},
2312
+ ...input.limit !== void 0 ? { limit: input.limit } : {}
2313
+ });
2314
+ return {
2315
+ total: result.paging.total,
2316
+ pos: result.results.map((p) => ({
2317
+ pos_id: p.id,
2318
+ external_id: p.external_id ?? null,
2319
+ store_id: p.store_id ?? null,
2320
+ name: p.name ?? null
2321
+ }))
2322
+ };
2323
+ }
2324
+ }),
2325
+ // ─────────────────────────────────────────────────────────────────────────
2326
+ // Disputes (v0.4 — read-only)
2327
+ // ─────────────────────────────────────────────────────────────────────────
2328
+ list_payment_disputes: ai.tool({
2329
+ description: desc("list_payment_disputes"),
2330
+ inputSchema: zod.z.object({ payment_id: zod.z.string() }),
2331
+ execute: async ({ payment_id }) => {
2332
+ const disputes = await client.listPaymentDisputes(payment_id);
2333
+ return {
2334
+ payment_id,
2335
+ count: disputes.length,
2336
+ disputes: disputes.map((d) => ({
2337
+ dispute_id: d.id,
2338
+ status: d.status,
2339
+ amount: d.amount ?? null,
2340
+ reason: d.reason ?? null,
2341
+ date_created: d.date_created ?? null,
2342
+ dashboard_url: `https://www.mercadopago.com.ar/disputes/${d.id}`
2343
+ }))
2344
+ };
2345
+ }
2346
+ }),
2347
+ get_dispute: ai.tool({
2348
+ description: desc("get_dispute"),
2349
+ inputSchema: zod.z.object({
2350
+ payment_id: zod.z.string(),
2351
+ dispute_id: zod.z.string()
2352
+ }),
2353
+ execute: async ({ payment_id, dispute_id }) => {
2354
+ const d = await client.getDispute(payment_id, dispute_id);
2355
+ return {
2356
+ dispute_id: d.id,
2357
+ status: d.status,
2358
+ amount: d.amount ?? null,
2359
+ reason: d.reason ?? null,
2360
+ reason_description: d.reason_description ?? null,
2361
+ resolution: d.resolution ?? null,
2362
+ date_created: d.date_created ?? null,
2363
+ dashboard_url: `https://www.mercadopago.com.ar/disputes/${d.id}`
2364
+ };
2365
+ }
2366
+ }),
2367
+ // ─────────────────────────────────────────────────────────────────────────
2368
+ // Lookup helpers (v0.4)
2369
+ // ─────────────────────────────────────────────────────────────────────────
2370
+ list_identification_types: ai.tool({
2371
+ description: desc("list_identification_types"),
2372
+ inputSchema: zod.z.object({}),
2373
+ execute: async () => {
2374
+ const types = await client.listIdentificationTypes();
2375
+ return {
2376
+ count: types.length,
2377
+ types: types.map((t) => ({
2378
+ id: t.id,
2379
+ name: t.name,
2380
+ type: t.type,
2381
+ min_length: t.min_length ?? null,
2382
+ max_length: t.max_length ?? null
2383
+ }))
2384
+ };
2385
+ }
2386
+ }),
2387
+ list_issuers: ai.tool({
2388
+ description: desc("list_issuers"),
2389
+ inputSchema: zod.z.object({
2390
+ payment_method_id: zod.z.string().describe("E.g. 'visa', 'master', 'naranja'"),
2391
+ bin: zod.z.string().min(6).max(8).optional().describe("First 6-8 digits of card for precise issuer detection")
2392
+ }),
2393
+ execute: async (input) => {
2394
+ const issuers = await client.listIssuers({
2395
+ paymentMethodId: input.payment_method_id,
2396
+ ...input.bin !== void 0 ? { bin: input.bin } : {}
2397
+ });
2398
+ return {
2399
+ payment_method_id: input.payment_method_id,
2400
+ count: issuers.length,
2401
+ issuers: issuers.map((i) => ({
2402
+ issuer_id: i.id,
2403
+ name: i.name,
2404
+ status: i.status ?? null
2405
+ }))
2406
+ };
2407
+ }
2408
+ }),
2409
+ // ─────────────────────────────────────────────────────────────────────────
2410
+ // Webhooks management (v0.4)
2411
+ // ─────────────────────────────────────────────────────────────────────────
2412
+ list_webhooks: ai.tool({
2413
+ description: desc("list_webhooks"),
2414
+ inputSchema: zod.z.object({}),
2415
+ execute: async () => {
2416
+ const hooks = await client.listWebhooks();
2417
+ return {
2418
+ count: hooks.length,
2419
+ webhooks: hooks.map((h) => ({
2420
+ webhook_id: h.id,
2421
+ url: h.url ?? null,
2422
+ topic: h.topic ?? null,
2423
+ status: h.status ?? null,
2424
+ date_created: h.date_created ?? null
2425
+ }))
2426
+ };
2427
+ }
2428
+ }),
2429
+ create_webhook: ai.tool({
2430
+ description: desc("create_webhook"),
2431
+ inputSchema: zod.z.object({
2432
+ url: zod.z.string().url(),
2433
+ topic: zod.z.string().describe("E.g. 'payment', 'subscription_authorized_payment', 'subscription_preapproval', 'merchant_order', 'point_integration_wh'")
2434
+ }),
2435
+ execute: async ({ url, topic }) => {
2436
+ const hook = await client.createWebhook({ url, topic });
2437
+ return {
2438
+ webhook_id: hook.id,
2439
+ url: hook.url ?? url,
2440
+ topic: hook.topic ?? topic,
2441
+ status: hook.status ?? null
2442
+ };
2443
+ }
2444
+ }),
2445
+ update_webhook: ai.tool({
2446
+ description: desc("update_webhook"),
2447
+ inputSchema: zod.z.object({
2448
+ webhook_id: zod.z.string(),
2449
+ url: zod.z.string().url().optional(),
2450
+ topic: zod.z.string().optional()
2451
+ }),
2452
+ execute: async (input) => {
2453
+ const hook = await client.updateWebhook(input.webhook_id, {
2454
+ ...input.url !== void 0 ? { url: input.url } : {},
2455
+ ...input.topic !== void 0 ? { topic: input.topic } : {}
2456
+ });
2457
+ return {
2458
+ webhook_id: hook.id,
2459
+ url: hook.url ?? null,
2460
+ topic: hook.topic ?? null,
2461
+ status: hook.status ?? null
2462
+ };
2463
+ }
2464
+ }),
2465
+ delete_webhook: ai.tool({
2466
+ description: desc("delete_webhook"),
2467
+ inputSchema: zod.z.object({ webhook_id: zod.z.string() }),
2468
+ execute: async ({ webhook_id }) => {
2469
+ await client.deleteWebhook(webhook_id);
2470
+ return { webhook_id, deleted: true };
2471
+ }
2472
+ }),
2473
+ // ─────────────────────────────────────────────────────────────────────────
2474
+ // v0.5 — Webhook handler combo
2475
+ // ─────────────────────────────────────────────────────────────────────────
2476
+ handle_webhook: ai.tool({
2477
+ description: desc("handle_webhook"),
2478
+ inputSchema: zod.z.object({
2479
+ raw_body: zod.z.string().describe(
2480
+ "The raw JSON body of the webhook request, exactly as received (do NOT re-stringify). Pass `await req.text()` from your handler."
2481
+ ),
2482
+ signature_header: zod.z.string().nullable().describe("Value of the `x-signature` request header."),
2483
+ request_id_header: zod.z.string().nullable().describe("Value of the `x-request-id` request header."),
2484
+ auto_fetch: zod.z.boolean().optional().default(true).describe(
2485
+ "If true (default), fetch the underlying resource (Payment, Subscription, etc.) AS the MP user the client is configured for. Set to false to skip the fetch (faster, useful when you only need the topic+id)."
2486
+ )
2487
+ }),
2488
+ execute: async ({
2489
+ raw_body,
2490
+ signature_header,
2491
+ request_id_header,
2492
+ auto_fetch
2493
+ }) => {
2494
+ if (!options.webhookSecret) {
2495
+ return {
2496
+ verified: false,
2497
+ error: "webhookSecret not configured in mercadoPagoTools options. Pass it from MP dev panel \u2192 Notificaciones \u2192 Webhooks.",
2498
+ event: null,
2499
+ resource: null
2500
+ };
2501
+ }
2502
+ let parsedBody;
2503
+ try {
2504
+ parsedBody = JSON.parse(raw_body);
2505
+ } catch {
2506
+ return {
2507
+ verified: false,
2508
+ error: "raw_body is not valid JSON.",
2509
+ event: null,
2510
+ resource: null
2511
+ };
2512
+ }
2513
+ const event = parseWebhookEvent(parsedBody);
2514
+ if (!event) {
2515
+ return {
2516
+ verified: false,
2517
+ error: "Could not extract topic + dataId from webhook body.",
2518
+ event: null,
2519
+ resource: null
2520
+ };
2521
+ }
2522
+ const verified = verifyWebhookSignature({
2523
+ requestId: request_id_header,
2524
+ dataId: event.dataId,
2525
+ signatureHeader: signature_header,
2526
+ secret: options.webhookSecret
2527
+ });
2528
+ if (!verified) {
2529
+ return {
2530
+ verified: false,
2531
+ error: "HMAC-SHA256 signature mismatch. Reject the webhook (HTTP 401).",
2532
+ event,
2533
+ resource: null
2534
+ };
2535
+ }
2536
+ let resource = null;
2537
+ let resourceError = null;
2538
+ if (auto_fetch) {
2539
+ try {
2540
+ switch (event.topic) {
2541
+ case "payment":
2542
+ case "payment.created":
2543
+ case "payment.updated":
2544
+ resource = await client.getPayment(event.dataId);
2545
+ break;
2546
+ case "preapproval":
2547
+ case "subscription_preapproval":
2548
+ resource = await client.getPreapproval(event.dataId);
2549
+ break;
2550
+ case "subscription_authorized_payment":
2551
+ resource = { id: event.dataId, hint: "Use list_subscription_payments to enumerate parent." };
2552
+ break;
2553
+ default:
2554
+ resource = null;
2555
+ resourceError = `No auto-fetch handler for topic '${event.topic}' yet.`;
2556
+ }
2557
+ } catch (err) {
2558
+ resourceError = err instanceof Error ? err.message : String(err);
2559
+ }
2560
+ }
2561
+ return {
2562
+ verified: true,
2563
+ event,
2564
+ resource,
2565
+ resource_error: resourceError
2566
+ };
2567
+ }
2568
+ }),
2569
+ // ─────────────────────────────────────────────────────────────────────────
2570
+ // v0.5 — OAuth Marketplace flow
2571
+ // ─────────────────────────────────────────────────────────────────────────
2572
+ oauth_authorize_url: ai.tool({
2573
+ description: desc("oauth_authorize_url"),
2574
+ inputSchema: zod.z.object({
2575
+ redirect_uri: zod.z.string().url().describe(
2576
+ "Where MP redirects the seller after approval. MUST be whitelisted in MP dev panel \u2192 Aplicaciones \u2192 tu app \u2192 Redirect URIs."
2577
+ ),
2578
+ state: zod.z.string().min(8).describe(
2579
+ "Opaque CSRF/session token echoed back. Bind to the user's session and verify on redirect."
2580
+ )
2581
+ }),
2582
+ execute: async ({ redirect_uri, state }) => {
2583
+ if (!options.oauth?.clientId) {
2584
+ return {
2585
+ available: false,
2586
+ error: "OAuth not configured. Pass `oauth: { clientId, clientSecret }` to mercadoPagoTools options.",
2587
+ url: null
2588
+ };
2589
+ }
2590
+ const url = buildAuthorizeUrl({
2591
+ clientId: options.oauth.clientId,
2592
+ redirectUri: redirect_uri,
2593
+ state
2594
+ });
2595
+ return {
2596
+ available: true,
2597
+ url,
2598
+ next_step: "Redirect the seller to `url`. After approval MP sends them to redirect_uri?code=...&state=... \u2014 verify state matches, then call oauth_exchange_code with the code."
2599
+ };
2600
+ }
2601
+ }),
2602
+ oauth_exchange_code: ai.tool({
2603
+ description: desc("oauth_exchange_code"),
2604
+ inputSchema: zod.z.object({
2605
+ code: zod.z.string().describe("The `code` query param from the OAuth redirect URL."),
2606
+ redirect_uri: zod.z.string().url().describe(
2607
+ "Must EXACTLY match the redirect_uri used in oauth_authorize_url."
2608
+ )
2609
+ }),
2610
+ execute: async ({ code, redirect_uri }) => {
2611
+ if (!options.oauth?.clientId || !options.oauth?.clientSecret) {
2612
+ return {
2613
+ available: false,
2614
+ error: "OAuth not configured. Pass `oauth: { clientId, clientSecret }` to mercadoPagoTools options.",
2615
+ token: null
2616
+ };
2617
+ }
2618
+ try {
2619
+ const token = await exchangeCodeForToken({
2620
+ clientId: options.oauth.clientId,
2621
+ clientSecret: options.oauth.clientSecret,
2622
+ code,
2623
+ redirectUri: redirect_uri
2624
+ });
2625
+ return {
2626
+ available: true,
2627
+ token,
2628
+ next_step: "PERSIST { user_id, access_token, refresh_token, expires_in } against this seller. Use access_token to instantiate `new MercadoPagoClient({ accessToken })` AS the seller for marketplace API calls."
2629
+ };
2630
+ } catch (err) {
2631
+ return {
2632
+ available: true,
2633
+ error: err instanceof Error ? err.message : String(err),
2634
+ token: null
2635
+ };
2636
+ }
2637
+ }
2638
+ }),
2639
+ oauth_refresh_token: ai.tool({
2640
+ description: desc("oauth_refresh_token"),
2641
+ inputSchema: zod.z.object({
2642
+ refresh_token: zod.z.string().describe("The saved refresh_token for this seller.")
2643
+ }),
2644
+ execute: async ({ refresh_token }) => {
2645
+ if (!options.oauth?.clientId || !options.oauth?.clientSecret) {
2646
+ return {
2647
+ available: false,
2648
+ error: "OAuth not configured. Pass `oauth: { clientId, clientSecret }` to mercadoPagoTools options.",
2649
+ token: null
2650
+ };
2651
+ }
2652
+ try {
2653
+ const token = await refreshAccessToken({
2654
+ clientId: options.oauth.clientId,
2655
+ clientSecret: options.oauth.clientSecret,
2656
+ refreshToken: refresh_token
2657
+ });
2658
+ return {
2659
+ available: true,
2660
+ token,
2661
+ next_step: "Replace the persisted access_token + refresh_token with these new values (refresh_token may have rotated)."
2662
+ };
2663
+ } catch (err) {
2664
+ return {
2665
+ available: true,
2666
+ error: err instanceof Error ? err.message : String(err),
2667
+ token: null
2668
+ };
2669
+ }
2670
+ }
2671
+ }),
2672
+ // ─────────────────────────────────────────────────────────────────────────
2673
+ // v0.5 — Order Management API
2674
+ // ─────────────────────────────────────────────────────────────────────────
2675
+ create_order: ai.tool({
2676
+ description: desc("create_order"),
2677
+ inputSchema: zod.z.object({
2678
+ type: zod.z.enum(["online", "in_store"]).describe("'online' for hosted/checkout flow, 'in_store' for QR/POS"),
2679
+ currency_id: zod.z.string().optional().default("ARS"),
2680
+ external_reference: zod.z.string().optional(),
2681
+ total_amount: zod.z.number().positive().optional(),
2682
+ items: zod.z.array(
2683
+ zod.z.object({
2684
+ title: zod.z.string(),
2685
+ unit_price: zod.z.number(),
2686
+ quantity: zod.z.number(),
2687
+ description: zod.z.string().optional()
2688
+ })
2689
+ ).optional(),
2690
+ payer_email: zod.z.string().email().optional(),
2691
+ capture_mode: zod.z.enum(["automatic", "manual"]).optional().describe(
2692
+ "'automatic' charges immediately; 'manual' authorizes only \u2014 capture later via capture_order."
2693
+ ),
2694
+ notification_url: zod.z.string().url().optional(),
2695
+ marketplace: zod.z.string().optional().describe(
2696
+ "Marketplace identifier (your app's name). Required for split payments."
2697
+ ),
2698
+ marketplace_fee: zod.z.number().optional().describe(
2699
+ "Fee in ARS (NOT %) credited to the marketplace's MP account."
2700
+ ),
2701
+ collector_id: zod.z.union([zod.z.string(), zod.z.number()]).optional().describe(
2702
+ "Seller's MP user_id (from oauth_exchange_code.user_id). Funds route here; marketplace_fee is split off to your account."
2703
+ )
2704
+ }),
2705
+ execute: async (input) => {
2706
+ const params = {
2707
+ type: input.type
2708
+ };
2709
+ if (input.currency_id) params.currency_id = input.currency_id;
2710
+ if (input.external_reference) params.external_reference = input.external_reference;
2711
+ if (input.total_amount !== void 0) params.total_amount = input.total_amount;
2712
+ if (input.items) params.items = input.items;
2713
+ if (input.payer_email) params.payer = { email: input.payer_email };
2714
+ if (input.capture_mode) params.capture_mode = input.capture_mode;
2715
+ if (input.notification_url) params.notification_url = input.notification_url;
2716
+ if (input.marketplace) params.marketplace = input.marketplace;
2717
+ if (input.marketplace_fee !== void 0) params.marketplace_fee = input.marketplace_fee;
2718
+ if (input.collector_id !== void 0) params.collector_id = input.collector_id;
2719
+ const order = await client.createOrder(params, {
2720
+ idempotencyKey: deterministicIdempotencyKey(
2721
+ "create_order",
2722
+ input.external_reference,
2723
+ input.total_amount,
2724
+ input.collector_id
2725
+ )
2726
+ });
2727
+ return {
2728
+ order_id: order.id,
2729
+ status: order.status ?? null,
2730
+ capture_mode: order.capture_mode ?? params.capture_mode ?? "automatic",
2731
+ total_amount: order.total_amount ?? null
2732
+ };
2733
+ }
2734
+ }),
2735
+ get_order: ai.tool({
2736
+ description: desc("get_order"),
2737
+ inputSchema: zod.z.object({ order_id: zod.z.string() }),
2738
+ execute: async ({ order_id }) => {
2739
+ const order = await client.getOrder(order_id);
2740
+ return order;
2741
+ }
2742
+ }),
2743
+ update_order: ai.tool({
2744
+ description: desc("update_order"),
2745
+ inputSchema: zod.z.object({
2746
+ order_id: zod.z.string(),
2747
+ external_reference: zod.z.string().optional(),
2748
+ total_amount: zod.z.number().optional()
2749
+ }),
2750
+ execute: async ({ order_id, external_reference, total_amount }) => {
2751
+ const patch = {};
2752
+ if (external_reference !== void 0) patch.external_reference = external_reference;
2753
+ if (total_amount !== void 0) patch.total_amount = total_amount;
2754
+ const order = await client.updateOrder(order_id, patch);
2755
+ return order;
2756
+ }
2757
+ }),
2758
+ capture_order: ai.tool({
2759
+ description: desc("capture_order"),
2760
+ inputSchema: zod.z.object({
2761
+ order_id: zod.z.string(),
2762
+ amount: zod.z.number().positive().optional().describe(
2763
+ "Optional partial-capture amount. Omit to capture the full authorized amount."
2764
+ )
2765
+ }),
2766
+ execute: async ({ order_id, amount }) => {
2767
+ const order = await client.captureOrder(order_id, amount);
2768
+ return {
2769
+ order_id: order.id,
2770
+ status: order.status ?? null,
2771
+ captured_amount: amount ?? order.total_amount ?? null
2772
+ };
2773
+ }
2774
+ }),
2775
+ cancel_order: ai.tool({
2776
+ description: desc("cancel_order"),
2777
+ inputSchema: zod.z.object({ order_id: zod.z.string() }),
2778
+ execute: async ({ order_id }) => {
2779
+ const order = await client.cancelOrder(order_id);
2780
+ return {
2781
+ order_id: order.id,
2782
+ status: order.status ?? "canceled"
2783
+ };
2784
+ }
2785
+ })
2786
+ };
2787
+ }
2788
+
2789
+ // src/state.ts
2790
+ var InMemoryStateAdapter = class {
2791
+ store = /* @__PURE__ */ new Map();
2792
+ async set(id, state) {
2793
+ const existing = this.store.get(id) ?? {};
2794
+ this.store.set(id, { ...existing, ...state });
2795
+ }
2796
+ async get(id) {
2797
+ return this.store.get(id) ?? null;
2798
+ }
2799
+ async list() {
2800
+ return Array.from(this.store.keys());
2801
+ }
2802
+ /** Test helper: drop everything. Not part of the adapter interface. */
2803
+ reset() {
2804
+ this.store.clear();
2805
+ }
2806
+ };
2302
2807
 
2303
2808
  exports.InMemoryStateAdapter = InMemoryStateAdapter;
2304
2809
  exports.MercadoPagoAccountTypeMismatchError = MercadoPagoAccountTypeMismatchError;
@@ -2312,9 +2817,14 @@ exports.MercadoPagoPaymentRejectedError = MercadoPagoPaymentRejectedError;
2312
2817
  exports.MercadoPagoRateLimitError = MercadoPagoRateLimitError;
2313
2818
  exports.MercadoPagoSelfPaymentError = MercadoPagoSelfPaymentError;
2314
2819
  exports.MercadoPagoTimeoutError = MercadoPagoTimeoutError;
2820
+ exports.buildAuthorizeUrl = buildAuthorizeUrl;
2315
2821
  exports.classifyError = classifyError;
2822
+ exports.exchangeCodeForToken = exchangeCodeForToken;
2823
+ exports.expirationTimeMs = expirationTimeMs;
2824
+ exports.isExpiringSoon = isExpiringSoon;
2316
2825
  exports.mercadoPagoTools = mercadoPagoTools;
2317
2826
  exports.parseWebhookEvent = parseWebhookEvent;
2827
+ exports.refreshAccessToken = refreshAccessToken;
2318
2828
  exports.verifyWebhookSignature = verifyWebhookSignature;
2319
2829
  //# sourceMappingURL=index.cjs.map
2320
2830
  //# sourceMappingURL=index.cjs.map