@agent402-dev/pay-mcp 0.2.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 +23 -1
- package/dist/agent.d.ts +6 -0
- package/dist/agent.js +17 -7
- package/dist/csv.d.ts +6 -0
- package/dist/csv.js +20 -0
- package/dist/history.d.ts +13 -0
- package/dist/history.js +15 -7
- package/dist/init.d.ts +12 -0
- package/dist/init.js +67 -0
- package/dist/policy.d.ts +15 -1
- package/dist/policy.js +25 -1
- package/dist/receipt.d.ts +26 -0
- package/dist/receipt.js +59 -0
- package/dist/server.js +66 -14
- package/dist/tools.js +13 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -20,8 +20,10 @@ Nothing is signed unless every rule passes. **With no configuration, every payme
|
|
|
20
20
|
| Max USDC per payment (USD) | `X402_MAX_USD` | `0.05` |
|
|
21
21
|
| Max USDC per UTC day (USD) | `X402_MAX_USD_PER_DAY` | `1` |
|
|
22
22
|
| Max payments per UTC day | `X402_MAX_PAYMENTS_PER_DAY` | `20` |
|
|
23
|
+
| Max USDC per recipient per UTC day (USD) | `X402_MAX_USD_PER_RECIPIENT_PER_DAY` | off (only the overall daily cap) |
|
|
23
24
|
| **Max PREQ per payment** (PREQ smallest units; 1 PREQ = 1,000,000) | `X402_MAX_PREQ_ATOMIC` | **not set → PREQ payments refused** |
|
|
24
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) |
|
|
25
27
|
| Ask a human at or above this USDC amount (USD) | `X402_CONFIRM_ABOVE_USD` | off |
|
|
26
28
|
| Ask a human at or above this PREQ amount (PREQ smallest units) | `X402_CONFIRM_ABOVE_PREQ_ATOMIC` | off |
|
|
27
29
|
|
|
@@ -33,11 +35,20 @@ Nothing is signed unless every rule passes. **With no configuration, every payme
|
|
|
33
35
|
- At most one signature per `x402_fetch` call. If the server answers 402 again after payment, it does not sign again.
|
|
34
36
|
- Redirects are followed manually and each hop must be an allowed domain; a disallowed hop is not contacted.
|
|
35
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.
|
|
36
39
|
- Daily totals count every payment this server signed, whatever the result.
|
|
37
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.
|
|
38
43
|
|
|
39
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`).
|
|
40
45
|
|
|
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.
|
|
51
|
+
|
|
41
52
|
## Connect
|
|
42
53
|
Claude Code (example — set your own allowlists and limits):
|
|
43
54
|
```bash
|
|
@@ -59,10 +70,21 @@ Node 20+. Without `X402_ALLOWED_DOMAINS` and `X402_TRUSTED_PAY_TO` every payment
|
|
|
59
70
|
| `x402_fetch` | Fetch a URL; pay only if the rules pass |
|
|
60
71
|
| `x402_quote` | Show payment requirements and which rules pass; never signs; returns `quoteId` |
|
|
61
72
|
| `wallet_status` | Address, balances, today's usage (count, USDC, PREQ), limits including both PREQ limits, allowlists |
|
|
62
|
-
| `payment_history` | Local log: time, URL, asset, amount, recipient, result, settlement transaction id |
|
|
73
|
+
| `payment_history` | Local log: time, URL, asset, amount, recipient, result, settlement transaction id (JSON, or CSV with `format: "csv"`) |
|
|
63
74
|
|
|
64
75
|
The log never stores keys or signed payment payloads.
|
|
65
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
|
+
|
|
66
88
|
## Use a small, dedicated wallet
|
|
67
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.
|
|
68
90
|
|
package/dist/agent.d.ts
CHANGED
|
@@ -42,6 +42,12 @@ export interface FetchOutcome {
|
|
|
42
42
|
}[];
|
|
43
43
|
/** Warnings (e.g. the deprecation notice when trying to pay with A402 (v1)) */
|
|
44
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
|
+
};
|
|
45
51
|
}
|
|
46
52
|
export declare function createAgent(d: AgentDeps): {
|
|
47
53
|
quote: (spec: RequestSpec) => Promise<FetchOutcome & {
|
package/dist/agent.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
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
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 { A402_DEPRECATION_WARNING, 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]);
|
|
8
9
|
/** Adds the deprecation warning if the chosen asset is A402 (v1) (there is no path that silently pays with A402) */
|
|
@@ -28,8 +29,8 @@ export function createAgent(d) {
|
|
|
28
29
|
}
|
|
29
30
|
return { refused: 'too_many_redirects' };
|
|
30
31
|
}
|
|
31
|
-
const
|
|
32
|
-
const t = (
|
|
32
|
+
const parseBody = (buf) => {
|
|
33
|
+
const t = new TextDecoder().decode(buf).slice(0, 20_000);
|
|
33
34
|
try {
|
|
34
35
|
return JSON.parse(t);
|
|
35
36
|
}
|
|
@@ -37,6 +38,7 @@ export function createAgent(d) {
|
|
|
37
38
|
return t;
|
|
38
39
|
}
|
|
39
40
|
};
|
|
41
|
+
const readBody = async (res) => parseBody(await res.arrayBuffer());
|
|
40
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 });
|
|
41
43
|
const host = (u) => { try {
|
|
42
44
|
return new URL(u).host;
|
|
@@ -67,7 +69,8 @@ export function createAgent(d) {
|
|
|
67
69
|
if (!rc.ok)
|
|
68
70
|
return { kind: 'refused', refused: `resource_on_disallowed_domain: ${rc.reason}` };
|
|
69
71
|
}
|
|
70
|
-
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())));
|
|
71
74
|
return { kind: '402', pr, evs, chosen: choose(d.policy, evs), finalUrl };
|
|
72
75
|
}
|
|
73
76
|
async function quote(spec) {
|
|
@@ -132,7 +135,8 @@ export function createAgent(d) {
|
|
|
132
135
|
return { result: 'failed', reasons: [sent.refused] };
|
|
133
136
|
}
|
|
134
137
|
const res = sent.res;
|
|
135
|
-
const
|
|
138
|
+
const buf = await res.arrayBuffer();
|
|
139
|
+
const body = parseBody(buf);
|
|
136
140
|
if (res.ok) {
|
|
137
141
|
const pr = res.headers.get('payment-response');
|
|
138
142
|
let tx;
|
|
@@ -142,8 +146,14 @@ export function createAgent(d) {
|
|
|
142
146
|
catch {
|
|
143
147
|
tx = undefined;
|
|
144
148
|
}
|
|
145
|
-
|
|
146
|
-
|
|
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 } : {}) };
|
|
147
157
|
}
|
|
148
158
|
const reason = typeof body === 'object' && body && 'reason' in body ? String(body.reason) : `http_${res.status}`;
|
|
149
159
|
const result = res.status === 402 ? 'rejected_by_server' : res.headers.get('x-payment-status') === 'not-settled' || res.status === 409 ? 'failed' : 'unknown';
|
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
|
@@ -16,6 +16,13 @@ export interface HistoryEntry {
|
|
|
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;
|
|
@@ -27,6 +34,12 @@ export interface History {
|
|
|
27
34
|
preq: bigint;
|
|
28
35
|
a402: bigint;
|
|
29
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
|
+
};
|
|
30
43
|
}
|
|
31
44
|
export declare function jsonlHistory(path: string, mints: () => {
|
|
32
45
|
USDC: string;
|
package/dist/history.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
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)
|
|
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 sum = (mint) => (mint ? xs.filter((e) => e.mint === mint && e.amount && /^\d+$/.test(e.amount)).reduce((s, e) => s + BigInt(e.amount), 0n) : 0n);
|
|
33
|
-
return { count: xs.length, usd, preq: sum(m.PREQ), a402: sum(m.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
|
@@ -37,6 +37,10 @@ export interface PayPolicy {
|
|
|
37
37
|
maxPaymentsPerDay: number;
|
|
38
38
|
/** Daily USDC total cap (USD) */
|
|
39
39
|
maxUsdPerDay: number;
|
|
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;
|
|
40
44
|
/** USDC payments at or above this amount (USD) need human confirmation. null = never ask */
|
|
41
45
|
confirmAboveUsd: number | null;
|
|
42
46
|
/** Per-token limits (base units). No defaults: both per-payment and daily must be set to pay in that token */
|
|
@@ -53,6 +57,8 @@ export interface PolicyEnv {
|
|
|
53
57
|
X402_MAX_USD?: string;
|
|
54
58
|
X402_MAX_PAYMENTS_PER_DAY?: string;
|
|
55
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;
|
|
56
62
|
X402_CONFIRM_ABOVE_USD?: string;
|
|
57
63
|
X402_MAX_PREQ_ATOMIC?: string;
|
|
58
64
|
X402_MAX_PREQ_PER_DAY_ATOMIC?: string;
|
|
@@ -90,6 +96,12 @@ export interface DayUsage {
|
|
|
90
96
|
/** Total A402 (v1) signed today (base units) */
|
|
91
97
|
a402: bigint;
|
|
92
98
|
}
|
|
99
|
+
/** Today's signed payments to one recipient (payTo) */
|
|
100
|
+
export interface RecipientUsage {
|
|
101
|
+
count: number;
|
|
102
|
+
usd: number;
|
|
103
|
+
preq: bigint;
|
|
104
|
+
}
|
|
93
105
|
export interface Evaluated {
|
|
94
106
|
requirement: PaymentRequirements;
|
|
95
107
|
asset: AssetSymbol | null;
|
|
@@ -102,6 +114,8 @@ export interface Evaluated {
|
|
|
102
114
|
}
|
|
103
115
|
export declare function symbolOf(p: PayPolicy, mint: string): AssetSymbol | null;
|
|
104
116
|
/** Evaluates one payment requirement against the policy (before signing) */
|
|
105
|
-
export declare function evaluate(p: PayPolicy, r: PaymentRequirements, usage: DayUsage): Evaluated;
|
|
117
|
+
export declare function evaluate(p: PayPolicy, r: PaymentRequirements, usage: DayUsage, recipient?: RecipientUsage): Evaluated;
|
|
106
118
|
/** Requirement to choose after evaluation (preferred asset first) */
|
|
107
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,3 +1,4 @@
|
|
|
1
|
+
import { formatUnits } from './units.js';
|
|
1
2
|
export const NETWORKS = {
|
|
2
3
|
mainnet: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
|
|
3
4
|
devnet: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',
|
|
@@ -54,6 +55,8 @@ export function policyFromEnv(env) {
|
|
|
54
55
|
maxUsdPerPayment: num(env.X402_MAX_USD, 0.05),
|
|
55
56
|
maxPaymentsPerDay: num(env.X402_MAX_PAYMENTS_PER_DAY, 20),
|
|
56
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),
|
|
57
60
|
confirmAboveUsd: env.X402_CONFIRM_ABOVE_USD ? Number(env.X402_CONFIRM_ABOVE_USD) : null,
|
|
58
61
|
tokenLimits: { PREQ: limitsFor('PREQ'), A402: limitsFor('A402') },
|
|
59
62
|
prefer,
|
|
@@ -79,6 +82,7 @@ export function domainCheck(p, url) {
|
|
|
79
82
|
return { ok: false, reason: `domain_not_allowed: ${host}` };
|
|
80
83
|
return { ok: true, host };
|
|
81
84
|
}
|
|
85
|
+
const NO_RECIPIENT_USAGE = { count: 0, usd: 0, preq: 0n };
|
|
82
86
|
export function symbolOf(p, mint) {
|
|
83
87
|
if (!mint)
|
|
84
88
|
return null;
|
|
@@ -86,7 +90,7 @@ export function symbolOf(p, mint) {
|
|
|
86
90
|
}
|
|
87
91
|
const usedToday = (usage, t) => (t === 'PREQ' ? usage.preq : usage.a402);
|
|
88
92
|
/** Evaluates one payment requirement against the policy (before signing) */
|
|
89
|
-
export function evaluate(p, r, usage) {
|
|
93
|
+
export function evaluate(p, r, usage, recipient = NO_RECIPIENT_USAGE) {
|
|
90
94
|
const reasons = [];
|
|
91
95
|
const asset = symbolOf(p, r.asset);
|
|
92
96
|
if (r.scheme !== 'exact')
|
|
@@ -117,6 +121,9 @@ export function evaluate(p, r, usage) {
|
|
|
117
121
|
reasons.push(`over_per_payment_limit: ${usd} USD > ${p.maxUsdPerPayment} USD`);
|
|
118
122
|
if (usage.usd + usd > p.maxUsdPerDay)
|
|
119
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
|
+
}
|
|
120
127
|
}
|
|
121
128
|
let needsTokenConfirm = false;
|
|
122
129
|
if (asset && asset !== 'USDC' && p.allowedAssets.includes(asset) && amount > 0n) {
|
|
@@ -132,6 +139,9 @@ export function evaluate(p, r, usage) {
|
|
|
132
139
|
reasons.push(`${lc}_limit_not_configured: set ${n.perDay} (max ${asset} per UTC day, in ${unit}: 1 ${asset} = 1,000,000)`);
|
|
133
140
|
else if (usedToday(usage, asset) + amount > l.perDay)
|
|
134
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
|
+
}
|
|
135
145
|
needsTokenConfirm = l.confirmAbove !== null && amount >= l.confirmAbove;
|
|
136
146
|
}
|
|
137
147
|
if (usage.count >= p.maxPaymentsPerDay)
|
|
@@ -144,3 +154,17 @@ export function choose(p, evs) {
|
|
|
144
154
|
const ok = evs.filter((e) => e.ok);
|
|
145
155
|
return ok.find((e) => e.asset === p.prefer) ?? ok[0] ?? null;
|
|
146
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,26 +1,78 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// @agent402-dev/pay-mcp (stdio)
|
|
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
3
|
// X402_KEYPAIR_PATH payment wallet key file (Solana CLI JSON). Without it, no payments (x402_quote only)
|
|
4
4
|
// X402_RPC_URL RPC used to build payment transactions (public RPC if unset)
|
|
5
5
|
// X402_HISTORY_PATH payment history JSONL (default ~/.agent402/payments.jsonl)
|
|
6
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
|
-
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
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 {
|
|
5
|
+
import { historyToCsv } from './csv.js';
|
|
6
|
+
import { nearLimits, tokenEnv } from './policy.js';
|
|
6
7
|
import { formatUnits } from './units.js';
|
|
7
8
|
const out = (obj, isError = false) => ({ content: [{ type: 'text', text: JSON.stringify(obj, null, 2) }], ...(isError ? { isError } : {}) });
|
|
8
9
|
const bigintSafe = (o) => JSON.parse(JSON.stringify(o, (_k, v) => (typeof v === 'bigint' ? v.toString() : v)));
|
|
@@ -36,7 +37,7 @@ function tokenLimitFields(p, t) {
|
|
|
36
37
|
};
|
|
37
38
|
}
|
|
38
39
|
export function createPayServer(d) {
|
|
39
|
-
const server = new McpServer({ name: 'a402-pay', version: '0.
|
|
40
|
+
const server = new McpServer({ name: 'a402-pay', version: '0.3.0' });
|
|
40
41
|
const confirm = async (message) => {
|
|
41
42
|
if (!server.server.getClientCapabilities()?.elicitation)
|
|
42
43
|
return 'unsupported';
|
|
@@ -51,7 +52,9 @@ export function createPayServer(d) {
|
|
|
51
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)); });
|
|
52
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'); });
|
|
53
54
|
server.tool('wallet_status', 'Payment wallet address, network, USDC and PREQ balances, payments signed today, and the configured limits and allowlists.', {}, async () => {
|
|
54
|
-
const
|
|
55
|
+
const usage = d.history.today(d.now?.());
|
|
56
|
+
const { preq, a402, ...today } = usage;
|
|
57
|
+
const near = nearLimits(d.policy, usage);
|
|
55
58
|
const balances = d.wallet ? await d.wallet.balances() : null;
|
|
56
59
|
// A402 (v1) is deprecated: shown only if allowed explicitly or if spent today
|
|
57
60
|
const showA402 = d.policy.allowedAssets.includes('A402') || a402 > 0n;
|
|
@@ -69,15 +72,20 @@ export function createPayServer(d) {
|
|
|
69
72
|
limits: {
|
|
70
73
|
maxUsdPerPayment: d.policy.maxUsdPerPayment, maxUsdPerDay: d.policy.maxUsdPerDay, maxPaymentsPerDay: d.policy.maxPaymentsPerDay,
|
|
71
74
|
confirmAboveUsd: d.policy.confirmAboveUsd,
|
|
75
|
+
maxUsdPerRecipientPerDay: d.policy.maxUsdPerRecipientPerDay,
|
|
76
|
+
maxPreqPerRecipientPerDayAtomic: d.policy.maxPreqPerRecipientPerDay,
|
|
72
77
|
...tokenLimitFields(d.policy, 'PREQ'),
|
|
73
78
|
...(showA402 ? tokenLimitFields(d.policy, 'A402') : {}),
|
|
74
79
|
units: '…Usd = US dollars (USDC); …Atomic = token smallest unit (1 PREQ = 1,000,000)',
|
|
75
80
|
},
|
|
76
81
|
allowedDomains: d.policy.allowedDomains, trustedPayTo: d.policy.trustedPayTo, allowedAssets: d.policy.allowedAssets,
|
|
77
|
-
...(d.policy.warnings.length ? { warnings: d.policy.warnings } : {}),
|
|
82
|
+
...(d.policy.warnings.length || near.length ? { warnings: [...d.policy.warnings, ...near] } : {}),
|
|
78
83
|
...(d.wallet ? {} : { note: 'No wallet configured (X402_KEYPAIR_PATH): x402_fetch will not pay.' }),
|
|
79
84
|
}));
|
|
80
85
|
});
|
|
81
|
-
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
|
+
});
|
|
82
90
|
return server;
|
|
83
91
|
}
|