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: remit.md MCP Server

购买(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_KEYX402_MAX_PER_REQUESTX402_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 的附加声明,并设置好你的支出上限。

A
license - permissive license
Not graded
quality - not tested
A
maintenance

Maintenance

Maintainers
Response time
0dRelease cycle
2Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

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.
    13
    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
    70
    2
    Inno Setup

View all related MCP servers

Related MCP Connectors

  • Attribution and settlement infrastructure for AI agent content access over HTTP 402 and MCP.

  • Provide AI agents and automation tools with contextual access to blockchain data including balance…

  • Keyless non-custodial crypto payments for AI agents: payment links and tip jars, no API key.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/devmster/x402-trinity'

If you have feedback or need assistance with the MCP directory API, please join our Discord server