Skip to main content
Glama

x402-trinity

一个能直接替换 fetch 的库,让 AI 智能体自己为商品付款——带有硬性支出限额、无需托管钱包服务,并且不需要改动智能体自身的代码。

零运行时依赖。gzip 后 7 KB。买方和卖方都用 TypeScript 实现;买方另有 Python 版本。

npm install x402-trinity

为什么

当智能体遇到付费资源时,会收到 402 Payment Required。如果没有相应处理,请求就直接失败了。

x402-trinity 会处理它:读取 challenge,对照你设定的限度检查,签名,重试。这一切都在本地完成——无需托管钱包服务,没有第三方 API,私钥也永远不会离开你的进程。

Gas 确实存在,但付款方不必支付它——根据 EIP-3009,由 facilitator 提交转账,所以智能体的钱包只需要持有 USDC。


Related MCP server: HTTPayer MCP

购买(AI 代理为物品付费)

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

或者对全局对象打补丁,让未修改的代码也能自动付费:

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

在注入资金之前,先确认哪个钱包会付款:

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

这串命令会打印地址以及它在每条链上的余额,并且永远不打印密钥。如果这个地址不是你想要的钱包,发任何币之前先停下来。

出售(对某个资源收费并获得付款)

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

这两个必填字段都是有意设计的。对于 facilitator,没有默认值,因为结算涉及的是某个人的真实资金,而且猜测一个接口端点不能作为默认行为。重放防护也必须比进程生存得更久:内存形式的防护会在重启后忘记所有已结算的付款,因此买方可以重新出示一张已经用过的授权,再次免费获得资源。构造函数会在任一字段模糊不清时直接抛出错误。

卖方从不持有私钥,也从不触碰资金。它开出价格,然后请求一个 facilitator 来验证并结算;资金会直接通过链上从买方流向你。

这个版本仅支持 Base + USDC。 其他任何 EVM 链都可以通过 customChains 使用;你在所有这些链上的地址都是一样的。


它能做什么

协议

x402 v1 和 v2,按每个响应自动检测。未知协议版本和 MPP 质询会被明确拒绝,绝不会猜测。

链

默认支持 Base 主网和 USDC。任何其他 EVM 链都可通过 customChains 使用

网络

短名称和 CAIP-2(eip155:8453)

托管

支持 privateKey、补充性 shards 或 remoteSign(HSM/MPC)——由你选择,而不是由架构决定

速度

3.2 微秒热 / 1.0 毫秒冷(TypeScript);1.2 微秒 / 1.7 毫秒(Python)

运行时

自动检测你去运行的 Cloudflare Workers 并改变策略;也就是不移动 Node、Bun、Deno 时,上面的策略会切换

安全性

强制上限、白名单、绝不重复支付的对账、时序加固的签名

其他链

Base 是默认链。签名本身与链无关,所以你可以添加任何你需要的链——包括先在链上试运行一下:

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

先针对已部署的合约验证配置:调用 DOMAIN_SEPARATOR(),确认它与此这个库计算出来的值一致。如果 name 或 version 写错了,会产生一个看起来有效但会被合约拒绝的签名。

它特意不会去做的

不会在链上广播 · 不会保管资金 · 不需要 gas 或 RPC · 不对付款收取分成(架构上也做不到——EIP-3009 只有一位收款人)· 不需要托管的签名者 · 不会无限制地支付 · 不会尝试它不会说的协议。


安全——在动真钱之前读一下

上限是强制的。 maxAmountPerRequest 和 totalBudget 没有默认值;wrapper 在缺少它们时会拒绝构造。一个没有上限的自动付款者,就像一个小漏洞,由任何运行服务端的人控制。

提醒:totalBudget 本身是每实例的。 它是内存计数器,重启、新建客户端,以及每次 Cloudflare Worker 隔离(每次请求)时重置。在主网上,这会把终身上限变成每次请求上限。因此主网需要一个持久化的 budgetStore,或者显式设置 acknowledgeEphemeralBudget: true:

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

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

私钥在进程里。 这就是放弃托管签名所的公平代价。给它界法边界:使用一个专用钱包,只放你能接受损失的资金;设置 allow 和 allowPayTo`,这样即使密钥被泄露,也无用通过这个 wrapper 转款给陌生人;如果需要,还可以用 remoteSign。

时序加固是加固,但仍是是证明。 秘密标量运算使用了盲化和 always-add-and-double,这会把时序散布从 99.6% 降到某关键点(Python:99.9% → 1.1%)。BigInt 逻辑本身是有不是恒定时间的,而没有任何纯 JS 实现能完全去除这一点。


MCP 服务器——给智能体一个钱包

MCP 就是让助手获得工具的方式。这里提供三个工具:

工具

check_price

查看资源的费用,但不付款

pay_and_fetch

获取资源,如果愿意在限制内则付款

wallet_status

地址、余额、已花金额、剩余金额

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

由模型决定这些工具何时运行。 它不能也预算限制讲道理,而且付费页面可以随意报出任何价格。所以那些限制并不是模型可以设置的参数——它们来自环境变量,而服务端在缺少这些变量的情况下会拒绝启动:X402_PRIVATE_KEY、X402_MAX_PER_REQUEST、X402_TOTAL_BUDGET。

还要设置 X402_BUDGET_FILE,否则生命周期上限会在每次重启后重置。有了 X402_ALLOW_HOSTS,其他任何 host 都无法被付款,无论 challenge 看起来多吸引人。使用一个只存放你能接受会损失的资金的钱包。


Python

同一协议,只用标准库。只有买方有——想出售资源,请用 TypeScript 的 seller 部分。它面向长生命周期进程:随身 agent、机器人控制器、收集脚本。

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

或者用作装饰器,让不知道密码的代码也可以直接工作:

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

热路径的速度是 1.1 µs,一个长时间运行的 controller 在第一次付款后就会是热状态。


开发

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

esbuild、typescript 和 wrangler 只是开发依赖,用于构建。发布到生态区的这个包已经是零运行时依赖。

许可证

MIT。本软件处理现实资金——见 LICENSE 的附加声明,并设置好你的支出上限。

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
    -