Skip to main content
Glama

x402-trinity

Un reemplazo total de fetch que permite a un agente de IA pagar por las cosas por sí solo — con límites de gasto estrictos, sin servicio de cartera alojado y sin cambios en el código del propio agente.

Cero dependencias en tiempo de ejecución. 7 KB comprimidos con gzip. Comprador y vendedor en TypeScript; comprador en Python.

npm install x402-trinity

Por qué

Cuando un agente se topa con un recurso de pago recibe 402 Payment Required. Sin algo que lo gestione, la solicitud simplemente falla.

x402-trinity se encarga de ello: lee el desafío, lo verifica contra los límites que tú estableces, firma y reintenta. Todo de manera local — sin servicio de cartera alojado, sin API de terceros, y con la clave que nunca sale de tu proceso.

El gas existe, pero el pagador no lo paga: mediante EIP-3009, el facilitador presenta la transferencia, de modo que la cartera del agente solo necesita USDC.


Related MCP server: HTTPayer MCP

Compra (el agente paga por las cosas)

import { createX402Fetch } from 'x402-trinity';

const x402Fetch = createX402Fetch({
  privateKey: process.env.X402_PRIVATE_KEY,   // never hardcode
  policy: {
    maxAmountPerRequest: '5000',              // 0.005 USDC max per call  (REQUIRED)
    totalBudget: '1000000',                   // 1.00 USDC lifetime       (REQUIRED)
    allowHosts: ['api.example.com'],
    allowPayTo: ['0x...'],
  },
});

const r = await x402Fetch('https://api.example.com/data');   // 402 handled, returns 200

O parchea el ámbito global para que el código no modificado pague automáticamente:

import { installX402 } from 'x402-trinity';
const uninstall = installX402(cfg);   // globalThis.fetch now pays 402s

Confirma qué cartera va a pagar antes de financiar nada:

X402_PRIVATE_KEY=0x... npx x402-trinity-whoami

Imprime la dirección y su saldo en cada cadena, y nunca imprime la clave. Si la dirección no es la cartera que querías, detente antes de enviar cualquier cosa.

Vender (cobra, por un recurso, y recibe el pago)

import { createX402Seller } from 'x402-trinity/seller';
import { createFileNonceStore } from 'x402-trinity/budget-file';

const seller = createX402Seller({
  payTo: '0xYourWallet',      // 100% of every payment lands here
  price: '10000',             // 0.01 USDC, atomic units
  network: 'base',
  facilitator: 'https://your-facilitator.example',   // REQUIRED — no default exists
  nonceStore: createFileNonceStore('./.x402-nonces.json'),  // REQUIRED — see below
});

// in any fetch-style handler:
const gate = await seller.guard(request);
if (gate.response) return gate.response;          // unpaid or refused — hand back the 402
return new Response(yourData, { headers: seller.receiptHeader(gate.settlement) });

Los dos campos obligatorios son deliberados. No hay un facilitador por defecto porque la liquidación es el dinero real de alguien, y adivinar un endpoint no puede ser una opción por defecto. La protección contra ataques de repetición tiene además que sobrevivir al proceso: en memoria, olvida cada pago ya liquidado al reiniciar, así que el comprador podría volver a presentar una autorización ya gastada y llevarse el recurso otra vez gratis. Le constructor lanza una excepción en lugar de permitir que cualquiera de las dos cosas quede implícita.

Esta versión solo incluye Base + USDC. Cualquier otra cadena compatible con EVM funciona a través de customChains; tu dirección es la misma en todas.


Qué hace

Protocols

protocolos x402 v1 y v2, detectados por red. Los que no conoce se declinan con claridad, nunca se adivinan

Chains

Base mainnet y USDC, incluidos como los predeterminados. El resto de cadenas EVM se agregan por customChains

Networks

nombres cortos y CAIP-2 (eip155:8453)

Signature

privateKey o remoteSign (HSM/MPC), e incluso shards; tú usas la tuya, no la que dicta la arquitectura

Speed

3.2 µs en caliente / 1.0 ms frío (TypeScript) · 1.2 µs / 1.7 ms (Python)

Runtime

