x402 Trinity

io.github.devmster由 GitHub 账号 devmster 发布v0.2.4更新于 Oct 24, 2026

Give an agent a wallet. Pays for x402 resources within hard limits. Base + USDC, gasless.

已验证STDIO仅桌面金融开发者工具

概览

AI 生成的概览

本地 MCP 服务器,为 AI 助手提供一个 USDC 钱包,使其能在硬性支出上限内查询价格并支付 x402 付费资源。

可以做什么
  • 在不付款的情况下查询某个付费资源的标价
  • 抓取资源,若返回 HTTP 402 且在限额内则自动完成支付
  • 查看付款钱包的地址、余额、已花费金额与剩余预算
  • 依据环境变量而非模型输入执行单次上限、总额上限、主机白名单与防重复支付校验
适用场景
当助手需要从返回 HTTP 402 的付费 API、数据集、文件或其他智能体服务购买内容,且希望支出由固定限额而非模型判断来控制时使用。
运行要求
以 stdio 在本地运行,通常通过 npx 启动。需要 X402_PRIVATE_KEY(付款钱包私钥)、X402_MAX_PER_REQUEST 和 X402_TOTAL_BUDGET(以最小单位计),缺少则拒绝启动。可选:X402_BUDGET_FILE 使预算在重启后保留、X402_ALLOW_HOSTS、X402_NETWORKS(默认 base)。钱包需在 Base 上持有 USDC,无需 gas。
安装前请注意
钱包私钥保存在服务器进程中,请使用只存放可承受损失金额的专用钱包。支付是真实资金,且由模型决定何时发生;务必设置 X402_MAX_PER_REQUEST、X402_TOTAL_BUDGET 和 X402_ALLOW_HOSTS,并设置 X402_BUDGET_FILE,否则总额上限每次重启都会重置。付费页面可任意标价,因此白名单很重要。

安装

在 SourceWeft 中

  1. 打开 控制台中的 x402 Trinity,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

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.

bash
npm install x402-trinity

Copy-paste setup

A ready-made brief for your coding agent. Paste it in and it does the install, the wallet, your spending limits, the price check and the purchase — you just say what you are buying and what it may spend.

→ Standard Purchase Harness

Buying from a paid API, a dataset, a file, or another agent's service — anything that answers HTTP 402.

More setups, and a marketplace for you to earn for your products or buy from the marketplace, at x402trinity.com.

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.


Buy (agent pays for things)

js
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:

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

Confirm which wallet will pay before funding anything:

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

js
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 402return 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

Protocolsx402 v1 and v2, detected per response. Unknown versions and MPP challenges declined with a clear reason, never guessed
ChainsBase mainnet + USDC, shipped as the default. Any other EVM chain via customChains
Networksshort names and CAIP-2 (eip155:8453)
CustodyprivateKey, additive shards, or remoteSign (HSM/MPC) — your choice, not the architecture's
Speed3.2 µs warm / 1.0 ms cold (TypeScript); 1.2 µs / 1.7 ms (Python)
Runtimeauto-detects Cloudflare Workers and changes strategy; also Node, Bun, Deno
Safetymandatory 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:

js
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:

js
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_pricewhat a resource costs, without paying
pay_and_fetchfetch it, paying if it is within your limits
wallet_statusaddress, balance, spent, remaining
json
{  "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.

python
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:

python
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

bash
npm installnpm 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.

来源:README.md,提交 edd7bf6

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

4
  1. v0.2.4最新Sep 27, 2026
  2. v0.2.3Sep 22, 2026
  3. v0.2.2Sep 18, 2026
  4. v0.2.1Sep 16, 2026

评分

已满足适用检查项的 40%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分

    请在仓库或注册中心条目中声明许可证。