@ar-agents/mercadopago 0.8.0 → 0.9.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.cts CHANGED
@@ -3,6 +3,171 @@ import { ToolSet } from 'ai';
3
3
  import { S as SubscriptionStateAdapter } from './state-C6Wzb_XX.cjs';
4
4
  export { I as IdempotencyCache, a as InMemoryIdempotencyCache, b as InMemoryOAuthTokenStore, c as InMemoryStateAdapter, O as OAuthTokenRecord, d as OAuthTokenStore, e as SubscriptionStateRecord } from './state-C6Wzb_XX.cjs';
5
5
 
6
+ /**
7
+ * Circuit breaker — protects your app from cascading failures when MP
8
+ * (or any upstream) is degraded.
9
+ *
10
+ * # Why
11
+ *
12
+ * When MP's API has an outage, naive retry-with-backoff still pounds the
13
+ * dead service N times per request × every concurrent request. That makes
14
+ * MP's outage worse AND your app's error rate worse (each request burns
15
+ * `requestTimeoutMs × maxRetries` ms of CPU/event-loop time before failing).
16
+ *
17
+ * A circuit breaker observes failures over a rolling window. After enough
18
+ * failures it OPENS — subsequent calls fail fast (no network round-trip)
19
+ * with a `CircuitOpenError`. After a cooldown it HALF-OPENs — lets one
20
+ * trial through. If that succeeds, it CLOSES (back to normal). If it
21
+ * fails, it RE-OPENs for another cooldown.
22
+ *
23
+ * # State machine
24
+ *
25
+ * CLOSED ──(failures ≥ threshold)──▶ OPEN
26
+ * ▲ │
27
+ * │ │ (cooldown elapsed)
28
+ * │ ▼
29
+ * │ HALF_OPEN
30
+ * │ │
31
+ * └──(trial succeeds)────────────────┤
32
+ * │ (trial fails)
33
+ * ▼
34
+ * OPEN
35
+ *
36
+ * # When to use
37
+ *
38
+ * - **Protects YOUR app** from being slow/dead when MP is slow/dead.
39
+ * - **Protects MP** from your app pummeling it during incidents.
40
+ * - **Surfaces a clear signal to ops**: `circuit_open` event tells you
41
+ * "MP is broken, my app is intentionally short-circuiting" — different
42
+ * from "MP timed out 30s × 3 retries × 1000 concurrent users".
43
+ *
44
+ * # When NOT to use
45
+ *
46
+ * - For idempotent reads where stale-cached data is acceptable, prefer
47
+ * a cache-aside pattern instead.
48
+ * - For fire-and-forget webhooks where the backpressure should propagate
49
+ * to MP itself (return 5xx, MP retries with backoff).
50
+ *
51
+ * # Configuration
52
+ *
53
+ * Defaults are tuned for typical MP traffic patterns:
54
+ * - `failureThreshold: 5` — open after 5 consecutive failures
55
+ * - `successThreshold: 2` — close after 2 trial successes (half-open)
56
+ * - `resetTimeoutMs: 30_000` — 30s cooldown before half-open trial
57
+ * - `monitoringWindowMs: 60_000` — count failures within a 60s window
58
+ *
59
+ * # Per-host vs global
60
+ *
61
+ * The default `MercadoPagoClient` uses ONE breaker per client instance
62
+ * (which means one per upstream host: `api.mercadopago.com` for prod,
63
+ * `api.mercadopago.com` sandbox for TEST). For multi-host setups (e.g.,
64
+ * marketplace flows with per-seller clients), instantiate a SHARED breaker
65
+ * and pass it to all clients — they all benefit from the same backpressure
66
+ * signal.
67
+ */
68
+ type CircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";
69
+ interface CircuitBreakerOptions {
70
+ /** Open the breaker after this many consecutive failures. Default 5. */
71
+ failureThreshold?: number;
72
+ /** Close the breaker after this many successive successes in HALF_OPEN. Default 2. */
73
+ successThreshold?: number;
74
+ /** Time to stay OPEN before allowing a HALF_OPEN trial. Default 30s. */
75
+ resetTimeoutMs?: number;
76
+ /** Rolling window for counting failures. Failures older than this don't count. Default 60s. */
77
+ monitoringWindowMs?: number;
78
+ /**
79
+ * Called on EVERY state transition. Useful for emitting metrics/logs.
80
+ * `cause` is the error that triggered the transition (when applicable).
81
+ */
82
+ onStateChange?: (event: {
83
+ from: CircuitState;
84
+ to: CircuitState;
85
+ cause?: unknown;
86
+ consecutiveFailures: number;
87
+ }) => void;
88
+ /**
89
+ * Predicate to decide whether an error should count as a circuit failure.
90
+ * By default, all errors count. Override to ignore expected business
91
+ * errors (e.g., 404s, validation errors) — they shouldn't open the breaker.
92
+ */
93
+ isFailure?: (error: unknown) => boolean;
94
+ /** Time provider (for tests). Defaults to `Date.now`. */
95
+ now?: () => number;
96
+ }
97
+ /**
98
+ * Thrown when a circuit breaker is OPEN and rejects a call without trying.
99
+ * Catch this separately from MercadoPagoError to differentiate "MP said no"
100
+ * from "we didn't even ask MP".
101
+ */
102
+ declare class CircuitOpenError extends Error {
103
+ readonly retryAfterMs: number;
104
+ readonly consecutiveFailures: number;
105
+ constructor(retryAfterMs: number, consecutiveFailures: number);
106
+ }
107
+ /**
108
+ * Thread-safe circuit breaker. Single-instance per upstream (typically per
109
+ * `MercadoPagoClient`). Pass to multiple clients to share state.
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * import { CircuitBreaker, MercadoPagoClient } from "@ar-agents/mercadopago";
114
+ *
115
+ * const breaker = new CircuitBreaker({
116
+ * failureThreshold: 5,
117
+ * resetTimeoutMs: 30_000,
118
+ * onStateChange: (e) => metrics.increment(`circuit.${e.to}`),
119
+ * });
120
+ *
121
+ * const client = new MercadoPagoClient({
122
+ * accessToken: process.env.MP_ACCESS_TOKEN!,
123
+ * circuitBreaker: breaker,
124
+ * });
125
+ * ```
126
+ */
127
+ declare class CircuitBreaker {
128
+ private state;
129
+ private consecutiveFailures;
130
+ private halfOpenSuccesses;
131
+ private openedAt;
132
+ /** Timestamps of failures within the monitoring window. */
133
+ private failureWindow;
134
+ private readonly failureThreshold;
135
+ private readonly successThreshold;
136
+ private readonly resetTimeoutMs;
137
+ private readonly monitoringWindowMs;
138
+ private readonly onStateChange;
139
+ private readonly isFailureFn;
140
+ private readonly now;
141
+ constructor(opts?: CircuitBreakerOptions);
142
+ /** Read the current state. Useful for health checks + metrics. */
143
+ getState(): CircuitState;
144
+ /** Read diagnostic state for health checks + dashboards. */
145
+ getStats(): {
146
+ state: CircuitState;
147
+ consecutiveFailures: number;
148
+ failuresInWindow: number;
149
+ msSinceOpened: number | null;
150
+ msUntilHalfOpen: number | null;
151
+ };
152
+ /**
153
+ * Execute `fn` under the breaker's protection.
154
+ * - If the breaker is OPEN, throws `CircuitOpenError` immediately.
155
+ * - If `fn` succeeds, may transition HALF_OPEN → CLOSED.
156
+ * - If `fn` fails (and the error counts as a failure), records the
157
+ * failure; may transition CLOSED → OPEN or HALF_OPEN → OPEN.
158
+ */
159
+ execute<T>(fn: () => Promise<T>): Promise<T>;
160
+ /** Manually force the breaker open. Useful for runbook / manual ops. */
161
+ trip(reason?: unknown): void;
162
+ /** Manually reset the breaker to CLOSED. */
163
+ reset(): void;
164
+ private recordSuccess;
165
+ private recordFailure;
166
+ private transitionTo;
167
+ private pruneWindow;
168
+ private failuresInCurrentWindow;
169
+ }
170
+
6
171
  /**
7
172
  * Base class for any error originating from the Mercado Pago integration. All
8
173
  * specific error types extend this. Carries the MP HTTP status, the parsed
@@ -1120,6 +1285,10 @@ interface MercadoPagoClientOptions {
1120
1285
  /**
1121
1286
  * Observability hook fired AFTER every request (success or failure).
1122
1287
  * Useful for logging, metrics, tracing. Synchronous, fire-and-forget.
1288
+ *
1289
+ * The `traceContext` field follows the W3C Trace Context spec — pass
1290
+ * an OpenTelemetry-compatible context propagator and you get full
1291
+ * distributed tracing for free. See `traceContext` option below.
1123
1292
  */