auto-detecta Cloudflare Workers y cambia la estrategia; también Node, Bun, Deno

Safety

topes obligatorios, whitelists, reconciliación para nunca pagar dos veces, firma endurecida contra ataques de tiempo

Otra cadena

Base es la opción por defecto. La firma no depende de la cadena, así que añade todo lo que necesites — incluso una red de pruebas para ensayar:

const fetch2 = createX402Fetch({
  privateKey: process.env.X402_PRIVATE_KEY,
  maxAmountPerRequest: '10000',
  totalBudget: '100000',
  customChains: {
    'base-sepolia': { id: 84532, asset: '0x036cbd53842c5426634e7929541ec2318f3dcf7e', name: 'USDC', version: '2' },
  },
});

Verifica antes la entrada contra el contrato ya desplegado: llama a DOMAIN_SEPARATOR() y comprueba que coincide con lo que esta biblioteca calcula. Un name o version erróneos producen una firma que parece válida… y el contrato la detecta.

Lo que deliberadamente no hará

Broadcast a una chain · dar un recibo · "gasless" por el gas (el retador vive en la red) · … no, mejor con texto plano: no va a retransmitir, no custodia fondos, no necesita gas mismo puede pedir, no acepta un bono… – qué será: no operar en cadenas externalizadas, pero sí: the sentence is:

It deliberately will not: broadcast to a chain, hold funds, need gas or an RPC, take a cut of a payment (structurally impossible — EIP-3009 has one recipient), require a hosted signer, pay without limits, or guess at a protocol it doesn't speak.

En español:

Deliberadamente no hará lo siguiente

Transmitir a una cadena · custodiar fondos · necesitar gas o un RPC · quedarse con una parte del e pago (estructuralmente imposible — EIP-3009 tiene un solo beneficiario) · exigir un firmante alojado ·osegurar pagos sin límites · adivinar un protocolo que se no hable.


Seguridad — lee esto antes de usar dinero real dinero

