x402-trinity-mcp
x402-trinity
**ドロップインの fetch 置き替えです。AI エージェントが自らでものの代金を支払いを可能にする。****厳しい支払い上限付き、ホスト型ウォレットサービス不要、エージェントのコース変更もし。
実行時依存ゼロ。gzip で 7 KB。バイヤー と セーラーが TypeScript に、バイヤーが Python に。
npm install x402-trinityなぜ
エージェントが有料リソースに直面すると 402 Payment Required が返されます。その処理が他になければ、リクエストは単に失敗します。
x402-trinity はこれにが処理します。チャレンジを読み取り、設定した制限と照合し、署名し、再試行します。すべてローカルで行います — ホスト型ウォレットサービスは不要、サードパーティ API も不要。鍵がプロセス外へ持ち出されることはありません。
ガス代は存在しますが、支払い者はそれを支払いません — EIP-3009 ではファシリテータが送金を行うため、エージェントのウォレットは USDC だけで十分です。
Related MCP server: HTTPayer MCP
買う(エージェントが代金を支払う)
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) });必須フィールドが2つあるのは、どちらも意図的です。ファシリテータのデフォルトは存在しません。決済は誰かの実際の資金に関わるため、エンドポイントの推測をデフォルトにすることはありません。また、リプレイ防止はプロセスより長生きする必要があります。インメメモリ実装では、再起動のたびに決済済みの支払いをすべて忘れてしまいので、買い手が使用済みの認可を再利用し、再びリソースをただ取りすることができます。よってコンストラクターは、どちらかを暗黙的にするのではなく、例外を投じます。
セラーは秘密鍵を保持せず、資金に触れることもません。価格を提示し、ファシリテータに検証と決済を依頼します。資金は、買い手 → あなたへ、on-chain で直接移動します。
このリリースは Base + USDC のみを対稽竹ています。 その他の EVM チェーンは
customChainsで利用できます。あなたのアドレスはどのチェーンでも同じです。
機能
プロトコル | x402 v1 と v2、レスポンスごとに検出。未知のバージョンや MP の嶮戦は、明確な理由を付して拒否し、推測しません |
チェーン | Base empt一メインネット + USDC をデフォルトで対象。その他の EVM チェーンは |
ネットワーク | 省略名 と CAIP-2( |
室任せ |
|
速度 | T型Script: ウォーム 3.2 µs / コールド 1.0 ms。 Python: ウォーム 1.2 µs / コールド 1.7 ms |
ラuntime | Cloudflare Workers を自動検出して戦策を変えます。その他 Node、Bun、Deno |
安全性 | 必須キャップ、許可リスト、二重支払いを防ぐ fher林、タイミングを harden 化する署名 |
他のチェーン
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 が誤っていると、見かけ上は有効に見える署名が生まれますが、コントラントはそれを拒否します。
意図的に行わないこと
事件のブロードキャストをしない · 資金を保保持しない · ガスや RPC を必要としない · 支払いから手数料を取らない(構造的に不可能 — EIP-3009 には受取者が1人しかいない) · ホスト型サインを必要としない · 上限なしで支払らない · 知らないトプロコを推測しない。
安全 — 実際のお金を扱う前にお読みください
上限は必須です。 maxAmountPerRequest と totalBudget にはデフォルトがありません。シラッパーはこれらなしに生成を拒否します。というのも、制限なしの自動支払いは、そのサーバーを運営する者にコントロールされる資金の薬洩れにだからです。
totalBudget 度はインスタンス単位です。 これはメモリ上のカウンターで、再起動、新しいインスタンス、そして Cloudflare Workers の各 isolate(つまり各リクエスト)でリセットされます。それため、メインストットで待てば、全期間の上限が1リクエストの上限に変ります。したがって、メイン統ットには永続型の budgetStore が必要です。代替できるのは明示的な acknowledgeEphemeralBudget: true です:
import { createFileBudgetStore } from 'x402-trinity/budget-file';
createX402Fetch({
...,
budgetStore: createFileBudgetStore('./.x402-budget.json'), // survives restarts
});秘密鍵はプロセスの中にあります。 それが、ホストされた署名器を置かないための代わりです。制かけなさい:自分が失わても許容できる額だけを保持する専用ウォレットを使う、漏え出た鍵をこのラッパーを通して他人に払えないよう allowPayTo を設定する、エンクレーブ相当の保管が必要なら remoteSign を使う。
タイミング耐性は「強化」であって「証明」ではありません。 秘密スカラーには、ブラインディングに加えて「常に加算と2倍算」を使います。これによりタイミングの打散布は99.6%から12%に減少します(Python: 99.9% → 1.1%)。BigInt の算術は自本的に可変時間です。純 JS の実装でそれを除取るものはありません。
MCPサーバー — エージェントにウォレットを
MCP は、アシスタントに戦を与えるための仕組みです。ここでは次の3つを公開します:
tool | |
| リソースの価格を、支払うことなく表示 |
| 上限内であれば支払ってリソースを取得 |
| アドレス、残高、支出済み、残り割当 |
{
"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 を設定すると、それ以外のお相手には支払えません。どんなにチャレンジらしみても。自分が失えて許容できる額だけを保持するウォレットにしてください。
Python
同プロトコルで、標準ライブラリのみ。バイヤー専用 — リ ソースに課金したい場合は TypeScript のセラーを使用してください。目標は、長く動き続けるプロセスに一体型のエージェント、ロボットコントローラー、収穫スクリティなどです。
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。長寿命のコントローラでは、初回の支払いの後はウォーム状態になります。
開発
npm install
npm run build # dist/*.js + *.min.js + *.d.tsesbuild、typescript、wranler は dev依存 です。ビルドにのみ使われます。配植されるパッケージは ランタイム依存ゼロ.
ライセンス
MIT. 本ソフトウェアは資金を移動させます — LICENSE の追加の又特記事項を参照し、自日の支払い上限を設定してください。
Available Tools
3 toolscheck_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.
| Name | Required | Description | Default |
|---|---|---|---|
| url | Yes | The resource to price. Must be http(s). |
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| url | Yes | The resource to fetch. Must be http(s). | |
| method | No | HTTP method. Default GET. | |
| max_response_chars | No | Truncate the body to this length. Default 20000. |
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
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.
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.
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.
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.
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.
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.
3 tool updates
v0.2.1- First observed
check_price - First observed
pay_and_fetch - First observed
wallet_status
TDQS
Scored across 3 tools
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.
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.
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.
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
Related MCP Connectors
Let your AI assistant pay for web content in USDC (x402) within a budget you set.
Attribution and settlement infrastructure for AI agent content access over HTTP 402 and MCP.
Approval layer for AI agent payments: budgets, rules, human approval. Sandbox, test credentials.
Wallet and payments for AI agents: auto-pay x402 APIs in USDC on XDC, within on-chain limits.
Related MCP Servers
- AlicenseNot gradedqualityFmaintenanceEnables 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 npmMIT
- AlicenseAqualityDmaintenanceEnables 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.648 npm2-
- AlicenseAqualityBmaintenanceEnables AI agents to discover, inspect, and pay for paid HTTP and MCP services using USDC on Solana with a self-custodial wallet.431 npm7Apache 2.0
- AlicenseNot gradedqualityDmaintenanceEnables pay-per-call access control for AI agents using HTTP 402 and on-chain settlement, allowing microtransactions for API usage.46 PyPIMIT