1124
1293
  onCall?: (event: {
1125
1294
  method: string;
@@ -1128,7 +1297,52 @@ interface MercadoPagoClientOptions {
1128
1297
  httpStatus: number | null;
1129
1298
  retried: number;
1130
1299
  success: boolean;
1300
+ /** v0.9: MP's `x-request-id` echo. Useful for support tickets. */
1301
+ requestId?: string | null;
1302
+ /** v0.9: MP's rate-limit headers when present. */
1303
+ rateLimit?: {
1304
+ remaining: number | null;
1305
+ resetSeconds: number | null;
1306
+ };
1307
+ /** v0.9: Circuit breaker state at the time of the call. */
1308
+ circuitState?: "CLOSED" | "OPEN" | "HALF_OPEN";
1309
+ /** v0.9: Trace context for OpenTelemetry-style propagation. */
1310
+ traceContext?: {
1311
+ traceId?: string;
1312
+ spanId?: string;
1313
+ };
1131
1314
  }) => void;
1315
+ /**
1316
+ * v0.9 — Opt-in circuit breaker. When MP is failing, fail fast instead of
1317
+ * piling up retries against a dead service. Pass a configured instance
1318
+ * (or share one across multiple clients to give them shared backpressure
1319
+ * signal).
1320
+ *
1321
+ * @example
1322
+ * ```ts
1323
+ * const breaker = new CircuitBreaker({
1324
+ * failureThreshold: 5,
1325
+ * resetTimeoutMs: 30_000,
1326
+ * onStateChange: (e) => metrics.gauge("circuit.state", e.to),
1327
+ * });
1328
+ * const client = new MercadoPagoClient({ accessToken: "...", circuitBreaker: breaker });
1329
+ * ```
1330
+ */
1331
+ circuitBreaker?: CircuitBreaker;
1332
+ /**
1333
+ * v0.9 — Optional W3C Trace Context propagator. If provided, the client
1334
+ * extracts traceId/spanId on each request, injects `traceparent` /
1335
+ * `tracestate` headers (MP echoes them back via x-request-id), and surfaces
1336
+ * them in `onCall` events. Compatible with OpenTelemetry without adding
1337
+ * `@opentelemetry/api` as a peer dep.
1338
+ *
1339
+ * If you have OTEL set up, just pass `() => trace.getActiveSpan()?.spanContext()`.
1340
+ */
1341
+ traceContext?: () => {
1342
+ traceId?: string;
1343
+ spanId?: string;
1344
+ traceFlags?: number;
1345
+ } | undefined;
1132
1346
  }
