@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.d.ts CHANGED
@@ -487,6 +487,15 @@ interface CreatePreferenceParams {
487
487
  expires?: boolean;
488
488
  expirationDateFrom?: string;
489
489
  expirationDateTo?: string;
490
+ /**
491
+ * Marketplace split — if set, funds route to `collector_id` (the seller)
492
+ * and `marketplaceFee` (in ARS) is credited to the marketplace's MP
493
+ * account. v0.5+. See `MarketplaceParams` for details.
494
+ */
495
+ marketplace?: string;
496
+ marketplaceFee?: number;
497
+ /** Seller's MP user_id. Funds route here when set. */
498
+ collectorId?: string | number;
490
499
  }
491
500
  declare const CustomerSchema: z.ZodObject<{
492
501
  id: z.ZodString;
@@ -799,6 +808,149 @@ interface CreateWebhookParams {
799
808
  /** Topic to subscribe to. */
800
809
  topic: WebhookTopic | string;
801
810
  }
811
+ /**
812
+ * Token response from MP's OAuth `/oauth/token` endpoint. The `access_token`
813
+ * is what you use to make API calls AS the linked seller; the `refresh_token`
814
+ * is what you use to refresh the access_token before expiration (~6 hours).
815
+ *
816
+ * **Persist the refresh_token**: it does NOT expire and is the only way to
817
+ * keep the integration alive long-term.
818
+ *
819
+ * **Always store `user_id`** alongside the tokens — it identifies WHICH
820
+ * seller these tokens belong to (you'll have many in a marketplace).
821
+ */
822
+ declare const OAuthTokenSchema: z.ZodObject<{
823
+ access_token: z.ZodString;
824
+ token_type: z.ZodOptional<z.ZodString>;
825
+ expires_in: z.ZodOptional<z.ZodNumber>;
826
+ scope: z.ZodOptional<z.ZodString>;
827
+ user_id: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>, z.ZodTransform<string, string | number>>;
828
+ refresh_token: z.ZodOptional<z.ZodString>;
829
+ public_key: z.ZodOptional<z.ZodString>;
830
+ live_mode: z.ZodOptional<z.ZodBoolean>;
831
+ }, z.core.$loose>;
832
+ type OAuthToken = z.infer<typeof OAuthTokenSchema>;
833
+ /**
834
+ * Status of an Order. Distinct from Payment status — an Order can have
835
+ * multiple payments and the Order status reflects the aggregate state.
836
+ */
837
+ declare const OrderStatusSchema: z.ZodUnion<readonly [z.ZodLiteral<"created">, z.ZodLiteral<"processed">, z.ZodLiteral<"action_required">, z.ZodLiteral<"canceled">, z.ZodLiteral<"expired">, z.ZodLiteral<"refunded">, z.ZodString]>;
838
+ type OrderStatus = z.infer<typeof OrderStatusSchema>;
839
+ declare const OrderItemSchema: z.ZodObject<{
840
+ title: z.ZodString;
841
+ unit_price: z.ZodNumber;
842
+ quantity: z.ZodNumber;
843
+ description: z.ZodOptional<z.ZodString>;
844
+ id: z.ZodOptional<z.ZodString>;
845
+ category_id: z.ZodOptional<z.ZodString>;
846
+ picture_url: z.ZodOptional<z.ZodString>;
847
+ }, z.core.$loose>;
848
+ type OrderItem = z.infer<typeof OrderItemSchema>;
849
+ declare const OrderSchema: z.ZodObject<{
850
+ id: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>, z.ZodTransform<string, string | number>>;
851
+ type: z.ZodOptional<z.ZodString>;
852
+ status: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"created">, z.ZodLiteral<"processed">, z.ZodLiteral<"action_required">, z.ZodLiteral<"canceled">, z.ZodLiteral<"expired">, z.ZodLiteral<"refunded">, z.ZodString]>>;
853
+ status_detail: z.ZodOptional<z.ZodString>;
854
+ external_reference: z.ZodOptional<z.ZodString>;
855
+ total_amount: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
856
+ currency_id: z.ZodOptional<z.ZodString>;
857
+ date_created: z.ZodOptional<z.ZodString>;
858
+ date_last_updated: z.ZodOptional<z.ZodString>;
859
+ items: z.ZodOptional<z.ZodArray<z.ZodObject<{
860
+ title: z.ZodString;
861
+ unit_price: z.ZodNumber;
862
+ quantity: z.ZodNumber;
863
+ description: z.ZodOptional<z.ZodString>;
864
+ id: z.ZodOptional<z.ZodString>;
865
+ category_id: z.ZodOptional<z.ZodString>;
866
+ picture_url: z.ZodOptional<z.ZodString>;
867
+ }, z.core.$loose>>>;
868
+ transactions: z.ZodOptional<z.ZodObject<{
869
+ payments: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
870
+ refunds: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
871
+ }, z.core.$loose>>;
872
+ capture_mode: z.ZodOptional<z.ZodString>;
873
+ }, z.core.$loose>;
874
+ type Order = z.infer<typeof OrderSchema>;
875
+ interface CreateOrderParams {
876
+ /**
877
+ * Order type. Common values:
878
+ * - "online" — checkout-style (the most common)
879
+ * - "in_store" — POS QR / in-person
880
+ */
881
+ type: "online" | "in_store" | string;
882
+ /** Currency (e.g. "ARS"). */
883
+ currency_id?: string;
884
+ /** External reference for reconciliation (your internal id). */
885
+ external_reference?: string;
886
+ /** Items being ordered. */
887
+ items?: OrderItem[];
888
+ /** Total amount if you'd rather not itemize. */
889
+ total_amount?: number;
890
+ /** Customer info (payer). */
891
+ payer?: {
892
+ email?: string;
893
+ first_name?: string;
894
+ last_name?: string;
895
+ identification?: {
896
+ type?: string;
897
+ number?: string;
898
+ };
899
+ };
900
+ /**
901
+ * Capture mode:
902
+ * - "automatic" (default) — charge immediately when paid.
903
+ * - "manual" — authorize only, capture later via captureOrder().
904
+ */
905
+ capture_mode?: "automatic" | "manual";
906
+ /**
907
+ * Notification URL — MP fires webhooks for order lifecycle events here.
908
+ */
909
+ notification_url?: string;
910
+ /**
911
+ * Marketplace fee + collector — required for marketplace integrations
912
+ * where YOU collect on behalf of a third-party seller (you take a fee,
913
+ * the rest goes to the seller).
914
+ */
915
+ marketplace?: string;
916
+ marketplace_fee?: number;
917
+ collector_id?: string | number;
918
+ }
919
+ /**
920
+ * Marketplace fee + collector params, applied to a Preference or Order.
921
+ *
922
+ * **How it works**: when you create a Preference or Order with
923
+ * `collector_id` set to a SELLER's MP user_id (not yours), and you have a
924
+ * valid OAuth access_token for that seller, MP routes the funds to the
925
+ * seller's MP account, and credits `marketplace_fee` (in ARS, not %) to
926
+ * YOUR marketplace account.
927
+ *
928
+ * Used for two-sided platforms (Rappi, MercadoLibre, Tienda Nube, etc.)
929
+ * where your platform takes a fee and the seller keeps the rest.
930
+ */
931
+ interface MarketplaceParams {
932
+ /**
933
+ * Marketplace identifier — your application's marketplace name (you set
934
+ * this when registering your app in MP's dev panel).
935
+ */
936
+ marketplace?: string;
937
+ /**
938
+ * Fee in ARS (NOT a percentage) that goes to your marketplace account.
939
+ * Compute it from your own commission rate before passing.
940
+ */
941
+ marketplace_fee?: number;
942
+ /**
943
+ * The SELLER's MP user_id. The funds go to this account; the
944
+ * `marketplace_fee` is split off and goes to YOUR account.
945
+ * Get this from `OAuthToken.user_id` after the seller authorizes your app.
946
+ */
947
+ collector_id?: string | number;
948
+ /**
949
+ * Optional: split among multiple sellers. If set, `collector_id` /
950
+ * `marketplace_fee` are ignored.
951
+ */
952
+ application_fee?: number;
953
+ }
802
954
 
