@agent402-dev/pay-mcp 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -12
- package/dist/agent.d.ts +10 -2
- package/dist/agent.js +32 -17
- package/dist/csv.d.ts +6 -0
- package/dist/csv.js +20 -0
- package/dist/history.d.ts +19 -4
- package/dist/history.js +16 -8
- package/dist/init.d.ts +12 -0
- package/dist/init.js +67 -0
- package/dist/policy.d.ts +68 -23
- package/dist/policy.js +89 -27
- package/dist/receipt.d.ts +26 -0
- package/dist/receipt.js +59 -0
- package/dist/server.js +70 -14
- package/dist/tools.d.ts +1 -1
- package/dist/tools.js +44 -17
- package/dist/units.d.ts +2 -2
- package/dist/units.js +3 -3
- package/dist/wallet.d.ts +3 -3
- package/dist/wallet.js +15 -7
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
# @agent402-dev/pay-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> **A402 (v1) is deprecated.** The token payment option is now **PREQ** (mint `aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX`). Official addresses: https://claude.ai/artifact/S6UafAfViJk3DJeMsDMAja
|
|
4
|
+
|
|
5
|
+
MCP server (stdio) that lets an AI agent call [x402](https://github.com/coinbase/x402) paid APIs on Solana and pay in **USDC** (or, if you allow it, **PREQ**) from **your own wallet on your machine**, only within the rules you set.
|
|
4
6
|
|
|
5
7
|
Part of the [Agent402 toolkit](https://github.com/agent402-dev/agent402-toolkit) (Solana).
|
|
6
8
|
Not related to `agent402.tools`, `@agents402` or other similarly named sites, accounts or projects, including projects named "a402" on other chains.
|
|
7
9
|
|
|
8
10
|
> It pays only what you allow and gives no opinion on any API or token. Not investment advice.
|
|
9
|
-
> 허용한 만큼만 결제하며 API나 토큰에 대한 의견을 주지 않습니다. 투자 권유가 아닙니다.
|
|
10
11
|
|
|
11
12
|
## Rules checked before signing
|
|
12
13
|
Nothing is signed unless every rule passes. **With no configuration, every payment is refused.**
|
|
@@ -15,25 +16,38 @@ Nothing is signed unless every rule passes. **With no configuration, every payme
|
|
|
15
16
|
|---|---|---|
|
|
16
17
|
| Allowed domains (host or host:port; https only, http only for localhost) | `X402_ALLOWED_DOMAINS` | empty → refuse all |
|
|
17
18
|
| Trusted recipients (payTo addresses) | `X402_TRUSTED_PAY_TO` | empty → refuse all |
|
|
18
|
-
| Allowed assets | `X402_ALLOWED_ASSETS` | `USDC` (
|
|
19
|
+
| Allowed assets | `X402_ALLOWED_ASSETS` | `USDC` (PREQ only if listed) |
|
|
19
20
|
| Max USDC per payment (USD) | `X402_MAX_USD` | `0.05` |
|
|
20
21
|
| Max USDC per UTC day (USD) | `X402_MAX_USD_PER_DAY` | `1` |
|
|
21
22
|
| Max payments per UTC day | `X402_MAX_PAYMENTS_PER_DAY` | `20` |
|
|
22
|
-
|
|
|
23
|
-
| **Max
|
|
23
|
+
| Max USDC per recipient per UTC day (USD) | `X402_MAX_USD_PER_RECIPIENT_PER_DAY` | off (only the overall daily cap) |
|
|
24
|
+
| **Max PREQ per payment** (PREQ smallest units; 1 PREQ = 1,000,000) | `X402_MAX_PREQ_ATOMIC` | **not set → PREQ payments refused** |
|
|
25
|
+
| **Max PREQ per UTC day** (PREQ smallest units; 1 PREQ = 1,000,000) | `X402_MAX_PREQ_PER_DAY_ATOMIC` | **not set → PREQ payments refused** |
|
|
26
|
+
| Max PREQ per recipient per UTC day (PREQ smallest units; 1 PREQ = 1,000,000) | `X402_MAX_PREQ_PER_RECIPIENT_PER_DAY_ATOMIC` | off (only the overall PREQ daily cap) |
|
|
24
27
|
| Ask a human at or above this USDC amount (USD) | `X402_CONFIRM_ABOVE_USD` | off |
|
|
25
|
-
| Ask a human at or above this
|
|
28
|
+
| Ask a human at or above this PREQ amount (PREQ smallest units) | `X402_CONFIRM_ABOVE_PREQ_ATOMIC` | off |
|
|
26
29
|
|
|
27
|
-
- **
|
|
28
|
-
- USD limits apply to USDC only.
|
|
30
|
+
- **PREQ units.** The PREQ variables take the smallest unit (PREQ has 6 decimals). Example: `X402_MAX_PREQ_ATOMIC=200000000000` is 200,000 PREQ per payment. `wallet_status` and `payment_history` also show PREQ amounts in smallest units (`…Atomic` fields).
|
|
31
|
+
- USD limits apply to USDC only. PREQ has its own two limits, and **both must be set** before any PREQ payment is made.
|
|
32
|
+
- **PREQ mint.** Until the PREQ mainnet mint is filled into this package, listing `PREQ` in `X402_ALLOWED_ASSETS` stops the server at start with an error (you can set `X402_PREQ_MINT` yourself).
|
|
33
|
+
- **A402 (v1) is deprecated.** It is never allowed by default. If you list `A402` in `X402_ALLOWED_ASSETS` (with its own `X402_MAX_A402_ATOMIC` and `X402_MAX_A402_PER_DAY_ATOMIC`, in A402 smallest units; 1 A402 = 1,000,000), the server prints "A402 (v1) is deprecated and no longer supported; use PREQ." at start, and `wallet_status`, `x402_quote` and `x402_fetch` results carry the same warning.
|
|
29
34
|
- Human confirmation uses MCP elicitation. If your MCP client cannot ask, the payment is not made (`confirmation_required`).
|
|
30
35
|
- At most one signature per `x402_fetch` call. If the server answers 402 again after payment, it does not sign again.
|
|
31
36
|
- Redirects are followed manually and each hop must be an allowed domain; a disallowed hop is not contacted.
|
|
32
37
|
- Pass `quoteId` from `x402_quote` to `x402_fetch` to refuse if the amount, asset or recipient changed.
|
|
38
|
+
- If the server sends a signed receipt (`X-Agent402-Receipt`, from `@agent402-dev/pay-server`), `x402_fetch` checks its signature and that it matches the request, the response body and the payment, reports `receipt.verified`, and keeps the receipt in the local log. A receipt shows which key signed it; whether that key belongs to the seller is for the seller to publish.
|
|
33
39
|
- Daily totals count every payment this server signed, whatever the result.
|
|
34
40
|
- Daily limits are counted from the local payment log file (`X402_HISTORY_PATH`). Deleting or moving that file resets the daily totals.
|
|
41
|
+
- Per-recipient caps count payments to the same `payTo` address in the current UTC day, on top of the overall caps.
|
|
42
|
+
- When today's usage reaches 80% of a daily cap (USDC, payment count or PREQ), `x402_fetch` results and `wallet_status` carry a `near_daily_…` warning. The payment itself is still decided by the caps.
|
|
43
|
+
|
|
44
|
+
Other settings: `X402_KEYPAIR_PATH` (wallet key file, Solana CLI JSON; without it nothing is paid), `X402_NETWORK` (`mainnet` | `devnet`), `X402_RPC_URL`, `X402_PAY_WITH` (`USDC` | `PREQ`), `X402_HISTORY_PATH` (default `~/.agent402/payments.jsonl`).
|
|
35
45
|
|
|
36
|
-
|
|
46
|
+
## Create a payment wallet
|
|
47
|
+
```bash
|
|
48
|
+
npx -y @agent402-dev/pay-mcp init
|
|
49
|
+
```
|
|
50
|
+
Creates a new key file at `~/.agent402/pay-wallet.json` and prints its address, a Solana Pay link to fund it with USDC, how to back it up and the command to connect it. It never overwrites an existing file (`--path <file>` chooses another location, `--network devnet` uses devnet). The key is generated on your machine and is not sent anywhere. Payments need no SOL: the facilitator pays the network fee.
|
|
37
51
|
|
|
38
52
|
## Connect
|
|
39
53
|
Claude Code (example — set your own allowlists and limits):
|
|
@@ -55,11 +69,22 @@ Node 20+. Without `X402_ALLOWED_DOMAINS` and `X402_TRUSTED_PAY_TO` every payment
|
|
|
55
69
|
|---|---|
|
|
56
70
|
| `x402_fetch` | Fetch a URL; pay only if the rules pass |
|
|
57
71
|
| `x402_quote` | Show payment requirements and which rules pass; never signs; returns `quoteId` |
|
|
58
|
-
| `wallet_status` | Address, balances, today's usage (count, USDC,
|
|
59
|
-
| `payment_history` | Local log: time, URL, asset, amount, recipient, result, settlement transaction id |
|
|
72
|
+
| `wallet_status` | Address, balances, today's usage (count, USDC, PREQ), limits including both PREQ limits, allowlists |
|
|
73
|
+
| `payment_history` | Local log: time, URL, asset, amount, recipient, result, settlement transaction id (JSON, or CSV with `format: "csv"`) |
|
|
60
74
|
|
|
61
75
|
The log never stores keys or signed payment payloads.
|
|
62
76
|
|
|
77
|
+
## Export payment history
|
|
78
|
+
```bash
|
|
79
|
+
npx -y @agent402-dev/pay-mcp export-csv --out payments.csv
|
|
80
|
+
```
|
|
81
|
+
Writes the local payment log as CSV, oldest first, without overwriting an existing file. Without `--out` it prints to the terminal.
|
|
82
|
+
|
|
83
|
+
## Data
|
|
84
|
+
- No telemetry and no analytics.
|
|
85
|
+
- pay-mcp contacts only the URLs your agent asks it to fetch (allowed domains only) and the Solana RPC (`X402_RPC_URL`, or the public RPC) to build payment transactions and read balances. The RPC provider can see your wallet address.
|
|
86
|
+
- The payment log and the key file stay on your machine. Payment servers and facilitators receive only the partially signed payment transaction.
|
|
87
|
+
|
|
63
88
|
## Use a small, dedicated wallet
|
|
64
89
|
Put only what you are willing to spend in the payment wallet. Never point this at a wallet that holds other funds. The key file stays on your machine; only a partially signed payment transaction is sent.
|
|
65
90
|
|
|
@@ -71,4 +96,4 @@ Put only what you are willing to spend in the payment wallet. Never point this a
|
|
|
71
96
|
Apache-2.0. See [LICENSE](https://github.com/agent402-dev/agent402-toolkit/blob/main/LICENSE) and [NOTICE](https://github.com/agent402-dev/agent402-toolkit/blob/main/NOTICE).
|
|
72
97
|
|
|
73
98
|
---
|
|
74
|
-
Factual information from public on-chain data. Not investment advice.
|
|
99
|
+
Factual information from public on-chain data. Not investment advice.
|
package/dist/agent.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export interface AgentDeps {
|
|
|
7
7
|
wallet: Wallet | null;
|
|
8
8
|
history: History;
|
|
9
9
|
fetch: typeof fetch;
|
|
10
|
-
/**
|
|
10
|
+
/** Human confirmation (MCP elicitation). If the client does not support it, 'unsupported' → no payment */
|
|
11
11
|
confirm: (message: string) => Promise<ConfirmAnswer>;
|
|
12
12
|
now?: () => Date;
|
|
13
13
|
maxRedirects?: number;
|
|
@@ -31,7 +31,7 @@ export interface FetchOutcome {
|
|
|
31
31
|
settlementTx?: string;
|
|
32
32
|
};
|
|
33
33
|
body?: unknown;
|
|
34
|
-
/**
|
|
34
|
+
/** Policy evaluation result (the reason for each condition when rejected) */
|
|
35
35
|
options?: {
|
|
36
36
|
asset: string | null;
|
|
37
37
|
mint: string;
|
|
@@ -40,6 +40,14 @@ export interface FetchOutcome {
|
|
|
40
40
|
ok: boolean;
|
|
41
41
|
reasons: string[];
|
|
42
42
|
}[];
|
|
43
|
+
/** Warnings (e.g. the deprecation notice when trying to pay with A402 (v1)) */
|
|
44
|
+
warnings?: string[];
|
|
45
|
+
/** Seller's signed receipt, if the server sent one (X-Agent402-Receipt) */
|
|
46
|
+
receipt?: {
|
|
47
|
+
signer: string | null;
|
|
48
|
+
verified: boolean;
|
|
49
|
+
reasons: string[];
|
|
50
|
+
};
|
|
43
51
|
}
|
|
44
52
|
export declare function createAgent(d: AgentDeps): {
|
|
45
53
|
quote: (spec: RequestSpec) => Promise<FetchOutcome & {
|
package/dist/agent.js
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// Payment decision and execution (core logic independent of MCP, separated for testing)
|
|
2
|
+
// Order: domain check → request (follows redirects itself, checking the domain each time) → on 402, evaluate the policy → (confirm the quote is unchanged) → (human confirmation) → sign once → re-request
|
|
3
|
+
// At most one signature per request. If another 402 comes after paying, it does not sign again
|
|
4
4
|
import { decodePaymentRequiredHeader, decodePaymentResponseHeader } from '@x402/core/http';
|
|
5
|
-
import { choose, domainCheck, evaluate } from './policy.js';
|
|
5
|
+
import { A402_DEPRECATION_WARNING, choose, domainCheck, evaluate, nearLimits } from './policy.js';
|
|
6
|
+
import { checkReceipt, RECEIPT_HEADER } from './receipt.js';
|
|
6
7
|
import { withSmallest } from './units.js';
|
|
7
8
|
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
9
|
+
/** Adds the deprecation warning if the chosen asset is A402 (v1) (there is no path that silently pays with A402) */
|
|
10
|
+
const withDeprecation = (o) => o.payment?.asset === 'A402' ? { ...o, warnings: [...(o.warnings ?? []), A402_DEPRECATION_WARNING] } : o;
|
|
8
11
|
export function createAgent(d) {
|
|
9
12
|
const now = d.now ?? (() => new Date());
|
|
10
13
|
const quotes = new Map();
|
|
11
14
|
const QUOTE_TTL_MS = 5 * 60_000;
|
|
12
|
-
/**
|
|
15
|
+
/** Follows redirects itself and checks the domain at each step */
|
|
13
16
|
async function send(spec, extraHeaders = {}, follow = true) {
|
|
14
17
|
let url = spec.url;
|
|
15
18
|
for (let hop = 0; hop <= (d.maxRedirects ?? 3); hop++) {
|
|
@@ -26,8 +29,8 @@ export function createAgent(d) {
|
|
|
26
29
|
}
|
|
27
30
|
return { refused: 'too_many_redirects' };
|
|
28
31
|
}
|
|
29
|
-
const
|
|
30
|
-
const t = (
|
|
32
|
+
const parseBody = (buf) => {
|
|
33
|
+
const t = new TextDecoder().decode(buf).slice(0, 20_000);
|
|
31
34
|
try {
|
|
32
35
|
return JSON.parse(t);
|
|
33
36
|
}
|
|
@@ -35,6 +38,7 @@ export function createAgent(d) {
|
|
|
35
38
|
return t;
|
|
36
39
|
}
|
|
37
40
|
};
|
|
41
|
+
const readBody = async (res) => parseBody(await res.arrayBuffer());
|
|
38
42
|
const describe = (e) => ({ asset: e.asset, mint: e.requirement.asset, amount: e.requirement.amount, payTo: e.requirement.payTo, ok: e.ok, reasons: e.reasons });
|
|
39
43
|
const host = (u) => { try {
|
|
40
44
|
return new URL(u).host;
|
|
@@ -43,7 +47,7 @@ export function createAgent(d) {
|
|
|
43
47
|
return '';
|
|
44
48
|
} };
|
|
45
49
|
const record = (e) => d.history.add({ at: now().toISOString(), ...e });
|
|
46
|
-
/** 402
|
|
50
|
+
/** Receives a 402 and evaluates it with the policy (no signing) */
|
|
47
51
|
async function assess(spec) {
|
|
48
52
|
const sent = await send(spec);
|
|
49
53
|
if ('refused' in sent)
|
|
@@ -59,13 +63,14 @@ export function createAgent(d) {
|
|
|
59
63
|
catch {
|
|
60
64
|
return { kind: 'refused', refused: 'invalid_payment_required_header' };
|
|
61
65
|
}
|
|
62
|
-
// 402
|
|
66
|
+
// If the 402 points to a resource at another address, that address must also be on the allowlist
|
|
63
67
|
if (pr.resource?.url) {
|
|
64
68
|
const rc = domainCheck(d.policy, pr.resource.url);
|
|
65
69
|
if (!rc.ok)
|
|
66
70
|
return { kind: 'refused', refused: `resource_on_disallowed_domain: ${rc.reason}` };
|
|
67
71
|
}
|
|
68
|
-
const
|
|
72
|
+
const usage = d.history.today(now());
|
|
73
|
+
const evs = pr.accepts.map((r) => evaluate(d.policy, r, usage, d.history.recipientToday(r.payTo, now())));
|
|
69
74
|
return { kind: '402', pr, evs, chosen: choose(d.policy, evs), finalUrl };
|
|
70
75
|
}
|
|
71
76
|
async function quote(spec) {
|
|
@@ -103,7 +108,7 @@ export function createAgent(d) {
|
|
|
103
108
|
record({ ...base, ...pay, result, reasons, signed: false });
|
|
104
109
|
return { result, reasons, options, payment: { asset: a.chosen.asset, mint: r.asset, amount: r.amount, payTo: r.payTo, network: r.network } };
|
|
105
110
|
};
|
|
106
|
-
//
|
|
111
|
+
// Same requirement as the quote? (reject if the amount or receiver changed between requests)
|
|
107
112
|
if (spec.quoteId) {
|
|
108
113
|
const q = quotes.get(spec.quoteId);
|
|
109
114
|
if (!q || q.url !== spec.url || now().getTime() - q.at > QUOTE_TTL_MS)
|
|
@@ -115,14 +120,14 @@ export function createAgent(d) {
|
|
|
115
120
|
if (!d.wallet)
|
|
116
121
|
return refuse('refused', ['no_wallet: set X402_KEYPAIR_PATH']);
|
|
117
122
|
if (a.chosen.needsConfirmation) {
|
|
118
|
-
const human = `Pay ${a.chosen.asset === 'USDC' ? `${a.chosen.usd} USDC` : withSmallest(r.amount, a.chosen.asset ?? '
|
|
123
|
+
const human = `Pay ${a.chosen.asset === 'USDC' ? `${a.chosen.usd} USDC` : withSmallest(r.amount, a.chosen.asset ?? 'tokens')} to ${r.payTo} for ${spec.url}?${a.chosen.asset === 'A402' ? ` (${A402_DEPRECATION_WARNING})` : ''}`;
|
|
119
124
|
const ans = await d.confirm(human).catch(() => 'unsupported');
|
|
120
125
|
if (ans === 'unsupported')
|
|
121
126
|
return refuse('confirmation_required', ['confirmation_required: this client cannot ask for confirmation (MCP elicitation); payment not made']);
|
|
122
127
|
if (ans === 'decline')
|
|
123
128
|
return refuse('declined_by_user', ['declined_by_user']);
|
|
124
129
|
}
|
|
125
|
-
//
|
|
130
|
+
// Sign (only once per request)
|
|
126
131
|
const header = await d.wallet.sign(a.pr.resource, r);
|
|
127
132
|
const sent = await send({ ...spec, url: a.finalUrl }, { 'payment-signature': header }, false);
|
|
128
133
|
if ('refused' in sent) {
|
|
@@ -130,7 +135,8 @@ export function createAgent(d) {
|
|
|
130
135
|
return { result: 'failed', reasons: [sent.refused] };
|
|
131
136
|
}
|
|
132
137
|
const res = sent.res;
|
|
133
|
-
const
|
|
138
|
+
const buf = await res.arrayBuffer();
|
|
139
|
+
const body = parseBody(buf);
|
|
134
140
|
if (res.ok) {
|
|
135
141
|
const pr = res.headers.get('payment-response');
|
|
136
142
|
let tx;
|
|
@@ -140,13 +146,22 @@ export function createAgent(d) {
|
|
|
140
146
|
catch {
|
|
141
147
|
tx = undefined;
|
|
142
148
|
}
|
|
143
|
-
|
|
144
|
-
|
|
149
|
+
const rt = res.headers.get(RECEIPT_HEADER);
|
|
150
|
+
const rc = rt
|
|
151
|
+
? await checkReceipt(rt, { method: spec.method ?? 'GET', url: a.finalUrl, requestBody: spec.body, responseBody: buf, payment: { network: r.network, asset: r.asset, amount: r.amount, payTo: r.payTo, transaction: tx } })
|
|
152
|
+
: null;
|
|
153
|
+
const receipt = rc ? { signer: rc.signer, verified: rc.verified, reasons: rc.reasons } : undefined;
|
|
154
|
+
record({ ...base, ...pay, result: 'paid', httpStatus: res.status, settlementTx: tx, signed: true, ...(rc ? { receipt: { ...receipt, token: rc.token } } : {}) });
|
|
155
|
+
const near = nearLimits(d.policy, d.history.today(now()));
|
|
156
|
+
return { result: 'paid', httpStatus: res.status, body, payment: { asset: a.chosen.asset, mint: r.asset, amount: r.amount, payTo: r.payTo, network: r.network, settlementTx: tx }, ...(receipt ? { receipt } : {}), ...(near.length ? { warnings: near } : {}) };
|
|
145
157
|
}
|
|
146
158
|
const reason = typeof body === 'object' && body && 'reason' in body ? String(body.reason) : `http_${res.status}`;
|
|
147
159
|
const result = res.status === 402 ? 'rejected_by_server' : res.headers.get('x-payment-status') === 'not-settled' || res.status === 409 ? 'failed' : 'unknown';
|
|
148
160
|
record({ ...base, ...pay, result, reasons: [reason], httpStatus: res.status, signed: true });
|
|
149
161
|
return { result, httpStatus: res.status, reasons: [reason], body };
|
|
150
162
|
}
|
|
151
|
-
return {
|
|
163
|
+
return {
|
|
164
|
+
quote: async (spec) => withDeprecation(await quote(spec)),
|
|
165
|
+
payAndFetch: async (spec) => withDeprecation(await payAndFetch(spec)),
|
|
166
|
+
};
|
|
152
167
|
}
|
package/dist/csv.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { HistoryEntry } from './history.js';
|
|
2
|
+
export declare const CSV_COLUMNS: readonly ["time_utc", "result", "signed", "asset", "amount_smallest_units", "amount", "pay_to", "host", "url", "network", "mint", "settlement_tx", "http_status", "reasons", "receipt_signer", "receipt_verified"];
|
|
3
|
+
/** One CSV field. Values a spreadsheet would run as a formula (=, +, -, @) get a leading apostrophe */
|
|
4
|
+
export declare function csvField(v: unknown): string;
|
|
5
|
+
/** Entries in the order given (pass oldest first for a chronological file) */
|
|
6
|
+
export declare function historyToCsv(entries: HistoryEntry[]): string;
|
package/dist/csv.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { formatUnits } from './units.js';
|
|
2
|
+
export const CSV_COLUMNS = [
|
|
3
|
+
'time_utc', 'result', 'signed', 'asset', 'amount_smallest_units', 'amount', 'pay_to', 'host', 'url', 'network', 'mint', 'settlement_tx', 'http_status', 'reasons', 'receipt_signer', 'receipt_verified',
|
|
4
|
+
];
|
|
5
|
+
/** One CSV field. Values a spreadsheet would run as a formula (=, +, -, @) get a leading apostrophe */
|
|
6
|
+
export function csvField(v) {
|
|
7
|
+
let s = v === undefined || v === null ? '' : String(v);
|
|
8
|
+
if (/^[=+\-@\t\r]/.test(s))
|
|
9
|
+
s = `'${s}`;
|
|
10
|
+
return /[",\r\n]/.test(s) || s !== s.trim() ? `"${s.replace(/"/g, '""')}"` : s;
|
|
11
|
+
}
|
|
12
|
+
/** Entries in the order given (pass oldest first for a chronological file) */
|
|
13
|
+
export function historyToCsv(entries) {
|
|
14
|
+
const rows = entries.map((e) => [
|
|
15
|
+
e.at, e.result, e.signed, e.asset, e.amount,
|
|
16
|
+
e.asset && e.amount && /^\d+$/.test(e.amount) ? formatUnits(e.amount, e.asset) : '',
|
|
17
|
+
e.payTo, e.host, e.url, e.network, e.mint, e.settlementTx, e.httpStatus, (e.reasons ?? []).join('; '), e.receipt?.signer, e.receipt ? e.receipt.verified : '',
|
|
18
|
+
].map(csvField).join(','));
|
|
19
|
+
return [CSV_COLUMNS.join(','), ...rows].join('\r\n') + '\r\n';
|
|
20
|
+
}
|
package/dist/history.d.ts
CHANGED
|
@@ -9,25 +9,40 @@ export interface HistoryEntry {
|
|
|
9
9
|
amount?: string;
|
|
10
10
|
payTo?: string;
|
|
11
11
|
result: PaymentResult;
|
|
12
|
-
/**
|
|
12
|
+
/** Reason for rejection or failure */
|
|
13
13
|
reasons?: string[];
|
|
14
14
|
httpStatus?: number;
|
|
15
|
-
/**
|
|
15
|
+
/** Settlement transaction id (PAYMENT-RESPONSE) */
|
|
16
16
|
settlementTx?: string;
|
|
17
|
-
/**
|
|
17
|
+
/** Whether it signed (true if it signed a payment transaction in this request) */
|
|
18
18
|
signed: boolean;
|
|
19
|
+
/** Seller's signed receipt (public evidence; contains no keys): signer, check result, and the receipt as received */
|
|
20
|
+
receipt?: {
|
|
21
|
+
signer: string | null;
|
|
22
|
+
verified: boolean;
|
|
23
|
+
reasons: string[];
|
|
24
|
+
token: string;
|
|
25
|
+
};
|
|
19
26
|
}
|
|
20
27
|
export interface History {
|
|
21
28
|
add(e: HistoryEntry): void;
|
|
22
29
|
list(limit?: number): HistoryEntry[];
|
|
23
|
-
/**
|
|
30
|
+
/** Today's (UTC) signed payment count, USDC total (USD), PREQ and A402 (v1) totals (base units), for limit checks */
|
|
24
31
|
today(now?: Date): {
|
|
25
32
|
count: number;
|
|
26
33
|
usd: number;
|
|
34
|
+
preq: bigint;
|
|
27
35
|
a402: bigint;
|
|
28
36
|
};
|
|
37
|
+
/** Today's (UTC) signed payments to one recipient: count, USDC total (USD), PREQ total (base units) */
|
|
38
|
+
recipientToday(payTo: string, now?: Date): {
|
|
39
|
+
count: number;
|
|
40
|
+
usd: number;
|
|
41
|
+
preq: bigint;
|
|
42
|
+
};
|
|
29
43
|
}
|
|
30
44
|
export declare function jsonlHistory(path: string, mints: () => {
|
|
31
45
|
USDC: string;
|
|
46
|
+
PREQ: string;
|
|
32
47
|
A402: string;
|
|
33
48
|
}): History;
|
package/dist/history.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// Payment history (JSONL, on the user's computer). Keys, payment signature headers and raw partially signed transactions are not stored.
|
|
2
|
+
// Stored: time, URL, host, asset, amount, receiver, result, reason, settlement tx id (public on-chain record), seller's signed receipt if any
|
|
3
3
|
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
4
4
|
import { dirname } from 'node:path';
|
|
5
5
|
const FORBIDDEN_KEYS = ['secret', 'privateKey', 'keypair', 'paymentSignature', 'transaction', 'payload'];
|
|
@@ -14,6 +14,13 @@ export function jsonlHistory(path, mints) {
|
|
|
14
14
|
return null;
|
|
15
15
|
} }).filter((x) => !!x);
|
|
16
16
|
};
|
|
17
|
+
// A signed payment counts as spent regardless of result (succeeded, rejected, unknown), to be conservative
|
|
18
|
+
const signedOn = (now) => {
|
|
19
|
+
const day = now.toISOString().slice(0, 10);
|
|
20
|
+
return read().filter((e) => e.signed && e.at.slice(0, 10) === day);
|
|
21
|
+
};
|
|
22
|
+
const usdOf = (xs, usdc) => xs.filter((e) => e.mint === usdc && e.amount).reduce((s, e) => s + Number(e.amount) / 1e6, 0);
|
|
23
|
+
const sumOf = (xs, mint) => (mint ? xs.filter((e) => e.mint === mint && e.amount && /^\d+$/.test(e.amount)).reduce((s, e) => s + BigInt(e.amount), 0n) : 0n);
|
|
17
24
|
return {
|
|
18
25
|
add(e) {
|
|
19
26
|
for (const k of FORBIDDEN_KEYS)
|
|
@@ -24,13 +31,14 @@ export function jsonlHistory(path, mints) {
|
|
|
24
31
|
},
|
|
25
32
|
list(limit = 50) { return read().slice(-limit).reverse(); },
|
|
26
33
|
today(now = new Date()) {
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
34
|
+
const xs = signedOn(now);
|
|
35
|
+
const m = mints();
|
|
36
|
+
return { count: xs.length, usd: usdOf(xs, m.USDC), preq: sumOf(xs, m.PREQ), a402: sumOf(xs, m.A402) };
|
|
37
|
+
},
|
|
38
|
+
recipientToday(payTo, now = new Date()) {
|
|
39
|
+
const xs = signedOn(now).filter((e) => e.payTo === payTo);
|
|
30
40
|
const m = mints();
|
|
31
|
-
|
|
32
|
-
const a402 = xs.filter((e) => e.mint === m.A402 && e.amount && /^\d+$/.test(e.amount)).reduce((s, e) => s + BigInt(e.amount), 0n);
|
|
33
|
-
return { count: xs.length, usd, a402 };
|
|
41
|
+
return { count: xs.length, usd: usdOf(xs, m.USDC), preq: sumOf(xs, m.PREQ) };
|
|
34
42
|
},
|
|
35
43
|
};
|
|
36
44
|
}
|
package/dist/init.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare const DEFAULT_WALLET_PATH: string;
|
|
2
|
+
export interface InitOptions {
|
|
3
|
+
path?: string;
|
|
4
|
+
network?: 'mainnet' | 'devnet';
|
|
5
|
+
}
|
|
6
|
+
export interface InitResult {
|
|
7
|
+
path: string;
|
|
8
|
+
address: string;
|
|
9
|
+
network: 'mainnet' | 'devnet';
|
|
10
|
+
text: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function initWallet(o?: InitOptions): Promise<InitResult>;
|
package/dist/init.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// `pay-mcp init`: creates a dedicated payment wallet key file on this computer and prints how to fund, back up and connect it.
|
|
2
|
+
// The key is generated locally and never sent anywhere. An existing file is never overwritten.
|
|
3
|
+
import { generateKeyPairSync } from 'node:crypto';
|
|
4
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { dirname, join, resolve } from 'node:path';
|
|
7
|
+
import { createKeyPairSignerFromBytes } from '@solana/kit';
|
|
8
|
+
import { policyFromEnv } from './policy.js';
|
|
9
|
+
export const DEFAULT_WALLET_PATH = join(homedir(), '.agent402', 'pay-wallet.json');
|
|
10
|
+
export async function initWallet(o = {}) {
|
|
11
|
+
const path = resolve(o.path ?? DEFAULT_WALLET_PATH);
|
|
12
|
+
const network = o.network === 'devnet' ? 'devnet' : 'mainnet';
|
|
13
|
+
const { privateKey, publicKey } = generateKeyPairSync('ed25519');
|
|
14
|
+
const seed = Buffer.from(privateKey.export({ format: 'jwk' }).d, 'base64url');
|
|
15
|
+
const pub = Buffer.from(publicKey.export({ format: 'jwk' }).x, 'base64url');
|
|
16
|
+
// Solana CLI key file format: 64 bytes = 32-byte secret seed + 32-byte public key
|
|
17
|
+
const bytes = Uint8Array.from([...seed, ...pub]);
|
|
18
|
+
let address;
|
|
19
|
+
try {
|
|
20
|
+
address = (await createKeyPairSignerFromBytes(bytes)).address; // also checks that the public key matches the seed
|
|
21
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
22
|
+
writeFileSync(path, JSON.stringify(Array.from(bytes)), { flag: 'wx', mode: 0o600 });
|
|
23
|
+
}
|
|
24
|
+
catch (e) {
|
|
25
|
+
if (e.code === 'EEXIST')
|
|
26
|
+
throw new Error(`A file already exists at ${path}. It was not changed. Use --path to choose another file.`);
|
|
27
|
+
throw e;
|
|
28
|
+
}
|
|
29
|
+
finally {
|
|
30
|
+
bytes.fill(0);
|
|
31
|
+
seed.fill(0);
|
|
32
|
+
}
|
|
33
|
+
const usdc = policyFromEnv({ X402_NETWORK: network }).mints.USDC;
|
|
34
|
+
const connect = [
|
|
35
|
+
'claude mcp add a402-pay',
|
|
36
|
+
`-e X402_KEYPAIR_PATH="${path}"`,
|
|
37
|
+
...(network === 'devnet' ? ['-e X402_NETWORK=devnet'] : []),
|
|
38
|
+
'-e X402_ALLOWED_DOMAINS=<api.example.com>',
|
|
39
|
+
'-e X402_TRUSTED_PAY_TO=<recipient address>',
|
|
40
|
+
'-e X402_MAX_USD=0.05 -e X402_MAX_USD_PER_DAY=1',
|
|
41
|
+
'-- npx -y @agent402-dev/pay-mcp',
|
|
42
|
+
].join(' ');
|
|
43
|
+
const text = [
|
|
44
|
+
`Created a payment wallet for @agent402-dev/pay-mcp (${network}).`,
|
|
45
|
+
'',
|
|
46
|
+
` Address: ${address}`,
|
|
47
|
+
` Key file: ${path}`,
|
|
48
|
+
'',
|
|
49
|
+
'1. Fund it with a small amount of USDC only: what you are willing to let the agent spend (for example 1-5 USDC).',
|
|
50
|
+
' No SOL is needed: the x402 facilitator pays the network fee.',
|
|
51
|
+
` Send USDC on Solana ${network} to ${address}`,
|
|
52
|
+
` Solana Pay link: solana:${address}?spl-token=${usdc}`,
|
|
53
|
+
'',
|
|
54
|
+
'2. Back up the key file. Anyone who has this file can spend from this wallet.',
|
|
55
|
+
' There is no seed phrase: copy the file to an offline place you control.',
|
|
56
|
+
' Never upload it, commit it to a repository or paste it into a chat.',
|
|
57
|
+
'',
|
|
58
|
+
'3. Connect it (Claude Code shown). Payments stay refused until you set both allowlists:',
|
|
59
|
+
` ${connect}`,
|
|
60
|
+
'',
|
|
61
|
+
' These limits allow at most 0.05 USDC per payment and 1 USDC per UTC day.',
|
|
62
|
+
' Optional: X402_MAX_USD_PER_RECIPIENT_PER_DAY caps the daily total per recipient;',
|
|
63
|
+
' X402_CONFIRM_ABOVE_USD asks you before larger payments (needs a client that supports MCP elicitation).',
|
|
64
|
+
' Check the wallet any time with the wallet_status tool.',
|
|
65
|
+
].join('\n');
|
|
66
|
+
return { path, address, network, text };
|
|
67
|
+
}
|
package/dist/policy.d.ts
CHANGED
|
@@ -3,30 +3,51 @@ export declare const NETWORKS: {
|
|
|
3
3
|
readonly mainnet: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
|
|
4
4
|
readonly devnet: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
|
|
5
5
|
};
|
|
6
|
-
|
|
6
|
+
/**
|
|
7
|
+
* PREQ mainnet mint (Token-2022, 6 decimals). Same value as PREQ_MAINNET_MINT in pay-server src/preq.ts.
|
|
8
|
+
* Set after the PREQ launch on 2026-11-21. X402_PREQ_MINT can override it (e.g. for devnet rehearsals)
|
|
9
|
+
*/
|
|
10
|
+
export declare const PREQ_MAINNET_MINT = "aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX";
|
|
11
|
+
export declare const A402_DEPRECATION_WARNING = "A402 (v1) is deprecated and no longer supported; use PREQ.";
|
|
12
|
+
export type AssetSymbol = 'USDC' | 'PREQ' | 'A402';
|
|
13
|
+
/** Tokens other than USDC (limits managed in base units) */
|
|
14
|
+
export type TokenSymbol = Exclude<AssetSymbol, 'USDC'>;
|
|
15
|
+
export declare const TOKEN_SYMBOLS: TokenSymbol[];
|
|
16
|
+
/** Limits for one token (all in base units, 1 token = 1,000,000) */
|
|
17
|
+
export interface TokenLimits {
|
|
18
|
+
/** Per-payment cap. null = not set → payments in that token are rejected */
|
|
19
|
+
perPayment: bigint | null;
|
|
20
|
+
/** Daily (UTC) total cap. null = not set → payments in that token are rejected */
|
|
21
|
+
perDay: bigint | null;
|
|
22
|
+
/** Ask a human at or above this amount. null = never ask */
|
|
23
|
+
confirmAbove: bigint | null;
|
|
24
|
+
}
|
|
7
25
|
export interface PayPolicy {
|
|
8
26
|
network: string;
|
|
27
|
+
/** Empty string = no mint on that network (that asset matches no payment requirement) */
|
|
9
28
|
mints: Record<AssetSymbol, string>;
|
|
10
|
-
/**
|
|
29
|
+
/** Domains allowed for paid calls (host or host:port, lowercase). Empty means reject all */
|
|
11
30
|
allowedDomains: string[];
|
|
12
|
-
/**
|
|
31
|
+
/** Receiving addresses allowed for payment. Empty means reject all */
|
|
13
32
|
trustedPayTo: string[];
|
|
14
|
-
/**
|
|
33
|
+
/** Assets allowed for payment (USDC only by default; PREQ must be enabled explicitly; A402 is deprecated) */
|
|
15
34
|
allowedAssets: AssetSymbol[];
|
|
16
|
-
/** USDC
|
|
35
|
+
/** Per-payment USDC cap (USD) */
|
|
17
36
|
maxUsdPerPayment: number;
|
|
18
|
-
/** A402 결제당 상한 (원 단위). null = 설정 안 됨 → A402 결제 거절 */
|
|
19
|
-
maxA402PerPayment: bigint | null;
|
|
20
|
-
/** A402 하루 합계 상한 (원 단위). null = 설정 안 됨 → A402 결제 거절 */
|
|
21
|
-
maxA402PerDay: bigint | null;
|
|
22
37
|
maxPaymentsPerDay: number;
|
|
23
|
-
/**
|
|
38
|
+
/** Daily USDC total cap (USD) */
|
|
24
39
|
maxUsdPerDay: number;
|
|
25
|
-
/**
|
|
40
|
+
/** Daily USDC cap per recipient (USD). null = only the overall daily cap applies */
|
|
41
|
+
maxUsdPerRecipientPerDay: number | null;
|
|
42
|
+
/** Daily PREQ cap per recipient (smallest units). null = only the overall PREQ daily cap applies */
|
|
43
|
+
maxPreqPerRecipientPerDay: bigint | null;
|
|
44
|
+
/** USDC payments at or above this amount (USD) need human confirmation. null = never ask */
|
|
26
45
|
confirmAboveUsd: number | null;
|
|
27
|
-
/**
|
|
28
|
-
|
|
46
|
+
/** Per-token limits (base units). No defaults: both per-payment and daily must be set to pay in that token */
|
|
47
|
+
tokenLimits: Record<TokenSymbol, TokenLimits>;
|
|
29
48
|
prefer: AssetSymbol;
|
|
49
|
+
/** Warnings to show at start (e.g. when A402 (v1) is enabled) */
|
|
50
|
+
warnings: string[];
|
|
30
51
|
}
|
|
31
52
|
export interface PolicyEnv {
|
|
32
53
|
X402_NETWORK?: string;
|
|
@@ -34,19 +55,32 @@ export interface PolicyEnv {
|
|
|
34
55
|
X402_TRUSTED_PAY_TO?: string;
|
|
35
56
|
X402_ALLOWED_ASSETS?: string;
|
|
36
57
|
X402_MAX_USD?: string;
|
|
37
|
-
X402_MAX_A402_ATOMIC?: string;
|
|
38
|
-
X402_MAX_A402_PER_DAY_ATOMIC?: string;
|
|
39
58
|
X402_MAX_PAYMENTS_PER_DAY?: string;
|
|
40
59
|
X402_MAX_USD_PER_DAY?: string;
|
|
60
|
+
X402_MAX_USD_PER_RECIPIENT_PER_DAY?: string;
|
|
61
|
+
X402_MAX_PREQ_PER_RECIPIENT_PER_DAY_ATOMIC?: string;
|
|
41
62
|
X402_CONFIRM_ABOVE_USD?: string;
|
|
63
|
+
X402_MAX_PREQ_ATOMIC?: string;
|
|
64
|
+
X402_MAX_PREQ_PER_DAY_ATOMIC?: string;
|
|
65
|
+
X402_CONFIRM_ABOVE_PREQ_ATOMIC?: string;
|
|
66
|
+
/** A402 (v1, deprecated): only meaningful when A402 is allowed explicitly */
|
|
67
|
+
X402_MAX_A402_ATOMIC?: string;
|
|
68
|
+
X402_MAX_A402_PER_DAY_ATOMIC?: string;
|
|
42
69
|
X402_CONFIRM_ABOVE_A402_ATOMIC?: string;
|
|
43
70
|
X402_PAY_WITH?: string;
|
|
44
|
-
/**
|
|
71
|
+
/** Only to change or set mints, e.g. in rehearsals */
|
|
45
72
|
X402_USDC_MINT?: string;
|
|
73
|
+
X402_PREQ_MINT?: string;
|
|
46
74
|
X402_A402_MINT?: string;
|
|
47
75
|
}
|
|
76
|
+
/** Environment variable names for token limits */
|
|
77
|
+
export declare const tokenEnv: (t: TokenSymbol) => {
|
|
78
|
+
perPayment: string;
|
|
79
|
+
perDay: string;
|
|
80
|
+
confirmAbove: string;
|
|
81
|
+
};
|
|
48
82
|
export declare function policyFromEnv(env: PolicyEnv): PayPolicy;
|
|
49
|
-
/**
|
|
83
|
+
/** Whether paying for this URL is allowed (domain allowlist + https; http only for localhost) */
|
|
50
84
|
export declare function domainCheck(p: PayPolicy, url: string): {
|
|
51
85
|
ok: true;
|
|
52
86
|
host: string;
|
|
@@ -56,21 +90,32 @@ export declare function domainCheck(p: PayPolicy, url: string): {
|
|
|
56
90
|
};
|
|
57
91
|
export interface DayUsage {
|
|
58
92
|
count: number;
|
|
59
|
-
usd: number;
|
|
93
|
+
usd: number;
|
|
94
|
+
/** Total PREQ signed today (base units) */
|
|
95
|
+
preq: bigint;
|
|
96
|
+
/** Total A402 (v1) signed today (base units) */
|
|
60
97
|
a402: bigint;
|
|
61
98
|
}
|
|
99
|
+
/** Today's signed payments to one recipient (payTo) */
|
|
100
|
+
export interface RecipientUsage {
|
|
101
|
+
count: number;
|
|
102
|
+
usd: number;
|
|
103
|
+
preq: bigint;
|
|
104
|
+
}
|
|
62
105
|
export interface Evaluated {
|
|
63
106
|
requirement: PaymentRequirements;
|
|
64
107
|
asset: AssetSymbol | null;
|
|
65
108
|
ok: boolean;
|
|
66
109
|
reasons: string[];
|
|
67
|
-
/**
|
|
110
|
+
/** Whether human confirmation is needed (meaningful only when ok) */
|
|
68
111
|
needsConfirmation: boolean;
|
|
69
|
-
/**
|
|
112
|
+
/** USD amount if USDC */
|
|
70
113
|
usd: number | null;
|
|
71
114
|
}
|
|
72
115
|
export declare function symbolOf(p: PayPolicy, mint: string): AssetSymbol | null;
|
|
73
|
-
/**
|
|
74
|
-
export declare function evaluate(p: PayPolicy, r: PaymentRequirements, usage: DayUsage): Evaluated;
|
|
75
|
-
/**
|
|
116
|
+
/** Evaluates one payment requirement against the policy (before signing) */
|
|
117
|
+
export declare function evaluate(p: PayPolicy, r: PaymentRequirements, usage: DayUsage, recipient?: RecipientUsage): Evaluated;
|
|
118
|
+
/** Requirement to choose after evaluation (preferred asset first) */
|
|
76
119
|
export declare function choose(p: PayPolicy, evs: Evaluated[]): Evaluated | null;
|
|
120
|
+
/** Warnings when today's usage has reached a share (default 80%) of a daily cap. Informational only; the caps themselves are enforced by evaluate() */
|
|
121
|
+
export declare function nearLimits(p: PayPolicy, usage: DayUsage, share?: number): string[];
|
package/dist/policy.js
CHANGED
|
@@ -1,37 +1,70 @@
|
|
|
1
|
+
import { formatUnits } from './units.js';
|
|
1
2
|
export const NETWORKS = {
|
|
2
3
|
mainnet: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
|
|
3
4
|
devnet: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',
|
|
4
5
|
};
|
|
6
|
+
/**
|
|
7
|
+
* PREQ mainnet mint (Token-2022, 6 decimals). Same value as PREQ_MAINNET_MINT in pay-server src/preq.ts.
|
|
8
|
+
* Set after the PREQ launch on 2026-11-21. X402_PREQ_MINT can override it (e.g. for devnet rehearsals)
|
|
9
|
+
*/
|
|
10
|
+
export const PREQ_MAINNET_MINT = 'aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX';
|
|
11
|
+
export const A402_DEPRECATION_WARNING = 'A402 (v1) is deprecated and no longer supported; use PREQ.';
|
|
5
12
|
const DEFAULT_MINTS = {
|
|
6
|
-
[NETWORKS.mainnet]: { USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', A402: 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X' },
|
|
7
|
-
|
|
13
|
+
[NETWORKS.mainnet]: { USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', PREQ: PREQ_MAINNET_MINT, A402: 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X' },
|
|
14
|
+
// No devnet PREQ mint; rehearsals pass one with X402_PREQ_MINT
|
|
15
|
+
[NETWORKS.devnet]: { USDC: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', PREQ: '', A402: '5R2rKmzsNk1S5mFPR99bU1anromo73brwNApghvXeb46' },
|
|
8
16
|
};
|
|
17
|
+
export const TOKEN_SYMBOLS = ['PREQ', 'A402'];
|
|
18
|
+
const ASSET_SYMBOLS = ['USDC', 'PREQ', 'A402'];
|
|
9
19
|
const list = (s) => (s ?? '').split(',').map((x) => x.trim()).filter(Boolean);
|
|
10
20
|
const num = (s, d) => (s && Number.isFinite(Number(s)) ? Number(s) : d);
|
|
11
|
-
/**
|
|
21
|
+
/** Integer in base units (positive only). null if missing or invalid */
|
|
12
22
|
const atomic = (s) => (s && /^\d+$/.test(s.trim()) && BigInt(s.trim()) > 0n ? BigInt(s.trim()) : null);
|
|
23
|
+
const isAsset = (a) => ASSET_SYMBOLS.includes(a);
|
|
24
|
+
/** Environment variable names for token limits */
|
|
25
|
+
export const tokenEnv = (t) => ({
|
|
26
|
+
perPayment: `X402_MAX_${t}_ATOMIC`,
|
|
27
|
+
perDay: `X402_MAX_${t}_PER_DAY_ATOMIC`,
|
|
28
|
+
confirmAbove: `X402_CONFIRM_ABOVE_${t}_ATOMIC`,
|
|
29
|
+
});
|
|
13
30
|
export function policyFromEnv(env) {
|
|
14
31
|
const network = env.X402_NETWORK === 'devnet' ? NETWORKS.devnet : NETWORKS.mainnet;
|
|
15
32
|
const m = DEFAULT_MINTS[network];
|
|
33
|
+
const e = env;
|
|
34
|
+
const mints = { USDC: env.X402_USDC_MINT ?? m.USDC, PREQ: env.X402_PREQ_MINT ?? m.PREQ, A402: env.X402_A402_MINT ?? m.A402 };
|
|
35
|
+
const allowedAssets = (list(env.X402_ALLOWED_ASSETS).length ? list(env.X402_ALLOWED_ASSETS) : ['USDC']).filter(isAsset);
|
|
36
|
+
if (allowedAssets.includes('PREQ') && !mints.PREQ) {
|
|
37
|
+
throw new Error('PREQ mint is not set: PREQ payments cannot be enabled yet. Fill PREQ_MAINNET_MINT in @agent402-dev/pay-mcp src/policy.ts after the PREQ launch, or set X402_PREQ_MINT.');
|
|
38
|
+
}
|
|
39
|
+
const warnings = [];
|
|
40
|
+
if (allowedAssets.includes('A402') || env.X402_PAY_WITH === 'A402')
|
|
41
|
+
warnings.push(A402_DEPRECATION_WARNING);
|
|
42
|
+
// Tokens have no defaults: both per-payment and daily must be set to pay (USD limits do not apply to tokens)
|
|
43
|
+
const limitsFor = (t) => {
|
|
44
|
+
const n = tokenEnv(t);
|
|
45
|
+
const c = e[n.confirmAbove];
|
|
46
|
+
return { perPayment: atomic(e[n.perPayment]), perDay: atomic(e[n.perDay]), confirmAbove: c && /^\d+$/.test(c.trim()) ? BigInt(c.trim()) : null };
|
|
47
|
+
};
|
|
48
|
+
const prefer = env.X402_PAY_WITH && isAsset(env.X402_PAY_WITH) ? env.X402_PAY_WITH : 'USDC';
|
|
16
49
|
return {
|
|
17
50
|
network,
|
|
18
|
-
mints
|
|
51
|
+
mints,
|
|
19
52
|
allowedDomains: list(env.X402_ALLOWED_DOMAINS).map((d) => d.toLowerCase()),
|
|
20
53
|
trustedPayTo: list(env.X402_TRUSTED_PAY_TO),
|
|
21
|
-
allowedAssets
|
|
54
|
+
allowedAssets,
|
|
22
55
|
maxUsdPerPayment: num(env.X402_MAX_USD, 0.05),
|
|
23
|
-
// A402 는 기본값 없음 — 둘 다 설정해야 A402 결제 가능 (USD 기준 한도가 A402 에는 적용되지 않으므로)
|
|
24
|
-
maxA402PerPayment: atomic(env.X402_MAX_A402_ATOMIC),
|
|
25
|
-
maxA402PerDay: atomic(env.X402_MAX_A402_PER_DAY_ATOMIC),
|
|
26
56
|
maxPaymentsPerDay: num(env.X402_MAX_PAYMENTS_PER_DAY, 20),
|
|
27
57
|
maxUsdPerDay: num(env.X402_MAX_USD_PER_DAY, 1),
|
|
58
|
+
maxUsdPerRecipientPerDay: Number(env.X402_MAX_USD_PER_RECIPIENT_PER_DAY) > 0 ? Number(env.X402_MAX_USD_PER_RECIPIENT_PER_DAY) : null,
|
|
59
|
+
maxPreqPerRecipientPerDay: atomic(env.X402_MAX_PREQ_PER_RECIPIENT_PER_DAY_ATOMIC),
|
|
28
60
|
confirmAboveUsd: env.X402_CONFIRM_ABOVE_USD ? Number(env.X402_CONFIRM_ABOVE_USD) : null,
|
|
29
|
-
|
|
30
|
-
prefer
|
|
61
|
+
tokenLimits: { PREQ: limitsFor('PREQ'), A402: limitsFor('A402') },
|
|
62
|
+
prefer,
|
|
63
|
+
warnings,
|
|
31
64
|
};
|
|
32
65
|
}
|
|
33
66
|
const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
34
|
-
/**
|
|
67
|
+
/** Whether paying for this URL is allowed (domain allowlist + https; http only for localhost) */
|
|
35
68
|
export function domainCheck(p, url) {
|
|
36
69
|
let u;
|
|
37
70
|
try {
|
|
@@ -49,11 +82,15 @@ export function domainCheck(p, url) {
|
|
|
49
82
|
return { ok: false, reason: `domain_not_allowed: ${host}` };
|
|
50
83
|
return { ok: true, host };
|
|
51
84
|
}
|
|
85
|
+
const NO_RECIPIENT_USAGE = { count: 0, usd: 0, preq: 0n };
|
|
52
86
|
export function symbolOf(p, mint) {
|
|
53
|
-
|
|
87
|
+
if (!mint)
|
|
88
|
+
return null;
|
|
89
|
+
return ASSET_SYMBOLS.find((s) => p.mints[s] && p.mints[s] === mint) ?? null;
|
|
54
90
|
}
|
|
55
|
-
|
|
56
|
-
|
|
91
|
+
const usedToday = (usage, t) => (t === 'PREQ' ? usage.preq : usage.a402);
|
|
92
|
+
/** Evaluates one payment requirement against the policy (before signing) */
|
|
93
|
+
export function evaluate(p, r, usage, recipient = NO_RECIPIENT_USAGE) {
|
|
57
94
|
const reasons = [];
|
|
58
95
|
const asset = symbolOf(p, r.asset);
|
|
59
96
|
if (r.scheme !== 'exact')
|
|
@@ -63,7 +100,7 @@ export function evaluate(p, r, usage) {
|
|
|
63
100
|
if (!asset)
|
|
64
101
|
reasons.push(`asset_not_allowed: unknown mint ${r.asset}`);
|
|
65
102
|
else if (!p.allowedAssets.includes(asset))
|
|
66
|
-
reasons.push(`asset_not_allowed: ${asset} (X402_ALLOWED_ASSETS)`);
|
|
103
|
+
reasons.push(`asset_not_allowed: ${asset} (X402_ALLOWED_ASSETS)${asset === 'A402' ? ' — A402 (v1) is deprecated; use PREQ' : ''}`);
|
|
67
104
|
if (!p.trustedPayTo.length)
|
|
68
105
|
reasons.push('pay_to_not_trusted: trusted recipient list is empty (X402_TRUSTED_PAY_TO)');
|
|
69
106
|
else if (!p.trustedPayTo.includes(r.payTo))
|
|
@@ -84,25 +121,50 @@ export function evaluate(p, r, usage) {
|
|
|
84
121
|
reasons.push(`over_per_payment_limit: ${usd} USD > ${p.maxUsdPerPayment} USD`);
|
|
85
122
|
if (usage.usd + usd > p.maxUsdPerDay)
|
|
86
123
|
reasons.push(`over_daily_usd_limit: ${usage.usd} + ${usd} > ${p.maxUsdPerDay} USD`);
|
|
124
|
+
if (p.maxUsdPerRecipientPerDay !== null && recipient.usd + usd > p.maxUsdPerRecipientPerDay) {
|
|
125
|
+
reasons.push(`over_daily_recipient_usd_limit: ${recipient.usd} + ${usd} > ${p.maxUsdPerRecipientPerDay} USD to ${r.payTo} (X402_MAX_USD_PER_RECIPIENT_PER_DAY)`);
|
|
126
|
+
}
|
|
87
127
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
128
|
+
let needsTokenConfirm = false;
|
|
129
|
+
if (asset && asset !== 'USDC' && p.allowedAssets.includes(asset) && amount > 0n) {
|
|
130
|
+
const l = p.tokenLimits[asset];
|
|
131
|
+
const n = tokenEnv(asset);
|
|
132
|
+
const lc = asset.toLowerCase();
|
|
133
|
+
const unit = `${asset} smallest units`;
|
|
134
|
+
if (l.perPayment === null)
|
|
135
|
+
reasons.push(`${lc}_limit_not_configured: set ${n.perPayment} (max ${asset} per payment, in ${unit}: 1 ${asset} = 1,000,000)`);
|
|
136
|
+
else if (amount > l.perPayment)
|
|
137
|
+
reasons.push(`over_per_payment_limit: ${amount} > ${l.perPayment} (${unit})`);
|
|
138
|
+
if (l.perDay === null)
|
|
139
|
+
reasons.push(`${lc}_limit_not_configured: set ${n.perDay} (max ${asset} per UTC day, in ${unit}: 1 ${asset} = 1,000,000)`);
|
|
140
|
+
else if (usedToday(usage, asset) + amount > l.perDay)
|
|
141
|
+
reasons.push(`over_daily_${lc}_limit: ${usedToday(usage, asset)} + ${amount} > ${l.perDay} (${unit})`);
|
|
142
|
+
if (asset === 'PREQ' && p.maxPreqPerRecipientPerDay !== null && recipient.preq + amount > p.maxPreqPerRecipientPerDay) {
|
|
143
|
+
reasons.push(`over_daily_recipient_preq_limit: ${recipient.preq} + ${amount} > ${p.maxPreqPerRecipientPerDay} (${unit}) to ${r.payTo} (X402_MAX_PREQ_PER_RECIPIENT_PER_DAY_ATOMIC)`);
|
|
144
|
+
}
|
|
145
|
+
needsTokenConfirm = l.confirmAbove !== null && amount >= l.confirmAbove;
|
|
97
146
|
}
|
|
98
147
|
if (usage.count >= p.maxPaymentsPerDay)
|
|
99
148
|
reasons.push(`over_daily_count_limit: ${p.maxPaymentsPerDay}`);
|
|
100
|
-
const needsConfirmation = (asset === 'USDC' && p.confirmAboveUsd !== null && usd !== null && usd >= p.confirmAboveUsd) ||
|
|
101
|
-
(asset === 'A402' && p.confirmAboveA402 !== null && amount >= p.confirmAboveA402);
|
|
149
|
+
const needsConfirmation = (asset === 'USDC' && p.confirmAboveUsd !== null && usd !== null && usd >= p.confirmAboveUsd) || needsTokenConfirm;
|
|
102
150
|
return { requirement: r, asset, ok: reasons.length === 0, reasons, needsConfirmation, usd };
|
|
103
151
|
}
|
|
104
|
-
/**
|
|
152
|
+
/** Requirement to choose after evaluation (preferred asset first) */
|
|
105
153
|
export function choose(p, evs) {
|
|
106
154
|
const ok = evs.filter((e) => e.ok);
|
|
107
155
|
return ok.find((e) => e.asset === p.prefer) ?? ok[0] ?? null;
|
|
108
156
|
}
|
|
157
|
+
/** Warnings when today's usage has reached a share (default 80%) of a daily cap. Informational only; the caps themselves are enforced by evaluate() */
|
|
158
|
+
export function nearLimits(p, usage, share = 0.8) {
|
|
159
|
+
const w = [];
|
|
160
|
+
const usd = Math.round(usage.usd * 1e6) / 1e6;
|
|
161
|
+
if (p.maxUsdPerDay > 0 && usd >= p.maxUsdPerDay * share - 1e-9)
|
|
162
|
+
w.push(`near_daily_usd_limit: ${usd} of ${p.maxUsdPerDay} USD used today (UTC)`);
|
|
163
|
+
if (p.maxPaymentsPerDay > 0 && usage.count >= p.maxPaymentsPerDay * share)
|
|
164
|
+
w.push(`near_daily_count_limit: ${usage.count} of ${p.maxPaymentsPerDay} payments today (UTC)`);
|
|
165
|
+
const preqCap = p.tokenLimits.PREQ.perDay;
|
|
166
|
+
if (preqCap !== null && usage.preq * 100n >= preqCap * BigInt(Math.round(share * 100))) {
|
|
167
|
+
w.push(`near_daily_preq_limit: ${formatUnits(usage.preq, 'PREQ')} of ${formatUnits(preqCap, 'PREQ')} used today (UTC)`);
|
|
168
|
+
}
|
|
169
|
+
return w;
|
|
170
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export declare const RECEIPT_HEADER = "x-agent402-receipt";
|
|
2
|
+
export interface ReceiptCheck {
|
|
3
|
+
/** Base58 public key that signed the receipt (null if unreadable) */
|
|
4
|
+
signer: string | null;
|
|
5
|
+
/** true only if the signature is valid and every field matches */
|
|
6
|
+
verified: boolean;
|
|
7
|
+
/** Why it is not verified */
|
|
8
|
+
reasons: string[];
|
|
9
|
+
/** The receipt as received (keep it as evidence) */
|
|
10
|
+
token: string;
|
|
11
|
+
}
|
|
12
|
+
export interface ReceiptExpect {
|
|
13
|
+
method: string;
|
|
14
|
+
/** URL the payment request was sent to (only path and query are compared, as the server may see another host behind a proxy) */
|
|
15
|
+
url: string;
|
|
16
|
+
requestBody?: string;
|
|
17
|
+
responseBody: ArrayBuffer;
|
|
18
|
+
payment: {
|
|
19
|
+
network: string;
|
|
20
|
+
asset: string;
|
|
21
|
+
amount: string;
|
|
22
|
+
payTo: string;
|
|
23
|
+
transaction?: string;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export declare function checkReceipt(token: string, e: ReceiptExpect): Promise<ReceiptCheck>;
|
package/dist/receipt.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Checks a seller's signed receipt (header x-agent402-receipt, made by @agent402-dev/pay-server) against what this client actually sent, received and paid.
|
|
2
|
+
// The receipt proves that the holder of the receipt key signed it. Which seller owns that key is up to the seller to publish.
|
|
3
|
+
import { getBase58Encoder } from '@solana/kit';
|
|
4
|
+
export const RECEIPT_HEADER = 'x-agent402-receipt';
|
|
5
|
+
const b64urlDecode = (s) => new Uint8Array(Buffer.from(s, 'base64url'));
|
|
6
|
+
const sha256Hex = async (d) => Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', d)), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
7
|
+
const pathOf = (u) => { try {
|
|
8
|
+
const x = new URL(u);
|
|
9
|
+
return `${x.pathname}${x.search}`;
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return u;
|
|
13
|
+
} };
|
|
14
|
+
export async function checkReceipt(token, e) {
|
|
15
|
+
const fail = (signer, reasons) => ({ signer, verified: false, reasons, token });
|
|
16
|
+
const parts = token.split('.');
|
|
17
|
+
if (parts.length !== 2 || token.length > 8_000)
|
|
18
|
+
return fail(null, ['receipt_malformed']);
|
|
19
|
+
let bytes;
|
|
20
|
+
let r;
|
|
21
|
+
try {
|
|
22
|
+
bytes = b64urlDecode(parts[0]);
|
|
23
|
+
r = JSON.parse(new TextDecoder().decode(bytes));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return fail(null, ['receipt_malformed']);
|
|
27
|
+
}
|
|
28
|
+
const signer = typeof r.signer === 'string' ? r.signer : null;
|
|
29
|
+
if (r.v !== 1 || r.kind !== 'agent402.x402-receipt' || !signer)
|
|
30
|
+
return fail(signer, ['receipt_unknown_format']);
|
|
31
|
+
let sigOk = false;
|
|
32
|
+
try {
|
|
33
|
+
const pub = getBase58Encoder().encode(signer);
|
|
34
|
+
const key = await crypto.subtle.importKey('raw', pub, { name: 'Ed25519' }, false, ['verify']);
|
|
35
|
+
sigOk = await crypto.subtle.verify('Ed25519', key, b64urlDecode(parts[1]), bytes);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
sigOk = false;
|
|
39
|
+
}
|
|
40
|
+
const reasons = [];
|
|
41
|
+
if (!sigOk)
|
|
42
|
+
reasons.push('receipt_bad_signature');
|
|
43
|
+
const p = r.payment ?? {};
|
|
44
|
+
for (const k of ['network', 'asset', 'amount', 'payTo'])
|
|
45
|
+
if (p[k] !== e.payment[k])
|
|
46
|
+
reasons.push(`receipt_payment_mismatch: ${k}`);
|
|
47
|
+
if (e.payment.transaction && p.transaction && p.transaction !== e.payment.transaction)
|
|
48
|
+
reasons.push('receipt_payment_mismatch: transaction');
|
|
49
|
+
if ((r.request?.method ?? '').toUpperCase() !== e.method.toUpperCase())
|
|
50
|
+
reasons.push('receipt_request_mismatch: method');
|
|
51
|
+
if (r.request?.path !== pathOf(e.url))
|
|
52
|
+
reasons.push('receipt_request_mismatch: path');
|
|
53
|
+
const reqHash = e.requestBody ? await sha256Hex(new TextEncoder().encode(e.requestBody)) : null;
|
|
54
|
+
if ((r.request?.bodySha256 ?? null) !== reqHash)
|
|
55
|
+
reasons.push('receipt_request_mismatch: body');
|
|
56
|
+
if (r.response?.bodySha256 !== (await sha256Hex(e.responseBody)))
|
|
57
|
+
reasons.push('receipt_response_mismatch: body');
|
|
58
|
+
return { signer, verified: reasons.length === 0, reasons, token };
|
|
59
|
+
}
|
package/dist/server.js
CHANGED
|
@@ -1,22 +1,78 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// @agent402-dev/pay-mcp (stdio)
|
|
3
|
-
// X402_KEYPAIR_PATH
|
|
4
|
-
// X402_RPC_URL
|
|
5
|
-
// X402_HISTORY_PATH
|
|
6
|
-
//
|
|
2
|
+
// @agent402-dev/pay-mcp. With no command it runs the MCP server (stdio), configured with environment variables: policy.ts PolicyEnv and the following:
|
|
3
|
+
// X402_KEYPAIR_PATH payment wallet key file (Solana CLI JSON). Without it, no payments (x402_quote only)
|
|
4
|
+
// X402_RPC_URL RPC used to build payment transactions (public RPC if unset)
|
|
5
|
+
// X402_HISTORY_PATH payment history JSONL (default ~/.agent402/payments.jsonl)
|
|
6
|
+
// Allowlists (X402_ALLOWED_DOMAINS, X402_TRUSTED_PAY_TO) default to empty = reject everything
|
|
7
|
+
// Commands: init (create a dedicated payment wallet key file), export-csv (payment history as CSV), help
|
|
8
|
+
import { writeFileSync } from 'node:fs';
|
|
7
9
|
import { homedir } from 'node:os';
|
|
8
10
|
import { join } from 'node:path';
|
|
9
11
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
12
|
+
import { historyToCsv } from './csv.js';
|
|
10
13
|
import { jsonlHistory } from './history.js';
|
|
14
|
+
import { initWallet } from './init.js';
|
|
11
15
|
import { policyFromEnv } from './policy.js';
|
|
12
16
|
import { createPayServer } from './tools.js';
|
|
13
17
|
import { loadWallet } from './wallet.js';
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
18
|
+
const DEFAULT_HISTORY = join(homedir(), '.agent402', 'payments.jsonl');
|
|
19
|
+
const HELP = `@agent402-dev/pay-mcp
|
|
20
|
+
|
|
21
|
+
npx -y @agent402-dev/pay-mcp run the MCP server (stdio)
|
|
22
|
+
npx -y @agent402-dev/pay-mcp init [--path <file>] [--network devnet]
|
|
23
|
+
create a dedicated payment wallet key file (default ~/.agent402/pay-wallet.json)
|
|
24
|
+
npx -y @agent402-dev/pay-mcp export-csv [--history <file>] [--out <file>]
|
|
25
|
+
write the local payment history as CSV (stdout unless --out)
|
|
26
|
+
`;
|
|
27
|
+
const [cmd, ...args] = process.argv.slice(2);
|
|
28
|
+
const opt = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; };
|
|
29
|
+
if (cmd === 'init') {
|
|
30
|
+
try {
|
|
31
|
+
const r = await initWallet({ path: opt('--path'), network: opt('--network') === 'devnet' ? 'devnet' : 'mainnet' });
|
|
32
|
+
console.log(r.text);
|
|
33
|
+
}
|
|
34
|
+
catch (e) {
|
|
35
|
+
console.error(e.message);
|
|
36
|
+
process.exitCode = 1;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
else if (cmd === 'export-csv') {
|
|
40
|
+
const history = jsonlHistory(opt('--history') ?? process.env.X402_HISTORY_PATH ?? DEFAULT_HISTORY, () => ({ USDC: '', PREQ: '', A402: '' }));
|
|
41
|
+
const entries = history.list(Number.MAX_SAFE_INTEGER).reverse(); // oldest first
|
|
42
|
+
const csv = historyToCsv(entries);
|
|
43
|
+
const outPath = opt('--out');
|
|
44
|
+
if (!outPath)
|
|
45
|
+
process.stdout.write(csv);
|
|
46
|
+
else {
|
|
47
|
+
try {
|
|
48
|
+
writeFileSync(outPath, csv, { flag: 'wx' });
|
|
49
|
+
console.error(`Wrote ${entries.length} payment record(s) to ${outPath}`);
|
|
50
|
+
}
|
|
51
|
+
catch (e) {
|
|
52
|
+
console.error(e.code === 'EEXIST' ? `A file already exists at ${outPath}. It was not changed.` : e.message);
|
|
53
|
+
process.exitCode = 1;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
else if (cmd === 'help' || cmd === '--help' || cmd === '-h') {
|
|
58
|
+
console.log(HELP);
|
|
59
|
+
}
|
|
60
|
+
else if (cmd) {
|
|
61
|
+
console.error(`Unknown command: ${cmd}\n\n${HELP}`);
|
|
62
|
+
process.exitCode = 2;
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
// If PREQ is allowed but its mint is empty, stop here with an error (policyFromEnv)
|
|
66
|
+
const policy = policyFromEnv(process.env);
|
|
67
|
+
// If A402 (v1) is enabled explicitly, print the deprecation warning (stderr; stdout is for MCP)
|
|
68
|
+
for (const w of policy.warnings)
|
|
69
|
+
console.error(`[a402-pay] WARNING: ${w}`);
|
|
70
|
+
const wallet = process.env.X402_KEYPAIR_PATH
|
|
71
|
+
? await loadWallet(process.env.X402_KEYPAIR_PATH, policy, process.env.X402_RPC_URL).catch((e) => {
|
|
72
|
+
console.error(`[a402-pay] could not load wallet, starting without payments: ${e.message}`);
|
|
73
|
+
return null;
|
|
74
|
+
})
|
|
75
|
+
: null;
|
|
76
|
+
const history = jsonlHistory(process.env.X402_HISTORY_PATH ?? DEFAULT_HISTORY, () => policy.mints);
|
|
77
|
+
await createPayServer({ policy, wallet, history, fetch }).connect(new StdioServerTransport());
|
|
78
|
+
}
|
package/dist/tools.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
2
|
import type { History } from './history.js';
|
|
3
|
-
import type
|
|
3
|
+
import { type PayPolicy } from './policy.js';
|
|
4
4
|
import type { Wallet } from './wallet.js';
|
|
5
5
|
export interface PayServerDeps {
|
|
6
6
|
policy: PayPolicy;
|
package/dist/tools.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
// @agent402-dev/pay-mcp
|
|
1
|
+
// @agent402-dev/pay-mcp's 4 tools: x402_fetch, x402_quote, wallet_status, payment_history
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
4
4
|
import { createAgent } from './agent.js';
|
|
5
|
+
import { historyToCsv } from './csv.js';
|
|
6
|
+
import { nearLimits, tokenEnv } from './policy.js';
|
|
5
7
|
import { formatUnits } from './units.js';
|
|
6
8
|
const out = (obj, isError = false) => ({ content: [{ type: 'text', text: JSON.stringify(obj, null, 2) }], ...(isError ? { isError } : {}) });
|
|
7
9
|
const bigintSafe = (o) => JSON.parse(JSON.stringify(o, (_k, v) => (typeof v === 'bigint' ? v.toString() : v)));
|
|
8
|
-
/**
|
|
10
|
+
/** Adds a unit description and display value to each { asset: 'USDC'|'PREQ'|'A402', amount: '<base units>' } in the result (token amounts always with units) */
|
|
9
11
|
function withUnits(o) {
|
|
10
12
|
if (Array.isArray(o))
|
|
11
13
|
return o.map(withUnits);
|
|
@@ -14,15 +16,28 @@ function withUnits(o) {
|
|
|
14
16
|
const r = {};
|
|
15
17
|
for (const [k, v] of Object.entries(o))
|
|
16
18
|
r[k] = withUnits(v);
|
|
17
|
-
if ((r.asset === 'USDC' || r.asset === 'A402') && typeof r.amount === 'string' && /^\d+$/.test(r.amount)) {
|
|
19
|
+
if ((r.asset === 'USDC' || r.asset === 'PREQ' || r.asset === 'A402') && typeof r.amount === 'string' && /^\d+$/.test(r.amount)) {
|
|
18
20
|
r.amountUnit = `${r.asset} smallest unit (1 ${r.asset} = 1,000,000)`;
|
|
19
21
|
r.amountDisplay = formatUnits(r.amount, r.asset);
|
|
20
22
|
}
|
|
21
23
|
return r;
|
|
22
24
|
}
|
|
23
|
-
const atomicLimit = (v, envName) => v === null ? `not set (${envName}) —
|
|
25
|
+
const atomicLimit = (v, envName, sym) => v === null ? `not set (${envName}) — ${sym} payments refused` : v;
|
|
26
|
+
/** Token limits in wallet_status (e.g. maxPreqPerPaymentAtomic, maxPreqPerPaymentDisplay …) */
|
|
27
|
+
function tokenLimitFields(p, t) {
|
|
28
|
+
const l = p.tokenLimits[t];
|
|
29
|
+
const n = tokenEnv(t);
|
|
30
|
+
const k = t === 'PREQ' ? 'Preq' : 'A402';
|
|
31
|
+
return {
|
|
32
|
+
[`max${k}PerPaymentAtomic`]: atomicLimit(l.perPayment, n.perPayment, t),
|
|
33
|
+
[`max${k}PerDayAtomic`]: atomicLimit(l.perDay, n.perDay, t),
|
|
34
|
+
...(l.perPayment !== null ? { [`max${k}PerPaymentDisplay`]: formatUnits(l.perPayment, t) } : {}),
|
|
35
|
+
...(l.perDay !== null ? { [`max${k}PerDayDisplay`]: formatUnits(l.perDay, t) } : {}),
|
|
36
|
+
[`confirmAbove${k}Atomic`]: l.confirmAbove,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
24
39
|
export function createPayServer(d) {
|
|
25
|
-
const server = new McpServer({ name: 'a402-pay', version: '0.
|
|
40
|
+
const server = new McpServer({ name: 'a402-pay', version: '0.3.0' });
|
|
26
41
|
const confirm = async (message) => {
|
|
27
42
|
if (!server.server.getClientCapabilities()?.elicitation)
|
|
28
43
|
return 'unsupported';
|
|
@@ -34,31 +49,43 @@ export function createPayServer(d) {
|
|
|
34
49
|
};
|
|
35
50
|
const agent = createAgent({ ...d, confirm });
|
|
36
51
|
const req = { url: z.string().url(), method: z.enum(['GET', 'POST']).optional(), headers: z.record(z.string(), z.string()).optional(), body: z.string().max(100_000).optional() };
|
|
37
|
-
server.tool('x402_fetch', 'Fetch a URL and, if it answers HTTP 402 (x402), pay from the configured wallet only when every rule passes before signing: allowed domain (X402_ALLOWED_DOMAINS), trusted recipient (X402_TRUSTED_PAY_TO), allowed asset (USDC by default;
|
|
52
|
+
server.tool('x402_fetch', 'Fetch a URL and, if it answers HTTP 402 (x402), pay from the configured wallet only when every rule passes before signing: allowed domain (X402_ALLOWED_DOMAINS), trusted recipient (X402_TRUSTED_PAY_TO), allowed asset (USDC by default; PREQ only if listed; A402 (v1) is deprecated), per-payment and daily limits, and human confirmation above the configured amount. Signs at most once per call. Pass quoteId from x402_quote to refuse if the requirements changed. The wallet key never leaves this machine.', { ...req, quoteId: z.string().optional() }, async (a) => { const r = await agent.payAndFetch(a); return out(withUnits(r), !['paid', 'not_required'].includes(r.result)); });
|
|
38
53
|
server.tool('x402_quote', 'Show the x402 payment requirements of a URL and whether each option passes the payment rules. Never signs or pays. Returns a quoteId that x402_fetch can use to pin the amount, asset and recipient.', req, async (a) => { const r = await agent.quote(a); return out(withUnits(r), r.result === 'refused'); });
|
|
39
|
-
server.tool('wallet_status', 'Payment wallet address, network, USDC and
|
|
40
|
-
const
|
|
54
|
+
server.tool('wallet_status', 'Payment wallet address, network, USDC and PREQ balances, payments signed today, and the configured limits and allowlists.', {}, async () => {
|
|
55
|
+
const usage = d.history.today(d.now?.());
|
|
56
|
+
const { preq, a402, ...today } = usage;
|
|
57
|
+
const near = nearLimits(d.policy, usage);
|
|
41
58
|
const balances = d.wallet ? await d.wallet.balances() : null;
|
|
59
|
+
// A402 (v1) is deprecated: shown only if allowed explicitly or if spent today
|
|
60
|
+
const showA402 = d.policy.allowedAssets.includes('A402') || a402 > 0n;
|
|
42
61
|
return out(bigintSafe({
|
|
43
62
|
address: d.wallet?.address ?? null,
|
|
44
63
|
network: d.policy.network,
|
|
45
|
-
//
|
|
64
|
+
// Balances in token units (e.g. "10 PREQ")
|
|
46
65
|
balances: balances ? Object.fromEntries(Object.entries(balances).map(([k, v]) => [k, /^[\d.]+$/.test(v) ? `${v} ${k}` : v])) : null,
|
|
47
|
-
today: {
|
|
66
|
+
today: {
|
|
67
|
+
...today, usdUnit: 'USD (USDC)',
|
|
68
|
+
preq, preqUnit: 'PREQ smallest unit (1 PREQ = 1,000,000)', preqDisplay: formatUnits(preq, 'PREQ'),
|
|
69
|
+
...(showA402 ? { a402, a402Unit: 'A402 smallest unit (1 A402 = 1,000,000)', a402Display: formatUnits(a402, 'A402') } : {}),
|
|
70
|
+
},
|
|
48
71
|
signedThisSession: d.wallet?.signedCount ?? 0,
|
|
49
72
|
limits: {
|
|
50
73
|
maxUsdPerPayment: d.policy.maxUsdPerPayment, maxUsdPerDay: d.policy.maxUsdPerDay, maxPaymentsPerDay: d.policy.maxPaymentsPerDay,
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
...(d.policy
|
|
55
|
-
|
|
56
|
-
units: '…Usd = US dollars (USDC); …Atomic =
|
|
74
|
+
confirmAboveUsd: d.policy.confirmAboveUsd,
|
|
75
|
+
maxUsdPerRecipientPerDay: d.policy.maxUsdPerRecipientPerDay,
|
|
76
|
+
maxPreqPerRecipientPerDayAtomic: d.policy.maxPreqPerRecipientPerDay,
|
|
77
|
+
...tokenLimitFields(d.policy, 'PREQ'),
|
|
78
|
+
...(showA402 ? tokenLimitFields(d.policy, 'A402') : {}),
|
|
79
|
+
units: '…Usd = US dollars (USDC); …Atomic = token smallest unit (1 PREQ = 1,000,000)',
|
|
57
80
|
},
|
|
58
81
|
allowedDomains: d.policy.allowedDomains, trustedPayTo: d.policy.trustedPayTo, allowedAssets: d.policy.allowedAssets,
|
|
82
|
+
...(d.policy.warnings.length || near.length ? { warnings: [...d.policy.warnings, ...near] } : {}),
|
|
59
83
|
...(d.wallet ? {} : { note: 'No wallet configured (X402_KEYPAIR_PATH): x402_fetch will not pay.' }),
|
|
60
84
|
}));
|
|
61
85
|
});
|
|
62
|
-
server.tool('payment_history', 'Recent payment records from the local JSONL log (time, URL, asset, amount, recipient, result, settlement transaction id). Keys and signed payment payloads are never stored.', { limit: z.number().int().min(1).max(500).optional() }, async ({ limit }) =>
|
|
86
|
+
server.tool('payment_history', 'Recent payment records from the local JSONL log (time, URL, asset, amount, recipient, result, settlement transaction id). Keys and signed payment payloads are never stored. format "csv" returns the records as CSV text (oldest first).', { limit: z.number().int().min(1).max(500).optional(), format: z.enum(['json', 'csv']).optional() }, async ({ limit, format }) => {
|
|
87
|
+
const xs = d.history.list(limit ?? 20);
|
|
88
|
+
return format === 'csv' ? { content: [{ type: 'text', text: historyToCsv([...xs].reverse()) }] } : out(withUnits(xs));
|
|
89
|
+
});
|
|
63
90
|
return server;
|
|
64
91
|
}
|
package/dist/units.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export declare const DECIMALS = 6;
|
|
2
|
-
/**
|
|
2
|
+
/** Base-unit integer → "140,000 PREQ" */
|
|
3
3
|
export declare function formatUnits(atomic: string | bigint, symbol: string): string;
|
|
4
|
-
/** "140,000
|
|
4
|
+
/** "140,000 PREQ (140000000000 smallest units)" */
|
|
5
5
|
export declare const withSmallest: (atomic: string | bigint, symbol: string) => string;
|
package/dist/units.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Amount display: USDC and PREQ (and the deprecated A402) all have 6 decimals. Token amounts are always shown with units
|
|
2
2
|
export const DECIMALS = 6;
|
|
3
|
-
/**
|
|
3
|
+
/** Base-unit integer → "140,000 PREQ" */
|
|
4
4
|
export function formatUnits(atomic, symbol) {
|
|
5
5
|
const s = atomic.toString().padStart(DECIMALS + 1, '0');
|
|
6
6
|
const int = s.slice(0, -DECIMALS).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
7
7
|
const frac = s.slice(-DECIMALS).replace(/0+$/, '');
|
|
8
8
|
return `${int}${frac ? '.' + frac : ''} ${symbol}`;
|
|
9
9
|
}
|
|
10
|
-
/** "140,000
|
|
10
|
+
/** "140,000 PREQ (140000000000 smallest units)" */
|
|
11
11
|
export const withSmallest = (atomic, symbol) => `${formatUnits(atomic, symbol)} (${atomic} smallest units)`;
|
package/dist/wallet.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import type { PaymentRequired, PaymentRequirements } from '@x402/core/types';
|
|
2
|
-
import type
|
|
2
|
+
import { type PayPolicy } from './policy.js';
|
|
3
3
|
export interface Wallet {
|
|
4
4
|
address: string;
|
|
5
5
|
network: string;
|
|
6
|
-
/**
|
|
6
|
+
/** Signs one requirement that passed the policy check → PAYMENT-SIGNATURE header value */
|
|
7
7
|
sign(resource: PaymentRequired['resource'], requirement: PaymentRequirements): Promise<string>;
|
|
8
|
-
/**
|
|
8
|
+
/** Number of signatures made in this process */
|
|
9
9
|
readonly signedCount: number;
|
|
10
10
|
balances(): Promise<Record<string, string>>;
|
|
11
11
|
}
|
package/dist/wallet.js
CHANGED
|
@@ -1,25 +1,30 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// Payment wallet: signs x402 exact payment transactions with a key file on the user's computer (official @x402 client).
|
|
2
|
+
// The key is never sent to the server; only the partially signed transaction goes in the PAYMENT-SIGNATURE header. This module signs only one requirement that passed the policy check
|
|
3
3
|
import { readFileSync } from 'node:fs';
|
|
4
4
|
import { createKeyPairSignerFromBytes } from '@solana/kit';
|
|
5
5
|
import { encodePaymentSignatureHeader } from '@x402/core/http';
|
|
6
6
|
import { x402Client } from '@x402/fetch';
|
|
7
7
|
import { toClientSvmSigner } from '@x402/svm';
|
|
8
8
|
import { ExactSvmScheme } from '@x402/svm/exact/client';
|
|
9
|
+
import { TOKEN_SYMBOLS } from './policy.js';
|
|
9
10
|
export async function loadWallet(keyPath, policy, rpcUrl) {
|
|
10
11
|
const bytes = Uint8Array.from(JSON.parse(readFileSync(keyPath, 'utf8')));
|
|
11
12
|
const signer = await createKeyPairSignerFromBytes(bytes);
|
|
12
13
|
bytes.fill(0);
|
|
13
14
|
let signed = 0;
|
|
14
|
-
|
|
15
|
+
const tokenAllow = TOKEN_SYMBOLS.flatMap((t) => {
|
|
16
|
+
const max = policy.tokenLimits[t].perPayment;
|
|
17
|
+
return policy.allowedAssets.includes(t) && policy.mints[t] && max !== null
|
|
18
|
+
? [{ network: policy.network, asset: policy.mints[t], maxAmountPerPayment: max.toString() }]
|
|
19
|
+
: [];
|
|
20
|
+
});
|
|
21
|
+
// The official client's spending limit is set to the same value (a second safety net)
|
|
15
22
|
const client = x402Client.fromConfig({
|
|
16
23
|
schemes: [{ network: policy.network, client: new ExactSvmScheme(toClientSvmSigner(signer), rpcUrl ? { rpcUrl } : undefined) }],
|
|
17
24
|
spendControls: {
|
|
18
25
|
maxAmountPerPayment: `$${policy.maxUsdPerPayment}`,
|
|
19
|
-
// A402
|
|
20
|
-
...(
|
|
21
|
-
? { allowedAssets: [{ network: policy.network, asset: policy.mints.A402, maxAmountPerPayment: policy.maxA402PerPayment.toString() }] }
|
|
22
|
-
: {}),
|
|
26
|
+
// Tokens (PREQ, A402 (v1)) are allowed in the official client only when allowed and a per-payment cap is set (without a cap the official client rejects too)
|
|
27
|
+
...(tokenAllow.length ? { allowedAssets: tokenAllow } : {}),
|
|
23
28
|
},
|
|
24
29
|
});
|
|
25
30
|
const rpc = rpcUrl ?? (policy.network.includes('EtWTRAB') ? 'https://api.devnet.solana.com' : 'https://api.mainnet-beta.solana.com');
|
|
@@ -35,6 +40,9 @@ export async function loadWallet(keyPath, policy, rpcUrl) {
|
|
|
35
40
|
async balances() {
|
|
36
41
|
const out = {};
|
|
37
42
|
for (const [sym, mint] of Object.entries(policy.mints)) {
|
|
43
|
+
// Skip assets without a mint and A402 (v1) when not allowed
|
|
44
|
+
if (!mint || (sym === 'A402' && !policy.allowedAssets.includes('A402')))
|
|
45
|
+
continue;
|
|
38
46
|
try {
|
|
39
47
|
const r = await fetch(rpc, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getTokenAccountsByOwner', params: [signer.address, { mint }, { encoding: 'jsonParsed' }] }) });
|
|
40
48
|
const j = (await r.json());
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent402-dev/pay-mcp",
|
|
3
|
-
"description": "MCP server that lets an AI agent pay x402 APIs (USDC,
|
|
3
|
+
"description": "MCP server that lets an AI agent pay x402 APIs (USDC, PREQ) from the user's own wallet on the user's machine, within limits and allowlists. With no configuration, every payment is refused.",
|
|
4
4
|
"keywords": [
|
|
5
5
|
"mcp",
|
|
6
6
|
"x402",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"@x402/svm": "2.31.0",
|
|
28
28
|
"zod": "^4.6.7"
|
|
29
29
|
},
|
|
30
|
-
"version": "0.
|
|
30
|
+
"version": "0.3.0",
|
|
31
31
|
"author": "Agent402",
|
|
32
32
|
"license": "Apache-2.0",
|
|
33
33
|
"type": "module",
|