1133
1347
  interface RequestOptions {
1134
1348
  /** Idempotency key. Required for POST/PUT to dedupe retries safely. */
@@ -1143,6 +1357,13 @@ interface RequestOptions {
1143
1357
  payerEmail?: string;
1144
1358
  sellerEmail?: string;
1145
1359
  };
1360
+ /**
1361
+ * v0.9 — Parent AbortSignal for deadline propagation. When the agent
1362
+ * has a fixed budget (e.g., 5s for the whole tool call), pass it here.
1363
+ * The client merges it with its own per-request timeout — whichever
1364
+ * fires first wins.
1365
+ */
1366
+ signal?: AbortSignal;
1146
1367
  }
1147
1368
  /**
1148
1369
  * Thin, typed wrapper around Mercado Pago's REST API. Exposes the surface
@@ -1158,8 +1379,16 @@ declare class MercadoPagoClient {
1158
1379
  private readonly requestTimeoutMs;
1159
1380
  private readonly maxRetries;
1160
1381
  private readonly onCall;
1382
+ private readonly circuitBreaker;
1383
+ private readonly traceContext;
1161
1384
  constructor(options: MercadoPagoClientOptions);
1385
+ /**
1386
+ * v0.9 — Inspect the circuit breaker state (when configured). Returns
1387
+ * `null` when no circuit breaker is wired. Useful for health checks.
1388
+ */
1389
+ getCircuitState(): ReturnType<CircuitBreaker["getStats"]> | null;
1162
1390
  private request;
1391
+ private requestUnprotected;
1163
1392
  /**
1164
1393
  * Create a recurring subscription (preapproval). The returned `init_point`
1165
1394
  * URL is where the buyer must complete the FIRST payment with their card +
@@ -1625,6 +1854,26 @@ declare class MercadoPagoClient {
1625
1854
  id: string;
1626
1855
  canceled: true;
1627
1856
  }>;
1857
+ /**
1858
+ * Liveness probe against MP. Returns latency + circuit-breaker state.
1859
+ * Use as a /health endpoint for k8s, Vercel cron, or status-page checks.
1860
+ *
1861
+ * Returns `{ ok: false, ... }` instead of throwing — designed for
1862
+ * monitoring loops that want to keep running.
1863
+ *
1864
+ * @param signal Optional AbortSignal to cap wait time (e.g., 2s for
1865
+ * status-page polling).
1866
+ */
1867
+ healthCheck(signal?: AbortSignal): Promise<{
1868
+ ok: boolean;
1869
+ latencyMs: number;
1870
+ /** MP user_id when reachable. */
1871
+ userId: string | null;
1872
+ /** Last error message when not OK. */
1873
+ error: string | null;
1874
+ /** Circuit breaker state when configured. */
1875
+ circuit: ReturnType<CircuitBreaker["getStats"]> | null;
1876
+ }>;
1628
1877
  }
1629
1878
 
1630
1879
  interface MercadoPagoToolsOptions {
@@ -1665,7 +1914,7 @@ interface MercadoPagoToolsOptions {
1665
1914
  clientSecret: string;
1666
1915
  };
1667
1916
  }