803
955
  interface MercadoPagoClientOptions {
804
956
  /** Access token. TEST- prefix for sandbox, APP_USR- for production. */
@@ -837,6 +989,20 @@ interface MercadoPagoClientOptions {
837
989
  success: boolean;
838
990
  }) => void;
839
991
  }
992
+ interface RequestOptions {
993
+ /** Idempotency key. Required for POST/PUT to dedupe retries safely. */
994
+ idempotencyKey?: string;
995
+ /** Query string params. Object → URLSearchParams. */
996
+ query?: Record<string, string | number | undefined>;
997
+ /** Context for error classification. */
998
+ classifyContext?: {
999
+ preapprovalId?: string;
1000
+ paymentId?: string;
1001
+ customerId?: string;
1002
+ payerEmail?: string;
1003
+ sellerEmail?: string;
1004
+ };
1005
+ }
840
1006
  /**
841
1007
  * Thin, typed wrapper around Mercado Pago's REST API. Exposes the surface
842
1008
  * the agent layer needs: Subscriptions (Preapprovals), Payments, Checkout Pro
@@ -1097,6 +1263,27 @@ declare class MercadoPagoClient {
1097
1263
  topic?: string;
1098
1264
  }): Promise<WebhookConfig>;
1099
1265
  deleteWebhook(id: string): Promise<void>;
1266
+ /**
1267
+ * Create a new Order. Use `capture_mode: "manual"` for auth-only flows
1268
+ * where you want to capture funds later (ride-share, hotels, marketplaces).
1269
+ *
1270
+ * For marketplace splits, set `marketplace`, `marketplace_fee`,
1271
+ * `collector_id` — see `MarketplaceParams`.
1272
+ */
1273
+ createOrder(params: CreateOrderParams, options?: RequestOptions): Promise<Order>;
1274
+ getOrder(id: string): Promise<Order>;
1275
+ updateOrder(id: string, patch: Partial<CreateOrderParams>): Promise<Order>;
1276
+ /**
1277
+ * Capture a previously-authorized Order (only for orders created with
1278
+ * `capture_mode: "manual"`). Captures up to the originally-authorized
1279
+ * amount; pass `amount` for partial capture.
1280
+ */
1281
+ captureOrder(id: string, amount?: number): Promise<Order>;
1282
+ /**
1283
+ * Cancel an Order. Releases any auth-holds; marks the Order as canceled.
1284
+ * For orders that have already been captured, use `createRefund` instead.
1285
+ */
1286
+ cancelOrder(id: string): Promise<Order>;
1100
1287
  }
