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