1668
- 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" | "get_account_balance" | "list_account_movements" | "list_settlements" | "get_settlement" | "analyze_payment_3ds" | "get_test_cards" | "get_customer" | "update_customer" | "create_customer_card" | "get_customer_card" | "get_subscription_plan" | "update_subscription" | "search_subscriptions" | "get_refund" | "update_payment_preference" | "get_merchant_order" | "search_merchant_orders" | "update_merchant_order" | "get_store" | "update_store" | "delete_store" | "get_pos" | "update_pos" | "delete_pos" | "list_bank_accounts" | "register_bank_account" | "list_point_devices" | "update_point_device_mode" | "create_point_payment_intent" | "get_point_payment_intent" | "cancel_point_payment_intent" | "compute_marketplace_fee" | "explain_payment_status";
1917
+ 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" | "get_account_balance" | "list_account_movements" | "list_settlements" | "get_settlement" | "analyze_payment_3ds" | "get_test_cards" | "get_customer" | "update_customer" | "create_customer_card" | "get_customer_card" | "get_subscription_plan" | "update_subscription" | "search_subscriptions" | "get_refund" | "update_payment_preference" | "get_merchant_order" | "search_merchant_orders" | "update_merchant_order" | "get_store" | "update_store" | "delete_store" | "get_pos" | "update_pos" | "delete_pos" | "list_bank_accounts" | "register_bank_account" | "list_point_devices" | "update_point_device_mode" | "create_point_payment_intent" | "get_point_payment_intent" | "cancel_point_payment_intent" | "compute_marketplace_fee" | "explain_payment_status" | "mp_health_check";
1669
1918
  /**
1670
1919
  * Build a tool set for the Vercel AI SDK that exposes Mercado Pago to an
1671
1920
  * agent. Pass directly to `Experimental_Agent`'s `tools` option, or merge with
@@ -2058,4 +2307,4 @@ interface PaymentStatusExplanation {
2058
2307
  */
2059
2308
  declare function explainPaymentStatus(payment: Payment): PaymentStatusExplanation;
2060
2309
 
2061
- export { type AccountBalance, type AccountInfo, type AccountMovement, type AutoRecurring, type BankAccount, type CardToken, type CreateCardTokenParams, type CreateCustomerParams, type CreateOrderParams, type CreatePaymentParams, type CreatePointPaymentIntentParams, 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, type InstallmentOffer, type Issuer, type MarketplaceFeeRule, type MarketplaceParams, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, type MercadoPagoClientOptions, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, type MercadoPagoToolsOptions, type MerchantOrder, type OAuthToken, type Order, type OrderItem, type OrderStatus, type ParsedWebhookEvent, type Payment, type PaymentMethod, type PaymentStatus, type PaymentStatusExplanation, type PaymentsSearchResult, type PointDevice, type PointPaymentIntent, type PointPaymentIntentState, type Pos, type Preapproval, type PreapprovalStatus, type Preference, type PreferenceItem, type QrOrder, type Refund, type SearchPaymentsParams, type Settlement, type SiteId, type Store, type SubscriptionPayment, type SubscriptionPlan, SubscriptionStateAdapter, TEST_CARDS_AR, TEST_PAYERS_AR, type TestCard, type ThreeDSInfo, type ThreeDSStatus, type WebhookBody, type WebhookConfig, type WebhookTopic, analyze3DS, buildAuthorizeUrl, buildTestCardScenario, classifyError, computeMarketplaceFee, exchangeCodeForToken, expirationTimeMs, explainPaymentStatus, isExpiringSoon, mercadoPagoTools, parseWebhookEvent, refreshAccessToken, verifyWebhookSignature };
2310
+ export { type AccountBalance, type AccountInfo, type AccountMovement, type AutoRecurring, type BankAccount, type CardToken, CircuitBreaker, type CircuitBreakerOptions, CircuitOpenError, type CircuitState, type CreateCardTokenParams, type CreateCustomerParams, type CreateOrderParams, type CreatePaymentParams, type CreatePointPaymentIntentParams, 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, type InstallmentOffer, type Issuer, type MarketplaceFeeRule, type MarketplaceParams, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, type MercadoPagoClientOptions, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, type MercadoPagoToolsOptions, type MerchantOrder, type OAuthToken, type Order, type OrderItem, type OrderStatus, type ParsedWebhookEvent, type Payment, type PaymentMethod, type PaymentStatus, type PaymentStatusExplanation, type PaymentsSearchResult, type PointDevice, type PointPaymentIntent, type PointPaymentIntentState, type Pos, type Preapproval, type PreapprovalStatus, type Preference, type PreferenceItem, type QrOrder, type Refund, type SearchPaymentsParams, type Settlement, type SiteId, type Store, type SubscriptionPayment, type SubscriptionPlan, SubscriptionStateAdapter, TEST_CARDS_AR, TEST_PAYERS_AR, type TestCard, type ThreeDSInfo, type ThreeDSStatus, type WebhookBody, type WebhookConfig, type WebhookTopic, analyze3DS, buildAuthorizeUrl, buildTestCardScenario, classifyError, computeMarketplaceFee, exchangeCodeForToken, expirationTimeMs, explainPaymentStatus, isExpiringSoon, mercadoPagoTools, parseWebhookEvent, refreshAccessToken, verifyWebhookSignature };
package/dist/index.d.ts CHANGED
@@ -3,6 +3,171 @@ import { ToolSet } from 'ai';
3
3
  import { S as SubscriptionStateAdapter } from './state-C6Wzb_XX.js';
