agent402-mcp 0.13.28 → 0.13.30
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 +20 -3
- package/index.js +145 -34
- package/known-assets.js +195 -22
- package/output-schemas.js +3 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@ Pick one setup. Both run locally through `npx`.
|
|
|
9
9
|
**1. Free, no wallet.** Pure-CPU tools (no outbound calls, keys or models) run free. Each call solves a proof-of-work puzzle with your CPU, typically well under a second on a laptop. Tools that reach the network or a model ask for a wallet.
|
|
10
10
|
|
|
11
11
|
```
|
|
12
|
-
claude mcp add agent402 -s user -- npx -y agent402-mcp@0.13.
|
|
12
|
+
claude mcp add agent402 -s user -- npx -y agent402-mcp@0.13.30
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
**2. Paid, with a wallet.** Paid tools are settled in USDC on each call.
|
|
@@ -19,7 +19,7 @@ claude mcp add agent402 -s user -- npx -y agent402-mcp@0.13.28
|
|
|
19
19
|
"mcpServers": {
|
|
20
20
|
"agent402": {
|
|
21
21
|
"command": "npx",
|
|
22
|
-
"args": ["-y", "agent402-mcp@0.13.
|
|
22
|
+
"args": ["-y", "agent402-mcp@0.13.30"],
|
|
23
23
|
"env": { "AGENT_KEY": "0xYOUR_PRIVATE_KEY" }
|
|
24
24
|
}
|
|
25
25
|
}
|
|
@@ -30,7 +30,7 @@ claude mcp add agent402 -s user -- npx -y agent402-mcp@0.13.28
|
|
|
30
30
|
|
|
31
31
|
Use `SOLANA_AGENT_KEY` instead for USDC on Solana. Each call is capped at $4 by default; there is no session budget unless you set `AGENT402_BUDGET`.
|
|
32
32
|
|
|
33
|
-
Claude Code with a wallet: `claude mcp add agent402 -s user -e AGENT_KEY=0xYOUR_PRIVATE_KEY -- npx -y agent402-mcp@0.13.
|
|
33
|
+
Claude Code with a wallet: `claude mcp add agent402 -s user -e AGENT_KEY=0xYOUR_PRIVATE_KEY -- npx -y agent402-mcp@0.13.30`
|
|
34
34
|
(use a new wallet holding only a few dollars of USDC; never your main wallet).
|
|
35
35
|
|
|
36
36
|
Advanced setup (chains, MPP, error codes, the hosted connector) is in [Advanced](#advanced).
|
|
@@ -72,6 +72,23 @@ report products run $0.60 to $2.00 per report (domain-audit $0.60 up to the tick
|
|
|
72
72
|
so the default per-call cap of $4 covers every tool; set `AGENT402_MAX_PER_CALL` lower for a
|
|
73
73
|
tighter ceiling.
|
|
74
74
|
|
|
75
|
+
**Held payments.** `payment.info` reports `heldThisSessionUsd`: money a wallet
|
|
76
|
+
call sent a signed payment for without a confirmed answer (an error status, a
|
|
77
|
+
dropped connection, a redirect, a job still running). It is held, not spent: a
|
|
78
|
+
seller that kept the authorization could still redeem it, so it counts against
|
|
79
|
+
`AGENT402_BUDGET` for the rest of the session. On the default target
|
|
80
|
+
(`https://agent402.tools`, matched by exact origin), an error status is never
|
|
81
|
+
settled, so a hold for one ends at the authorization's `validBefore` plus 10
|
|
82
|
+
minutes (15 minutes after the answer when no `validBefore` is readable). A held
|
|
83
|
+
amount whose authorization expires unused is released, never charged. A payment
|
|
84
|
+
option asking to stay valid for more than a day is refused before anything is
|
|
85
|
+
signed, so no signed authorization outlives a day.
|
|
86
|
+
|
|
87
|
+
**Keys stay local.** `AGENT_KEY`, `SOLANA_AGENT_KEY` and `AGENT402_CREDITS_KEY`
|
|
88
|
+
are replaced with `[redacted]` wherever they would appear in a tool result, a
|
|
89
|
+
protocol error or a console line, and a key that does not parse is reported by
|
|
90
|
+
its variable name, not its value.
|
|
91
|
+
|
|
75
92
|
## Advanced
|
|
76
93
|
|
|
77
94
|
**Hosted connector (no install).** Add `https://agent402.tools/mcp` as a remote MCP server (for example claude.ai → Settings → Connectors → Add custom connector). Pure-CPU tools run free there, rate-limited. Paid tools are payable on the connector over [MPP](https://agent402.tools/what-is-mpp): the connector answers with an `isError` tool result whose text names every way to pay and whose `_meta["org.paymentauth/payment-required"]` carries the challenges. A presented credential that is refused answers JSON-RPC `-32043`, and a call on the tasks path answers `-32042`, both with `data.challenges`. An MCP client wrapped with `mppx`'s `McpClient.wrap()` pays and retries on its own, with the receipt in `_meta`. This package runs locally for no rate limit, or to pay over x402.
|
package/index.js
CHANGED
|
@@ -26,8 +26,9 @@
|
|
|
26
26
|
// Robinhood Chain, "base,solana", or a raw CAIP-2 like eip155:4663), optional
|
|
27
27
|
import { createHash } from "node:crypto";
|
|
28
28
|
import { readFileSync } from "node:fs";
|
|
29
|
+
import { format } from "node:util";
|
|
29
30
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
30
|
-
import { quoteOf, guardSigning } from "./known-assets.js";
|
|
31
|
+
import { quoteOf, guardSigning, signedExpirySeconds, MAX_VALIDITY_SECONDS } from "./known-assets.js";
|
|
31
32
|
import { parseNetworkPrefs, withNetworkPreference, distrustFetch } from "./networks.js";
|
|
32
33
|
import { fetchDiscovery, discoveryFailure, getDiscoveryJson } from "./discovery.js";
|
|
33
34
|
import { awaitJob, shouldRequestAsync, AsyncJobPendingError, DEFAULT_ASYNC_TIMEOUT_MS, jobState } from "./async-job.js";
|
|
@@ -57,7 +58,8 @@ import {
|
|
|
57
58
|
clipToolDescription,
|
|
58
59
|
} from "./output-schemas.js";
|
|
59
60
|
|
|
60
|
-
const
|
|
61
|
+
const DEFAULT_URL = "https://agent402.tools";
|
|
62
|
+
const BASE = (process.env.AGENT402_URL || DEFAULT_URL).replace(/\/$/, "");
|
|
61
63
|
// Catalog and seller requests (the 402 and the paid retry included) go through
|
|
62
64
|
// a dedicated dispatcher that refuses a TLS chain through a distrusted
|
|
63
65
|
// intermediate CA (networks.js).
|
|
@@ -87,6 +89,62 @@ const CREDITS_KEY = (process.env.AGENT402_CREDITS_KEY || "").trim();
|
|
|
87
89
|
const SHOW_ROUTER = HAS_WALLET || process.env.AGENT402_SHOW_ROUTER === "1";
|
|
88
90
|
const HIDDEN_WITHOUT_WALLET = new Set(["router.execute", META_MCP_NAMES.list_top_sellers]);
|
|
89
91
|
const HAS_CREDITS = /^a402_[A-Za-z0-9_-]{32,64}$/.test(CREDITS_KEY);
|
|
92
|
+
// The secrets this process holds never leave it in text: every tool result,
|
|
93
|
+
// every protocol error and every console line passes through redactSecrets,
|
|
94
|
+
// which replaces each configured key (and the spellings a library may print
|
|
95
|
+
// it in: without its 0x prefix, in either case, a byte array without spaces)
|
|
96
|
+
// with [redacted]. Key parsing also throws fixed messages that name the
|
|
97
|
+
// variable only (walletKeyError), since a parser's own message can quote its
|
|
98
|
+
// input.
|
|
99
|
+
const SECRET_FORMS = (() => {
|
|
100
|
+
const out = new Set();
|
|
101
|
+
for (const raw of [AGENT_KEY, SOLANA_AGENT_KEY, CREDITS_KEY]) {
|
|
102
|
+
const v = String(raw || "").trim();
|
|
103
|
+
if (v.length < 8) continue;
|
|
104
|
+
out.add(v);
|
|
105
|
+
const hex = v.replace(/^0x/i, "");
|
|
106
|
+
if (/^[0-9a-f]+$/i.test(hex) && hex.length >= 8) { out.add(hex); out.add(hex.toLowerCase()); out.add(hex.toUpperCase()); }
|
|
107
|
+
if (v.startsWith("[")) out.add(v.replace(/\s+/g, ""));
|
|
108
|
+
}
|
|
109
|
+
return [...out].sort((a, b) => b.length - a.length);
|
|
110
|
+
})();
|
|
111
|
+
function redactSecrets(text) {
|
|
112
|
+
let t = String(text);
|
|
113
|
+
for (const f of SECRET_FORMS) if (t.includes(f)) t = t.split(f).join("[redacted]");
|
|
114
|
+
return t;
|
|
115
|
+
}
|
|
116
|
+
/** A copy of a tool result (or any JSON value) with every string redacted. */
|
|
117
|
+
function redactDeep(v, depth = 0) {
|
|
118
|
+
if (!SECRET_FORMS.length) return v;
|
|
119
|
+
if (typeof v === "string") return redactSecrets(v);
|
|
120
|
+
if (depth > 64 || v == null || typeof v !== "object") return v;
|
|
121
|
+
if (Array.isArray(v)) return v.map((x) => redactDeep(x, depth + 1));
|
|
122
|
+
const out = {};
|
|
123
|
+
for (const [k, x] of Object.entries(v)) out[k] = redactDeep(x, depth + 1);
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
/** A handler whose answer, and whose thrown error's message, are redacted. */
|
|
127
|
+
const redacted = (handler) => async (req, extra) => {
|
|
128
|
+
try {
|
|
129
|
+
return redactDeep(await handler(req, extra));
|
|
130
|
+
} catch (e) {
|
|
131
|
+
if (SECRET_FORMS.length && e && typeof e.message === "string") {
|
|
132
|
+
try { e.message = redactSecrets(e.message); if (typeof e.stack === "string") e.stack = redactSecrets(e.stack); } catch { /* a frozen error */ throw new Error(redactSecrets(e.message)); }
|
|
133
|
+
}
|
|
134
|
+
throw e;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
// Every console line, a library's included, is redacted before it is written.
|
|
138
|
+
if (SECRET_FORMS.length) {
|
|
139
|
+
for (const m of ["log", "info", "warn", "error", "debug", "trace"]) {
|
|
140
|
+
const orig = console[m].bind(console);
|
|
141
|
+
console[m] = (...a) => orig(redactSecrets(format(...a)));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/** A fixed error for a key that does not parse: the variable's name, never
|
|
145
|
+
* the parser's message (it can quote the value). */
|
|
146
|
+
const walletKeyError = (name, what) => new Error(`${name} is set but is not ${what}; check the value (it is never printed)`);
|
|
147
|
+
|
|
90
148
|
// Slow paid routes (async.recommended on their /api/pricing row) are sent with
|
|
91
149
|
// Prefer: respond-async and collected from their job link (./async-job.js).
|
|
92
150
|
// AGENT402_ASYNC=off waits on the connection instead; =always uses a job on
|
|
@@ -113,12 +171,36 @@ const capFromEnv = (name, def) => {
|
|
|
113
171
|
if (raw === "off") return Infinity;
|
|
114
172
|
const n = Number(raw);
|
|
115
173
|
if (Number.isFinite(n) && n >= 0) return n;
|
|
116
|
-
console.error(`[agent402-mcp] ${name}=${JSON.stringify(process.env[name])} is not a USD amount or "off"; using the default (${def === Infinity ? "no cap" : `$${def}`})`);
|
|
174
|
+
console.error(`[agent402-mcp] ${name}=${String(process.env[name]).length <= 16 ? JSON.stringify(process.env[name]) : "(a long value, not shown)"} is not a USD amount or "off"; using the default (${def === Infinity ? "no cap" : `$${def}`})`);
|
|
117
175
|
return def;
|
|
118
176
|
};
|
|
119
177
|
const MAX_PER_CALL = capFromEnv("AGENT402_MAX_PER_CALL", DEFAULT_MAX_PER_CALL_USD);
|
|
120
178
|
const BUDGET = capFromEnv("AGENT402_BUDGET", DEFAULT_BUDGET_USD);
|
|
121
179
|
let spentUsd = 0;
|
|
180
|
+
// Signed payments that were sent without a confirmed answer (an error status,
|
|
181
|
+
// a dropped connection, a redirect, a job still running). The seller holds a
|
|
182
|
+
// signed authorization it may still redeem, so the amount counts against the
|
|
183
|
+
// session budget for the rest of the session, beside what was spent.
|
|
184
|
+
// The default host (DEFAULT_URL, matched by exact origin) settles a payment
|
|
185
|
+
// only on an answer below 400, so a sent payment it answered with an error
|
|
186
|
+
// status can be redeemed only until its authorization expires: that hold ends
|
|
187
|
+
// at the signed validBefore plus HOLD_SLACK_MS, or OWN_HOST_BLIND_HOLD_MS after
|
|
188
|
+
// the answer when the payload names no readable expiry.
|
|
189
|
+
const HOLD_SLACK_MS = 10 * 60 * 1000;
|
|
190
|
+
const OWN_HOST_BLIND_HOLD_MS = 15 * 60 * 1000;
|
|
191
|
+
const DEFAULT_ORIGIN = new URL(DEFAULT_URL).origin;
|
|
192
|
+
const holds = []; // [{ usd, until }], until Infinity = the rest of the session
|
|
193
|
+
const holdPayment = (usd, until = Infinity) => { holds.push({ usd, until }); };
|
|
194
|
+
const heldNow = () => { const now = Date.now(); let t = 0; for (const h of holds) if (h.until > now) t += h.usd; return t; };
|
|
195
|
+
/** When a sent payload can no longer settle plus the clock slack: an EIP-3009
|
|
196
|
+
* validBefore or a Permit2 deadline, in seconds, never later than
|
|
197
|
+
* MAX_VALIDITY_SECONDS from now (the signing guard refuses to send a payload
|
|
198
|
+
* valid for longer); null when none is readable. */
|
|
199
|
+
function signedValidUntilMs(paymentPayload, nowMs = Date.now()) {
|
|
200
|
+
const v = signedExpirySeconds(paymentPayload);
|
|
201
|
+
if (v == null || !Number.isFinite(v)) return null;
|
|
202
|
+
return Math.min(v * 1000, nowMs + MAX_VALIDITY_SECONDS * 1000) + HOLD_SLACK_MS;
|
|
203
|
+
}
|
|
122
204
|
// Wallet calls in flight, each holding what it may sign until it settles or
|
|
123
205
|
// fails, so concurrent calls cannot each pass against the same budget. The
|
|
124
206
|
// signing guard reads the one being signed from signCtx.
|
|
@@ -128,7 +210,7 @@ const pendingUsd = (except = null) => { let t = 0; for (const e of pendingSpend)
|
|
|
128
210
|
/** The most the payment being signed may ask for: the per-call cap and what is
|
|
129
211
|
* left of the session budget after every other call in flight. */
|
|
130
212
|
function signAllowance() {
|
|
131
|
-
return Math.max(0, Math.min(MAX_PER_CALL, BUDGET - spentUsd - pendingUsd(signCtx.getStore() || null)));
|
|
213
|
+
return Math.max(0, Math.min(MAX_PER_CALL, BUDGET - spentUsd - heldNow() - pendingUsd(signCtx.getStore() || null)));
|
|
132
214
|
}
|
|
133
215
|
|
|
134
216
|
const DEFAULT_CURATED = [
|
|
@@ -218,10 +300,13 @@ function getPayFetch() {
|
|
|
218
300
|
onSign: (usd) => { const e = signCtx.getStore(); if (e) { e.usd = usd; e.signed = true; } },
|
|
219
301
|
onRefuse: (detail) => { const e = signCtx.getStore(); if (e) e.refusal = detail; },
|
|
220
302
|
});
|
|
303
|
+
// Registered after the guard's check of the signed amount, so it runs only
|
|
304
|
+
// for a payload about to be sent: from here the payment is outstanding.
|
|
305
|
+
client.onAfterPaymentCreation(async ({ paymentPayload } = {}) => { const e = signCtx.getStore(); if (e && e.signed) { e.sent = true; e.until = signedValidUntilMs(paymentPayload); } });
|
|
221
306
|
if (AGENT_KEY) {
|
|
222
307
|
const { registerExactEvmScheme } = await import("@x402/evm/exact/client");
|
|
223
308
|
const { privateKeyToAccount } = await import("viem/accounts");
|
|
224
|
-
registerExactEvmScheme(client, { signer: privateKeyToAccount
|
|
309
|
+
registerExactEvmScheme(client, { signer: evmAccount(privateKeyToAccount) });
|
|
225
310
|
}
|
|
226
311
|
if (SOLANA_AGENT_KEY) {
|
|
227
312
|
const { registerExactSvmScheme } = await import("@x402/svm/exact/client");
|
|
@@ -238,6 +323,11 @@ function getPayFetch() {
|
|
|
238
323
|
return payFetchPromise;
|
|
239
324
|
}
|
|
240
325
|
|
|
326
|
+
/** The viem account for AGENT_KEY, or walletKeyError. */
|
|
327
|
+
function evmAccount(privateKeyToAccount) {
|
|
328
|
+
try { return privateKeyToAccount(AGENT_KEY.trim()); } catch { throw walletKeyError("AGENT_KEY", "a 0x-prefixed 32-byte hex private key"); }
|
|
329
|
+
}
|
|
330
|
+
|
|
241
331
|
// @solana/kit KeyPairSigner from SOLANA_AGENT_KEY, base58 64-byte secret key
|
|
242
332
|
// (Phantom / solana-keygen export) or a JSON byte array ([12,34,…]).
|
|
243
333
|
let solanaSignerPromise;
|
|
@@ -245,10 +335,14 @@ function solanaSigner() {
|
|
|
245
335
|
solanaSignerPromise ??= (async () => {
|
|
246
336
|
const { createKeyPairSignerFromBytes, getBase58Encoder } = await import("@solana/kit");
|
|
247
337
|
const raw = SOLANA_AGENT_KEY.trim();
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
338
|
+
try {
|
|
339
|
+
const bytes = raw.startsWith("[")
|
|
340
|
+
? Uint8Array.from(JSON.parse(raw))
|
|
341
|
+
: new Uint8Array(getBase58Encoder().encode(raw));
|
|
342
|
+
return await createKeyPairSignerFromBytes(bytes);
|
|
343
|
+
} catch {
|
|
344
|
+
throw walletKeyError("SOLANA_AGENT_KEY", "a base58 or JSON byte-array 64-byte Solana secret key");
|
|
345
|
+
}
|
|
252
346
|
})();
|
|
253
347
|
return solanaSignerPromise;
|
|
254
348
|
}
|
|
@@ -404,6 +498,7 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
|
|
|
404
498
|
};
|
|
405
499
|
|
|
406
500
|
let res;
|
|
501
|
+
let heldNote = "";
|
|
407
502
|
if (!HAS_WALLET && HAS_CREDITS) {
|
|
408
503
|
// Credits key: same budget guards as the wallet path, against the same
|
|
409
504
|
// number - the credits gate holds and debits what the 402 quotes for THIS
|
|
@@ -446,40 +541,51 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
|
|
|
446
541
|
};
|
|
447
542
|
}
|
|
448
543
|
const inFlight = pendingUsd();
|
|
449
|
-
|
|
544
|
+
const heldUsd = heldNow();
|
|
545
|
+
if (spentUsd + heldUsd + inFlight + price > BUDGET) {
|
|
450
546
|
return {
|
|
451
|
-
content: [{ type: "text", text: `Refused without paying: session budget exhausted ($${spentUsd.toFixed(4)} of $${BUDGET} spent${inFlight ? `, $${inFlight.toFixed(4)} in flight` : ""}; "${tool.slug}" lists at ${tool.price}). Restart the MCP server or raise AGENT402_BUDGET.` }],
|
|
547
|
+
content: [{ type: "text", text: `Refused without paying: session budget exhausted ($${spentUsd.toFixed(4)} of $${BUDGET} spent${heldUsd ? `, $${heldUsd.toFixed(4)} held for sent payments whose outcome is unknown` : ""}${inFlight ? `, $${inFlight.toFixed(4)} in flight` : ""}; "${tool.slug}" lists at ${tool.price}). Restart the MCP server or raise AGENT402_BUDGET.` }],
|
|
452
548
|
isError: true,
|
|
453
549
|
};
|
|
454
550
|
}
|
|
455
551
|
const payFetch = await getPayFetch();
|
|
456
552
|
// Held until the call settles or fails; the guard replaces `usd` with the
|
|
457
553
|
// amount it lets the wallet sign.
|
|
458
|
-
const entry = { usd: price, signed: false, refusal: null };
|
|
554
|
+
const entry = { usd: price, signed: false, sent: false, refusal: null };
|
|
459
555
|
pendingSpend.add(entry);
|
|
460
556
|
try {
|
|
461
557
|
const first = await signCtx.run(entry, () => payFetch(url, { ...paidInit, headers: { ...init.headers, ...asyncHeaders } }));
|
|
462
558
|
if (isRedirect(first)) {
|
|
463
559
|
pendingSpend.delete(entry);
|
|
464
560
|
// A signature already sent leaves that payment's outcome unknown, so
|
|
465
|
-
// it
|
|
466
|
-
if (entry.
|
|
561
|
+
// it is held against the session budget.
|
|
562
|
+
if (entry.sent) holdPayment(entry.usd);
|
|
467
563
|
return redirectRefusal(first);
|
|
468
564
|
}
|
|
469
565
|
res = await collect(first);
|
|
470
566
|
}
|
|
471
567
|
catch (e) {
|
|
472
568
|
pendingSpend.delete(entry);
|
|
473
|
-
//
|
|
474
|
-
|
|
475
|
-
if (entry.
|
|
569
|
+
// Once a payment was sent, any failure (a job still running, a dropped
|
|
570
|
+
// connection) leaves its authorization redeemable, so it is held.
|
|
571
|
+
if (entry.sent) holdPayment(entry.usd);
|
|
572
|
+
if (e instanceof AsyncJobPendingError) return pendingJobResult(tool, e);
|
|
573
|
+
if (entry.refusal && !entry.sent) return signingRefusal(tool, entry.refusal);
|
|
476
574
|
throw e;
|
|
477
575
|
}
|
|
478
576
|
pendingSpend.delete(entry);
|
|
479
|
-
//
|
|
480
|
-
//
|
|
481
|
-
//
|
|
482
|
-
if (entry.
|
|
577
|
+
// A sent payment is spent when the server confirms settlement (payment
|
|
578
|
+
// receipt header) or answers 2xx; any other answer leaves the signed
|
|
579
|
+
// authorization with the seller, so it is held, never released.
|
|
580
|
+
if (entry.sent) {
|
|
581
|
+
if (res.headers.get("payment-response") || res.headers.get("x-payment-response") || res.ok) spentUsd += entry.usd;
|
|
582
|
+
else if (res.status >= 400 && url.origin === DEFAULT_ORIGIN) {
|
|
583
|
+
// The default host did not settle it: held until it expires unused.
|
|
584
|
+
const until = entry.until ?? Date.now() + OWN_HOST_BLIND_HOLD_MS;
|
|
585
|
+
holdPayment(entry.usd, until);
|
|
586
|
+
heldNote = ` A payment of $${entry.usd} was sent with this request and ${new URL(DEFAULT_URL).host} does not settle a failed answer: it stays held against AGENT402_BUDGET until its authorization expires unused (${new Date(until).toISOString()}), then is released, never charged.`;
|
|
587
|
+
} else { holdPayment(entry.usd); heldNote = ` A payment of $${entry.usd} was sent with this request, so its outcome is unknown: it stays held against AGENT402_BUDGET for this session.`; }
|
|
588
|
+
}
|
|
483
589
|
} else if (tool.computePayable) {
|
|
484
590
|
// No wallet: pay with compute up front, solving before the call skips the
|
|
485
591
|
// 402 round-trip entirely (challenges are single-use and tool-scoped).
|
|
@@ -503,7 +609,7 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
|
|
|
503
609
|
}
|
|
504
610
|
const text = await res.text();
|
|
505
611
|
if (res.status >= 400) {
|
|
506
|
-
return { content: [{ type: "text", text: failureText(res.status, text) }], isError: true };
|
|
612
|
+
return { content: [{ type: "text", text: failureText(res.status, text) + heldNote }], isError: true };
|
|
507
613
|
}
|
|
508
614
|
let parsed;
|
|
509
615
|
try { parsed = JSON.parse(text); } catch { parsed = { raw: text }; }
|
|
@@ -522,6 +628,10 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
|
|
|
522
628
|
function signingRefusal(tool, d) {
|
|
523
629
|
const text = d.reason === "unknown-asset"
|
|
524
630
|
? `Refused without paying: "${tool.slug}" asked to be paid in an asset this server cannot price (USDC or USDG on a known network), so nothing was signed.`
|
|
631
|
+
: d.reason === "signed-amount" || d.reason === "signed-validity"
|
|
632
|
+
? `Refused without paying: for "${tool.slug}", ${d.detail}, so the payment was not sent.`
|
|
633
|
+
: d.reason === "validity"
|
|
634
|
+
? `Refused without paying: for "${tool.slug}", ${d.detail}, so nothing was signed.`
|
|
525
635
|
: `Refused without paying: "${tool.slug}" asked for $${d.priceUsd} on the paid request, above the $${Number(d.allowanceUsd.toFixed(6))} this server may sign (AGENT402_MAX_PER_CALL ${MAX_PER_CALL === Infinity ? "off" : `$${MAX_PER_CALL}`}, AGENT402_BUDGET ${BUDGET === Infinity ? "off" : `$${BUDGET}`} with $${spentUsd.toFixed(4)} spent). Nothing was signed.`;
|
|
526
636
|
return { content: [{ type: "text", text }], isError: true };
|
|
527
637
|
}
|
|
@@ -648,7 +758,7 @@ const server = new Server(
|
|
|
648
758
|
// MCP-aware client. The list is fetched once at boot in loadCatalog(); the
|
|
649
759
|
// per-prompt rendering is delegated to the hosted service so the npm package
|
|
650
760
|
// stays thin and prompt text stays canonical with the website at /skills.
|
|
651
|
-
server.setRequestHandler(ListPromptsRequestSchema, async () => ({
|
|
761
|
+
server.setRequestHandler(ListPromptsRequestSchema, redacted(async () => ({
|
|
652
762
|
prompts: skillPacks.map((p) => ({
|
|
653
763
|
name: p.slug,
|
|
654
764
|
title: p.title,
|
|
@@ -659,8 +769,8 @@ server.setRequestHandler(ListPromptsRequestSchema, async () => ({
|
|
|
659
769
|
required: a.required ?? true,
|
|
660
770
|
})),
|
|
661
771
|
})),
|
|
662
|
-
}));
|
|
663
|
-
server.setRequestHandler(GetPromptRequestSchema, async (req) => {
|
|
772
|
+
})));
|
|
773
|
+
server.setRequestHandler(GetPromptRequestSchema, redacted(async (req) => {
|
|
664
774
|
const { name, arguments: args = {} } = req.params;
|
|
665
775
|
const pack = skillPacks.find((p) => p.slug === name);
|
|
666
776
|
if (!pack) throw new Error(`Unknown prompt "${name}". List available with prompts/list.`);
|
|
@@ -671,7 +781,7 @@ server.setRequestHandler(GetPromptRequestSchema, async (req) => {
|
|
|
671
781
|
const { res, attempts } = await fetchDiscovery(url);
|
|
672
782
|
if (!res.ok) throw new Error(`Failed to render prompt "${name}" from ${BASE}: ${discoveryFailure(url, res, attempts)}`);
|
|
673
783
|
return await res.json();
|
|
674
|
-
});
|
|
784
|
+
}));
|
|
675
785
|
|
|
676
786
|
let curated = [];
|
|
677
787
|
let pricingInfo = null;
|
|
@@ -706,7 +816,7 @@ async function ensureCatalog() {
|
|
|
706
816
|
}
|
|
707
817
|
const withCatalog = (handler) => async (req, extra) => { await ensureCatalog(); return handler(req, extra); };
|
|
708
818
|
|
|
709
|
-
server.setRequestHandler(ListToolsRequestSchema, withCatalog(async () => {
|
|
819
|
+
server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () => {
|
|
710
820
|
// Read-only only for lookups that stay on this machine (describe, payment
|
|
711
821
|
// info). Anything that reaches the network or can spend is NET: not read-only,
|
|
712
822
|
// open-world. A host reads readOnlyHint to decide whether to ask first.
|
|
@@ -837,9 +947,9 @@ server.setRequestHandler(ListToolsRequestSchema, withCatalog(async () => {
|
|
|
837
947
|
// AGENT402_SHOW_ROUTER=1 opts in. Calls to them still route when unlisted.
|
|
838
948
|
const listed = SHOW_ROUTER ? tools : tools.filter((t) => !HIDDEN_WITHOUT_WALLET.has(t.name));
|
|
839
949
|
return { tools: listed };
|
|
840
|
-
}));
|
|
950
|
+
})));
|
|
841
951
|
|
|
842
|
-
server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) => {
|
|
952
|
+
server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req, extra) => {
|
|
843
953
|
const { name: rawName, arguments: args = {} } = req.params;
|
|
844
954
|
const name = resolveListedName(rawName);
|
|
845
955
|
const overBound = toolInputBoundRefusal(rawName, args);
|
|
@@ -901,7 +1011,7 @@ server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) =
|
|
|
901
1011
|
let address = null;
|
|
902
1012
|
if (AGENT_KEY) {
|
|
903
1013
|
const { privateKeyToAccount } = await import("viem/accounts");
|
|
904
|
-
address = privateKeyToAccount
|
|
1014
|
+
try { address = evmAccount(privateKeyToAccount).address; } catch { address = "invalid AGENT_KEY"; }
|
|
905
1015
|
}
|
|
906
1016
|
let solanaAddress = null;
|
|
907
1017
|
if (SOLANA_AGENT_KEY) {
|
|
@@ -928,7 +1038,8 @@ server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) =
|
|
|
928
1038
|
maxPerCallUsd: MAX_PER_CALL === Infinity ? "unlimited" : MAX_PER_CALL,
|
|
929
1039
|
sessionBudgetUsd: BUDGET === Infinity ? "unlimited" : BUDGET,
|
|
930
1040
|
spentThisSessionUsd: Number(spentUsd.toFixed(6)),
|
|
931
|
-
|
|
1041
|
+
heldThisSessionUsd: Number(heldNow().toFixed(6)),
|
|
1042
|
+
remainingUsd: BUDGET === Infinity ? "unlimited" : Number(Math.max(0, BUDGET - spentUsd - heldNow()).toFixed(6)),
|
|
932
1043
|
}
|
|
933
1044
|
: "n/a (proof-of-work mode spends CPU, not money)",
|
|
934
1045
|
note: HAS_WALLET
|
|
@@ -940,7 +1051,7 @@ server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) =
|
|
|
940
1051
|
claudeCodeHosted: `claude mcp add --transport http agent402 ${BASE}/mcp`,
|
|
941
1052
|
claudeCodeNpm: `claude mcp add agent402 -s user -- npx -y agent402-mcp@${AGENT402_MCP_VERSION}`,
|
|
942
1053
|
cursorHosted: { mcpServers: { agent402: { url: `${BASE}/mcp` } } },
|
|
943
|
-
npm: "npx -y agent402-mcp@0.13.
|
|
1054
|
+
npm: "npx -y agent402-mcp@0.13.30",
|
|
944
1055
|
maintainer: "Havok Holdings LLC",
|
|
945
1056
|
},
|
|
946
1057
|
positioning: `Flagship search/answer first, 500+ long-tail tools via catalog.find / catalog.search / catalog.call. Agent402 is the applied layer of Agentic Finance: agents that pay and get paid per request over x402 or MPP (Machine Payments Protocol), both on the same 402 - ${BASE}/agentic-finance, ${BASE}/glossary.`,
|
|
@@ -960,7 +1071,7 @@ server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) =
|
|
|
960
1071
|
install: {
|
|
961
1072
|
claudeCodeHosted: `claude mcp add --transport http agent402 ${BASE}/mcp`,
|
|
962
1073
|
claudeCodeNpm: `claude mcp add agent402 -s user -- npx -y agent402-mcp@${AGENT402_MCP_VERSION}`,
|
|
963
|
-
npm: "npx -y agent402-mcp@0.13.
|
|
1074
|
+
npm: "npx -y agent402-mcp@0.13.30",
|
|
964
1075
|
maintainer: "Havok Holdings LLC",
|
|
965
1076
|
},
|
|
966
1077
|
tools: catalog.size,
|
|
@@ -1101,7 +1212,7 @@ server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) =
|
|
|
1101
1212
|
} catch (err) {
|
|
1102
1213
|
return { content: [{ type: "text", text: `Agent402 call failed: ${err.message}` }], isError: true };
|
|
1103
1214
|
}
|
|
1104
|
-
}));
|
|
1215
|
+
})));
|
|
1105
1216
|
|
|
1106
1217
|
// ---------------------------------------------------------------------------
|
|
1107
1218
|
try {
|
package/known-assets.js
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
// Known payment assets, and the USD value of an x402 accept priced from them.
|
|
2
2
|
//
|
|
3
|
-
// An x402 "exact" signer signs the accept's raw base-unit
|
|
4
|
-
// accept's `asset
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
3
|
+
// An x402 "exact" signer signs the accept's raw base-unit amount for the
|
|
4
|
+
// accept's `asset`: `amount` under x402 v2, `maxAmountRequired` under v1. A
|
|
5
|
+
// spending cap therefore has to price the field the signer of that version
|
|
6
|
+
// reads, with the asset's real decimals, and a decimals hint the seller sends
|
|
7
|
+
// beside it (for example `extra.decimals`) is not evidence of anything. So the
|
|
8
|
+
// price of an accept comes from its challenge's version and this table alone:
|
|
9
|
+
// the stablecoins each network settles on the Agent402 rails, with their
|
|
10
|
+
// on-chain decimals. An accept whose (network, asset) pair is not in the table,
|
|
11
|
+
// or that carries both amount fields with different values, cannot be priced,
|
|
12
|
+
// and a buyer with a cap does not sign it. The table is keyed by CAIP-2 ids
|
|
13
|
+
// only: a bare v1 network name (for example "base") is not priced.
|
|
11
14
|
//
|
|
12
15
|
// The same file ships in agent402-client, agent402-mcp and agent402-openclaw;
|
|
13
16
|
// the parent repo's scripts/test-known-assets.js keeps the copies identical and
|
|
@@ -85,13 +88,33 @@ export function knownAsset(network, asset) {
|
|
|
85
88
|
return list.find((e) => sameAsset(e.asset, asset)) || null;
|
|
86
89
|
}
|
|
87
90
|
|
|
88
|
-
/** The
|
|
89
|
-
* `maxAmountRequired`
|
|
90
|
-
*
|
|
91
|
-
|
|
91
|
+
/** The base-unit amount the signer of `x402Version` signs for one accept, as
|
|
92
|
+
* a string of digits: `maxAmountRequired` under v1, `amount` under v2. With
|
|
93
|
+
* no version, the one field present (or both, when they agree). null when
|
|
94
|
+
* the field that version signs is missing or not a whole number, when the
|
|
95
|
+
* version is neither 1 nor 2, and whenever the accept carries both fields
|
|
96
|
+
* with different values: such an accept means one price to one reader and
|
|
97
|
+
* another to the next, so it is not priced at all. */
|
|
98
|
+
export function acceptAmount(accept, x402Version = undefined) {
|
|
92
99
|
if (!accept || typeof accept !== "object") return null;
|
|
93
|
-
const
|
|
94
|
-
|
|
100
|
+
const has = (x) => x != null && x !== "";
|
|
101
|
+
const v2 = accept.amount, v1 = accept.maxAmountRequired;
|
|
102
|
+
if (has(v2) && has(v1) && String(v2) !== String(v1)) return null;
|
|
103
|
+
let raw;
|
|
104
|
+
if (x402Version === 1) raw = v1;
|
|
105
|
+
else if (x402Version === 2) raw = v2;
|
|
106
|
+
else if (x402Version == null) raw = has(v2) ? v2 : v1;
|
|
107
|
+
else return null;
|
|
108
|
+
if (!has(raw) || !/^\d+$/.test(String(raw))) return null;
|
|
109
|
+
return String(raw);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The USD value of one accept: the base-unit amount its version's signer
|
|
113
|
+
* signs (acceptAmount) over the KNOWN decimals of its asset. null when the
|
|
114
|
+
* asset is not known or the amount cannot be read. */
|
|
115
|
+
export function acceptUsd(accept, x402Version = undefined) {
|
|
116
|
+
const raw = acceptAmount(accept, x402Version);
|
|
117
|
+
if (raw == null) return null;
|
|
95
118
|
const entry = knownAsset(accept.network, accept.asset);
|
|
96
119
|
if (!entry) return null;
|
|
97
120
|
return Number(raw) / 10 ** entry.decimals;
|
|
@@ -99,11 +122,11 @@ export function acceptUsd(accept) {
|
|
|
99
122
|
|
|
100
123
|
/** The USD values of a 402's accepts: `max` and `min` over the accepts that can
|
|
101
124
|
* be priced, and `unknown`, the count that cannot. null when there are none. */
|
|
102
|
-
export function quoteOf(accepts) {
|
|
125
|
+
export function quoteOf(accepts, x402Version = undefined) {
|
|
103
126
|
if (!Array.isArray(accepts) || !accepts.length) return null;
|
|
104
127
|
let max = null, min = null, unknown = 0;
|
|
105
128
|
for (const a of accepts) {
|
|
106
|
-
const usd = acceptUsd(a);
|
|
129
|
+
const usd = acceptUsd(a, x402Version);
|
|
107
130
|
if (usd == null) { unknown++; continue; }
|
|
108
131
|
if (max == null || usd > max) max = usd;
|
|
109
132
|
if (min == null || usd < min) min = usd;
|
|
@@ -111,6 +134,51 @@ export function quoteOf(accepts) {
|
|
|
111
134
|
return { max, min, unknown, total: accepts.length };
|
|
112
135
|
}
|
|
113
136
|
|
|
137
|
+
// The longest a signed payment may stay redeemable. An EVM "exact" signer
|
|
138
|
+
// sets validBefore (EIP-3009) or deadline (Permit2) to the moment of signing
|
|
139
|
+
// plus the accept's maxTimeoutSeconds, and the signed payload is a bearer
|
|
140
|
+
// claim until then, so a seller that quotes years gets an authorization it
|
|
141
|
+
// could redeem for years and a held amount that never stops counting. Honest
|
|
142
|
+
// accepts ask for minutes (Agent402's own ask 300 s); a day admits every
|
|
143
|
+
// one of them. An accept that asks for longer is dropped before selection,
|
|
144
|
+
// and a payload signed past it is refused before it is sent.
|
|
145
|
+
export const MAX_VALIDITY_SECONDS = 24 * 3600;
|
|
146
|
+
// Signing reads the clock a moment before the check after it does.
|
|
147
|
+
const VALIDITY_CLOCK_SLACK_SECONDS = 60;
|
|
148
|
+
|
|
149
|
+
/** True when an accept asks for a validity window past MAX_VALIDITY_SECONDS.
|
|
150
|
+
* An accept with no readable maxTimeoutSeconds is left to the check of what
|
|
151
|
+
* was signed (signedValidityProblem). */
|
|
152
|
+
export function acceptValidityTooLong(accept, maxSeconds = MAX_VALIDITY_SECONDS) {
|
|
153
|
+
const raw = accept?.maxTimeoutSeconds;
|
|
154
|
+
if (raw == null || raw === "") return false;
|
|
155
|
+
const n = Number(raw);
|
|
156
|
+
return !Number.isFinite(n) || n > maxSeconds;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The expiry a signed payload carries, in unix seconds: an EIP-3009
|
|
160
|
+
* `authorization.validBefore` or a Permit2 `deadline`. null when the payload
|
|
161
|
+
* names none (a Solana transaction, an unknown scheme). NaN when it names
|
|
162
|
+
* one that is not a whole number of seconds. */
|
|
163
|
+
export function signedExpirySeconds(paymentPayload) {
|
|
164
|
+
const p = paymentPayload?.payload;
|
|
165
|
+
const v = p?.authorization?.validBefore ?? p?.permit2Authorization?.deadline;
|
|
166
|
+
if (v == null) return null;
|
|
167
|
+
return /^\d{1,15}$/.test(String(v)) ? Number(v) : NaN;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Why a created payment payload stays redeemable for too long, or null: its
|
|
171
|
+
* expiry is past `nowMs` plus `maxSeconds` (and a minute of clock slack), or
|
|
172
|
+
* it names an expiry that cannot be read. */
|
|
173
|
+
export function signedValidityProblem(paymentPayload, { maxSeconds = MAX_VALIDITY_SECONDS, nowMs = Date.now() } = {}) {
|
|
174
|
+
const exp = signedExpirySeconds(paymentPayload);
|
|
175
|
+
if (exp == null) return null;
|
|
176
|
+
if (!Number.isFinite(exp)) return "the signed authorization's expiry cannot be read";
|
|
177
|
+
const left = exp - Math.floor(nowMs / 1000);
|
|
178
|
+
if (left > maxSeconds + VALIDITY_CLOCK_SLACK_SECONDS) return `the signed authorization stays valid for ${left} seconds, past the ${maxSeconds}-second ceiling`;
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
114
182
|
/** Enforce a USD allowance at signing on an @x402/core x402Client.
|
|
115
183
|
*
|
|
116
184
|
* `allowance()` is the most this buyer may sign for the payment being built
|
|
@@ -118,8 +186,10 @@ export function quoteOf(accepts) {
|
|
|
118
186
|
* for none). A registered policy drops every accept that cannot be priced or
|
|
119
187
|
* is over the allowance, so the client selects among the ones that fit, and a
|
|
120
188
|
* hook before payload creation checks the selected accept again and passes
|
|
121
|
-
* its USD value to `onSign`.
|
|
122
|
-
*
|
|
189
|
+
* its USD value to `onSign`. An accept asking for a validity window past
|
|
190
|
+
* MAX_VALIDITY_SECONDS is dropped and refused the same way. A refusal throws
|
|
191
|
+
* (from the policy) or aborts (from the hook) before any signature exists;
|
|
192
|
+
* `onRefuse` hears why first. */
|
|
123
193
|
export function guardSigning(client, { allowance, onSign = null, onRefuse = null }) {
|
|
124
194
|
if (!client || typeof client.registerPolicy !== "function" || typeof client.onBeforePaymentCreation !== "function") {
|
|
125
195
|
throw new TypeError("guardSigning needs an @x402/core x402Client (registerPolicy and onBeforePaymentCreation)");
|
|
@@ -128,9 +198,14 @@ export function guardSigning(client, { allowance, onSign = null, onRefuse = null
|
|
|
128
198
|
const refuse = (detail) => { try { onRefuse?.(detail); } catch { /* the refusal stands */ } return detail; };
|
|
129
199
|
client.registerPolicy((version, accepts) => {
|
|
130
200
|
const cap = allowance();
|
|
131
|
-
const
|
|
201
|
+
const priced = accepts.filter((a) => { const usd = acceptUsd(a, version); return usd != null && usd <= cap; });
|
|
202
|
+
const kept = priced.filter((a) => !acceptValidityTooLong(a));
|
|
203
|
+
if (!kept.length && priced.length) {
|
|
204
|
+
const d = refuse({ reason: "validity", priceUsd: null, allowanceUsd: cap, detail: `every payment option it may sign asks to stay valid for more than ${MAX_VALIDITY_SECONDS} seconds` });
|
|
205
|
+
throw new Error(`spending guard: ${d.detail}; nothing was signed`);
|
|
206
|
+
}
|
|
132
207
|
if (!kept.length) {
|
|
133
|
-
const q = quoteOf(accepts);
|
|
208
|
+
const q = quoteOf(accepts, version);
|
|
134
209
|
const d = refuse({ reason: q && q.min != null ? "over-allowance" : "unknown-asset", priceUsd: q ? q.min : null, allowanceUsd: cap });
|
|
135
210
|
throw new Error(d.reason === "unknown-asset"
|
|
136
211
|
? "spending guard: no payment option is in a known asset, so none can be priced; nothing was signed"
|
|
@@ -138,8 +213,8 @@ export function guardSigning(client, { allowance, onSign = null, onRefuse = null
|
|
|
138
213
|
}
|
|
139
214
|
return kept;
|
|
140
215
|
});
|
|
141
|
-
client.onBeforePaymentCreation(async ({ selectedRequirements: r }) => {
|
|
142
|
-
const usd = acceptUsd(r);
|
|
216
|
+
client.onBeforePaymentCreation(async ({ paymentRequired, selectedRequirements: r }) => {
|
|
217
|
+
const usd = acceptUsd(r, paymentRequired?.x402Version);
|
|
143
218
|
const cap = allowance();
|
|
144
219
|
if (usd == null) {
|
|
145
220
|
refuse({ reason: "unknown-asset", priceUsd: null, allowanceUsd: cap });
|
|
@@ -149,8 +224,106 @@ export function guardSigning(client, { allowance, onSign = null, onRefuse = null
|
|
|
149
224
|
refuse({ reason: "over-allowance", priceUsd: usd, allowanceUsd: cap });
|
|
150
225
|
return { abort: true, reason: `spending guard: the selected payment option asks $${usd}, above the $${cap} this buyer may sign; nothing was signed` };
|
|
151
226
|
}
|
|
227
|
+
if (acceptValidityTooLong(r)) {
|
|
228
|
+
const d = refuse({ reason: "validity", priceUsd: usd, allowanceUsd: cap, detail: `the selected payment option asks to stay valid for ${r.maxTimeoutSeconds} seconds, past the ${MAX_VALIDITY_SECONDS}-second ceiling` });
|
|
229
|
+
return { abort: true, reason: `spending guard: ${d.detail}; nothing was signed` };
|
|
230
|
+
}
|
|
152
231
|
onSign?.(usd, r);
|
|
153
232
|
return undefined;
|
|
154
233
|
});
|
|
234
|
+
guardSignedAmount(client, { allowance, onRefuse: refuse });
|
|
235
|
+
return client;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// The token programs a Solana "exact" payment moves its asset through, and
|
|
239
|
+
// the TransferChecked instruction's tag.
|
|
240
|
+
const SOLANA_TOKEN_PROGRAMS = new Set(["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"]);
|
|
241
|
+
const TRANSFER_CHECKED = 12;
|
|
242
|
+
|
|
243
|
+
/** The amount a Solana payment transaction moves: its one token-program
|
|
244
|
+
* instruction, which must be a TransferChecked, read as base units and
|
|
245
|
+
* decimals. Decoded with @solana/kit, the peer every Solana x402 signer
|
|
246
|
+
* already loads. null when the transaction cannot be read or does not hold
|
|
247
|
+
* exactly that one transfer. */
|
|
248
|
+
async function solanaTransferOf(transaction) {
|
|
249
|
+
if (typeof transaction !== "string" || !transaction) return null;
|
|
250
|
+
try {
|
|
251
|
+
const kit = await import("@solana/kit");
|
|
252
|
+
const tx = kit.getTransactionDecoder().decode(kit.getBase64Encoder().encode(transaction));
|
|
253
|
+
const msg = kit.getCompiledTransactionMessageDecoder().decode(tx.messageBytes);
|
|
254
|
+
const keys = msg.staticAccounts || [];
|
|
255
|
+
const ixs = msg.version === 1
|
|
256
|
+
? (msg.instructionHeaders || []).map((h, i) => ({ program: keys[h.programAccountIndex], data: msg.instructionPayloads?.[i]?.instructionData }))
|
|
257
|
+
: (msg.instructions || []).map((ix) => ({ program: keys[ix.programAddressIndex], data: ix.data }));
|
|
258
|
+
const token = ixs.filter((ix) => SOLANA_TOKEN_PROGRAMS.has(String(ix.program)));
|
|
259
|
+
if (token.length !== 1) return null;
|
|
260
|
+
const d = token[0].data;
|
|
261
|
+
if (!d || d.length !== 10 || d[0] !== TRANSFER_CHECKED) return null;
|
|
262
|
+
let amount = 0n;
|
|
263
|
+
for (let i = 8; i >= 1; i--) amount = (amount << 8n) | BigInt(d[i]);
|
|
264
|
+
return { amount: amount.toString(), decimals: d[9] };
|
|
265
|
+
} catch {
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** The base-unit amount a created x402 payment payload commits the buyer to,
|
|
271
|
+
* read from what was signed: an EVM EIP-3009 `authorization.value`, an EVM
|
|
272
|
+
* Permit2 `permitted.amount`, or a Solana transaction's transfer. Returns
|
|
273
|
+
* `{ amount, decimals? }`, `{ unchecked: true }` for a network whose payload
|
|
274
|
+
* this reader does not decode (neither EVM nor Solana), or null when an EVM or
|
|
275
|
+
* Solana payload holds no amount it can read. */
|
|
276
|
+
export async function signedAmountOf(paymentPayload, network) {
|
|
277
|
+
const p = paymentPayload?.payload;
|
|
278
|
+
const net = String(network || "");
|
|
279
|
+
if (net.startsWith("eip155:")) {
|
|
280
|
+
const vals = [p?.authorization?.value, p?.permit2Authorization?.permitted?.amount].filter((x) => x != null);
|
|
281
|
+
if (vals.length !== 1 || !/^\d+$/.test(String(vals[0]))) return null;
|
|
282
|
+
return { amount: BigInt(String(vals[0])).toString() };
|
|
283
|
+
}
|
|
284
|
+
if (net.startsWith("solana:")) return solanaTransferOf(p?.transaction);
|
|
285
|
+
return { unchecked: true };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Check a created payment payload against the accept it was built for,
|
|
289
|
+
* before it is sent: the amount that was signed must be the amount the
|
|
290
|
+
* allowance was checked against (acceptAmount under the challenge's
|
|
291
|
+
* version), in the known asset's decimals, and within `cap`. Returns null
|
|
292
|
+
* when it holds, else why not. */
|
|
293
|
+
export async function signedPaymentProblem(paymentPayload, requirements, x402Version, cap = Infinity) {
|
|
294
|
+
const expected = acceptAmount(requirements, x402Version);
|
|
295
|
+
const entry = knownAsset(requirements?.network, requirements?.asset);
|
|
296
|
+
if (expected == null) return "the selected payment option's amount cannot be read";
|
|
297
|
+
const signed = await signedAmountOf(paymentPayload, requirements?.network);
|
|
298
|
+
if (signed == null) return "the signed payment's amount cannot be read";
|
|
299
|
+
if (signed.unchecked) return null;
|
|
300
|
+
if (signed.amount !== BigInt(expected).toString()) return `the signed amount (${signed.amount}) differs from the priced amount (${expected})`;
|
|
301
|
+
if (signed.decimals != null && entry && signed.decimals !== entry.decimals) return "the signed transfer's decimals differ from the known asset's";
|
|
302
|
+
if (Number.isFinite(cap)) {
|
|
303
|
+
if (!entry) return "the selected payment option is not in a known asset";
|
|
304
|
+
const usd = Number(signed.amount) / 10 ** entry.decimals;
|
|
305
|
+
if (usd > cap) return `the signed amount asks ${usd}, above the ${cap} this buyer may sign`;
|
|
306
|
+
}
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Refuse to send a payment payload whose signed amount is not the one the
|
|
311
|
+
* allowance passed, or whose expiry is past MAX_VALIDITY_SECONDS from now
|
|
312
|
+
* (signedValidityProblem): registered after payload creation, so the check
|
|
313
|
+
* reads what was actually signed, and a throw here stops the payment-aware
|
|
314
|
+
* fetch before the payload leaves the process. guardSigning registers it; a
|
|
315
|
+
* client with its own selector (and no guardSigning) can register it alone. */
|
|
316
|
+
export function guardSignedAmount(client, { allowance = () => Infinity, onRefuse = null } = {}) {
|
|
317
|
+
if (!client || typeof client.onAfterPaymentCreation !== "function") {
|
|
318
|
+
throw new TypeError("guardSignedAmount needs an @x402/core x402Client (onAfterPaymentCreation)");
|
|
319
|
+
}
|
|
320
|
+
client.onAfterPaymentCreation(async ({ paymentRequired, selectedRequirements: r, paymentPayload }) => {
|
|
321
|
+
const cap = allowance();
|
|
322
|
+
const amountProblem = await signedPaymentProblem(paymentPayload, r, paymentRequired?.x402Version, cap);
|
|
323
|
+
const problem = amountProblem || signedValidityProblem(paymentPayload);
|
|
324
|
+
if (!problem) return;
|
|
325
|
+
try { onRefuse?.({ reason: amountProblem ? "signed-amount" : "signed-validity", priceUsd: null, allowanceUsd: cap, detail: problem }); } catch { /* the refusal stands */ }
|
|
326
|
+
throw new Error(`spending guard: ${problem}; the payment was not sent`);
|
|
327
|
+
});
|
|
155
328
|
return client;
|
|
156
329
|
}
|
package/output-schemas.js
CHANGED
|
@@ -492,7 +492,7 @@ export function mcpJsonResult(obj) {
|
|
|
492
492
|
* Hosted URL is parameterized; npm / Claude Code / Cursor notes
|
|
493
493
|
* match docs/ecosystem-listings.md + wiki/MCP-Connector.md.
|
|
494
494
|
*/
|
|
495
|
-
export const AGENT402_MCP_VERSION = "0.13.
|
|
495
|
+
export const AGENT402_MCP_VERSION = "0.13.30";
|
|
496
496
|
|
|
497
497
|
/** A listed MCP tool description, at most `max` characters. Hosts truncate or
|
|
498
498
|
* skip long descriptions, so the listing keeps the first whole sentences; the
|
|
@@ -524,12 +524,12 @@ export function mcpInstallHints(baseUrl) {
|
|
|
524
524
|
mcpServers: {
|
|
525
525
|
agent402: {
|
|
526
526
|
command: "npx",
|
|
527
|
-
args: ["-y", "agent402-mcp@0.13.
|
|
527
|
+
args: ["-y", "agent402-mcp@0.13.30"],
|
|
528
528
|
env: { AGENT_KEY: "0xYOUR_PRIVATE_KEY" },
|
|
529
529
|
},
|
|
530
530
|
},
|
|
531
531
|
},
|
|
532
|
-
npm: "npx -y agent402-mcp@0.13.
|
|
532
|
+
npm: "npx -y agent402-mcp@0.13.30",
|
|
533
533
|
maintainer: "Havok Holdings LLC",
|
|
534
534
|
};
|
|
535
535
|
}
|
package/package.json
CHANGED