@ar-agents/mercadopago 0.10.0 → 0.12.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/CHANGELOG.md +55 -0
- package/MIGRATION.md +176 -0
- package/cookbook/09-otel-wired.ts +155 -0
- package/cookbook/README.md +1 -0
- package/dist/audit-B9Nhj3PH.d.cts +294 -0
- package/dist/audit-B9Nhj3PH.d.ts +294 -0
- package/dist/index.cjs +588 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +270 -194
- package/dist/index.d.ts +270 -194
- package/dist/index.js +581 -5
- package/dist/index.js.map +1 -1
- package/dist/vercel-kv.cjs +81 -0
- package/dist/vercel-kv.cjs.map +1 -1
- package/dist/vercel-kv.d.cts +38 -2
- package/dist/vercel-kv.d.ts +38 -2
- package/dist/vercel-kv.js +81 -1
- package/dist/vercel-kv.js.map +1 -1
- package/package.json +4 -3
- package/tools.manifest.json +1 -1
- package/dist/state-C6Wzb_XX.d.cts +0 -106
- package/dist/state-C6Wzb_XX.d.ts +0 -106
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { I as IdempotencyCache, S as SubscriptionStateAdapter } from './
|
|
3
|
-
export {
|
|
4
|
-
import { ToolSet } from 'ai';
|
|
2
|
+
import { I as IdempotencyCache, S as SubscriptionStateAdapter, A as AuditLogger, a as AuditOperation } from './audit-B9Nhj3PH.cjs';
|
|
3
|
+
export { b as AuditEntry, c as AuditLogAdapter, d as InMemoryAuditLog, e as InMemoryIdempotencyCache, f as InMemoryOAuthTokenStore, g as InMemoryStateAdapter, O as OAuthTokenRecord, h as OAuthTokenStore, i as SubscriptionStateRecord } from './audit-B9Nhj3PH.cjs';
|
|
4
|
+
import { ToolSet, Tool } from 'ai';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Circuit breaker — protects your app from cascading failures when MP
|
|
@@ -463,15 +463,86 @@ interface CreatePaymentParams {
|
|
|
463
463
|
};
|
|
464
464
|
/** Webhook override URL. Falls back to dashboard config if omitted. */
|
|
465
465
|
notificationUrl?: string;
|
|
466
|
-
/**
|
|
466
|
+
/**
|
|
467
|
+
* Additional information passed to MP for fraud scoring + receipt details.
|
|
468
|
+
*
|
|
469
|
+
* **Critical for fraud scoring**: every field you fill in here improves
|
|
470
|
+
* MP's risk model's confidence and reduces false-positive rejections.
|
|
471
|
+
* For card payments above ~$50k ARS, ALWAYS include `payer` + `ip_address`
|
|
472
|
+
* + `shipments` (when applicable) — payments without enrichment have a
|
|
473
|
+
* 3-5x higher rejection rate per MP's published guidance (RG 5286/2023).
|
|
474
|
+
*/
|
|
467
475
|
additionalInfo?: {
|
|
476
|
+
/** Items in the cart — used for receipt + fraud scoring. */
|
|
468
477
|
items?: Array<{
|
|
469
478
|
id?: string;
|
|
470
479
|
title: string;
|
|
471
480
|
quantity: number;
|
|
472
481
|
unit_price: number;
|
|
473
482
|
description?: string;
|
|
483
|
+
picture_url?: string;
|
|
484
|
+
category_id?: string;
|
|
474
485
|
}>;
|
|
486
|
+
/**
|
|
487
|
+
* Buyer profile fields. The more fields populated, the better MP's
|
|
488
|
+
* risk engine can assess the transaction. `registration_date` is
|
|
489
|
+
* particularly impactful (newer accounts = higher risk).
|
|
490
|
+
*/
|
|
491
|
+
payer?: {
|
|
492
|
+
first_name?: string;
|
|
493
|
+
last_name?: string;
|
|
494
|
+
phone?: {
|
|
495
|
+
area_code?: string;
|
|
496
|
+
number?: string;
|
|
497
|
+
};
|
|
498
|
+
address?: {
|
|
499
|
+
zip_code?: string;
|
|
500
|
+
street_name?: string;
|
|
501
|
+
street_number?: number;
|
|
502
|
+
};
|
|
503
|
+
/** ISO 8601 date — when the buyer registered on YOUR platform. */
|
|
504
|
+
registration_date?: string;
|
|
505
|
+
/**
|
|
506
|
+
* Whether the buyer is a returning customer. Strong fraud-scoring
|
|
507
|
+
* signal — repeat buyers are lower risk.
|
|
508
|
+
*/
|
|
509
|
+
authentication_type?: "Cellphone" | "Email" | "Facebook" | "Gmail" | "Native app" | string;
|
|
510
|
+
/** Whether the buyer has set up 2FA on YOUR platform. */
|
|
511
|
+
is_prime_user?: boolean;
|
|
512
|
+
/** Whether the buyer has paid you successfully before. */
|
|
513
|
+
is_first_purchase_online?: boolean;
|
|
514
|
+
/** ISO 8601 — last successful purchase on your platform. */
|
|
515
|
+
last_purchase?: string;
|
|
516
|
+
};
|
|
517
|
+
/**
|
|
518
|
+
* Shipping info. Used by fraud engine to compare against payer address.
|
|
519
|
+
* Mismatch (different city/province) = higher risk score.
|
|
520
|
+
*/
|
|
521
|
+
shipments?: {
|
|
522
|
+
receiver_address?: {
|
|
523
|
+
zip_code?: string;
|
|
524
|
+
street_name?: string;
|
|
525
|
+
street_number?: number;
|
|
526
|
+
floor?: string;
|
|
527
|
+
apartment?: string;
|
|
528
|
+
city_name?: string;
|
|
529
|
+
state_name?: string;
|
|
530
|
+
country_name?: string;
|
|
531
|
+
};
|
|
532
|
+
/** Express shipment flag — fraud engine treats high-value+express as suspicious. */
|
|
533
|
+
express_shipment?: boolean;
|
|
534
|
+
/** True if the buyer picks up at a store (no shipment). Reduces fraud risk. */
|
|
535
|
+
local_pickup?: boolean;
|
|
536
|
+
};
|
|
537
|
+
/**
|
|
538
|
+
* Buyer's IP address (from your X-Forwarded-For / req.headers).
|
|
539
|
+
* **Strongly recommended** for any card payment — MP's fraud engine
|
|
540
|
+
* checks IP geolocation, ASN reputation, proxy/VPN detection.
|
|
541
|
+
* Without IP, MP defaults to "unknown" which raises risk score.
|
|
542
|
+
*/
|
|
543
|
+
ip_address?: string;
|
|
544
|
+
/** Referrer URL — useful for affiliate / channel attribution + fraud signal. */
|
|
545
|
+
referral_url?: string;
|
|
475
546
|
};
|
|
476
547
|
/** Statement descriptor — what shows on the buyer's card statement. Max 13 chars. */
|
|
477
548
|
statementDescriptor?: string;
|
|
@@ -2020,194 +2091,6 @@ declare class WebhookDedup {
|
|
|
2020
2091
|
private deriveKey;
|
|
2021
2092
|
}
|
|
2022
2093
|
|
|
2023
|
-
/**
|
|
2024
|
-
* Compute SHA-256 hash of `input`. Returns the full 64-char hex digest.
|
|
2025
|
-
*
|
|
2026
|
-
* Used for deterministic idempotency keys derived from caller-meaningful
|
|
2027
|
-
* fields. Truncate the output to 32 chars for storage if needed.
|
|
2028
|
-
*/
|
|
2029
|
-
declare function sha256Hex(input: string): Promise<string>;
|
|
2030
|
-
|
|
2031
|
-
/**
|
|
2032
|
-
* Audit logging — financial-grade compliance trail for every state-mutating
|
|
2033
|
-
* operation. Captures who/what/when/idempotency_key/before/after/result.
|
|
2034
|
-
*
|
|
2035
|
-
* # Why this is a tier-1 feature
|
|
2036
|
-
*
|
|
2037
|
-
* Every mature payment integration has an audit log. The compliance officer
|
|
2038
|
-
* asks "show me every refund issued in March 2026 by user X" and you need
|
|
2039
|
-
* to answer in <60 seconds. Without an audit log, you're trawling through
|
|
2040
|
-
* application logs hoping nothing was filtered out.
|
|
2041
|
-
*
|
|
2042
|
-
* # What gets logged
|
|
2043
|
-
*
|
|
2044
|
-
* Every **state-mutating** tool call automatically:
|
|
2045
|
-
* - `create_payment`, `charge_saved_card`, `cancel_payment`, `capture_payment`
|
|
2046
|
-
* - `refund_payment`
|
|
2047
|
-
* - `create_subscription`, `cancel/pause/resume_subscription`, `update_subscription`
|
|
2048
|
-
* - `create_order`, `capture_order`, `cancel_order`
|
|
2049
|
-
* - `create_payment_preference`, `update_payment_preference`
|
|
2050
|
-
* - `create_customer`, `update_customer`, `create_customer_card`, `delete_customer_card`
|
|
2051
|
-
* - `create_subscription_plan`, `update_subscription_plan`
|
|
2052
|
-
* - `create_store/pos`, `update_store/pos`, `delete_store/pos`
|
|
2053
|
-
* - `create_qr_payment`, `cancel_qr_payment`
|
|
2054
|
-
* - `create_point_payment_intent`, `cancel_point_payment_intent`, `update_point_device_mode`
|
|
2055
|
-
* - OAuth: `oauth_exchange_code`, `oauth_refresh_token`
|
|
2056
|
-
* - `register_bank_account`
|
|
2057
|
-
* - `create_webhook`, `update_webhook`, `delete_webhook`
|
|
2058
|
-
*
|
|
2059
|
-
* **Read-only** tools do NOT emit audit entries (would flood the log without
|
|
2060
|
-
* value): get_*, search_*, list_*, calculate_*, validate_*, lookup_*, analyze_*.
|
|
2061
|
-
*
|
|
2062
|
-
* # PII handling
|
|
2063
|
-
*
|
|
2064
|
-
* The audit log captures `inputSummary` (a deterministic hash of the input
|
|
2065
|
-
* fields, NOT the raw input) by default. Configure `redact: false` to log
|
|
2066
|
-
* raw inputs (payer email, CUIT, etc.) — only when your data-residency
|
|
2067
|
-
* policy permits.
|
|
2068
|
-
*
|
|
2069
|
-
* # Storage
|
|
2070
|
-
*
|
|
2071
|
-
* Pluggable adapter pattern. Ships:
|
|
2072
|
-
* - `InMemoryAuditLog` — for tests + single-process demos.
|
|
2073
|
-
* - `VercelKVAuditLog` (in `/vercel-kv` subpath) — production-ready, KV-backed
|
|
2074
|
-
* with daily-bucket indexing for efficient time-range queries.
|
|
2075
|
-
*
|
|
2076
|
-
* Implement your own for Postgres / S3 / SIEM integration.
|
|
2077
|
-
*/
|
|
2078
|
-
|
|
2079
|
-
type AuditOperation = "create_payment" | "charge_saved_card" | "cancel_payment" | "capture_payment" | "refund_payment" | "create_subscription" | "cancel_subscription" | "pause_subscription" | "resume_subscription" | "update_subscription" | "subscribe_to_plan" | "create_subscription_plan" | "update_subscription_plan" | "create_order" | "capture_order" | "cancel_order" | "update_order" | "create_payment_preference" | "update_payment_preference" | "create_customer" | "update_customer" | "create_customer_card" | "delete_customer_card" | "create_store" | "update_store" | "delete_store" | "create_pos" | "update_pos" | "delete_pos" | "create_qr_payment" | "cancel_qr_payment" | "create_point_payment_intent" | "cancel_point_payment_intent" | "update_point_device_mode" | "oauth_exchange_code" | "oauth_refresh_token" | "register_bank_account" | "create_webhook" | "update_webhook" | "delete_webhook" | (string & {});
|
|
2080
|
-
interface AuditEntry {
|
|
2081
|
-
/**
|
|
2082
|
-
* Unique entry id. Format: `mpaud-{ISO date}-{random}`. Use as primary
|
|
2083
|
-
* key in your storage layer.
|
|
2084
|
-
*/
|
|
2085
|
-
id: string;
|
|
2086
|
-
/** ISO 8601 timestamp. */
|
|
2087
|
-
timestamp: string;
|
|
2088
|
-
/** The MP operation performed. */
|
|
2089
|
-
operation: AuditOperation;
|
|
2090
|
-
/**
|
|
2091
|
-
* Logical actor that initiated the call. Caller-provided. Examples:
|
|
2092
|
-
* `"agent:billing-bot"`, `"user:42"`, `"cron:daily-charge"`.
|
|
2093
|
-
*
|
|
2094
|
-
* Defaults to `"unknown"` when not provided. **Always pass this in
|
|
2095
|
-
* production** — without it, your compliance trail is meaningless.
|
|
2096
|
-
*/
|
|
2097
|
-
actor: string;
|
|
2098
|
-
/** Optional tenant/seller id for multi-tenant marketplace setups. */
|
|
2099
|
-
tenantId?: string;
|
|
2100
|
-
/**
|
|
2101
|
-
* SHA-256 hex of the meaningful input fields (deterministic). Useful as
|
|
2102
|
-
* a join key with the IdempotencyCache. Does NOT contain raw PII.
|
|
2103
|
-
*/
|
|
2104
|
-
inputHash: string;
|
|
2105
|
-
/**
|
|
2106
|
-
* Optional raw input — only populated when `redact: false` was configured.
|
|
2107
|
-
* Defaults to undefined to comply with data-minimization principles.
|
|
2108
|
-
*/
|
|
2109
|
-
inputRaw?: Record<string, unknown>;
|
|
2110
|
-
/** Outcome: success or error code. */
|
|
2111
|
-
outcome: "ok" | "error";
|
|
2112
|
-
/** Error code when `outcome === "error"`. */
|
|
2113
|
-
errorCode?: string;
|
|
2114
|
-
/** Error message when `outcome === "error"`. */
|
|
2115
|
-
errorMessage?: string;
|
|
2116
|
-
/**
|
|
2117
|
-
* MP resource id created/updated by the operation (e.g., payment id).
|
|
2118
|
-
* Allows joining audit entries to the actual MP resource.
|
|
2119
|
-
*/
|
|
2120
|
-
resourceId?: string;
|
|
2121
|
-
/** Idempotency key passed to MP (for join with MP-side dedup logs). */
|
|
2122
|
-
idempotencyKey?: string;
|
|
2123
|
-
/** Duration in ms. */
|
|
2124
|
-
durationMs?: number;
|
|
2125
|
-
/** Free-form metadata bag. */
|
|
2126
|
-
metadata?: Record<string, unknown>;
|
|
2127
|
-
}
|
|
2128
|
-
interface AuditLogAdapter {
|
|
2129
|
-
append(entry: AuditEntry): Promise<void>;
|
|
2130
|
-
/** Query a time range. Optional — implementations that don't support it can omit. */
|
|
2131
|
-
query?(filter: {
|
|
2132
|
-
actor?: string;
|
|
2133
|
-
operation?: AuditOperation;
|
|
2134
|
-
tenantId?: string;
|
|
2135
|
-
from?: string;
|
|
2136
|
-
to?: string;
|
|
2137
|
-
limit?: number;
|
|
2138
|
-
}): Promise<AuditEntry[]>;
|
|
2139
|
-
}
|
|
2140
|
-
/**
|
|
2141
|
-
* Volatile, single-process audit log. Tests + dev only. Production deployments
|
|
2142
|
-
* must use a durable adapter (`VercelKVAuditLog`, your Postgres/S3 impl, etc.)
|
|
2143
|
-
*/
|
|
2144
|
-
declare class InMemoryAuditLog implements AuditLogAdapter {
|
|
2145
|
-
private readonly entries;
|
|
2146
|
-
append(entry: AuditEntry): Promise<void>;
|
|
2147
|
-
query(filter: {
|
|
2148
|
-
actor?: string;
|
|
2149
|
-
operation?: AuditOperation;
|
|
2150
|
-
tenantId?: string;
|
|
2151
|
-
from?: string;
|
|
2152
|
-
to?: string;
|
|
2153
|
-
limit?: number;
|
|
2154
|
-
}): Promise<AuditEntry[]>;
|
|
2155
|
-
/** All entries (test helper, not part of the adapter interface). */
|
|
2156
|
-
all(): AuditEntry[];
|
|
2157
|
-
reset(): void;
|
|
2158
|
-
}
|
|
2159
|
-
/**
|
|
2160
|
-
* Audit logger — the user-facing facade that builds + ships entries.
|
|
2161
|
-
*
|
|
2162
|
-
* @example
|
|
2163
|
-
* ```ts
|
|
2164
|
-
* const audit = new AuditLogger({
|
|
2165
|
-
* adapter: new InMemoryAuditLog(),
|
|
2166
|
-
* defaultActor: "agent:billing-bot",
|
|
2167
|
-
* redact: true, // default — hashes input, no raw PII
|
|
2168
|
-
* });
|
|
2169
|
-
*
|
|
2170
|
-
* const tools = mercadoPagoTools(client, {
|
|
2171
|
-
* state, backUrl, audit,
|
|
2172
|
-
* });
|
|
2173
|
-
* ```
|
|
2174
|
-
*/
|
|
2175
|
-
declare class AuditLogger {
|
|
2176
|
-
private readonly adapter;
|
|
2177
|
-
private readonly defaultActor;
|
|
2178
|
-
private readonly redact;
|
|
2179
|
-
private readonly hash;
|
|
2180
|
-
constructor(options: {
|
|
2181
|
-
adapter: AuditLogAdapter;
|
|
2182
|
-
defaultActor?: string;
|
|
2183
|
-
redact?: boolean;
|
|
2184
|
-
/** Override hash (testing). */
|
|
2185
|
-
hashFn?: typeof sha256Hex;
|
|
2186
|
-
});
|
|
2187
|
-
/**
|
|
2188
|
-
* Wrap a tool execute() function with auto-audit. The returned function:
|
|
2189
|
-
* 1. Computes inputHash before the call.
|
|
2190
|
-
* 2. Invokes the original execute().
|
|
2191
|
-
* 3. On success, appends an entry with outcome="ok" + resourceId.
|
|
2192
|
-
* 4. On failure, appends an entry with outcome="error" + errorCode/Message.
|
|
2193
|
-
* 5. Re-throws the error transparently.
|
|
2194
|
-
*/
|
|
2195
|
-
record<I, O>(args: {
|
|
2196
|
-
operation: AuditOperation;
|
|
2197
|
-
input: I;
|
|
2198
|
-
actor?: string;
|
|
2199
|
-
tenantId?: string;
|
|
2200
|
-
idempotencyKey?: string;
|
|
2201
|
-
/**
|
|
2202
|
-
* Function that extracts the resourceId from the result. Default: tries
|
|
2203
|
-
* `result.id`, `result.payment_id`, `result.subscription_id`, `result.order_id`.
|
|
2204
|
-
*/
|
|
2205
|
-
extractResourceId?: (result: O) => string | undefined;
|
|
2206
|
-
/** The actual operation to execute. */
|
|
2207
|
-
fn: () => Promise<O>;
|
|
2208
|
-
}): Promise<O>;
|
|
2209
|
-
}
|
|
2210
|
-
|
|
2211
2094
|
interface MercadoPagoToolsOptions {
|
|
2212
2095
|
/** State adapter for persisting subscription records. */
|
|
2213
2096
|
state: SubscriptionStateAdapter;
|
|
@@ -2264,7 +2147,7 @@ interface MercadoPagoToolsOptions {
|
|
|
2264
2147
|
*/
|
|
2265
2148
|
webhookDedup?: WebhookDedup;
|
|
2266
2149
|
}
|
|
2267
|
-
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" | "find_applicable_promos" | "confirm_3ds_challenge" | "search_payments_all" | "list_settlements_all";
|
|
2150
|
+
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" | "find_applicable_promos" | "confirm_3ds_challenge" | "search_payments_all" | "list_settlements_all" | "validate_tax_id";
|
|
2268
2151
|
/**
|
|
2269
2152
|
* Build a tool set for the Vercel AI SDK that exposes Mercado Pago to an
|
|
2270
2153
|
* agent. Pass directly to `Experimental_Agent`'s `tools` option, or merge with
|
|
@@ -2952,6 +2835,199 @@ declare function findApplicablePromos(args: {
|
|
|
2952
2835
|
includeAhoraProgram?: boolean;
|
|
2953
2836
|
}): CuotasPromo[];
|
|
2954
2837
|
|
|
2838
|
+
/**
|
|
2839
|
+
* Tool middleware — composable wrappers around any Vercel AI SDK tool.
|
|
2840
|
+
*
|
|
2841
|
+
* # The pattern
|
|
2842
|
+
*
|
|
2843
|
+
* Vercel AI SDK tools have a uniform shape: `{ description, inputSchema, execute }`.
|
|
2844
|
+
* Middleware wraps a tool's `execute()` with cross-cutting concerns (logging,
|
|
2845
|
+
* rate limiting, retries, metrics) WITHOUT modifying the tool itself.
|
|
2846
|
+
*
|
|
2847
|
+
* Compose middleware to layer behaviors:
|
|
2848
|
+
*
|
|
2849
|
+
* ```ts
|
|
2850
|
+
* import { withAuditLog, withRateLimit, withMetrics, compose } from "@ar-agents/mercadopago";
|
|
2851
|
+
*
|
|
2852
|
+
* const baseTools = mercadoPagoTools(client, { state, backUrl });
|
|
2853
|
+
*
|
|
2854
|
+
* const tools = Object.fromEntries(
|
|
2855
|
+
* Object.entries(baseTools).map(([name, tool]) => [
|
|
2856
|
+
* name,
|
|
2857
|
+
* compose(
|
|
2858
|
+
* withMetrics(name, { onMetric: (m) => statsd.increment(...) }),
|
|
2859
|
+
* withRateLimit(rateLimiter),
|
|
2860
|
+
* withAuditLog(auditLogger, name),
|
|
2861
|
+
* )(tool),
|
|
2862
|
+
* ])
|
|
2863
|
+
* );
|
|
2864
|
+
* ```
|
|
2865
|
+
*
|
|
2866
|
+
* # Why this matters
|
|
2867
|
+
*
|
|
2868
|
+
* Without middleware, every cross-cutting concern (audit, rate limit, retry)
|
|
2869
|
+
* has to be wired INTO the tool implementation OR repeated at every call
|
|
2870
|
+
* site. Middleware lets you add/remove/swap concerns from a single config
|
|
2871
|
+
* point — clean separation of concerns + testable in isolation.
|
|
2872
|
+
*/
|
|
2873
|
+
|
|
2874
|
+
/**
|
|
2875
|
+
* A tool middleware — takes a tool, returns a wrapped tool with the same
|
|
2876
|
+
* shape but enhanced behavior in `execute()`.
|
|
2877
|
+
*/
|
|
2878
|
+
type ToolMiddleware = <T extends Tool<unknown, unknown>>(tool: T) => T;
|
|
2879
|
+
/**
|
|
2880
|
+
* Compose multiple middleware functions. The LAST middleware in the list
|
|
2881
|
+
* runs INNERMOST (closest to the original tool's execute):
|
|
2882
|
+
*
|
|
2883
|
+
* ```
|
|
2884
|
+
* compose(a, b, c)(tool) == a(b(c(tool)))
|
|
2885
|
+
* ```
|
|
2886
|
+
*
|
|
2887
|
+
* Reasoning: the most "core" concerns (e.g. audit log) typically wrap the
|
|
2888
|
+
* actual call closely (innermost), while observability layers (e.g. metrics,
|
|
2889
|
+
* tracing) sit outside.
|
|
2890
|
+
*
|
|
2891
|
+
* @example
|
|
2892
|
+
* ```ts
|
|
2893
|
+
* const enhance = compose(
|
|
2894
|
+
* withMetrics("create_payment"), // outer (records duration of everything below)
|
|
2895
|
+
* withRateLimit(limiter), // middle (rate-limits before the call)
|
|
2896
|
+
* withAuditLog(audit, "create_payment"), // inner (records the call result)
|
|
2897
|
+
* );
|
|
2898
|
+
* const enhanced = enhance(originalTool);
|
|
2899
|
+
* ```
|
|
2900
|
+
*/
|
|
2901
|
+
declare function compose(...middlewares: ToolMiddleware[]): ToolMiddleware;
|
|
2902
|
+
/**
|
|
2903
|
+
* Wrap a tool's `execute()` with audit logging. Every call records an entry
|
|
2904
|
+
* with operation, actor, inputHash, outcome, and duration.
|
|
2905
|
+
*
|
|
2906
|
+
* @param logger The configured AuditLogger.
|
|
2907
|
+
* @param operation The operation name (matches AuditOperation union).
|
|
2908
|
+
* @param actor Optional actor override (defaults to logger's defaultActor).
|
|
2909
|
+
*/
|
|
2910
|
+
declare function withAuditLog(logger: AuditLogger, operation: AuditOperation, actor?: string): ToolMiddleware;
|
|
2911
|
+
/**
|
|
2912
|
+
* Wrap a tool's `execute()` with rate limiting. Acquires a token from the
|
|
2913
|
+
* bucket BEFORE the call; if the bucket is empty, awaits up to the bucket's
|
|
2914
|
+
* `acquireTimeoutMs`. Throws `RateLimitTimeoutError` if the wait exceeds it.
|
|
2915
|
+
*/
|
|
2916
|
+
declare function withRateLimit(limiter: TokenBucketRateLimiter): ToolMiddleware;
|
|
2917
|
+
interface MetricsHook {
|
|
2918
|
+
/**
|
|
2919
|
+
* Called after every tool invocation. Synchronous, fire-and-forget.
|
|
2920
|
+
* Compatible with Datadog, StatsD, Prometheus client, OTEL meter, etc.
|
|
2921
|
+
*/
|
|
2922
|
+
onMetric: (event: {
|
|
2923
|
+
toolName: string;
|
|
2924
|
+
durationMs: number;
|
|
2925
|
+
success: boolean;
|
|
2926
|
+
errorCode?: string;
|
|
2927
|
+
}) => void;
|
|
2928
|
+
}
|
|
2929
|
+
/**
|
|
2930
|
+
* Wrap a tool's `execute()` with metrics emission. Records duration + a
|
|
2931
|
+
* success/error counter for every call.
|
|
2932
|
+
*/
|
|
2933
|
+
declare function withMetrics(toolName: string, hook: MetricsHook): ToolMiddleware;
|
|
2934
|
+
interface RetryOptions {
|
|
2935
|
+
/** Max attempts including initial. Default 3. */
|
|
2936
|
+
maxAttempts?: number;
|
|
2937
|
+
/** Base backoff in ms (multiplied by 2^attempt). Default 250. */
|
|
2938
|
+
baseBackoffMs?: number;
|
|
2939
|
+
/**
|
|
2940
|
+
* Predicate: should this error trigger a retry? Default: retries on
|
|
2941
|
+
* any thrown Error EXCEPT MercadoPagoError 4xx (those are user errors).
|
|
2942
|
+
*/
|
|
2943
|
+
shouldRetry?: (err: unknown, attempt: number) => boolean;
|
|
2944
|
+
/** Optional hook fired on every retry attempt. */
|
|
2945
|
+
onRetry?: (event: {
|
|
2946
|
+
attempt: number;
|
|
2947
|
+
error: unknown;
|
|
2948
|
+
delayMs: number;
|
|
2949
|
+
}) => void;
|
|
2950
|
+
}
|
|
2951
|
+
/**
|
|
2952
|
+
* Wrap a tool's `execute()` with retry-with-backoff. Useful for tools that
|
|
2953
|
+
* call external APIs not protected by the underlying client's retry budget
|
|
2954
|
+
* (e.g., agent-side aggregation tools).
|
|
2955
|
+
*
|
|
2956
|
+
* The MercadoPagoClient already retries internally on 5xx/429, so layering
|
|
2957
|
+
* this on top of MP-backed tools usually means total retries = client × tool.
|
|
2958
|
+
* Use sparingly.
|
|
2959
|
+
*/
|
|
2960
|
+
declare function withRetry(opts?: RetryOptions): ToolMiddleware;
|
|
2961
|
+
/**
|
|
2962
|
+
* Apply a middleware to every tool in a ToolSet. Useful for blanket policies:
|
|
2963
|
+
* "all tools rate-limited", "all tools metrics-emitted".
|
|
2964
|
+
*
|
|
2965
|
+
* @example
|
|
2966
|
+
* ```ts
|
|
2967
|
+
* const baseTools = mercadoPagoTools(client, { state, backUrl });
|
|
2968
|
+
* const limited = applyToAllTools(baseTools, withRateLimit(limiter));
|
|
2969
|
+
* ```
|
|
2970
|
+
*/
|
|
2971
|
+
declare function applyToAllTools<T extends Record<string, Tool<unknown, unknown>>>(tools: T, middleware: ToolMiddleware): T;
|
|
2972
|
+
|
|
2973
|
+
/**
|
|
2974
|
+
* TaxID validation across LATAM — pure-algorithm validators for the major
|
|
2975
|
+
* jurisdictions where MP operates. NO network calls.
|
|
2976
|
+
*
|
|
2977
|
+
* # Why
|
|
2978
|
+
*
|
|
2979
|
+
* Marketplace-style apps that span multiple LATAM countries need to
|
|
2980
|
+
* validate buyer/seller tax IDs in their respective formats: AR (DNI/CUIT/CUIL),
|
|
2981
|
+
* BR (CPF/CNPJ), MX (RFC), CL (RUT), CO (NIT), UY (RUT), PE (RUC).
|
|
2982
|
+
*
|
|
2983
|
+
* Each country has its own checksum algorithm. Wiring this once per app
|
|
2984
|
+
* is annoying + error-prone. Embedding it here means the agent can
|
|
2985
|
+
* validate ANY LATAM tax ID with a single tool call.
|
|
2986
|
+
*
|
|
2987
|
+
* # Sources
|
|
2988
|
+
*
|
|
2989
|
+
* - AR DNI/CUIT/CUIL: AFIP RG 100/1998 (modulo-11 checksum)
|
|
2990
|
+
* - BR CPF: Receita Federal (two-step modulo-11)
|
|
2991
|
+
* - BR CNPJ: Receita Federal (two-step weighted modulo)
|
|
2992
|
+
* - MX RFC: SAT regex + 13-char structure
|
|
2993
|
+
* - CL RUT: SII modulo-11 + check digit "0-9, K"
|
|
2994
|
+
* - CO NIT: DIAN modulo-11
|
|
2995
|
+
* - UY RUT: 12-digit numeric + checksum
|
|
2996
|
+
* - PE RUC: SUNAT 11-digit + checksum
|
|
2997
|
+
*/
|
|
2998
|
+
type TaxIdCountry = "AR" | "BR" | "MX" | "CL" | "CO" | "UY" | "PE";
|
|
2999
|
+
type TaxIdType = "DNI" | "CUIT" | "CUIL" | "CPF" | "CNPJ" | "RFC" | "RUT_CL" | "NIT" | "RUT_UY" | "RUC";
|
|
3000
|
+
interface TaxIdValidationResult {
|
|
3001
|
+
valid: boolean;
|
|
3002
|
+
/** Bare digits/chars after normalization (no separators). */
|
|
3003
|
+
normalized: string;
|
|
3004
|
+
/** Pretty-formatted version with country-specific separators. */
|
|
3005
|
+
formatted: string | null;
|
|
3006
|
+
type: TaxIdType;
|
|
3007
|
+
country: TaxIdCountry;
|
|
3008
|
+
/** Spanish error message when invalid. Surface verbatim to users. */
|
|
3009
|
+
error: string | null;
|
|
3010
|
+
}
|
|
3011
|
+
/**
|
|
3012
|
+
* Validate a tax ID against the appropriate country algorithm.
|
|
3013
|
+
*
|
|
3014
|
+
* @example
|
|
3015
|
+
* validateTaxId("20-41758101-5", "CUIT")
|
|
3016
|
+
* // → { valid: true, normalized: "20417581015", formatted: "20-41758101-5", ... }
|
|
3017
|
+
*
|
|
3018
|
+
* @example
|
|
3019
|
+
* validateTaxId("123.456.789-09", "CPF")
|
|
3020
|
+
* // → { valid: true, normalized: "12345678909", ... }
|
|
3021
|
+
*/
|
|
3022
|
+
declare function validateTaxId(input: string, type: TaxIdType): TaxIdValidationResult;
|
|
3023
|
+
/**
|
|
3024
|
+
* Convenience: try to detect the type from the input shape + country, then
|
|
3025
|
+
* validate. Useful when the agent doesn't know if it's a CPF or a CNPJ.
|
|
3026
|
+
*
|
|
3027
|
+
* @returns null when the input doesn't match any known type for the country
|
|
3028
|
+
*/
|
|
3029
|
+
declare function detectAndValidate(input: string, country: TaxIdCountry): TaxIdValidationResult | null;
|
|
3030
|
+
|
|
2955
3031
|
/**
|
|
2956
3032
|
* Pure helpers — no I/O, deterministic, fast. Importable directly from the
|
|
2957
3033
|
* package root or used via the agent tools (`compute_marketplace_fee`,
|
|
@@ -3017,4 +3093,4 @@ interface PaymentStatusExplanation {
|
|
|
3017
3093
|
*/
|
|
3018
3094
|
declare function explainPaymentStatus(payment: Payment): PaymentStatusExplanation;
|
|
3019
3095
|
|
|
3020
|
-
export { AHORA_PROGRAM_PROMOS, AR_ISSUER_PROMOS, type AccountBalance, type AccountInfo, type AccountMovement,
|
|
3096
|
+
export { AHORA_PROGRAM_PROMOS, AR_ISSUER_PROMOS, type AccountBalance, type AccountInfo, type AccountMovement, AuditLogger, AuditOperation, 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 CuotasPromo, type CurrencyId, type Customer, type CustomerCard, type DedupResult, type Dispute, type FrequencyType, IdempotencyCache, 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 MetricsHook, type OAuthToken, type Order, type OrderItem, type OrderStatus, type PaginateOptions, 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, RateLimitTimeoutError, type RateLimiterOptions, type Refund, type RetryOptions, type SearchPaymentsParams, type Settlement, type SiteId, type Store, type SubscriptionPayment, type SubscriptionPlan, SubscriptionStateAdapter, TEST_CARDS_AR, TEST_PAYERS_AR, type TaxIdCountry, type TaxIdType, type TaxIdValidationResult, type TestCard, type ThreeDSInfo, type ThreeDSStatus, TokenBucketRateLimiter, type ToolMiddleware, type WebhookBody, type WebhookConfig, WebhookDedup, type WebhookDedupOptions, type WebhookTopic, analyze3DS, applyToAllTools, buildAuthorizeUrl, buildTestCardScenario, classifyError, collect, compose, computeMarketplaceFee, confirmChallengeAndPoll, detectAndValidate, exchangeCodeForToken, expirationTimeMs, explainPaymentStatus, findApplicablePromos, isExpiringSoon, mercadoPagoTools, paginate, paginateAccountMovements, paginateMerchantOrders, paginatePayments, paginateSettlements, paginateSubscriptionPayments, paginateSubscriptionPlans, paginateSubscriptions, parseWebhookEvent, refreshAccessToken, validateTaxId, verifyWebhookSignature, withAuditLog, withMetrics, withRateLimit, withRetry };
|