4
4
  export { I as IdempotencyCache, a as InMemoryIdempotencyCache, b as InMemoryOAuthTokenStore, c as InMemoryStateAdapter, O as OAuthTokenRecord, d as OAuthTokenStore, e as SubscriptionStateRecord } from './state-C6Wzb_XX.js';
5
5
 
6
+ /**
7
+ * Circuit breaker — protects your app from cascading failures when MP
8
+ * (or any upstream) is degraded.
9
+ *
10
+ * # Why
11
+ *
12
+ * When MP's API has an outage, naive retry-with-backoff still pounds the
13
+ * dead service N times per request × every concurrent request. That makes
14
+ * MP's outage worse AND your app's error rate worse (each request burns
15
+ * `requestTimeoutMs × maxRetries` ms of CPU/event-loop time before failing).
16
+ *
17
+ * A circuit breaker observes failures over a rolling window. After enough
18
+ * failures it OPENS — subsequent calls fail fast (no network round-trip)
19
+ * with a `CircuitOpenError`. After a cooldown it HALF-OPENs — lets one
20
+ * trial through. If that succeeds, it CLOSES (back to normal). If it
21
+ * fails, it RE-OPENs for another cooldown.
22
+ *
23
+ * # State machine
24
+ *
25
+ * CLOSED ──(failures ≥ threshold)──▶ OPEN
26
+ * ▲ │
27
+ * │ │ (cooldown elapsed)
28
+ * │ ▼
29
+ * │ HALF_OPEN
30
+ * │ │
31
+ * └──(trial succeeds)────────────────┤
32
+ * │ (trial fails)
33
+ * ▼
34
+ * OPEN
35
+ *
36
+ * # When to use
37
+ *
38
+ * - **Protects YOUR app** from being slow/dead when MP is slow/dead.
39
+ * - **Protects MP** from your app pummeling it during incidents.
40
+ * - **Surfaces a clear signal to ops**: `circuit_open` event tells you
41
+ * "MP is broken, my app is intentionally short-circuiting" — different
42
+ * from "MP timed out 30s × 3 retries × 1000 concurrent users".
43
+ *
44
+ * # When NOT to use
45
+ *
46
+ * - For idempotent reads where stale-cached data is acceptable, prefer
47
+ * a cache-aside pattern instead.
48
+ * - For fire-and-forget webhooks where the backpressure should propagate
49
+ * to MP itself (return 5xx, MP retries with backoff).
50
+ *
51
+ * # Configuration
52
+ *
53
+ * Defaults are tuned for typical MP traffic patterns:
54
+ * - `failureThreshold: 5` — open after 5 consecutive failures
55
+ * - `successThreshold: 2` — close after 2 trial successes (half-open)
56
+ * - `resetTimeoutMs: 30_000` — 30s cooldown before half-open trial
57
+ * - `monitoringWindowMs: 60_000` — count failures within a 60s window
58
+ *
59
+ * # Per-host vs global
60
+ *
61
+ * The default `MercadoPagoClient` uses ONE breaker per client instance
62
+ * (which means one per upstream host: `api.mercadopago.com` for prod,
63
+ * `api.mercadopago.com` sandbox for TEST). For multi-host setups (e.g.,
64
+ * marketplace flows with per-seller clients), instantiate a SHARED breaker
65
+ * and pass it to all clients — they all benefit from the same backpressure
66
+ * signal.
67
+ */
68
+ type CircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";
69
+ interface CircuitBreakerOptions {
70
+ /** Open the breaker after this many consecutive failures. Default 5. */
71
+ failureThreshold?: number;
72
+ /** Close the breaker after this many successive successes in HALF_OPEN. Default 2. */
73
+ successThreshold?: number;
74
+ /** Time to stay OPEN before allowing a HALF_OPEN trial. Default 30s. */
75
+ resetTimeoutMs?: number;
76
+ /** Rolling window for counting failures. Failures older than this don't count. Default 60s. */
77
+ monitoringWindowMs?: number;
78
+ /**
79
+ * Called on EVERY state transition. Useful for emitting metrics/logs.
80
+ * `cause` is the error that triggered the transition (when applicable).
81
+ */
82
+ onStateChange?: (event: {
83
+ from: CircuitState;
84
+ to: CircuitState;
85
+ cause?: unknown;
86
+ consecutiveFailures: number;
87
+ }) => void;
88
+ /**
89
+ * Predicate to decide whether an error should count as a circuit failure.
90
+ * By default, all errors count. Override to ignore expected business
91
+ * errors (e.g., 404s, validation errors) — they shouldn't open the breaker.
92
+ */
93
+ isFailure?: (error: unknown) => boolean;
94
+ /** Time provider (for tests). Defaults to `Date.now`. */
95
+ now?: () => number;
96
+ }
97
+ /**
98
+ * Thrown when a circuit breaker is OPEN and rejects a call without trying.
99
+ * Catch this separately from MercadoPagoError to differentiate "MP said no"
100
+ * from "we didn't even ask MP".
101
+ */
102
+ declare class CircuitOpenError extends Error {
103
+ readonly retryAfterMs: number;
104
+ readonly consecutiveFailures: number;
105
+ constructor(retryAfterMs: number, consecutiveFailures: number);
106
+ }
107
+ /**
108
+ * Thread-safe circuit breaker. Single-instance per upstream (typically per
109
+ * `MercadoPagoClient`). Pass to multiple clients to share state.
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * import { CircuitBreaker, MercadoPagoClient } from "@ar-agents/mercadopago";
114
+ *
115
+ * const breaker = new CircuitBreaker({
116
+ * failureThreshold: 5,
117
+ * resetTimeoutMs: 30_000,
118
+ * onStateChange: (e) => metrics.increment(`circuit.${e.to}`),
119
+ * });
120
+ *
121
+ * const client = new MercadoPagoClient({
122
+ * accessToken: process.env.MP_ACCESS_TOKEN!,
123
+ * circuitBreaker: breaker,
124
+ * });
125
+ * ```
126
+ */
127
+ declare class CircuitBreaker {
128
+ private state;
129
+ private consecutiveFailures;
130
+ private halfOpenSuccesses;
131
+ private openedAt;
132
+ /** Timestamps of failures within the monitoring window. */
133
+ private failureWindow;
134
+ private readonly failureThreshold;
135
+ private readonly successThreshold;
136
+ private readonly resetTimeoutMs;
137
+ private readonly monitoringWindowMs;
138
+ private readonly onStateChange;
139
+ private readonly isFailureFn;
140
+ private readonly now;
141
+ constructor(opts?: CircuitBreakerOptions);
142
+ /** Read the current state. Useful for health checks + metrics. */
143
+ getState(): CircuitState;
144
+ /** Read diagnostic state for health checks + dashboards. */
145
+ getStats(): {
146
+ state: CircuitState;
147
+ consecutiveFailures: number;
148
+ failuresInWindow: number;
149
+ msSinceOpened: number | null;
150
+ msUntilHalfOpen: number | null;
151
+ };
152
+ /**
153
+ * Execute `fn` under the breaker's protection.
154
+ * - If the breaker is OPEN, throws `CircuitOpenError` immediately.
155
+ * - If `fn` succeeds, may transition HALF_OPEN → CLOSED.
156
+ * - If `fn` fails (and the error counts as a failure), records the
157
+ * failure; may transition CLOSED → OPEN or HALF_OPEN → OPEN.
158
+ */
159
+ execute<T>(fn: () => Promise<T>): Promise<T>;
160
+ /** Manually force the breaker open. Useful for runbook / manual ops. */
161
+ trip(reason?: unknown): void;
162
+ /** Manually reset the breaker to CLOSED. */
163
+ reset(): void;
164
+ private recordSuccess;
165
+ private recordFailure;
166
+ private transitionTo;
167
+ private pruneWindow;
168
+ private failuresInCurrentWindow;
169
+ }
170
+
6
171
  /**
7
172
  * Base class for any error originating from the Mercado Pago integration. All
8
173
  * specific error types extend this. Carries the MP HTTP status, the parsed
@@ -1120,6 +1285,10 @@ interface MercadoPagoClientOptions {
1120
1285
  /**
1121
1286
  * Observability hook fired AFTER every request (success or failure).
1122
1287
  * Useful for logging, metrics, tracing. Synchronous, fire-and-forget.
1288
+ *
1289
+ * The `traceContext` field follows the W3C Trace Context spec — pass
1290
+ * an OpenTelemetry-compatible context propagator and you get full
1291
+ * distributed tracing for free. See `traceContext` option below.
1123
1292
  */