1101
1288
 
1102
1289
  /**
@@ -1164,8 +1351,26 @@ interface MercadoPagoToolsOptions {
1164
1351
  * Optional — MP falls back to dashboard config if not set.
1165
1352
  */
1166
1353
  notificationUrl?: string;
1354
+ /**
1355
+ * Webhook secret for the `handle_webhook` tool. Required to verify
1356
+ * incoming webhook HMAC-SHA256 signatures. Get it from MP dev panel →
1357
+ * "Notificaciones" → "Webhooks" → "Configurar notificaciones".
1358
+ * If omitted, `handle_webhook` returns `{ verified: false, error: ... }`
1359
+ * and the agent should reject the webhook.
1360
+ */
1361
+ webhookSecret?: string;
1362
+ /**
1363
+ * OAuth credentials for the marketplace flow. Required for
1364
+ * `oauth_exchange_code` and `oauth_refresh_token` (the secret cannot be
1365
+ * passed by the agent — it's a server-side secret). If omitted, those
1366
+ * tools return `{ available: false }` with setup instructions.
1367
+ */
1368
+ oauth?: {
1369
+ clientId: string;
1370
+ clientSecret: string;
1371
+ };
1167
1372
  }
1168
- type ToolName = "create_subscription" | "get_subscription_status" | "cancel_subscription" | "pause_subscription" | "resume_subscription" | "create_payment" | "get_payment" | "search_payments" | "cancel_payment" | "capture_payment" | "refund_payment" | "list_refunds" | "create_payment_preference" | "get_payment_preference" | "create_customer" | "find_customer_by_email" | "list_customer_cards" | "delete_customer_card" | "list_payment_methods" | "calculate_installments" | "get_account_info" | "charge_saved_card" | "create_qr_payment" | "cancel_qr_payment" | "create_subscription_plan" | "list_subscription_plans" | "update_subscription_plan" | "subscribe_to_plan" | "list_subscription_payments" | "create_store" | "list_stores" | "create_pos" | "list_pos" | "list_payment_disputes" | "get_dispute" | "list_identification_types" | "list_issuers" | "list_webhooks" | "create_webhook" | "update_webhook" | "delete_webhook";
1373
+ type ToolName = "create_subscription" | "get_subscription_status" | "cancel_subscription" | "pause_subscription" | "resume_subscription" | "create_payment" | "get_payment" | "search_payments" | "cancel_payment" | "capture_payment" | "refund_payment" | "list_refunds" | "create_payment_preference" | "get_payment_preference" | "create_customer" | "find_customer_by_email" | "list_customer_cards" | "delete_customer_card" | "list_payment_methods" | "calculate_installments" | "get_account_info" | "charge_saved_card" | "create_qr_payment" | "cancel_qr_payment" | "create_subscription_plan" | "list_subscription_plans" | "update_subscription_plan" | "subscribe_to_plan" | "list_subscription_payments" | "create_store" | "list_stores" | "create_pos" | "list_pos" | "list_payment_disputes" | "get_dispute" | "list_identification_types" | "list_issuers" | "list_webhooks" | "create_webhook" | "update_webhook" | "delete_webhook" | "handle_webhook" | "oauth_authorize_url" | "oauth_exchange_code" | "oauth_refresh_token" | "create_order" | "get_order" | "update_order" | "capture_order" | "cancel_order";
1169
1374
  /**
1170
1375
  * Build a tool set for the Vercel AI SDK that exposes Mercado Pago to an
1171
1376
  * agent. Pass directly to `Experimental_Agent`'s `tools` option, or merge with
@@ -1231,4 +1436,116 @@ declare function verifyWebhookSignature(params: {
1231
1436
  secret: string;
1232
1437
  }): boolean;
1233
1438
 
1234
- export { type AccountInfo, type AutoRecurring, type CardToken, type CreateCardTokenParams, type CreateCustomerParams, type CreatePaymentParams, type CreatePosParams, type CreatePreapprovalParams, type CreatePreferenceParams, type CreateQrPaymentParams, type CreateRefundParams, type CreateStoreParams, type CreateSubscriptionPlanParams, type CreateWebhookParams, type CurrencyId, type Customer, type CustomerCard, type Dispute, type FrequencyType, type IdentificationType, InMemoryStateAdapter, type InstallmentOffer, type Issuer, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, type MercadoPagoClientOptions, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, type MercadoPagoToolsOptions, type ParsedWebhookEvent, type Payment, type PaymentMethod, type PaymentStatus, type PaymentsSearchResult, type Pos, type Preapproval, type PreapprovalStatus, type Preference, type PreferenceItem, type QrOrder, type Refund, type SearchPaymentsParams, type SiteId, type Store, type SubscriptionPayment, type SubscriptionPlan, type SubscriptionStateAdapter, type SubscriptionStateRecord, type WebhookBody, type WebhookConfig, type WebhookTopic, classifyError, mercadoPagoTools, parseWebhookEvent, verifyWebhookSignature };
1439
+ /**
1440
+ * Mercado Pago OAuth flow — for marketplace integrations where YOUR app
1441
+ * cobra a través de cuentas MP de terceros (sellers in your platform).
1442
+ *
1443
+ * # The flow (3 legs)
1444
+ *
1445
+ * 1. **Authorize URL** — Redirect the seller to `buildAuthorizeUrl()`. They
1446
+ * log in to MP and approve your app. MP redirects them back to your
1447
+ * `redirect_uri` with `?code=AUTH_CODE&state=YOUR_STATE`.
1448
+ * 2. **Code exchange** — Your server POSTs to `/oauth/token` via
1449
+ * `exchangeCodeForToken()` with the code. Returns `{ access_token,
1450
+ * refresh_token, user_id, expires_in (~6h), ... }`. **Persist all of it.**
1451
+ * 3. **Token refresh** — Before `expires_in` runs out (or on 401), call
1452
+ * `refreshAccessToken()` with the saved `refresh_token` to get a fresh
1453
+ * access_token. The refresh_token does NOT expire and is the only way
1454
+ * to keep the integration alive long-term.
1455
+ *
1456
+ * # Per-seller MercadoPagoClient
1457
+ *
1458
+ * Once you have an OAuth `access_token` for a seller, instantiate a
1459
+ * `MercadoPagoClient({ accessToken })` AS THAT SELLER. All API calls then
1460
+ * happen on the seller's behalf — payments, refunds, subscriptions,
1461
+ * everything.
1462
+ *
1463
+ * # Marketplace fee
1464
+ *
1465
+ * To take a fee while collecting on the seller's behalf, pass
1466
+ * `marketplace`, `marketplaceFee`, `collectorId` to `createPreference()`
1467
+ * or `createOrder()`. See `MarketplaceParams` for details.
1468
+ *
1469
+ * # Setup
1470
+ *
1471
+ * 1. Register your application in MP's dev panel
1472
+ * (https://www.mercadopago.com.ar/developers/panel/applications) to get
1473
+ * `clientId` (= application id) and `clientSecret`.
1474
+ * 2. Configure the `redirect_uri` whitelist in the same panel — MP rejects
1475
+ * redirects to URIs not whitelisted.
1476
+ * 3. Pick a `marketplace` identifier (used in fee routing).
1477
+ */
1478
+
1479
+ /**
1480
+ * Build the URL the seller visits to authorize your app. Redirect them here.
1481
+ * On approval, MP redirects them to `redirect_uri?code=...&state=...`.
1482
+ *
1483
+ * @param state Optional opaque value echoed back in the redirect — use this
1484
+ * to bind the OAuth round-trip to a specific user/session and
1485
+ * prevent CSRF. Always set it in production.
1486
+ */
1487
+ declare function buildAuthorizeUrl(params: {
1488
+ /** Your app's client ID (= application id from MP dev panel). */
1489
+ clientId: string;
1490
+ /** Where MP redirects after approval. Must be whitelisted in MP panel. */
1491
+ redirectUri: string;
1492
+ /** CSRF / session-binding token, echoed back. Strongly recommended. */
1493
+ state?: string;
1494
+ /**
1495
+ * Override the authorize endpoint base. Default points to AR; for other
1496
+ * sites use `https://auth.mercadopago.com.{br,mx,co,cl,uy}/authorization`.
1497
+ */
1498
+ authorizeUrl?: string;
1499
+ }): string;
1500
+ /**
1501
+ * Exchange the authorization code (from the OAuth redirect) for an
1502
+ * `OAuthToken`. POSTs to `/oauth/token` with `grant_type=authorization_code`.
1503
+ *
1504
+ * **Persist the entire response** — the `refresh_token` is the only way to
1505
+ * keep the integration alive long-term, and `user_id` identifies the seller.
1506
+ */
1507
+ declare function exchangeCodeForToken(params: {
1508
+ clientId: string;
1509
+ clientSecret: string;
1510
+ /** The `code` query param from the OAuth redirect. */
1511
+ code: string;
1512
+ /** Must match the `redirect_uri` used in `buildAuthorizeUrl`. */
1513
+ redirectUri: string;
1514
+ /** Override the token endpoint (testing). */
1515
+ tokenUrl?: string;
1516
+ /** Custom fetch (testing). */
1517
+ fetchImpl?: typeof fetch;
1518
+ }): Promise<OAuthToken>;
1519
+ /**
1520
+ * Refresh an access_token using the saved refresh_token. Call this
1521
+ * proactively before `expires_in` runs out, or reactively on a 401 from a
1522
+ * per-seller MercadoPagoClient.
1523
+ *
1524
+ * The new response includes a fresh `refresh_token` — **always persist it,
1525
+ * replacing the old one**, even though MP often returns the same value.
1526
+ */
1527
+ declare function refreshAccessToken(params: {
1528
+ clientId: string;
1529
+ clientSecret: string;
1530
+ refreshToken: string;
1531
+ tokenUrl?: string;
1532
+ fetchImpl?: typeof fetch;
1533
+ }): Promise<OAuthToken>;
1534
+ /**
1535
+ * Compute when an access_token will expire, given the timestamp it was
1536
+ * issued and the `expires_in` value (in seconds).
1537
+ *
1538
+ * @returns A unix-ms timestamp.
1539
+ */
1540
+ declare function expirationTimeMs(issuedAtMs: number, expiresInSeconds: number | undefined): number;
1541
+ /**
1542
+ * Check whether an access_token is close to expiring. Use this to decide
1543
+ * whether to proactively refresh BEFORE making an API call.
1544
+ *
1545
+ * @param skewSeconds Buffer to refresh early (default 5 min). MP tokens
1546
+ * typically last 6h; refreshing in the last 5 min avoids
1547
+ * races with API calls that take a few seconds.
1548
+ */
1549
+ declare function isExpiringSoon(expirationMs: number, skewSeconds?: number): boolean;
1550
+
1551
+ export { type AccountInfo, type AutoRecurring, type CardToken, type CreateCardTokenParams, type CreateCustomerParams, type CreateOrderParams, type CreatePaymentParams, type CreatePosParams, type CreatePreapprovalParams, type CreatePreferenceParams, type CreateQrPaymentParams, type CreateRefundParams, type CreateStoreParams, type CreateSubscriptionPlanParams, type CreateWebhookParams, type CurrencyId, type Customer, type CustomerCard, type Dispute, type FrequencyType, type IdentificationType, InMemoryStateAdapter, type InstallmentOffer, type Issuer, type MarketplaceParams, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, type MercadoPagoClientOptions, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, type MercadoPagoToolsOptions, type OAuthToken, type Order, type OrderItem, type OrderStatus, type ParsedWebhookEvent, type Payment, type PaymentMethod, type PaymentStatus, type PaymentsSearchResult, type Pos, type Preapproval, type PreapprovalStatus, type Preference, type PreferenceItem, type QrOrder, type Refund, type SearchPaymentsParams, type SiteId, type Store, type SubscriptionPayment, type SubscriptionPlan, type SubscriptionStateAdapter, type SubscriptionStateRecord, type WebhookBody, type WebhookConfig, type WebhookTopic, buildAuthorizeUrl, classifyError, exchangeCodeForToken, expirationTimeMs, isExpiringSoon, mercadoPagoTools, parseWebhookEvent, refreshAccessToken, verifyWebhookSignature };