Skip to main content
Glama

x402-trinity

A drop-in fetch replacement that lets an AI agent pay for things by itself — with hard spending limits, no hosted wallet service, and no changes to the agent's own code.

Zero runtime dependencies. 7 KB gzipped. Buyer and seller in TypeScript; buyer in Python.

npm install x402-trinity

Why

When an agent hits a paid resource it gets 402 Payment Required. Without something to handle that, the request simply fails.

x402-trinity handles it: reads the challenge, checks it against limits you set, signs, retries. All of it locally — no hosted wallet service, no third-party API, and the key never leaves your process.

Gas exists but the payer doesn't pay it — under EIP-3009 the facilitator submits the transfer, so an agent's wallet only ever needs USDC.


Related MCP server: remit.md MCP Server

Buy (agent pays for things)

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

Or patch the global so unmodified code pays automatically:

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

Confirm which wallet will pay before funding anything:

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

It prints the address and its balance on every chain, and never prints the key. If the address is not the wallet you meant, stop before sending anything.

Sell (charge for a resource, get paid)

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) });

Both required fields are deliberate. There is no default facilitator because settling is someone's real money and guessing an endpoint is not a default. And the replay guard has to outlive the process: an in-memory one forgets every settled payment on restart, so a buyer could re-present a spent authorization and get the resource again for free. The constructor throws rather than let either be implicit.

The seller never holds a private key and never touches funds. It quotes a price and asks a facilitator to verify and settle; money moves buyer → you directly on-chain.

This release ships Base + USDC only. Any other EVM chain works through customChains; your address is the same on all of them.


What it does

Protocols

x402 v1 and v2, detected per response. Unknown versions and MPP challenges declined with a clear reason, never guessed

Chains

Base mainnet + USDC, shipped as the default. Any other EVM chain via customChains

Networks

short names and CAIP-2 (eip155:8453)

Custody

privateKey, additive shards, or remoteSign (HSM/MPC) — your choice, not the architecture's

Speed

3.2 µs warm / 1.0 ms cold (TypeScript); 1.2 µs / 1.7 ms (Python)

Runtime

auto-detects Cloudflare Workers and changes strategy; also Node, Bun, Deno

Safety

mandatory caps, allowlists, never-pay-twice reconciliation, timing-hardened signing

Another chain

Base is the default. The signing is chain-agnostic, so add whatever you need — including a testnet to rehearse on:

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

Verify the entry against the deployed contract first: call DOMAIN_SEPARATOR() and check it equals what this library computes. A wrong name or version produces a signature that looks valid and the contract rejects.

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 · guess at a protocol it doesn't speak.


Safety — read this before real money

Caps are mandatory. maxAmountPerRequest and totalBudget have no defaults; the wrapper refuses to construct without them. An auto-payer without limits is a money leak controlled by whoever runs the server.

totalBudget alone is per-instance. It is an in-memory counter that resets on restart, on a new client, and on every Cloudflare Worker isolate — which is per request. On mainnet that turns a lifetime cap into a per-request cap. Mainnet therefore requires a durable budgetStore, or an explicit acknowledgeEphemeralBudget: true:

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

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

The key is in the process. That is the trade for having no hosted signer. Bound it: use a dedicated wallet holding only what you would accept losing, set allowPayTo so an exfiltrated key still cannot pay a stranger through this wrapper, and use remoteSign if you need enclave-grade custody.

Timing hardening is hardening, not a proof. Secret scalars use blinding plus always-add-and-double, which cut the timing spread from 99.6% to 12% (Python: 99.9% → 1.1%). BigInt arithmetic is itself variable-time and no pure-JS implementation removes that.


MCP server — give an agent a wallet

MCP is how an assistant gets tools. This exposes three:

tool

check_price

what a resource costs, without paying

pay_and_fetch

fetch it, paying if it is within your limits

wallet_status

address, balance, spent, remaining

{
  "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"
      }
    }
  }
}

A model decides when these run. It cannot be reasoned with about budgets, and a paywalled page can claim any price it likes. So the limits are not parameters the model can set — they come from the environment, and the server refuses to start without X402_PRIVATE_KEY, X402_MAX_PER_REQUEST and X402_TOTAL_BUDGET.

Set X402_BUDGET_FILE too, or the lifetime ceiling resets every restart. Set X402_ALLOW_HOSTS and nothing else can be paid, however convincing the challenge looks. Use a wallet holding only what you would accept losing.


Python

Same protocol, standard library only. Buyer only — to charge for a resource, use the TypeScript seller. Aimed at long-lived processes: on-body agents, robotics controllers, harvesting scripts.

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()

Or as a decorator, so payment-unaware code just works:

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()

The warm path is 1.1 µs — a long-lived controller is warm after its first payment.


Development

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

esbuild, typescript and wrangler are dev dependencies only, used for building. The shipped package has zero runtime dependencies.

License

Business Source License 1.1. The source is open to read, modify and use non-commercially; production use is granted except as a hosted or managed service offering its functionality to third parties. It converts to MIT on 2029-08-25. See LICENSE.

This software moves money — read the additional notice there, and set your spending caps.

Convenience fee: 0.1% per transaction and 1 cent every 100 transactions.

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

  • F
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to access paid content by integrating cryptocurrency payments through the x402 protocol, allowing LLMs to verify payments and retrieve paid resources automatically.
    1
    -
  • 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.
    8 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
    40 npm
    2
    -