1124
1293
  onCall?: (event: {
1125
1294
  method: string;
@@ -1128,7 +1297,52 @@ interface MercadoPagoClientOptions {
1128
1297
  httpStatus: number | null;
1129
1298
  retried: number;
1130
1299
  success: boolean;
1300
+ /** v0.9: MP's `x-request-id` echo. Useful for support tickets. */
1301
+ requestId?: string | null;
1302
+ /** v0.9: MP's rate-limit headers when present. */
1303
+ rateLimit?: {
1304
+ remaining: number | null;
1305
+ resetSeconds: number | null;
1306
+ };
1307
+ /** v0.9: Circuit breaker state at the time of the call. */
1308
+ circuitState?: "CLOSED" | "OPEN" | "HALF_OPEN";
1309
+ /** v0.9: Trace context for OpenTelemetry-style propagation. */
1310
+ traceContext?: {
1311
+ traceId?: string;
1312
+ spanId?: string;
1313
+ };
1131
1314
  }) => void;
1315
+ /**
1316
+ * v0.9 — Opt-in circuit breaker. When MP is failing, fail fast instead of
1317
+ * piling up retries against a dead service. Pass a configured instance
1318
+ * (or share one across multiple clients to give them shared backpressure
1319
+ * signal).
1320
+ *
1321
+ * @example
1322
+ * ```ts
1323
+ * const breaker = new CircuitBreaker({
1324
+ * failureThreshold: 5,
1325
+ * resetTimeoutMs: 30_000,
1326
+ * onStateChange: (e) => metrics.gauge("circuit.state", e.to),
1327
+ * });
1328
+ * const client = new MercadoPagoClient({ accessToken: "...", circuitBreaker: breaker });
1329
+ * ```
1330
+ */
1331
+ circuitBreaker?: CircuitBreaker;
1332
+ /**
1333
+ * v0.9 — Optional W3C Trace Context propagator. If provided, the client
1334
+ * extracts traceId/spanId on each request, injects `traceparent` /
1335
+ * `tracestate` headers (MP echoes them back via x-request-id), and surfaces
1336
+ * them in `onCall` events. Compatible with OpenTelemetry without adding
1337
+ * `@opentelemetry/api` as a peer dep.
1338
+ *
1339
+ * If you have OTEL set up, just pass `() => trace.getActiveSpan()?.spanContext()`.
1340
+ */
1341
+ traceContext?: () => {
1342
+ traceId?: string;
1343
+ spanId?: string;
1344
+ traceFlags?: number;
1345
+ } | undefined;
1132
1346
  }
