@agent402-dev/pay-mcp 0.1.0 → 0.2.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 +14 -11
- package/dist/agent.d.ts +4 -2
- package/dist/agent.js +16 -11
- package/dist/history.d.ts +6 -4
- package/dist/history.js +5 -5
- package/dist/policy.d.ts +53 -22
- package/dist/policy.js +64 -26
- package/dist/server.js +9 -5
- package/dist/tools.d.ts +1 -1
- package/dist/tools.js +35 -16
- 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,17 +16,19 @@ 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
|
-
| **Max
|
|
23
|
-
| **Max
|
|
23
|
+
| **Max PREQ per payment** (PREQ smallest units; 1 PREQ = 1,000,000) | `X402_MAX_PREQ_ATOMIC` | **not set → PREQ payments refused** |
|
|
24
|
+
| **Max PREQ per UTC day** (PREQ smallest units; 1 PREQ = 1,000,000) | `X402_MAX_PREQ_PER_DAY_ATOMIC` | **not set → PREQ payments refused** |
|
|
24
25
|
| Ask a human at or above this USDC amount (USD) | `X402_CONFIRM_ABOVE_USD` | off |
|
|
25
|
-
| Ask a human at or above this
|
|
26
|
+
| Ask a human at or above this PREQ amount (PREQ smallest units) | `X402_CONFIRM_ABOVE_PREQ_ATOMIC` | off |
|
|
26
27
|
|
|
27
|
-
- **
|
|
28
|
-
- USD limits apply to USDC only.
|
|
28
|
+
- **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).
|
|
29
|
+
- USD limits apply to USDC only. PREQ has its own two limits, and **both must be set** before any PREQ payment is made.
|
|
30
|
+
- **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).
|
|
31
|
+
- **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
32
|
- Human confirmation uses MCP elicitation. If your MCP client cannot ask, the payment is not made (`confirmation_required`).
|
|
30
33
|
- At most one signature per `x402_fetch` call. If the server answers 402 again after payment, it does not sign again.
|
|
31
34
|
- Redirects are followed manually and each hop must be an allowed domain; a disallowed hop is not contacted.
|
|
@@ -33,7 +36,7 @@ Nothing is signed unless every rule passes. **With no configuration, every payme
|
|
|
33
36
|
- Daily totals count every payment this server signed, whatever the result.
|
|
34
37
|
- Daily limits are counted from the local payment log file (`X402_HISTORY_PATH`). Deleting or moving that file resets the daily totals.
|
|
35
38
|
|
|
36
|
-
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` | `
|
|
39
|
+
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`).
|
|
37
40
|
|
|
38
41
|
## Connect
|
|
39
42
|
Claude Code (example — set your own allowlists and limits):
|
|
@@ -55,7 +58,7 @@ Node 20+. Without `X402_ALLOWED_DOMAINS` and `X402_TRUSTED_PAY_TO` every payment
|
|
|
55
58
|
|---|---|
|
|
56
59
|
| `x402_fetch` | Fetch a URL; pay only if the rules pass |
|
|
57
60
|
| `x402_quote` | Show payment requirements and which rules pass; never signs; returns `quoteId` |
|
|
58
|
-
| `wallet_status` | Address, balances, today's usage (count, USDC,
|
|
61
|
+
| `wallet_status` | Address, balances, today's usage (count, USDC, PREQ), limits including both PREQ limits, allowlists |
|
|
59
62
|
| `payment_history` | Local log: time, URL, asset, amount, recipient, result, settlement transaction id |
|
|
60
63
|
|
|
61
64
|
The log never stores keys or signed payment payloads.
|
|
@@ -71,4 +74,4 @@ Put only what you are willing to spend in the payment wallet. Never point this a
|
|
|
71
74
|
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
75
|
|
|
73
76
|
---
|
|
74
|
-
Factual information from public on-chain data. Not investment advice.
|
|
77
|
+
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,8 @@ 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[];
|
|
43
45
|
}
|
|
44
46
|
export declare function createAgent(d: AgentDeps): {
|
|
45
47
|
quote: (spec: RequestSpec) => Promise<FetchOutcome & {
|
package/dist/agent.js
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
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 } from './policy.js';
|
|
6
6
|
import { withSmallest } from './units.js';
|
|
7
7
|
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
8
|
+
/** Adds the deprecation warning if the chosen asset is A402 (v1) (there is no path that silently pays with A402) */
|
|
9
|
+
const withDeprecation = (o) => o.payment?.asset === 'A402' ? { ...o, warnings: [...(o.warnings ?? []), A402_DEPRECATION_WARNING] } : o;
|
|
8
10
|
export function createAgent(d) {
|
|
9
11
|
const now = d.now ?? (() => new Date());
|
|
10
12
|
const quotes = new Map();
|
|
11
13
|
const QUOTE_TTL_MS = 5 * 60_000;
|
|
12
|
-
/**
|
|
14
|
+
/** Follows redirects itself and checks the domain at each step */
|
|
13
15
|
async function send(spec, extraHeaders = {}, follow = true) {
|
|
14
16
|
let url = spec.url;
|
|
15
17
|
for (let hop = 0; hop <= (d.maxRedirects ?? 3); hop++) {
|
|
@@ -43,7 +45,7 @@ export function createAgent(d) {
|
|
|
43
45
|
return '';
|
|
44
46
|
} };
|
|
45
47
|
const record = (e) => d.history.add({ at: now().toISOString(), ...e });
|
|
46
|
-
/** 402
|
|
48
|
+
/** Receives a 402 and evaluates it with the policy (no signing) */
|
|
47
49
|
async function assess(spec) {
|
|
48
50
|
const sent = await send(spec);
|
|
49
51
|
if ('refused' in sent)
|
|
@@ -59,7 +61,7 @@ export function createAgent(d) {
|
|
|
59
61
|
catch {
|
|
60
62
|
return { kind: 'refused', refused: 'invalid_payment_required_header' };
|
|
61
63
|
}
|
|
62
|
-
// 402
|
|
64
|
+
// If the 402 points to a resource at another address, that address must also be on the allowlist
|
|
63
65
|
if (pr.resource?.url) {
|
|
64
66
|
const rc = domainCheck(d.policy, pr.resource.url);
|
|
65
67
|
if (!rc.ok)
|
|
@@ -103,7 +105,7 @@ export function createAgent(d) {
|
|
|
103
105
|
record({ ...base, ...pay, result, reasons, signed: false });
|
|
104
106
|
return { result, reasons, options, payment: { asset: a.chosen.asset, mint: r.asset, amount: r.amount, payTo: r.payTo, network: r.network } };
|
|
105
107
|
};
|
|
106
|
-
//
|
|
108
|
+
// Same requirement as the quote? (reject if the amount or receiver changed between requests)
|
|
107
109
|
if (spec.quoteId) {
|
|
108
110
|
const q = quotes.get(spec.quoteId);
|
|
109
111
|
if (!q || q.url !== spec.url || now().getTime() - q.at > QUOTE_TTL_MS)
|
|
@@ -115,14 +117,14 @@ export function createAgent(d) {
|
|
|
115
117
|
if (!d.wallet)
|
|
116
118
|
return refuse('refused', ['no_wallet: set X402_KEYPAIR_PATH']);
|
|
117
119
|
if (a.chosen.needsConfirmation) {
|
|
118
|
-
const human = `Pay ${a.chosen.asset === 'USDC' ? `${a.chosen.usd} USDC` : withSmallest(r.amount, a.chosen.asset ?? '
|
|
120
|
+
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
121
|
const ans = await d.confirm(human).catch(() => 'unsupported');
|
|
120
122
|
if (ans === 'unsupported')
|
|
121
123
|
return refuse('confirmation_required', ['confirmation_required: this client cannot ask for confirmation (MCP elicitation); payment not made']);
|
|
122
124
|
if (ans === 'decline')
|
|
123
125
|
return refuse('declined_by_user', ['declined_by_user']);
|
|
124
126
|
}
|
|
125
|
-
//
|
|
127
|
+
// Sign (only once per request)
|
|
126
128
|
const header = await d.wallet.sign(a.pr.resource, r);
|
|
127
129
|
const sent = await send({ ...spec, url: a.finalUrl }, { 'payment-signature': header }, false);
|
|
128
130
|
if ('refused' in sent) {
|
|
@@ -148,5 +150,8 @@ export function createAgent(d) {
|
|
|
148
150
|
record({ ...base, ...pay, result, reasons: [reason], httpStatus: res.status, signed: true });
|
|
149
151
|
return { result, httpStatus: res.status, reasons: [reason], body };
|
|
150
152
|
}
|
|
151
|
-
return {
|
|
153
|
+
return {
|
|
154
|
+
quote: async (spec) => withDeprecation(await quote(spec)),
|
|
155
|
+
payAndFetch: async (spec) => withDeprecation(await payAndFetch(spec)),
|
|
156
|
+
};
|
|
152
157
|
}
|
package/dist/history.d.ts
CHANGED
|
@@ -9,25 +9,27 @@ 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
19
|
}
|
|
20
20
|
export interface History {
|
|
21
21
|
add(e: HistoryEntry): void;
|
|
22
22
|
list(limit?: number): HistoryEntry[];
|
|
23
|
-
/**
|
|
23
|
+
/** Today's (UTC) signed payment count, USDC total (USD), PREQ and A402 (v1) totals (base units), for limit checks */
|
|
24
24
|
today(now?: Date): {
|
|
25
25
|
count: number;
|
|
26
26
|
usd: number;
|
|
27
|
+
preq: bigint;
|
|
27
28
|
a402: bigint;
|
|
28
29
|
};
|
|
29
30
|
}
|
|
30
31
|
export declare function jsonlHistory(path: string, mints: () => {
|
|
31
32
|
USDC: string;
|
|
33
|
+
PREQ: string;
|
|
32
34
|
A402: string;
|
|
33
35
|
}): 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)
|
|
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'];
|
|
@@ -25,12 +25,12 @@ export function jsonlHistory(path, mints) {
|
|
|
25
25
|
list(limit = 50) { return read().slice(-limit).reverse(); },
|
|
26
26
|
today(now = new Date()) {
|
|
27
27
|
const day = now.toISOString().slice(0, 10);
|
|
28
|
-
//
|
|
28
|
+
// A signed payment counts as spent regardless of result (succeeded, rejected, unknown), to be conservative
|
|
29
29
|
const xs = read().filter((e) => e.signed && e.at.slice(0, 10) === day);
|
|
30
30
|
const m = mints();
|
|
31
31
|
const usd = xs.filter((e) => e.mint === m.USDC && e.amount).reduce((s, e) => s + Number(e.amount) / 1e6, 0);
|
|
32
|
-
const
|
|
33
|
-
return { count: xs.length, usd, a402 };
|
|
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) };
|
|
34
34
|
},
|
|
35
35
|
};
|
|
36
36
|
}
|
package/dist/policy.d.ts
CHANGED
|
@@ -3,30 +3,47 @@ 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
|
+
/** USDC payments at or above this amount (USD) need human confirmation. null = never ask */
|
|
26
41
|
confirmAboveUsd: number | null;
|
|
27
|
-
/**
|
|
28
|
-
|
|
42
|
+
/** Per-token limits (base units). No defaults: both per-payment and daily must be set to pay in that token */
|
|
43
|
+
tokenLimits: Record<TokenSymbol, TokenLimits>;
|
|
29
44
|
prefer: AssetSymbol;
|
|
45
|
+
/** Warnings to show at start (e.g. when A402 (v1) is enabled) */
|
|
46
|
+
warnings: string[];
|
|
30
47
|
}
|
|
31
48
|
export interface PolicyEnv {
|
|
32
49
|
X402_NETWORK?: string;
|
|
@@ -34,19 +51,30 @@ export interface PolicyEnv {
|
|
|
34
51
|
X402_TRUSTED_PAY_TO?: string;
|
|
35
52
|
X402_ALLOWED_ASSETS?: string;
|
|
36
53
|
X402_MAX_USD?: string;
|
|
37
|
-
X402_MAX_A402_ATOMIC?: string;
|
|
38
|
-
X402_MAX_A402_PER_DAY_ATOMIC?: string;
|
|
39
54
|
X402_MAX_PAYMENTS_PER_DAY?: string;
|
|
40
55
|
X402_MAX_USD_PER_DAY?: string;
|
|
41
56
|
X402_CONFIRM_ABOVE_USD?: string;
|
|
57
|
+
X402_MAX_PREQ_ATOMIC?: string;
|
|
58
|
+
X402_MAX_PREQ_PER_DAY_ATOMIC?: string;
|
|
59
|
+
X402_CONFIRM_ABOVE_PREQ_ATOMIC?: string;
|
|
60
|
+
/** A402 (v1, deprecated): only meaningful when A402 is allowed explicitly */
|
|
61
|
+
X402_MAX_A402_ATOMIC?: string;
|
|
62
|
+
X402_MAX_A402_PER_DAY_ATOMIC?: string;
|
|
42
63
|
X402_CONFIRM_ABOVE_A402_ATOMIC?: string;
|
|
43
64
|
X402_PAY_WITH?: string;
|
|
44
|
-
/**
|
|
65
|
+
/** Only to change or set mints, e.g. in rehearsals */
|
|
45
66
|
X402_USDC_MINT?: string;
|
|
67
|
+
X402_PREQ_MINT?: string;
|
|
46
68
|
X402_A402_MINT?: string;
|
|
47
69
|
}
|
|
70
|
+
/** Environment variable names for token limits */
|
|
71
|
+
export declare const tokenEnv: (t: TokenSymbol) => {
|
|
72
|
+
perPayment: string;
|
|
73
|
+
perDay: string;
|
|
74
|
+
confirmAbove: string;
|
|
75
|
+
};
|
|
48
76
|
export declare function policyFromEnv(env: PolicyEnv): PayPolicy;
|
|
49
|
-
/**
|
|
77
|
+
/** Whether paying for this URL is allowed (domain allowlist + https; http only for localhost) */
|
|
50
78
|
export declare function domainCheck(p: PayPolicy, url: string): {
|
|
51
79
|
ok: true;
|
|
52
80
|
host: string;
|
|
@@ -56,7 +84,10 @@ export declare function domainCheck(p: PayPolicy, url: string): {
|
|
|
56
84
|
};
|
|
57
85
|
export interface DayUsage {
|
|
58
86
|
count: number;
|
|
59
|
-
usd: number;
|
|
87
|
+
usd: number;
|
|
88
|
+
/** Total PREQ signed today (base units) */
|
|
89
|
+
preq: bigint;
|
|
90
|
+
/** Total A402 (v1) signed today (base units) */
|
|
60
91
|
a402: bigint;
|
|
61
92
|
}
|
|
62
93
|
export interface Evaluated {
|
|
@@ -64,13 +95,13 @@ export interface Evaluated {
|
|
|
64
95
|
asset: AssetSymbol | null;
|
|
65
96
|
ok: boolean;
|
|
66
97
|
reasons: string[];
|
|
67
|
-
/**
|
|
98
|
+
/** Whether human confirmation is needed (meaningful only when ok) */
|
|
68
99
|
needsConfirmation: boolean;
|
|
69
|
-
/**
|
|
100
|
+
/** USD amount if USDC */
|
|
70
101
|
usd: number | null;
|
|
71
102
|
}
|
|
72
103
|
export declare function symbolOf(p: PayPolicy, mint: string): AssetSymbol | null;
|
|
73
|
-
/**
|
|
104
|
+
/** Evaluates one payment requirement against the policy (before signing) */
|
|
74
105
|
export declare function evaluate(p: PayPolicy, r: PaymentRequirements, usage: DayUsage): Evaluated;
|
|
75
|
-
/**
|
|
106
|
+
/** Requirement to choose after evaluation (preferred asset first) */
|
|
76
107
|
export declare function choose(p: PayPolicy, evs: Evaluated[]): Evaluated | null;
|
package/dist/policy.js
CHANGED
|
@@ -2,36 +2,66 @@ export const NETWORKS = {
|
|
|
2
2
|
mainnet: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
|
|
3
3
|
devnet: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',
|
|
4
4
|
};
|
|
5
|
+
/**
|
|
6
|
+
* PREQ mainnet mint (Token-2022, 6 decimals). Same value as PREQ_MAINNET_MINT in pay-server src/preq.ts.
|
|
7
|
+
* Set after the PREQ launch on 2026-11-21. X402_PREQ_MINT can override it (e.g. for devnet rehearsals)
|
|
8
|
+
*/
|
|
9
|
+
export const PREQ_MAINNET_MINT = 'aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX';
|
|
10
|
+
export const A402_DEPRECATION_WARNING = 'A402 (v1) is deprecated and no longer supported; use PREQ.';
|
|
5
11
|
const DEFAULT_MINTS = {
|
|
6
|
-
[NETWORKS.mainnet]: { USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', A402: 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X' },
|
|
7
|
-
|
|
12
|
+
[NETWORKS.mainnet]: { USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', PREQ: PREQ_MAINNET_MINT, A402: 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X' },
|
|
13
|
+
// No devnet PREQ mint; rehearsals pass one with X402_PREQ_MINT
|
|
14
|
+
[NETWORKS.devnet]: { USDC: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', PREQ: '', A402: '5R2rKmzsNk1S5mFPR99bU1anromo73brwNApghvXeb46' },
|
|
8
15
|
};
|
|
16
|
+
export const TOKEN_SYMBOLS = ['PREQ', 'A402'];
|
|
17
|
+
const ASSET_SYMBOLS = ['USDC', 'PREQ', 'A402'];
|
|
9
18
|
const list = (s) => (s ?? '').split(',').map((x) => x.trim()).filter(Boolean);
|
|
10
19
|
const num = (s, d) => (s && Number.isFinite(Number(s)) ? Number(s) : d);
|
|
11
|
-
/**
|
|
20
|
+
/** Integer in base units (positive only). null if missing or invalid */
|
|
12
21
|
const atomic = (s) => (s && /^\d+$/.test(s.trim()) && BigInt(s.trim()) > 0n ? BigInt(s.trim()) : null);
|
|
22
|
+
const isAsset = (a) => ASSET_SYMBOLS.includes(a);
|
|
23
|
+
/** Environment variable names for token limits */
|
|
24
|
+
export const tokenEnv = (t) => ({
|
|
25
|
+
perPayment: `X402_MAX_${t}_ATOMIC`,
|
|
26
|
+
perDay: `X402_MAX_${t}_PER_DAY_ATOMIC`,
|
|
27
|
+
confirmAbove: `X402_CONFIRM_ABOVE_${t}_ATOMIC`,
|
|
28
|
+
});
|
|
13
29
|
export function policyFromEnv(env) {
|
|
14
30
|
const network = env.X402_NETWORK === 'devnet' ? NETWORKS.devnet : NETWORKS.mainnet;
|
|
15
31
|
const m = DEFAULT_MINTS[network];
|
|
32
|
+
const e = env;
|
|
33
|
+
const mints = { USDC: env.X402_USDC_MINT ?? m.USDC, PREQ: env.X402_PREQ_MINT ?? m.PREQ, A402: env.X402_A402_MINT ?? m.A402 };
|
|
34
|
+
const allowedAssets = (list(env.X402_ALLOWED_ASSETS).length ? list(env.X402_ALLOWED_ASSETS) : ['USDC']).filter(isAsset);
|
|
35
|
+
if (allowedAssets.includes('PREQ') && !mints.PREQ) {
|
|
36
|
+
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.');
|
|
37
|
+
}
|
|
38
|
+
const warnings = [];
|
|
39
|
+
if (allowedAssets.includes('A402') || env.X402_PAY_WITH === 'A402')
|
|
40
|
+
warnings.push(A402_DEPRECATION_WARNING);
|
|
41
|
+
// Tokens have no defaults: both per-payment and daily must be set to pay (USD limits do not apply to tokens)
|
|
42
|
+
const limitsFor = (t) => {
|
|
43
|
+
const n = tokenEnv(t);
|
|
44
|
+
const c = e[n.confirmAbove];
|
|
45
|
+
return { perPayment: atomic(e[n.perPayment]), perDay: atomic(e[n.perDay]), confirmAbove: c && /^\d+$/.test(c.trim()) ? BigInt(c.trim()) : null };
|
|
46
|
+
};
|
|
47
|
+
const prefer = env.X402_PAY_WITH && isAsset(env.X402_PAY_WITH) ? env.X402_PAY_WITH : 'USDC';
|
|
16
48
|
return {
|
|
17
49
|
network,
|
|
18
|
-
mints
|
|
50
|
+
mints,
|
|
19
51
|
allowedDomains: list(env.X402_ALLOWED_DOMAINS).map((d) => d.toLowerCase()),
|
|
20
52
|
trustedPayTo: list(env.X402_TRUSTED_PAY_TO),
|
|
21
|
-
allowedAssets
|
|
53
|
+
allowedAssets,
|
|
22
54
|
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
55
|
maxPaymentsPerDay: num(env.X402_MAX_PAYMENTS_PER_DAY, 20),
|
|
27
56
|
maxUsdPerDay: num(env.X402_MAX_USD_PER_DAY, 1),
|
|
28
57
|
confirmAboveUsd: env.X402_CONFIRM_ABOVE_USD ? Number(env.X402_CONFIRM_ABOVE_USD) : null,
|
|
29
|
-
|
|
30
|
-
prefer
|
|
58
|
+
tokenLimits: { PREQ: limitsFor('PREQ'), A402: limitsFor('A402') },
|
|
59
|
+
prefer,
|
|
60
|
+
warnings,
|
|
31
61
|
};
|
|
32
62
|
}
|
|
33
63
|
const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
34
|
-
/**
|
|
64
|
+
/** Whether paying for this URL is allowed (domain allowlist + https; http only for localhost) */
|
|
35
65
|
export function domainCheck(p, url) {
|
|
36
66
|
let u;
|
|
37
67
|
try {
|
|
@@ -50,9 +80,12 @@ export function domainCheck(p, url) {
|
|
|
50
80
|
return { ok: true, host };
|
|
51
81
|
}
|
|
52
82
|
export function symbolOf(p, mint) {
|
|
53
|
-
|
|
83
|
+
if (!mint)
|
|
84
|
+
return null;
|
|
85
|
+
return ASSET_SYMBOLS.find((s) => p.mints[s] && p.mints[s] === mint) ?? null;
|
|
54
86
|
}
|
|
55
|
-
|
|
87
|
+
const usedToday = (usage, t) => (t === 'PREQ' ? usage.preq : usage.a402);
|
|
88
|
+
/** Evaluates one payment requirement against the policy (before signing) */
|
|
56
89
|
export function evaluate(p, r, usage) {
|
|
57
90
|
const reasons = [];
|
|
58
91
|
const asset = symbolOf(p, r.asset);
|
|
@@ -63,7 +96,7 @@ export function evaluate(p, r, usage) {
|
|
|
63
96
|
if (!asset)
|
|
64
97
|
reasons.push(`asset_not_allowed: unknown mint ${r.asset}`);
|
|
65
98
|
else if (!p.allowedAssets.includes(asset))
|
|
66
|
-
reasons.push(`asset_not_allowed: ${asset} (X402_ALLOWED_ASSETS)`);
|
|
99
|
+
reasons.push(`asset_not_allowed: ${asset} (X402_ALLOWED_ASSETS)${asset === 'A402' ? ' — A402 (v1) is deprecated; use PREQ' : ''}`);
|
|
67
100
|
if (!p.trustedPayTo.length)
|
|
68
101
|
reasons.push('pay_to_not_trusted: trusted recipient list is empty (X402_TRUSTED_PAY_TO)');
|
|
69
102
|
else if (!p.trustedPayTo.includes(r.payTo))
|
|
@@ -85,23 +118,28 @@ export function evaluate(p, r, usage) {
|
|
|
85
118
|
if (usage.usd + usd > p.maxUsdPerDay)
|
|
86
119
|
reasons.push(`over_daily_usd_limit: ${usage.usd} + ${usd} > ${p.maxUsdPerDay} USD`);
|
|
87
120
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
121
|
+
let needsTokenConfirm = false;
|
|
122
|
+
if (asset && asset !== 'USDC' && p.allowedAssets.includes(asset) && amount > 0n) {
|
|
123
|
+
const l = p.tokenLimits[asset];
|
|
124
|
+
const n = tokenEnv(asset);
|
|
125
|
+
const lc = asset.toLowerCase();
|
|
126
|
+
const unit = `${asset} smallest units`;
|
|
127
|
+
if (l.perPayment === null)
|
|
128
|
+
reasons.push(`${lc}_limit_not_configured: set ${n.perPayment} (max ${asset} per payment, in ${unit}: 1 ${asset} = 1,000,000)`);
|
|
129
|
+
else if (amount > l.perPayment)
|
|
130
|
+
reasons.push(`over_per_payment_limit: ${amount} > ${l.perPayment} (${unit})`);
|
|
131
|
+
if (l.perDay === null)
|
|
132
|
+
reasons.push(`${lc}_limit_not_configured: set ${n.perDay} (max ${asset} per UTC day, in ${unit}: 1 ${asset} = 1,000,000)`);
|
|
133
|
+
else if (usedToday(usage, asset) + amount > l.perDay)
|
|
134
|
+
reasons.push(`over_daily_${lc}_limit: ${usedToday(usage, asset)} + ${amount} > ${l.perDay} (${unit})`);
|
|
135
|
+
needsTokenConfirm = l.confirmAbove !== null && amount >= l.confirmAbove;
|
|
97
136
|
}
|
|
98
137
|
if (usage.count >= p.maxPaymentsPerDay)
|
|
99
138
|
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);
|
|
139
|
+
const needsConfirmation = (asset === 'USDC' && p.confirmAboveUsd !== null && usd !== null && usd >= p.confirmAboveUsd) || needsTokenConfirm;
|
|
102
140
|
return { requirement: r, asset, ok: reasons.length === 0, reasons, needsConfirmation, usd };
|
|
103
141
|
}
|
|
104
|
-
/**
|
|
142
|
+
/** Requirement to choose after evaluation (preferred asset first) */
|
|
105
143
|
export function choose(p, evs) {
|
|
106
144
|
const ok = evs.filter((e) => e.ok);
|
|
107
145
|
return ok.find((e) => e.asset === p.prefer) ?? ok[0] ?? null;
|
package/dist/server.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
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 (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
7
|
import { homedir } from 'node:os';
|
|
8
8
|
import { join } from 'node:path';
|
|
9
9
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
@@ -11,7 +11,11 @@ import { jsonlHistory } from './history.js';
|
|
|
11
11
|
import { policyFromEnv } from './policy.js';
|
|
12
12
|
import { createPayServer } from './tools.js';
|
|
13
13
|
import { loadWallet } from './wallet.js';
|
|
14
|
+
// If PREQ is allowed but its mint is empty, stop here with an error (policyFromEnv)
|
|
14
15
|
const policy = policyFromEnv(process.env);
|
|
16
|
+
// If A402 (v1) is enabled explicitly, print the deprecation warning (stderr; stdout is for MCP)
|
|
17
|
+
for (const w of policy.warnings)
|
|
18
|
+
console.error(`[a402-pay] WARNING: ${w}`);
|
|
15
19
|
const wallet = process.env.X402_KEYPAIR_PATH
|
|
16
20
|
? await loadWallet(process.env.X402_KEYPAIR_PATH, policy, process.env.X402_RPC_URL).catch((e) => {
|
|
17
21
|
console.error(`[a402-pay] could not load wallet, starting without payments: ${e.message}`);
|
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,12 @@
|
|
|
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 { tokenEnv } from './policy.js';
|
|
5
6
|
import { formatUnits } from './units.js';
|
|
6
7
|
const out = (obj, isError = false) => ({ content: [{ type: 'text', text: JSON.stringify(obj, null, 2) }], ...(isError ? { isError } : {}) });
|
|
7
8
|
const bigintSafe = (o) => JSON.parse(JSON.stringify(o, (_k, v) => (typeof v === 'bigint' ? v.toString() : v)));
|
|
8
|
-
/**
|
|
9
|
+
/** 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
10
|
function withUnits(o) {
|
|
10
11
|
if (Array.isArray(o))
|
|
11
12
|
return o.map(withUnits);
|
|
@@ -14,15 +15,28 @@ function withUnits(o) {
|
|
|
14
15
|
const r = {};
|
|
15
16
|
for (const [k, v] of Object.entries(o))
|
|
16
17
|
r[k] = withUnits(v);
|
|
17
|
-
if ((r.asset === 'USDC' || r.asset === 'A402') && typeof r.amount === 'string' && /^\d+$/.test(r.amount)) {
|
|
18
|
+
if ((r.asset === 'USDC' || r.asset === 'PREQ' || r.asset === 'A402') && typeof r.amount === 'string' && /^\d+$/.test(r.amount)) {
|
|
18
19
|
r.amountUnit = `${r.asset} smallest unit (1 ${r.asset} = 1,000,000)`;
|
|
19
20
|
r.amountDisplay = formatUnits(r.amount, r.asset);
|
|
20
21
|
}
|
|
21
22
|
return r;
|
|
22
23
|
}
|
|
23
|
-
const atomicLimit = (v, envName) => v === null ? `not set (${envName}) —
|
|
24
|
+
const atomicLimit = (v, envName, sym) => v === null ? `not set (${envName}) — ${sym} payments refused` : v;
|
|
25
|
+
/** Token limits in wallet_status (e.g. maxPreqPerPaymentAtomic, maxPreqPerPaymentDisplay …) */
|
|
26
|
+
function tokenLimitFields(p, t) {
|
|
27
|
+
const l = p.tokenLimits[t];
|
|
28
|
+
const n = tokenEnv(t);
|
|
29
|
+
const k = t === 'PREQ' ? 'Preq' : 'A402';
|
|
30
|
+
return {
|
|
31
|
+
[`max${k}PerPaymentAtomic`]: atomicLimit(l.perPayment, n.perPayment, t),
|
|
32
|
+
[`max${k}PerDayAtomic`]: atomicLimit(l.perDay, n.perDay, t),
|
|
33
|
+
...(l.perPayment !== null ? { [`max${k}PerPaymentDisplay`]: formatUnits(l.perPayment, t) } : {}),
|
|
34
|
+
...(l.perDay !== null ? { [`max${k}PerDayDisplay`]: formatUnits(l.perDay, t) } : {}),
|
|
35
|
+
[`confirmAbove${k}Atomic`]: l.confirmAbove,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
24
38
|
export function createPayServer(d) {
|
|
25
|
-
const server = new McpServer({ name: 'a402-pay', version: '0.
|
|
39
|
+
const server = new McpServer({ name: 'a402-pay', version: '0.2.0' });
|
|
26
40
|
const confirm = async (message) => {
|
|
27
41
|
if (!server.server.getClientCapabilities()?.elicitation)
|
|
28
42
|
return 'unsupported';
|
|
@@ -34,28 +48,33 @@ export function createPayServer(d) {
|
|
|
34
48
|
};
|
|
35
49
|
const agent = createAgent({ ...d, confirm });
|
|
36
50
|
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;
|
|
51
|
+
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
52
|
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 today = d.history.today(d.now?.());
|
|
53
|
+
server.tool('wallet_status', 'Payment wallet address, network, USDC and PREQ balances, payments signed today, and the configured limits and allowlists.', {}, async () => {
|
|
54
|
+
const { preq, a402, ...today } = d.history.today(d.now?.());
|
|
41
55
|
const balances = d.wallet ? await d.wallet.balances() : null;
|
|
56
|
+
// A402 (v1) is deprecated: shown only if allowed explicitly or if spent today
|
|
57
|
+
const showA402 = d.policy.allowedAssets.includes('A402') || a402 > 0n;
|
|
42
58
|
return out(bigintSafe({
|
|
43
59
|
address: d.wallet?.address ?? null,
|
|
44
60
|
network: d.policy.network,
|
|
45
|
-
//
|
|
61
|
+
// Balances in token units (e.g. "10 PREQ")
|
|
46
62
|
balances: balances ? Object.fromEntries(Object.entries(balances).map(([k, v]) => [k, /^[\d.]+$/.test(v) ? `${v} ${k}` : v])) : null,
|
|
47
|
-
today: {
|
|
63
|
+
today: {
|
|
64
|
+
...today, usdUnit: 'USD (USDC)',
|
|
65
|
+
preq, preqUnit: 'PREQ smallest unit (1 PREQ = 1,000,000)', preqDisplay: formatUnits(preq, 'PREQ'),
|
|
66
|
+
...(showA402 ? { a402, a402Unit: 'A402 smallest unit (1 A402 = 1,000,000)', a402Display: formatUnits(a402, 'A402') } : {}),
|
|
67
|
+
},
|
|
48
68
|
signedThisSession: d.wallet?.signedCount ?? 0,
|
|
49
69
|
limits: {
|
|
50
70
|
maxUsdPerPayment: d.policy.maxUsdPerPayment, maxUsdPerDay: d.policy.maxUsdPerDay, maxPaymentsPerDay: d.policy.maxPaymentsPerDay,
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
...(
|
|
54
|
-
|
|
55
|
-
confirmAboveUsd: d.policy.confirmAboveUsd, confirmAboveA402Atomic: d.policy.confirmAboveA402,
|
|
56
|
-
units: '…Usd = US dollars (USDC); …Atomic = A402 smallest unit (1 A402 = 1,000,000)',
|
|
71
|
+
confirmAboveUsd: d.policy.confirmAboveUsd,
|
|
72
|
+
...tokenLimitFields(d.policy, 'PREQ'),
|
|
73
|
+
...(showA402 ? tokenLimitFields(d.policy, 'A402') : {}),
|
|
74
|
+
units: '…Usd = US dollars (USDC); …Atomic = token smallest unit (1 PREQ = 1,000,000)',
|
|
57
75
|
},
|
|
58
76
|
allowedDomains: d.policy.allowedDomains, trustedPayTo: d.policy.trustedPayTo, allowedAssets: d.policy.allowedAssets,
|
|
77
|
+
...(d.policy.warnings.length ? { warnings: d.policy.warnings } : {}),
|
|
59
78
|
...(d.wallet ? {} : { note: 'No wallet configured (X402_KEYPAIR_PATH): x402_fetch will not pay.' }),
|
|
60
79
|
}));
|
|
61
80
|
});
|
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.2.0",
|
|
31
31
|
"author": "Agent402",
|
|
32
32
|
"license": "Apache-2.0",
|
|
33
33
|
"type": "module",
|