Los límites son obligatorios. maxAmountPerRequest y `totalBudgetirú no tienen valor por defecto; el wrapper se niega a construirse sin ellos. Un pagador automático sin limitaciones es una fuga de dinero a cargo de quien controle el servidor.

totalBudget solo vale por instancia. Es un contador en memoria que se resetea al reiniciar el proceso, al crearte un cliente nuevo y en cada aislado de Cloudflare Workers — unpoco de cada solicitud. En mainnet, eso convierte un límite de por vida en un límite por petición. Por eso, en mainnet se necesita un budgetStore persistente, o bien una aceptación explícita de acknowledgeEphemeralBudget: true:

import { createFileBudgetStore } from 'x402-trinity/budget-file';

createX402Fetch({
  ...,
  budgetStore: createFileBudgetStore('./.x402-budget.json'),   // survives restarts
});

**Custodia del pago.If the key is in the process, esa es la concesión de no tener un firmador alojado. Limitar los daños: usa una cartera dedicada que solo contenga lo que acepta perder, establece allowPayTo para que una clave exfiltrada no pueda pagar a un desconocido por este envoltorio, y remite a remoteSign si necesitas una custodia a nivel de recinto.

La arquitectura de tiempo es eso: una defensa, no es una herramienta. Los escalares secretos usan ofuscación y siempre suman dobles, lo que reduce la muestra de tiempo del 99.6% al 12% (Python, del 99.9% al 1.1%).t; but la aritmética BigInt es de por sí de tiempo variable.


Servidor MCP — dale un inicio a un agente un

MCP es la forma en que un asistente al

herramienta

check_price

cuál es el precio de un recurso, sin pagarlo

pay_and_fetch

y lo lee fuera con

wallet_status

dirección, saldo, gastado, restante

{
  "mcpServers": {
    "x402-trinity": {
      "command": "npx",
      "args": ["-y", "x402-trinity-mcp"],
      "env": {
        "X402_PRIVATE_KEY": "0x...",
        "X402_MAX_PER_REQUEST": "50000",
        "X402_TOTAL_BUDGET": "1000000",
        "X402_BUDGET_FILE": "./.x402-budget.json",
        "X402_ALLOW_HOSTS": "api.example.com",
        "X402_NETWORKS": "base"
      }
    }
  }
}

El modelo decide si se ejecutan con él. un supuesto presupuesto no se puede razonar: una web de pago puede declarar el precio que quiera. El límite, por tanto, no es son parámetros que the model set: provienen del entorno, y el servidor se niega a arrancar si no están X402_PRIVATE_KEY, X402_MAX_PER_REQUEST y no X402_TOTAL_BUDGET.

Configura también X402_BUDGET_FILE, o el límite de por vida se reiniciosobre cada reinicio. Definir un X402_ALLOW_HOSTS y nada más puede ser pagado:aunque el desafío provenga de qualquerón. Usa un el monedero dedicado.


Python

Mismo protocolo, solo biblioteca optimizada. Solo comprador — para cobrar por vender un recurso usa el vendedor TypeScript. Diseñado para procesos de larga vida: agentes personales, controladores de robótica, copias de seguridad.

from x402_trinity import X402Client, Policy

client = X402Client(
    private_key=os.environ["X402_PRIVATE_KEY"],
    policy=Policy(max_amount_per_request=5000, total_budget=1_000_000,
                  allow_hosts=["api.example.com"]),
)
body = client.urlopen("https://api.example.com/data").read()

Para usarlo como decorador:

from x402_trinity import x402_telemetry

@x402_telemetry(private_key=KEY, policy=Policy(...))
def harvest():
    return urllib.request.urlopen("https://sensor.local/v1/lidar").read()

La vía cálida es 1.1 µs — el controlador de un proceso de larga vida queda en forma desde la primera transacción.


Desarrollo

npm install
npm run build        # dist/*.js + *.min.js + *.d.ts

esbuild, typescript y wrangler son solo para extender el proyecto y no formas parte del entorno en tiempo de ejecución. El paquete resultante no tiene dependencias.

Licencia

MIT. Este software mueve dinero real, preste atención al aviso adicional LICENSE y define con dinero tus límites —tope máximo de validez**.

Available Tools

3 tools
check_priceA

Look at what a paid resource costs WITHOUT paying for it. Fetches the URL, and if it answers 402 Payment Required, reports the price, recipient, chain and whether it falls within the configured spending limits. Use this before pay_and_fetch when the cost matters, or to check whether a URL is paywalled at all.

ParametersJSON Schema
NameRequiredDescriptionDefault
urlYesThe resource to price. Must be http(s).

TDQS

A4.4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden and does well: it discloses the no-payment guarantee, the trigger condition (HTTP 402), and what gets reported (price, recipient, chain, spending-limit check). The remaining gap is behavior for non-402 responses (e.g., a 200 that is not paywalled) and any auth/rate-limit constraints, which are left unstated.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three tightly written sentences, front-loaded with the core purpose and the key constraint ('WITHOUT paying'), followed by behavior and routing guidance. No sentence is filler.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a one-parameter tool with no annotations and no output schema, the description is nearly self-sufficient: it explains the trigger, the returned fields, and when to prefer the sibling. It only falls short on the non-402 return path, which an agent would otherwise have to discover empirically.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100% and the single url parameter is already documented as http(s) in the schema. The description adds no syntax or format detail beyond what the schema provides, so the baseline 3 applies.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb+resource ('look at what a paid resource costs') with a sharp scope qualifier ('WITHOUT paying for it'). It explicitly distinguishes itself from the sibling pay_and_fetch, so an agent can route correctly without opening any schema.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Gives an explicit when-to-use rule ('before pay_and_fetch when the cost matters') and a second distinct condition ('to check whether a URL is paywalled at all'). The alternative is named, not merely implied.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

pay_and_fetchA

Fetch a resource, paying automatically if it answers 402 Payment Required. THIS SPENDS REAL MONEY from the configured wallet. The payment is refused unless it is within the per-request cap, the remaining lifetime budget, the allowed hosts and the allowed chains - those limits are set by the operator and cannot be raised from here. If a resource is not paywalled it is simply fetched, costing nothing.

ParametersJSON Schema
NameRequiredDescriptionDefault
urlYesThe resource to fetch. Must be http(s).
methodNoHTTP method. Default GET.
max_response_charsNoTruncate the body to this length. Default 20000.

TDQS

A4.4/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden and does so well: it warns that real money is spent, that payment is gated by per-request cap, lifetime budget, allowed hosts and chains, that these limits are operator-set and cannot be raised, and that non-paywalled resources cost nothing. This is exactly the behavioral context an agent needs before invoking a spending tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The most important fact — that this spends real money — is front-loaded in the second sentence, and every remaining sentence adds a distinct constraint or edge case without repetition.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a 3-parameter, no-output-schema tool this covers purpose, cost, and gating limits thoroughly. It could say a little more about what happens on payment refusal or failure (error vs. partial fetch), which is the only remaining gap.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so url, method and max_response_chars are already documented in the schema. The description adds no parameter-level meaning (e.g., unit or format of max_response_chars), so the baseline 3 applies.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb (fetch) and resource, plus the distinctive behavior (automatic payment on HTTP 402). It is immediately distinguishable from siblings check_price and wallet_status, which do not fetch.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Gives clear context for use: fetch a resource and pay only if it is paywalled. It does not explicitly route the agent to check_price or wallet_status first, nor state when-not to use it, so it falls short of a 5.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

wallet_statusA

Report the paying wallet: its address, its on-chain USDC balance, how much has been spent so far and how much of the budget remains. Reads only - never moves money and never reveals the private key.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full behavioral burden and does well: it states that it reads only, never moves money, and never reveals the private key, which is exactly the safety surface an agent needs for a wallet tool. It stops short of disclosing freshness/caching of the on-chain balance or error conditions (e.g., unreachable RPC).

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences with no filler. The returned fields are front-loaded and the safety caveat is placed last as a short, high-value clause; every clause earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

With no output schema and no parameters, the description is the only source of return information and it enumerates the four returned values well, which is sufficient. Minor gap: nothing is said about whether the balance is a fresh on-chain read or cached, which matters for a wallet-balance tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool takes zero parameters, so there is nothing for the description to disambiguate; the baseline of 4 applies. The description correctly adds no parameter discussion because none is needed.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Specific verb ('Report') plus a precisely named resource ('the paying wallet') and an explicit enumeration of what is reported: address, on-chain USDC balance, spent amount, remaining budget. The read-only framing also distinguishes it from the sibling pay_and_fetch, which by name moves money.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Usage is only implied: an agent can infer this is the tool to call before paying to check budget, but the description never states when to use it or names an alternative. No prerequisites or sequencing relative to pay_and_fetch are given, so the routing is left to inference.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 3 tool updatesv0.2.1
    • First observedcheck_price
    • First observedpay_and_fetch
    • First observedwallet_status

TDQS

A4.4/5.0

Scored across 3 tools

Disambiguation5/5

Each tool has a clearly distinct role: check_price only reads cost, pay_and_fetch performs payment, wallet_status reports wallet state. Descriptions explicitly cross-reference (use check_price before pay_and_fetch) and there is no overlap.

Naming Consistency5/5

All three names use a consistent snake_case verb_noun pattern (check_price, pay_and_fetch, wallet_status) that reads naturally and follows one convention throughout.

Tool Count4/5

Three tools is a tight, well-scoped surface for a pay-per-fetch wallet server, with each tool earning its place. It is on the lean side but nothing is missing that would bloat the scope.

Completeness4/5

The core lifecycle is covered: inspect price, authorize/pay, and check wallet budget/balance. Minor gaps exist, such as viewing payment history or a dry-run of a specific payment, but agents can work around these.

Maintenance

ActivityMaintained
ResponsivenessWithin a week

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    F
    maintenance
    Enables AI agents to perform financial transactions such as direct payments, escrows, and bounty management using natural language with zero code integration. It provides a comprehensive suite of tools for fund streaming, subscriptions, and reputation tracking to facilitate secure agent-to-agent commerce.
    11 npm
    MIT
  • A
    license
    A
    quality
    D
    maintenance
    Enables AI agents to call x402-gated APIs using a central credit balance, abstracting away blockchain complexity and payment proofs. It provides tools to fetch data from payment-required endpoints, check usage balances, and simulate transaction costs.
    6
    48 npm
    2
    -