1133
1347
  interface RequestOptions {
1134
1348
  /** Idempotency key. Required for POST/PUT to dedupe retries safely. */
@@ -1143,6 +1357,13 @@ interface RequestOptions {
1143
1357
  payerEmail?: string;
1144
1358
  sellerEmail?: string;
1145
1359
  };
1360
+ /**
1361
+ * v0.9 — Parent AbortSignal for deadline propagation. When the agent
1362
+ * has a fixed budget (e.g., 5s for the whole tool call), pass it here.
1363
+ * The client merges it with its own per-request timeout — whichever
1364
+ * fires first wins.
1365
+ */
1366
+ signal?: AbortSignal;
1146
1367
  }
1147
1368
  /**
1148
1369
  * Thin, typed wrapper around Mercado Pago's REST API. Exposes the surface
@@ -1158,8 +1379,16 @@ declare class MercadoPagoClient {
1158
1379
  private readonly requestTimeoutMs;
1159
1380
  private readonly maxRetries;
1160
1381
  private readonly onCall;
1382
+ private readonly circuitBreaker;
1383
+ private readonly traceContext;
1161
1384
  constructor(options: MercadoPagoClientOptions);
1385
+ /**
1386
+ * v0.9 — Inspect the circuit breaker state (when configured). Returns
1387
+ * `null` when no circuit breaker is wired. Useful for health checks.
1388
+ */
1389
+ getCircuitState(): ReturnType<CircuitBreaker["getStats"]> | null;
1162
1390
  private request;
1391
+ private requestUnprotected;
1163
1392
  /**
1164
1393
  * Create a recurring subscription (preapproval). The returned `init_point`
1165
1394
  * URL is where the buyer must complete the FIRST payment with their card +
@@ -1625,6 +1854,26 @@ declare class MercadoPagoClient {
1625
1854
  id: string;
1626
1855
  canceled: true;
1627
1856
  }>;
1857
+ /**
1858
+ * Liveness probe against MP. Returns latency + circuit-breaker state.
1859
+ * Use as a /health endpoint for k8s, Vercel cron, or status-page checks.
1860
+ *
1861
+ * Returns `{ ok: false, ... }` instead of throwing — designed for
1862
+ * monitoring loops that want to keep running.
1863
+ *
1864
+ * @param signal Optional AbortSignal to cap wait time (e.g., 2s for
1865
+ * status-page polling).
1866
+ */
1867
+ healthCheck(signal?: AbortSignal): Promise<{
1868
+ ok: boolean;
1869
+ latencyMs: number;
1870
+ /** MP user_id when reachable. */
1871
+ userId: string | null;
1872
+ /** Last error message when not OK. */
1873
+ error: string | null;
1874
+ /** Circuit breaker state when configured. */
1875
+ circuit: ReturnType<CircuitBreaker["getStats"]> | null;
1876
+ }>;
1628
1877
  }
1629
1878
 
1630
1879
  interface MercadoPagoToolsOptions {
@@ -1665,7 +1914,7 @@ interface MercadoPagoToolsOptions {
1665
1914
  clientSecret: string;
1666
1915
  };
1667
1916
  }
1668
- 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" | "get_account_balance" | "list_account_movements" | "list_settlements" | "get_settlement" | "analyze_payment_3ds" | "get_test_cards" | "get_customer" | "update_customer" | "create_customer_card" | "get_customer_card" | "get_subscription_plan" | "update_subscription" | "search_subscriptions" | "get_refund" | "update_payment_preference" | "get_merchant_order" | "search_merchant_orders" | "update_merchant_order" | "get_store" | "update_store" | "delete_store" | "get_pos" | "update_pos" | "delete_pos" | "list_bank_accounts" | "register_bank_account" | "list_point_devices" | "update_point_device_mode" | "create_point_payment_intent" | "get_point_payment_intent" | "cancel_point_payment_intent" | "compute_marketplace_fee" | "explain_payment_status";
1917
+ 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" | "get_account_balance" | "list_account_movements" | "list_settlements" | "get_settlement" | "analyze_payment_3ds" | "get_test_cards" | "get_customer" | "update_customer" | "create_customer_card" | "get_customer_card" | "get_subscription_plan" | "update_subscription" | "search_subscriptions" | "get_refund" | "update_payment_preference" | "get_merchant_order" | "search_merchant_orders" | "update_merchant_order" | "get_store" | "update_store" | "delete_store" | "get_pos" | "update_pos" | "delete_pos" | "list_bank_accounts" | "register_bank_account" | "list_point_devices" | "update_point_device_mode" | "create_point_payment_intent" | "get_point_payment_intent" | "cancel_point_payment_intent" | "compute_marketplace_fee" | "explain_payment_status" | "mp_health_check";
1669
1918
  /**
1670
1919
  * Build a tool set for the Vercel AI SDK that exposes Mercado Pago to an
1671
1920
  * agent. Pass directly to `Experimental_Agent`'s `tools` option, or merge with
@@ -2058,4 +2307,4 @@ interface PaymentStatusExplanation {
2058
2307
  */
2059
2308
  declare function explainPaymentStatus(payment: Payment): PaymentStatusExplanation;
2060
2309
 
2061
- export { type AccountBalance, type AccountInfo, type AccountMovement, type AutoRecurring, type BankAccount, type CardToken, type CreateCardTokenParams, type CreateCustomerParams, type CreateOrderParams, type CreatePaymentParams, type CreatePointPaymentIntentParams, 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, type InstallmentOffer, type Issuer, type MarketplaceFeeRule, type MarketplaceParams, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, type MercadoPagoClientOptions, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, type MercadoPagoToolsOptions, type MerchantOrder, type OAuthToken, type Order, type OrderItem, type OrderStatus, type ParsedWebhookEvent, type Payment, type PaymentMethod, type PaymentStatus, type PaymentStatusExplanation, type PaymentsSearchResult, type PointDevice, type PointPaymentIntent, type PointPaymentIntentState, type Pos, type Preapproval, type PreapprovalStatus, type Preference, type PreferenceItem, type QrOrder, type Refund, type SearchPaymentsParams, type Settlement, type SiteId, type Store, type SubscriptionPayment, type SubscriptionPlan, SubscriptionStateAdapter, TEST_CARDS_AR, TEST_PAYERS_AR, type TestCard, type ThreeDSInfo, type ThreeDSStatus, type WebhookBody, type WebhookConfig, type WebhookTopic, analyze3DS, buildAuthorizeUrl, buildTestCardScenario, classifyError, computeMarketplaceFee, exchangeCodeForToken, expirationTimeMs, explainPaymentStatus, isExpiringSoon, mercadoPagoTools, parseWebhookEvent, refreshAccessToken, verifyWebhookSignature };
2310
+ export { type AccountBalance, type AccountInfo, type AccountMovement, type AutoRecurring, type BankAccount, type CardToken, CircuitBreaker, type CircuitBreakerOptions, CircuitOpenError, type CircuitState, type CreateCardTokenParams, type CreateCustomerParams, type CreateOrderParams, type CreatePaymentParams, type CreatePointPaymentIntentParams, 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, type InstallmentOffer, type Issuer, type MarketplaceFeeRule, type MarketplaceParams, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, type MercadoPagoClientOptions, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, type MercadoPagoToolsOptions, type MerchantOrder, type OAuthToken, type Order, type OrderItem, type OrderStatus, type ParsedWebhookEvent, type Payment, type PaymentMethod, type PaymentStatus, type PaymentStatusExplanation, type PaymentsSearchResult, type PointDevice, type PointPaymentIntent, type PointPaymentIntentState, type Pos, type Preapproval, type PreapprovalStatus, type Preference, type PreferenceItem, type QrOrder, type Refund, type SearchPaymentsParams, type Settlement, type SiteId, type Store, type SubscriptionPayment, type SubscriptionPlan, SubscriptionStateAdapter, TEST_CARDS_AR, TEST_PAYERS_AR, type TestCard, type ThreeDSInfo, type ThreeDSStatus, type WebhookBody, type WebhookConfig, type WebhookTopic, analyze3DS, buildAuthorizeUrl, buildTestCardScenario, classifyError, computeMarketplaceFee, exchangeCodeForToken, expirationTimeMs, explainPaymentStatus, isExpiringSoon, mercadoPagoTools, parseWebhookEvent, refreshAccessToken, verifyWebhookSignature };