Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(x402-mcp): add 17 named commerce tools and a local spending report

nirholas06650c7216c6
diff --git a/packages/x402-mcp/README.md b/packages/x402-mcp/README.md
index 3225c21ee..cafffa8e9 100644
--- a/packages/x402-mcp/README.md
+++ b/packages/x402-mcp/README.md
@@ -68,6 +68,31 @@ claude mcp add x402 --env SOLANA_SECRET_KEY=<base58> -- npx -y @three-ws/x402-mc
| `find_services` | read-only | Search the live x402 bazaar (PayAI + Coinbase CDP) for paid HTTP/MCP services with prices. |
| `inspect_endpoint` | read-only | Read any endpoint's 402 payment requirements (scheme, network, asset, price, pay-to) **without paying**. |
| `pay_and_call` | **execution** | Pay an x402 endpoint in USDC from your Solana key and return its result. Bounded by `MAX_PAY_USD`. |
+| `spending_report` | read-only | Totals of everything `pay_and_call` and the named tools below have paid, by merchant and by day. |
+
+Plus 17 named tools, one per fixed three.ws x402 service, each cheaper for a model to call correctly than composing a raw `pay_and_call(url)`:
+
+| Tool | Price | Endpoint |
+| ------------------------ | ------- | -------------------------------- |
+| `weather_forecast` | $0.001 | `/api/x402/weather-guard-forecast` |
+| `weather_go_no_go` | $0.002 | `/api/x402/weather-guard-decision` |
+| `carbon_now` | $0.001 | `/api/x402/carbon-now` |
+| `carbon_best_window` | $0.002 | `/api/x402/carbon-best-window` |
+| `domain_rdap_check` | $0.001 | `/api/x402/domains-check` |
+| `domain_rdap_check_bulk` | $0.005 | `/api/x402/domains-bulk` |
+| `research_search` | $0.002 | `/api/x402/research-search` |
+| `research_paper` | $0.003 | `/api/x402/research-paper` |
+| `research_bibliography` | $0.005 | `/api/x402/research-bibliography` |
+| `book_search` | $0.001 | `/api/x402/books-search` |
+| `book_read` | $0.01 | `/api/x402/books-read` |
+| `news_wire_search` | $0.003 | `/api/x402/news-wire-query` |
+| `news_wire_poll` | $0.002 | `/api/x402/news-wire-pulse` |
+| `transit_plan` | $0.002 | `/api/x402/transit-plan` |
+| `transit_delays` | $0.001 | `/api/x402/transit-delays` |
+| `places_search` | $0.002 | `/api/x402/places-search` |
+| `places_detail` | $0.002 | `/api/x402/places-detail` |
+
+Each takes the same arguments as its endpoint (see `src/tools.json` for the full schemas) and pays with the same `SOLANA_SECRET_KEY` / `session_token` settlement modes as `pay_and_call`, gated by the same `MAX_PAY_USD` cap and `REQUIRE_CONFIRM` flag. Prefer a named tool over `pay_and_call` whenever one exists for the endpoint you need: the fixed schema and stated price make the model far less likely to misdial the call.
### Safety
@@ -140,6 +165,9 @@ calls `pay_and_call`, so nothing is signed and nothing is spent. See
| `MAX_PAY_USD` | no | `1` |
| `REQUIRE_CONFIRM` | no | `true` |
| `THREE_WS_BASE` | no | `https://three.ws` |
+| `X402_MCP_LEDGER_PATH` | no | `~/.three-ws/x402-mcp-ledger.jsonl` |
+
+`X402_MCP_LEDGER_PATH` points at the append-only JSON-lines file every settled payment (`pay_and_call` and the named tools) is recorded to; `spending_report` reads it back.
## Links
diff --git a/packages/x402-mcp/examples/README.md b/packages/x402-mcp/examples/README.md
index 3094ef15a..06c9c1ddf 100644
--- a/packages/x402-mcp/examples/README.md
+++ b/packages/x402-mcp/examples/README.md
@@ -6,7 +6,7 @@ JSON-RPC to it, and hit live data. Neither one pays for anything.
| File | What it does | Run |
|---|---|---|
-| [`list-tools.mjs`](list-tools.mjs) | Prints all <!-- mcp-count:x402-mcp.tools -->4<!-- /mcp-count --> tools with titles, annotation hints, and full input schemas. | `node examples/list-tools.mjs` |
+| [`list-tools.mjs`](list-tools.mjs) | Prints all <!-- mcp-count:x402-mcp.tools -->22<!-- /mcp-count --> tools with titles, annotation hints, and full input schemas. | `node examples/list-tools.mjs` |
| [`inspect-price.mjs`](inspect-price.mjs) | Searches the live x402 bazaar with `find_services`, then reads one endpoint's 402 price with `inspect_endpoint`, without paying. | `node examples/inspect-price.mjs` |
Run them from the package directory:
@@ -28,9 +28,9 @@ Runs the MCP `initialize` handshake, then `tools/list`, and formats every tool.
Expected output (abridged):
```
-server: x402-mcp v0.2.1 (stdio)
+server: x402-mcp v0.2.3 (stdio)
capabilities: tools
-tools: 4
+tools: 22
1. x402_wallet
title: The agent's x402 spending wallet (address + balance)
@@ -52,10 +52,26 @@ tools: 4
4. pay_and_call
hints: destructive, open-world
+
+5. spending_report
+ title: Spending report: totals by merchant and day
+ hints: read-only
+ params:
+ - merchant (optional; string)
+ - since (optional; string)
+
+6. weather_forecast
+ hints: destructive, open-world
+
+... (16 more named tools: weather_go_no_go, carbon_now, carbon_best_window,
+ domain_rdap_check, domain_rdap_check_bulk, research_search, research_paper,
+ research_bibliography, book_search, book_read, news_wire_search,
+ news_wire_poll, transit_plan, transit_delays, places_search, places_detail)
```
-`pay_and_call` is the only tool that carries `destructiveHint`. That is the flag
-annotation-aware clients use to prompt before spending.
+`pay_and_call` and every named tool from `weather_forecast` on carry
+`destructiveHint`. That is the flag annotation-aware clients use to prompt
+before spending.
## inspect-price.mjs
diff --git a/packages/x402-mcp/src/index.js b/packages/x402-mcp/src/index.js
index ddcba382e..73bf05e30 100755
--- a/packages/x402-mcp/src/index.js
+++ b/packages/x402-mcp/src/index.js
@@ -6,6 +6,9 @@
// • find_services — search the live x402 bazaar for paid services (read-only)
// • inspect_endpoint— read an endpoint's price/requirements without paying (read-only)
// • pay_and_call — pay an x402 endpoint in USDC and return its result (execution)
+// • spending_report: this wallet's local spend ledger, totaled by merchant/day (read-only)
+// • one named tool per entry in tools.json (weather_forecast, domain_rdap_check, book_read, ...),
+// each a fixed-endpoint, fixed-price wrapper around pay_and_call (execution)
//
// Self-custodial: payments are signed by YOUR Solana key (SOLANA_SECRET_KEY),
// not a custodial wallet. The read tools work with no key. Real @x402/* libs do
@@ -27,11 +30,13 @@ import { def as x402Wallet } from './tools/x402-wallet.js';
import { def as findServices } from './tools/find-services.js';
import { def as inspectEndpoint } from './tools/inspect-endpoint.js';
import { def as payAndCall } from './tools/pay-and-call.js';
+import { def as spendingReport } from './tools/spending-report.js';
+import { NAMED_SERVICE_TOOLS } from './tools/named-services.js';
const require = createRequire(import.meta.url);
const { version: PKG_VERSION } = require('../package.json');
-export const TOOLS = [x402Wallet, findServices, inspectEndpoint, payAndCall];
+export const TOOLS = [x402Wallet, findServices, inspectEndpoint, payAndCall, spendingReport, ...NAMED_SERVICE_TOOLS];
/**
* Construct a fully-registered McpServer without connecting a transport or
@@ -51,8 +56,11 @@ export function buildServer() {
"any endpoint's price/requirements WITHOUT paying. x402_wallet shows the signer wallet's address " +
'and SOL/USDC balance. pay_and_call is an EXECUTION ACTION: it pays an x402 endpoint in USDC from ' +
'your Solana key (SOLANA_SECRET_KEY or a per-call `secret`) and returns the result, bounded by ' +
- 'MAX_PAY_USD and gated by REQUIRE_CONFIRM. Settlement is the Solana `exact` scheme via the real ' +
- '@x402 libraries — never a wallet you do not control.',
+ 'MAX_PAY_USD and gated by REQUIRE_CONFIRM. Prefer a named tool (weather_forecast, domain_rdap_check, ' +
+ 'book_read, and the rest listed in tools.json) over pay_and_call when one covers the endpoint: it ' +
+ "carries a fixed description and price ceiling. Settlement is the Solana `exact` scheme via the real " +
+ "@x402 libraries, never a wallet you do not control. spending_report reads this wallet's local " +
+ 'ledger back, totaled by merchant and day.',
},
);
diff --git a/packages/x402-mcp/src/lib/json-schema-to-zod.js b/packages/x402-mcp/src/lib/json-schema-to-zod.js
new file mode 100644
index 000000000..e9cf1cf13
--- /dev/null
+++ b/packages/x402-mcp/src/lib/json-schema-to-zod.js
@@ -0,0 +1,64 @@
+// Minimal JSON Schema (draft-07 subset) -> zod converter, just expressive
+// enough for tools.json's property shapes (string/number/integer/boolean/array,
+// enum, min/max, minItems/maxItems, default, description). Named tools are
+// authored once as plain JSON in tools.json (so the hosted dispatcher can read
+// the same facts without pulling in zod); this turns that JSON into the zod
+// shape McpServer.registerTool expects.
+
+import { z } from 'zod';
+
+function propertyToZod(prop) {
+ let schema;
+ switch (prop.type) {
+ case 'string':
+ schema = Array.isArray(prop.enum) ? z.enum(prop.enum) : z.string();
+ if (!Array.isArray(prop.enum)) {
+ if (typeof prop.minLength === 'number') schema = schema.min(prop.minLength);
+ if (typeof prop.maxLength === 'number') schema = schema.max(prop.maxLength);
+ }
+ break;
+ case 'integer':
+ schema = z.number().int();
+ if (typeof prop.minimum === 'number') schema = schema.min(prop.minimum);
+ if (typeof prop.maximum === 'number') schema = schema.max(prop.maximum);
+ break;
+ case 'number':
+ schema = z.number();
+ if (typeof prop.minimum === 'number') schema = schema.min(prop.minimum);
+ if (typeof prop.maximum === 'number') schema = schema.max(prop.maximum);
+ break;
+ case 'boolean':
+ schema = z.boolean();
+ break;
+ case 'array':
+ schema = z.array(prop.items ? propertyToZod(prop.items) : z.any());
+ if (typeof prop.minItems === 'number') schema = schema.min(prop.minItems);
+ if (typeof prop.maxItems === 'number') schema = schema.max(prop.maxItems);
+ break;
+ default:
+ schema = z.any();
+ }
+ if (prop.description) schema = schema.describe(prop.description);
+ if (prop.default !== undefined) schema = schema.default(prop.default);
+ return schema;
+}
+
+/**
+ * Convert a JSON Schema object (`{ type: 'object', required, properties }`)
+ * into a zod raw shape (the plain `{ key: ZodType }` object McpServer's
+ * registerTool and tool `def.inputSchema` both expect, as used throughout
+ * this package).
+ * @param {object} jsonSchema
+ * @returns {Record<string, import('zod').ZodTypeAny>}
+ */
+export function jsonSchemaToZodShape(jsonSchema) {
+ const properties = jsonSchema?.properties || {};
+ const required = new Set(jsonSchema?.required || []);
+ const shape = {};
+ for (const [key, prop] of Object.entries(properties)) {
+ let field = propertyToZod(prop);
+ if (!required.has(key) && prop.default === undefined) field = field.optional();
+ shape[key] = field;
+ }
+ return shape;
+}
diff --git a/packages/x402-mcp/src/lib/ledger.js b/packages/x402-mcp/src/lib/ledger.js
new file mode 100644
index 000000000..578069b6e
--- /dev/null
+++ b/packages/x402-mcp/src/lib/ledger.js
@@ -0,0 +1,117 @@
+// Local spending ledger for the x402 buyer MCP. Every settled payment (from
+// pay_and_call or a named tool in named-services.js) appends one JSON line
+// here; spending_report reads it back and totals by merchant and day. This is
+// the only state this stdio server keeps: everything else is stateless,
+// per-call. File-based so the ledger survives across separate server runs
+// (each `npx @three-ws/x402-mcp` invocation is a fresh process).
+
+import { appendFile, mkdir, readFile } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import path from 'node:path';
+
+import { env } from '../config.js';
+
+export const LEDGER_PATH = env('X402_MCP_LEDGER_PATH', path.join(homedir(), '.three-ws', 'x402-mcp-ledger.jsonl'));
+
+/**
+ * Append one settled-payment record. Never throws: a ledger write failure
+ * (e.g. a read-only filesystem) must not fail the payment that already
+ * happened.
+ * @param {{tool?: string, url: string, amountUsd: number|null, token: string, network?: string|null, settlement?: unknown}} entry
+ */
+export async function recordSpend(entry) {
+ const line = JSON.stringify({
+ at: new Date().toISOString(),
+ tool: entry.tool ?? null,
+ url: entry.url,
+ merchant: safeHostname(entry.url),
+ amountUsd: typeof entry.amountUsd === 'number' && Number.isFinite(entry.amountUsd) ? entry.amountUsd : null,
+ token: entry.token ?? 'usdc',
+ network: entry.network ?? null,
+ settlement: entry.settlement ?? null,
+ });
+ try {
+ await mkdir(path.dirname(LEDGER_PATH), { recursive: true });
+ await appendFile(LEDGER_PATH, line + '\n', 'utf8');
+ } catch {
+ // Ledger is best-effort bookkeeping, not the source of truth for the
+ // payment itself (the chain is), so swallow write failures.
+ }
+}
+
+function safeHostname(url) {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return 'unknown';
+ }
+}
+
+/** Read every ledger entry, oldest first. Missing file reads as empty. */
+export async function readEntries() {
+ let text;
+ try {
+ text = await readFile(LEDGER_PATH, 'utf8');
+ } catch (err) {
+ if (err?.code === 'ENOENT') return [];
+ throw err;
+ }
+ const entries = [];
+ for (const line of text.split('\n')) {
+ if (!line.trim()) continue;
+ try {
+ entries.push(JSON.parse(line));
+ } catch {
+ // Skip a corrupted line rather than failing the whole report.
+ }
+ }
+ return entries;
+}
+
+/**
+ * Total ledger entries by merchant (hostname) and by day (UTC date), with an
+ * optional `since` (ISO timestamp, inclusive) and `merchant` filter.
+ * @param {{since?: string, merchant?: string}} [opts]
+ */
+export async function summarize(opts = {}) {
+ let entries = await readEntries();
+ if (opts.since) {
+ const sinceMs = Date.parse(opts.since);
+ if (Number.isFinite(sinceMs)) entries = entries.filter((e) => Date.parse(e.at) >= sinceMs);
+ }
+ if (opts.merchant) {
+ const want = String(opts.merchant).toLowerCase();
+ entries = entries.filter((e) => String(e.merchant).toLowerCase() === want);
+ }
+
+ const byMerchant = new Map();
+ const byDay = new Map();
+ let totalUsd = 0;
+ let unpricedCalls = 0;
+
+ for (const e of entries) {
+ const day = String(e.at).slice(0, 10);
+ const usd = typeof e.amountUsd === 'number' ? e.amountUsd : 0;
+ if (e.amountUsd == null) unpricedCalls += 1;
+ totalUsd += usd;
+
+ const m = byMerchant.get(e.merchant) || { merchant: e.merchant, totalUsd: 0, calls: 0 };
+ m.totalUsd += usd;
+ m.calls += 1;
+ byMerchant.set(e.merchant, m);
+
+ const d = byDay.get(day) || { date: day, totalUsd: 0, calls: 0 };
+ d.totalUsd += usd;
+ d.calls += 1;
+ byDay.set(day, d);
+ }
+
+ const round = (n) => Math.round(n * 1e6) / 1e6;
+ return {
+ totalUsd: round(totalUsd),
+ totalCalls: entries.length,
+ unpricedCalls,
+ byMerchant: [...byMerchant.values()].map((m) => ({ ...m, totalUsd: round(m.totalUsd) })).sort((a, b) => b.totalUsd - a.totalUsd),
+ byDay: [...byDay.values()].map((d) => ({ ...d, totalUsd: round(d.totalUsd) })).sort((a, b) => (a.date < b.date ? 1 : -1)),
+ };
+}
diff --git a/packages/x402-mcp/src/lib/pay-core.js b/packages/x402-mcp/src/lib/pay-core.js
new file mode 100644
index 000000000..fb16bcae4
--- /dev/null
+++ b/packages/x402-mcp/src/lib/pay-core.js
@@ -0,0 +1,213 @@
+// Shared payment core for pay_and_call and every named tool in
+// named-services.js: probe, enforce the spend cap, require confirm, settle,
+// and record the spend in the local ledger. One implementation so a named
+// tool (e.g. weather_go_no_go) and the generic pay_and_call behave identically
+// for the same URL.
+
+import { buildPayingFetch, decodeSettlement, probeChallenge, isThreeAccept, isUsdcAccept } from './x402-buyer.js';
+import { recordSpend } from './ledger.js';
+import { MAX_PAY_USD, REQUIRE_CONFIRM, SOLANA_DEFAULT_SECRET, THREE_WS_BASE, HTTP_TIMEOUT_MS } from '../config.js';
+
+// Split a challenge's Solana accepts into the two main assets so we can price
+// and pay in the caller's chosen token.
+function pickSolanaAccepts(accepts) {
+ const sol = (Array.isArray(accepts) ? accepts : []).filter((a) => String(a.network || '').startsWith('solana'));
+ return { sol, usdc: sol.find(isUsdcAccept) || null, three: sol.find(isThreeAccept) || null };
+}
+
+// USD value of a USDC accept (6-decimal atomic, or a "$x" string). Returns null
+// when unknown; $THREE accepts have no USD price (their amount is a token count).
+function usdFromAccept(a) {
+ if (!a) return null;
+ const raw = a.price ?? a.maxAmountRequired ?? a.amount;
+ if (raw == null) return null;
+ if (typeof raw === 'string' && raw.trim().startsWith('$')) return Number(raw.replace('$', '').trim());
+ const atomics = Number(raw);
+ return Number.isFinite(atomics) ? atomics / 1_000_000 : null;
+}
+
+/**
+ * Pay a single x402 URL and return its result, exactly as pay_and_call does.
+ * @param {string} url
+ * @param {object} args
+ * @param {'GET'|'POST'} [args.method]
+ * @param {object} [args.body]
+ * @param {string} [args.session_token]
+ * @param {'usdc'|'three'} [args.token]
+ * @param {number} [args.max_usd]
+ * @param {string} [args.secret]
+ * @param {boolean} [args.confirm]
+ * @param {string} [args.idempotency_key]
+ * @param {string} [args.toolName] Named-tool name, for the ledger only.
+ */
+export async function payUrl(url, args = {}) {
+ const method = args.method === 'POST' ? 'POST' : 'GET';
+
+ // ── Session-governed mode ───────────────────────────────────────────────
+ const sessionToken = args.session_token || process.env.PAYMENT_SESSION_TOKEN || '';
+ if (sessionToken) {
+ const ceiling = Math.min(MAX_PAY_USD, args.max_usd ?? Infinity);
+
+ if (REQUIRE_CONFIRM && args.confirm !== true) {
+ return {
+ ok: false,
+ error: 'confirm_required',
+ message: `This will spend up to $${ceiling} (session-governed) on ${url}. Re-issue with confirm:true to proceed (or set REQUIRE_CONFIRM=0).`,
+ mode: 'session',
+ url,
+ };
+ }
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);
+ let res, text;
+ try {
+ res = await fetch(`${THREE_WS_BASE}/api/pay/execute`, {
+ method: 'POST',
+ signal: controller.signal,
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify({
+ session_token: sessionToken,
+ url,
+ method,
+ body: args.body ?? undefined,
+ idempotency_key: args.idempotency_key ?? undefined,
+ }),
+ });
+ text = await res.text();
+ } catch (err) {
+ throw Object.assign(new Error(`Session payment failed: ${err?.message}`), { code: 'session_execute_failed' });
+ } finally {
+ clearTimeout(timer);
+ }
+
+ let result;
+ try {
+ result = text ? JSON.parse(text) : null;
+ } catch {
+ result = text;
+ }
+
+ if (!res.ok) {
+ throw Object.assign(new Error(result?.message || result?.error || `Session execute returned HTTP ${res.status}`), {
+ code: result?.code || 'session_execute_failed',
+ status: res.status,
+ body: result,
+ });
+ }
+
+ await recordSpend({
+ tool: args.toolName,
+ url,
+ amountUsd: typeof result?.price_usd === 'number' ? result.price_usd : null,
+ token: args.token === 'three' ? 'three' : 'usdc',
+ network: result?.network ?? 'solana',
+ settlement: result?.settlement ?? null,
+ });
+
+ return { ...result, mode: 'session' };
+ }
+
+ // ── Self-custodial mode ─────────────────────────────────────────────────
+ const secret = args.secret || SOLANA_DEFAULT_SECRET;
+ if (!secret) {
+ throw Object.assign(
+ new Error('No signer configured. Set SOLANA_SECRET_KEY / pass `secret`, or provide a `session_token` for session-governed payments.'),
+ { code: 'no_signer' },
+ );
+ }
+
+ // Probe first so we never pay blind and can enforce the cap pre-payment.
+ const probe = await probeChallenge(url, { method, body: args.body });
+ if (!probe.paid) {
+ return {
+ ok: true,
+ paid: false,
+ url,
+ note: 'Endpoint is not paywalled, called directly, no payment needed.',
+ status: probe.status,
+ result: probe.result,
+ };
+ }
+
+ const token = args.token === 'three' ? 'three' : 'usdc';
+ const { sol, usdc, three } = pickSolanaAccepts(probe.accepts);
+ if (!sol.length) {
+ throw Object.assign(new Error('Endpoint has no Solana (solana:*) payment option this wallet can settle.'), {
+ code: 'no_solana_requirement',
+ });
+ }
+ if (token === 'three' && !three) {
+ throw Object.assign(new Error('Endpoint does not advertise a $THREE payment option, retry with token:"usdc".'), {
+ code: 'three_not_offered',
+ });
+ }
+ const priceUsd = usdFromAccept(usdc);
+ const ceiling = Math.min(MAX_PAY_USD, args.max_usd ?? Infinity);
+ if (priceUsd != null && priceUsd > ceiling) {
+ throw Object.assign(new Error(`Price $${priceUsd} exceeds the cap $${ceiling}. Raise max_usd / MAX_PAY_USD to allow it.`), {
+ code: 'over_cap',
+ price_usd: priceUsd,
+ cap_usd: ceiling,
+ });
+ }
+ const threeAmount = token === 'three' ? String(three.amount ?? three.maxAmountRequired ?? three.price ?? '') : null;
+ const spendLabel = token === 'three' ? `${threeAmount} atomic $THREE` : `$${priceUsd ?? '?'} USDC`;
+ if (REQUIRE_CONFIRM && args.confirm !== true) {
+ return {
+ ok: false,
+ error: 'confirm_required',
+ message: `This will spend up to ${spendLabel} on ${url}. Re-issue with confirm:true to proceed (or set REQUIRE_CONFIRM=0).`,
+ mode: 'self_custodial',
+ token,
+ price_usd: priceUsd,
+ ...(threeAmount ? { three_amount: threeAmount } : {}),
+ url,
+ };
+ }
+
+ const { payingFetch, address } = await buildPayingFetch(secret, { preferToken: token });
+ const init = {
+ method,
+ headers: { accept: 'application/json', ...(args.body !== undefined ? { 'content-type': 'application/json' } : {}) },
+ body: args.body !== undefined ? JSON.stringify(args.body) : undefined,
+ };
+ const res = await payingFetch(url, init);
+ const text = await res.text();
+ let result;
+ try {
+ result = text ? JSON.parse(text) : null;
+ } catch {
+ result = text;
+ }
+ if (!res.ok) {
+ throw Object.assign(new Error(`Paid call to ${url} returned HTTP ${res.status}`), {
+ code: 'call_failed',
+ status: res.status,
+ body: result,
+ });
+ }
+ const settlement = await decodeSettlement(res);
+
+ await recordSpend({
+ tool: args.toolName,
+ url,
+ amountUsd: priceUsd,
+ token,
+ network: usdc?.network || three?.network || 'solana',
+ settlement,
+ });
+
+ return {
+ ok: true,
+ paid: true,
+ mode: 'self_custodial',
+ url,
+ payer: address,
+ token,
+ price_usd: priceUsd,
+ ...(threeAmount ? { three_amount: threeAmount } : {}),
+ settlement,
+ result,
+ };
+}
diff --git a/packages/x402-mcp/src/tools.json b/packages/x402-mcp/src/tools.json
new file mode 100644
index 000000000..f9ee36301
--- /dev/null
+++ b/packages/x402-mcp/src/tools.json
@@ -0,0 +1,292 @@
+{
+ "_comment": "Named-tool registry for the x402 buyer MCP. Each entry becomes one MCP tool (packages/x402-mcp/src/tools/named-services.js builds them) that pays a single, fixed three.ws x402 endpoint, instead of the model composing a raw pay_and_call(url) call. Mirrored in api/_mcpagent/named-services-tools.js for the hosted agent. Source of the facts below: api/_lib/service-catalog/services/*.js (order 516).",
+ "tools": [
+ {
+ "name": "weather_forecast",
+ "title": "Weather Guard: Forecast",
+ "path": "/api/x402/weather-guard-forecast",
+ "method": "GET",
+ "priceUsd": 0.001,
+ "description": "Pay $0.001 USDC (or use the free daily per-IP quota) for the next 24 hours of hourly temperature, wind speed, precipitation probability and WMO weather conditions at any latitude/longitude, sourced live from Open-Meteo with a US National Weather Service fallback and active NWS severe-weather alerts for US coordinates.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["lat", "lon"],
+ "properties": {
+ "lat": { "type": "number", "minimum": -90, "maximum": 90, "description": "Latitude." },
+ "lon": { "type": "number", "minimum": -180, "maximum": 180, "description": "Longitude." }
+ }
+ }
+ },
+ {
+ "name": "weather_go_no_go",
+ "title": "Weather Guard: Activity Decision",
+ "path": "/api/x402/weather-guard-decision",
+ "method": "GET",
+ "priceUsd": 0.002,
+ "description": "Pay $0.002 USDC per call to turn the next 6 hours of live forecast at any lat/lon into a go / caution / no-go verdict for a named activity (running, cycling, outdoor-event, drone-flight, photography), with the exact thresholds crossed and any active NWS severe-weather alert that forced a no-go.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["lat", "lon", "activity"],
+ "properties": {
+ "lat": { "type": "number", "minimum": -90, "maximum": 90, "description": "Latitude." },
+ "lon": { "type": "number", "minimum": -180, "maximum": 180, "description": "Longitude." },
+ "activity": {
+ "type": "string",
+ "enum": ["running", "cycling", "outdoor-event", "drone-flight", "photography"],
+ "description": "Activity to judge the forecast against."
+ }
+ }
+ }
+ },
+ {
+ "name": "carbon_now",
+ "title": "Grid Carbon: Now",
+ "path": "/api/x402/carbon-now",
+ "method": "GET",
+ "priceUsd": 0.001,
+ "description": "Pay $0.001 USDC (or use the free daily per-IP quota) for the current UK national grid carbon intensity in gCO2/kWh with its forecast/actual/index reading and full generation mix, live from the National Grid ESO Carbon Intensity API. Pass a GB postcode outcode for the regional reading instead.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "postcode": { "type": "string", "description": "GB postcode outcode, e.g. \"SW1A\". Omit for the national reading." }
+ }
+ }
+ },
+ {
+ "name": "carbon_best_window",
+ "title": "Grid Carbon: Best Window",
+ "path": "/api/x402/carbon-best-window",
+ "method": "GET",
+ "priceUsd": 0.002,
+ "description": "Pay $0.002 USDC per call to scan the live 48h National Grid ESO carbon-intensity forecast for the lowest-carbon window of a given length (1 to 12 hours), nationally or for one GB postcode region, with the best window, up to 3 runners-up, the worst window, and a plain-language recommendation.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "hours": { "type": "integer", "minimum": 1, "maximum": 12, "default": 4, "description": "Length of the window to find, in hours." },
+ "postcode": { "type": "string", "description": "GB postcode outcode, e.g. \"SW1A\". Omit for the national forecast." }
+ }
+ }
+ },
+ {
+ "name": "domain_rdap_check",
+ "title": "Domain Check (RDAP)",
+ "path": "/api/x402/domains-check",
+ "method": "GET",
+ "priceUsd": 0.001,
+ "description": "Pay $0.001 USDC (or use the free daily per-IP quota) to query the authoritative RDAP server for a domain (IANA bootstrap registry, rdap.org fallback) and get its registration status, registrar, creation/update/expiry dates, nameservers, status flags, and DNSSEC signing state.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["domain"],
+ "properties": {
+ "domain": { "type": "string", "description": "Domain name to check, e.g. \"example.com\"." }
+ }
+ }
+ },
+ {
+ "name": "domain_rdap_check_bulk",
+ "title": "Domain Check (Bulk RDAP)",
+ "path": "/api/x402/domains-bulk",
+ "method": "POST",
+ "priceUsd": 0.005,
+ "description": "Pay $0.005 USDC per call to check up to 50 domains in one request against their authoritative RDAP servers, with bounded concurrency. Returns a per-domain registration breakdown plus registered/available/unknown counts.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["domains"],
+ "properties": {
+ "domains": {
+ "type": "array",
+ "items": { "type": "string" },
+ "minItems": 1,
+ "maxItems": 50,
+ "description": "Domains to check, 1 to 50 per call."
+ }
+ }
+ }
+ },
+ {
+ "name": "research_search",
+ "title": "Scholarly Search",
+ "path": "/api/x402/research-search",
+ "method": "GET",
+ "priceUsd": 0.002,
+ "description": "Pay $0.002 USDC (or use the free daily per-IP quota) to query arXiv, Crossref, and Semantic Scholar in parallel and get a merged, de-duplicated ranking of papers with authors, year, venue, DOI, arXiv id, abstract, and citation count.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["q"],
+ "properties": {
+ "q": { "type": "string", "description": "Search query." },
+ "limit": { "type": "integer", "minimum": 1, "maximum": 25, "default": 10, "description": "Max papers to return." }
+ }
+ }
+ },
+ {
+ "name": "research_paper",
+ "title": "Paper Detail & Citation Graph",
+ "path": "/api/x402/research-paper",
+ "method": "GET",
+ "priceUsd": 0.003,
+ "description": "Pay $0.003 USDC per call for a single paper's full metadata (title, abstract, TL;DR, year, venue, authors, fields of study, open-access PDF link) plus a two-sided citation graph, keyed by DOI, arXiv id, or Semantic Scholar id.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["id"],
+ "properties": {
+ "id": { "type": "string", "description": "A DOI, arXiv id (e.g. \"1706.03762\"), or Semantic Scholar paper id." }
+ }
+ }
+ },
+ {
+ "name": "research_bibliography",
+ "title": "Bibliography Formatter",
+ "path": "/api/x402/research-bibliography",
+ "method": "POST",
+ "priceUsd": 0.005,
+ "description": "Pay $0.005 USDC per call to get formatted BibTeX and/or APA 7 citation entries for up to 25 DOIs in one request, sourced live from Crossref.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["dois"],
+ "properties": {
+ "dois": { "type": "array", "items": { "type": "string" }, "minItems": 1, "maxItems": 25, "description": "DOIs to format, 1 to 25 per call." },
+ "format": { "type": "string", "enum": ["bibtex", "apa", "both"], "default": "both", "description": "Citation format to return." }
+ }
+ }
+ },
+ {
+ "name": "book_search",
+ "title": "Book Search",
+ "path": "/api/x402/books-search",
+ "method": "GET",
+ "priceUsd": 0.001,
+ "description": "Pay $0.001 USDC (or use the free daily per-IP quota) to search OpenLibrary editions by title (and optionally author) and get each edition annotated with whether a cleaned Project Gutenberg full text can be bought with book_read, resolved live via Gutendex with a gutenberg.org fallback.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["q"],
+ "properties": {
+ "q": { "type": "string", "description": "Title to search for." },
+ "author": { "type": "string", "description": "Optional author filter." },
+ "limit": { "type": "integer", "minimum": 1, "maximum": 25, "default": 5, "description": "Max editions to return." }
+ }
+ }
+ },
+ {
+ "name": "book_read",
+ "title": "Book Read",
+ "path": "/api/x402/books-read",
+ "method": "GET",
+ "priceUsd": 0.01,
+ "description": "Pay $0.01 USDC per call to receive the complete text of a public-domain Project Gutenberg book, licence boilerplate stripped and split into chapters, as markdown JSON. Find a gutenbergId with book_search first.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["gutenbergId"],
+ "properties": {
+ "gutenbergId": { "type": "integer", "description": "Project Gutenberg ebook id, from book_search." }
+ }
+ }
+ },
+ {
+ "name": "news_wire_search",
+ "title": "Global News Wire Search",
+ "path": "/api/x402/news-wire-query",
+ "method": "GET",
+ "priceUsd": 0.003,
+ "description": "Pay $0.003 USDC (or use the free daily per-IP quota) to search the GDELT Project's real-time index of worldwide news media in 65+ languages. Returns matching articles plus a coverage-volume timeline. For an ongoing poll loop, switch to news_wire_poll after the first search.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["q"],
+ "properties": {
+ "q": { "type": "string", "description": "Search query. Free text is quoted automatically; GDELT operators (AND, OR, sourcelang:, etc) pass through as-is." },
+ "timespan": { "type": "string", "default": "3d", "description": "GDELT lookback window, e.g. 1d, 3d, 1w, 1m." },
+ "maxRecords": { "type": "integer", "minimum": 1, "maximum": 75, "default": 25 },
+ "sourceLang": { "type": "string", "description": "Restrict to a GDELT source language code, e.g. eng." },
+ "sourceCountry": { "type": "string", "description": "Restrict to a GDELT source country code, e.g. us." },
+ "includeTimeline": { "type": "boolean", "default": true, "description": "Include the coverage-volume timeline (one extra upstream call)." }
+ }
+ }
+ },
+ {
+ "name": "news_wire_poll",
+ "title": "Global News Wire Pulse",
+ "path": "/api/x402/news-wire-pulse",
+ "method": "GET",
+ "priceUsd": 0.002,
+ "description": "Pay $0.002 USDC per call to get only the GDELT articles that have appeared for your query since a cursor you supply, plus a fresh cursor for the next poll. Start with news_wire_search to get a query working, then switch here for ongoing monitoring without re-fetching the same articles.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["q", "cursor"],
+ "properties": {
+ "q": { "type": "string", "description": "Search query, same syntax as news_wire_search." },
+ "cursor": { "type": "string", "description": "GDELT timestamp (YYYYMMDDHHMMSS) or ISO-8601 timestamp to poll since." },
+ "maxRecords": { "type": "integer", "minimum": 1, "maximum": 75, "default": 50 }
+ }
+ }
+ },
+ {
+ "name": "transit_plan",
+ "title": "Transit Trip Plan",
+ "path": "/api/x402/transit-plan",
+ "method": "GET",
+ "priceUsd": 0.002,
+ "description": "Pay $0.002 USDC (or use the free daily per-IP quota) to plan a trip between two MBTA stops from the public GTFS feed. Each place accepts a feed stop id, a station name, or a \"lat,lon\" pair. Returns direct and one-transfer itineraries, with realtime predictions overlaid where the GTFS-Realtime feed has them.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["from", "to"],
+ "properties": {
+ "from": { "type": "string", "description": "Origin: stop id, station name, or \"lat,lon\"." },
+ "to": { "type": "string", "description": "Destination: stop id, station name, or \"lat,lon\"." },
+ "departAfter": { "type": "string", "description": "ISO 8601 timestamp. Defaults to now." },
+ "max": { "type": "integer", "minimum": 1, "maximum": 10, "default": 3, "description": "Max itineraries to return." }
+ }
+ }
+ },
+ {
+ "name": "transit_delays",
+ "title": "Transit Delay Snapshot",
+ "path": "/api/x402/transit-delays",
+ "method": "GET",
+ "priceUsd": 0.001,
+ "description": "Pay $0.001 USDC per call to see how the MBTA's realtime feed compares to the scheduled timetable right now at a stop, optionally filtered to one route. Returns a per-arrival breakdown plus a running-well / minor-delays / significant-delays verdict. Find a stop id with transit_plan first.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["stop"],
+ "properties": {
+ "stop": { "type": "string", "description": "Stop id, station name, or \"lat,lon\"." },
+ "route": { "type": "string", "description": "Optional feed route id to filter by." },
+ "limit": { "type": "integer", "minimum": 1, "maximum": 100, "default": 20 }
+ }
+ }
+ },
+ {
+ "name": "places_search",
+ "title": "Places Search",
+ "path": "/api/x402/places-search",
+ "method": "GET",
+ "priceUsd": 0.002,
+ "description": "Pay $0.002 USDC (or use the free daily per-IP quota) to search OpenStreetMap via the Overpass API for points of interest within a radius of a coordinate, optionally filtered to a category (cafe, restaurant, pharmacy, museum, etc). Returns each place's name, category, coordinates, opening hours, phone, website, address, and cuisine where tagged.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["lat", "lon"],
+ "properties": {
+ "lat": { "type": "number", "minimum": -90, "maximum": 90 },
+ "lon": { "type": "number", "minimum": -180, "maximum": 180 },
+ "radius": { "type": "integer", "minimum": 1, "maximum": 5000, "default": 500, "description": "Search radius in metres." },
+ "category": { "type": "string", "description": "OSM tag value such as cafe, restaurant, pharmacy, bar, museum." },
+ "limit": { "type": "integer", "minimum": 1, "maximum": 50, "default": 20 }
+ }
+ }
+ },
+ {
+ "name": "places_detail",
+ "title": "Place Detail",
+ "path": "/api/x402/places-detail",
+ "method": "GET",
+ "priceUsd": 0.002,
+ "description": "Pay $0.002 USDC per call to fetch the full live OpenStreetMap record for one place, by the id returned from places_search (e.g. \"node-1072800838\"). Returns every OSM tag alongside the structured fields.",
+ "inputSchema": {
+ "type": "object",
+ "required": ["id"],
+ "properties": {
+ "id": { "type": "string", "description": "Place id from places_search, e.g. \"node-1072800838\", \"way-55\", \"relation-9\"." }
+ }
+ }
+ }
+ ]
+}
diff --git a/packages/x402-mcp/src/tools/named-services.js b/packages/x402-mcp/src/tools/named-services.js
new file mode 100644
index 000000000..283c00685
--- /dev/null
+++ b/packages/x402-mcp/src/tools/named-services.js
@@ -0,0 +1,79 @@
+// Named commerce tools: one MCP tool per three.ws x402 service, generated
+// from ../tools.json. A model names weather_go_no_go or domain_rdap_check far more
+// reliably than it composes a raw pay_and_call(url) call, and a fixed
+// description + price ceiling per tool beats a free-form URL every time.
+//
+// Every tool here pays a FIXED endpoint (THREE_WS_BASE + entry.path); the only
+// thing the caller supplies is the service's own input (lat/lon, a domain,
+// a query, ...) plus the usual payment knobs (confirm, max_usd, token,
+// secret, session_token, idempotency_key). Settlement goes through the same
+// ../lib/pay-core.js used by pay_and_call, so behavior (confirm gate, spend
+// cap, ledger) is identical.
+
+import { z } from 'zod';
+import { createRequire } from 'node:module';
+
+import { jsonSchemaToZodShape } from '../lib/json-schema-to-zod.js';
+import { payUrl } from '../lib/pay-core.js';
+import { THREE_WS_BASE } from '../config.js';
+
+const require = createRequire(import.meta.url);
+const registry = require('../tools.json');
+
+const PAYMENT_ARG_KEYS = ['method', 'token', 'max_usd', 'secret', 'confirm', 'session_token', 'idempotency_key'];
+
+const paymentArgsShape = {
+ token: z.enum(['usdc', 'three']).default('usdc').describe('Settlement token. "usdc" (default) or "three", when this endpoint advertises it.'),
+ max_usd: z.number().positive().optional().describe(`Hard ceiling for THIS call in USD. Can only lower the service's listed price, never raise it.`),
+ secret: z.string().optional().describe('Per-call base58 Solana signer override (defaults to SOLANA_SECRET_KEY).'),
+ confirm: z.boolean().optional().describe('Must be true to execute when REQUIRE_CONFIRM is on (the default).'),
+ session_token: z.string().optional().describe('three.ws Payment Session token (pss_…). When set, the platform wallet pays instead of a local key.'),
+ idempotency_key: z.string().optional().describe('Deduplication key, recommended with session_token so a retry cannot double-charge.'),
+};
+
+function buildUrl(entry, serviceArgs) {
+ const url = new URL(entry.path, THREE_WS_BASE);
+ if (entry.method === 'GET') {
+ for (const [key, value] of Object.entries(serviceArgs)) {
+ if (value === undefined) continue;
+ url.searchParams.set(key, Array.isArray(value) ? value.join(',') : String(value));
+ }
+ }
+ return url.toString();
+}
+
+function splitArgs(args) {
+ const serviceArgs = {};
+ const paymentArgs = {};
+ for (const [key, value] of Object.entries(args || {})) {
+ if (PAYMENT_ARG_KEYS.includes(key)) paymentArgs[key] = value;
+ else serviceArgs[key] = value;
+ }
+ return { serviceArgs, paymentArgs };
+}
+
+function buildTool(entry) {
+ const serviceShape = jsonSchemaToZodShape(entry.inputSchema);
+ return {
+ name: entry.name,
+ title: entry.title,
+ // Pays a real three.ws x402 service: execution, not read-only, and the
+ // service lives behind an open, external-feeling endpoint.
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
+ description: `[$${entry.priceUsd} USDC per call] ${entry.description}`,
+ inputSchema: { ...serviceShape, ...paymentArgsShape },
+ async handler(args) {
+ const { serviceArgs, paymentArgs } = splitArgs(args);
+ const url = buildUrl(entry, serviceArgs);
+ return payUrl(url, {
+ ...paymentArgs,
+ method: entry.method,
+ body: entry.method === 'POST' ? serviceArgs : undefined,
+ max_usd: paymentArgs.max_usd ?? entry.priceUsd,
+ toolName: entry.name,
+ });
+ },
+ };
+}
+
+export const NAMED_SERVICE_TOOLS = registry.tools.map(buildTool);
diff --git a/packages/x402-mcp/src/tools/pay-and-call.js b/packages/x402-mcp/src/tools/pay-and-call.js
index 64f19918f..cef546170 100644
--- a/packages/x402-mcp/src/tools/pay-and-call.js
+++ b/packages/x402-mcp/src/tools/pay-and-call.js
@@ -8,31 +8,14 @@
// session's budget/allowlist/per-tx policy is enforced. No key needed.
//
// Guards before any payment: probe the 402 to read the Solana price, refuse if it
-// exceeds max_usd or MAX_PAY_USD, and (when REQUIRE_CONFIRM is on) require an
+// exceeds max_usd or MAX_PAY_USD (and (when REQUIRE_CONFIRM is on) require an
// explicit confirm:true. Payment + settlement are done by the real @x402/* libs.
+// The actual probe/pay/settle/ledger logic lives in ../lib/pay-core.js, shared
+// with every named tool in named-services.js.
import { z } from 'zod';
-import { buildPayingFetch, decodeSettlement, probeChallenge, isThreeAccept, isUsdcAccept } from '../lib/x402-buyer.js';
-import { MAX_PAY_USD, REQUIRE_CONFIRM, SOLANA_DEFAULT_SECRET, THREE_WS_BASE, HTTP_TIMEOUT_MS } from '../config.js';
-
-// Split a challenge's Solana accepts into the two main assets so we can price
-// and pay in the caller's chosen token.
-function pickSolanaAccepts(accepts) {
- const sol = (Array.isArray(accepts) ? accepts : []).filter((a) => String(a.network || '').startsWith('solana'));
- return { sol, usdc: sol.find(isUsdcAccept) || null, three: sol.find(isThreeAccept) || null };
-}
-
-// USD value of a USDC accept (6-decimal atomic, or a "$x" string). Returns null
-// when unknown — $THREE accepts have no USD price (their amount is a token count).
-function usdFromAccept(a) {
- if (!a) return null;
- const raw = a.price ?? a.maxAmountRequired ?? a.amount;
- if (raw == null) return null;
- if (typeof raw === 'string' && raw.trim().startsWith('$')) return Number(raw.replace('$', '').trim());
- const atomics = Number(raw);
- return Number.isFinite(atomics) ? atomics / 1_000_000 : null;
-}
+import { payUrl } from '../lib/pay-core.js';
export const def = {
name: 'pay_and_call',
@@ -40,7 +23,7 @@ export const def = {
// Moves real funds — irreversible transfer.
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
description:
- 'Call a paid x402 endpoint and settle the payment automatically, then return the result. Use this after inspect_endpoint has shown the price and the user has approved paying it; a settled payment cannot be undone.\n\nTwo modes:\n• Self-custodial (default): signs with SOLANA_SECRET_KEY or `secret` arg; you hold the key.\n• Session-governed: pass `session_token` (a three.ws Payment Session token); the platform wallet signs on your behalf; the session\'s budget, allowlist, and per-tx cap are enforced by the platform. No private key required. Supports Solana USDC and Base USDC sessions.\n\nPay in USDC (default) or, when the endpoint advertises it, in $THREE (set token:"three"). Bounded by max_usd and the MAX_PAY_USD cap; refuses before any money moves if the price is over the cap. With REQUIRE_CONFIRM on, the call refuses until re-issued with confirm:true.',
+ 'Call a paid x402 endpoint and settle the payment automatically, then return the result. Use this after inspect_endpoint has shown the price and the user has approved paying it; a settled payment cannot be undone.\n\nTwo modes:\n• Self-custodial (default): signs with SOLANA_SECRET_KEY or `secret` arg; you hold the key.\n• Session-governed: pass `session_token` (a three.ws Payment Session token); the platform wallet signs on your behalf; the session\'s budget, allowlist, and per-tx cap are enforced by the platform. No private key required. Supports Solana USDC and Base USDC sessions.\n\nPay in USDC (default) or, when the endpoint advertises it, in $THREE (set token:"three"). Bounded by max_usd and the MAX_PAY_USD cap; refuses before any money moves if the price is over the cap. With REQUIRE_CONFIRM on, the call refuses until re-issued with confirm:true.\n\nIf a named tool already covers this endpoint (weather_forecast, domain_rdap_check, etc, see tools.json), prefer it: it carries a fixed description and price ceiling, which a model composes more reliably than a raw URL.',
inputSchema: {
url: z.string().url().describe('The x402 endpoint to pay and call.'),
method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method.'),
@@ -64,155 +47,6 @@ export const def = {
},
async handler(args) {
const url = String(args?.url ?? '').trim();
- const method = args?.method === 'POST' ? 'POST' : 'GET';
-
- // ── Session-governed mode ───────────────────────────────────────────
- // When a session_token is provided, delegate everything to the three.ws
- // /api/pay/execute endpoint: probing, governance, signing, and settlement.
- // No local wallet needed.
- const sessionToken = args?.session_token || process.env.PAYMENT_SESSION_TOKEN || '';
- if (sessionToken) {
- const ceiling = Math.min(MAX_PAY_USD, args?.max_usd ?? Infinity);
-
- if (REQUIRE_CONFIRM && args?.confirm !== true) {
- // We don't know the exact price without probing — let the user confirm intent.
- return {
- ok: false,
- error: 'confirm_required',
- message: `This will spend up to $${ceiling} (session-governed) on ${url}. Re-issue with confirm:true to proceed (or set REQUIRE_CONFIRM=0).`,
- mode: 'session',
- url,
- };
- }
-
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);
- let res, text;
- try {
- res = await fetch(`${THREE_WS_BASE}/api/pay/execute`, {
- method: 'POST',
- signal: controller.signal,
- headers: { 'content-type': 'application/json', accept: 'application/json' },
- body: JSON.stringify({
- session_token: sessionToken,
- url,
- method,
- body: args?.body ?? undefined,
- idempotency_key: args?.idempotency_key ?? undefined,
- }),
- });
- text = await res.text();
- } catch (err) {
- throw Object.assign(new Error(`Session payment failed: ${err?.message}`), {
- code: 'session_execute_failed',
- });
- } finally {
- clearTimeout(timer);
- }
-
- let result;
- try { result = text ? JSON.parse(text) : null; } catch { result = text; }
-
- if (!res.ok) {
- throw Object.assign(
- new Error(result?.message || result?.error || `Session execute returned HTTP ${res.status}`),
- { code: result?.code || 'session_execute_failed', status: res.status, body: result },
- );
- }
-
- return { ...result, mode: 'session' };
- }
-
- // ── Self-custodial mode ─────────────────────────────────────────────
- const secret = args?.secret || SOLANA_DEFAULT_SECRET;
- if (!secret) {
- throw Object.assign(
- new Error('No signer configured. Set SOLANA_SECRET_KEY / pass `secret`, or provide a `session_token` for session-governed payments.'),
- { code: 'no_signer' },
- );
- }
-
- // Probe first so we never pay blind and can enforce the cap pre-payment.
- const probe = await probeChallenge(url, { method, body: args?.body });
- if (!probe.paid) {
- return {
- ok: true,
- paid: false,
- url,
- note: 'Endpoint is not paywalled — called directly, no payment needed.',
- status: probe.status,
- result: probe.result,
- };
- }
-
- const token = args?.token === 'three' ? 'three' : 'usdc';
- const { sol, usdc, three } = pickSolanaAccepts(probe.accepts);
- if (!sol.length) {
- throw Object.assign(new Error('Endpoint has no Solana (solana:*) payment option this wallet can settle.'), {
- code: 'no_solana_requirement',
- });
- }
- if (token === 'three' && !three) {
- throw Object.assign(new Error('Endpoint does not advertise a $THREE payment option — retry with token:"usdc".'), {
- code: 'three_not_offered',
- });
- }
- const priceUsd = usdFromAccept(usdc);
- const ceiling = Math.min(MAX_PAY_USD, args?.max_usd ?? Infinity);
- if (priceUsd != null && priceUsd > ceiling) {
- throw Object.assign(
- new Error(`Price $${priceUsd} exceeds the cap $${ceiling}. Raise max_usd / MAX_PAY_USD to allow it.`),
- { code: 'over_cap', price_usd: priceUsd, cap_usd: ceiling },
- );
- }
- const threeAmount = token === 'three' ? String(three.amount ?? three.maxAmountRequired ?? three.price ?? '') : null;
- const spendLabel = token === 'three' ? `${threeAmount} atomic $THREE` : `$${priceUsd ?? '?'} USDC`;
- if (REQUIRE_CONFIRM && args?.confirm !== true) {
- return {
- ok: false,
- error: 'confirm_required',
- message: `This will spend up to ${spendLabel} on ${url}. Re-issue with confirm:true to proceed (or set REQUIRE_CONFIRM=0).`,
- mode: 'self_custodial',
- token,
- price_usd: priceUsd,
- ...(threeAmount ? { three_amount: threeAmount } : {}),
- url,
- };
- }
-
- const { payingFetch, address } = await buildPayingFetch(secret, { preferToken: token });
- const init = {
- method,
- headers: { accept: 'application/json', ...(args?.body !== undefined ? { 'content-type': 'application/json' } : {}) },
- body: args?.body !== undefined ? JSON.stringify(args.body) : undefined,
- };
- const res = await payingFetch(url, init);
- const text = await res.text();
- let result;
- try {
- result = text ? JSON.parse(text) : null;
- } catch {
- result = text;
- }
- if (!res.ok) {
- throw Object.assign(new Error(`Paid call to ${url} returned HTTP ${res.status}`), {
- code: 'call_failed',
- status: res.status,
- body: result,
- });
- }
- const settlement = await decodeSettlement(res);
- return {
- ok: true,
- paid: true,
- mode: 'self_custodial',
- url,
- payer: address,
- token,
- price_usd: priceUsd,
- ...(threeAmount ? { three_amount: threeAmount } : {}),
- settlement,
- result,
- };
+ return payUrl(url, { ...args, toolName: 'pay_and_call' });
},
};
diff --git a/packages/x402-mcp/src/tools/spending-report.js b/packages/x402-mcp/src/tools/spending-report.js
new file mode 100644
index 000000000..21c829b8b
--- /dev/null
+++ b/packages/x402-mcp/src/tools/spending-report.js
@@ -0,0 +1,24 @@
+// `spending_report`: read-only totals from this wallet's local ledger
+// (../lib/ledger.js), so a human can ask what the agent spent without reading
+// raw JSONL. Every settled pay_and_call or named-tool call appends one entry;
+// this just reads them back and sums by merchant and by day.
+
+import { z } from 'zod';
+
+import { summarize, LEDGER_PATH } from '../lib/ledger.js';
+
+export const def = {
+ name: 'spending_report',
+ title: "This wallet's x402 spending report (totals by merchant and day)",
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
+ description:
+ 'Report what this wallet has spent through pay_and_call and the named service tools, from the local ledger. Returns a grand total, totals per merchant (the endpoint\'s hostname), and totals per UTC day. Read-only, local file only: never touches the network or a key. Optionally filter by `since` (ISO-8601 timestamp) or `merchant`.',
+ inputSchema: {
+ since: z.string().datetime({ offset: true }).optional().describe('Only include payments at or after this ISO-8601 timestamp.'),
+ merchant: z.string().optional().describe('Only include payments to this merchant hostname (e.g. "three.ws").'),
+ },
+ async handler(args) {
+ const report = await summarize({ since: args?.since, merchant: args?.merchant });
+ return { ok: true, ledger_path: LEDGER_PATH, ...report };
+ },
+};
diff --git a/packages/x402-mcp/test/ledger.test.mjs b/packages/x402-mcp/test/ledger.test.mjs
new file mode 100644
index 000000000..e88513a8c
--- /dev/null
+++ b/packages/x402-mcp/test/ledger.test.mjs
@@ -0,0 +1,99 @@
+// src/lib/ledger.js backs spending_report (order 521). LEDGER_PATH is read from
+// X402_MCP_LEDGER_PATH at module-load time, so this test sets that env var to a
+// throwaway temp file BEFORE the first dynamic import of ledger.js, then cleans
+// the file up afterward. Pure file I/O, no network, no key.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+const dir = await mkdtemp(path.join(tmpdir(), 'x402-mcp-ledger-test-'));
+process.env.X402_MCP_LEDGER_PATH = path.join(dir, 'ledger.jsonl');
+
+const { recordSpend, summarize, readEntries, LEDGER_PATH } = await import('../src/lib/ledger.js');
+const { def: spendingReportDef } = await import('../src/tools/spending-report.js');
+
+test.after(async () => {
+ await rm(dir, { recursive: true, force: true });
+});
+
+test('LEDGER_PATH picked up the env override', () => {
+ assert.equal(LEDGER_PATH, process.env.X402_MCP_LEDGER_PATH);
+});
+
+test('recordSpend appends, readEntries reads back in order', async () => {
+ await recordSpend({ tool: 'weather_forecast', url: 'https://three.ws/api/x402/weather-guard-forecast', amountUsd: 0.001, token: 'usdc' });
+ await recordSpend({ tool: 'domain_rdap_check', url: 'https://three.ws/api/x402/domains-check', amountUsd: 0.001, token: 'usdc' });
+ const entries = await readEntries();
+ assert.equal(entries.length, 2);
+ assert.equal(entries[0].tool, 'weather_forecast');
+ assert.equal(entries[0].merchant, 'three.ws');
+ assert.equal(entries[1].tool, 'domain_rdap_check');
+});
+
+test('summarize totals by merchant and by day', async () => {
+ await recordSpend({ tool: 'book_read', url: 'https://three.ws/api/x402/books-read', amountUsd: 0.01, token: 'usdc' });
+ await recordSpend({ tool: 'weather_forecast', url: 'https://other.example/api/x', amountUsd: 0.002, token: 'usdc' });
+
+ const report = await summarize();
+ assert.equal(report.totalCalls, 4);
+ assert.equal(report.unpricedCalls, 0);
+ assert.ok(Math.abs(report.totalUsd - 0.014) < 1e-9, `expected ~0.014, got ${report.totalUsd}`);
+
+ const threeWs = report.byMerchant.find((m) => m.merchant === 'three.ws');
+ assert.ok(threeWs, 'three.ws should have an aggregated row');
+ assert.equal(threeWs.calls, 3);
+ assert.ok(Math.abs(threeWs.totalUsd - 0.012) < 1e-9);
+
+ const other = report.byMerchant.find((m) => m.merchant === 'other.example');
+ assert.ok(other, 'other.example should have its own aggregated row');
+ assert.equal(other.calls, 1);
+
+ assert.equal(report.byDay.length, 1, 'all four calls happened the same UTC day in this test run');
+ assert.equal(report.byDay[0].calls, 4);
+});
+
+test('summarize filters by merchant', async () => {
+ const report = await summarize({ merchant: 'other.example' });
+ assert.equal(report.totalCalls, 1);
+ assert.equal(report.byMerchant.length, 1);
+ assert.equal(report.byMerchant[0].merchant, 'other.example');
+});
+
+test('summarize filters by since, excluding entries before the cutoff', async () => {
+ const future = new Date(Date.now() + 60_000).toISOString();
+ const report = await summarize({ since: future });
+ assert.equal(report.totalCalls, 0);
+ assert.equal(report.totalUsd, 0);
+});
+
+test('spending_report tool handler returns ok, the ledger path, and the same totals as summarize()', async () => {
+ const result = await spendingReportDef.handler({});
+ assert.equal(result.ok, true);
+ assert.equal(result.ledger_path, LEDGER_PATH);
+ assert.equal(result.totalCalls, 4);
+});
+
+test('spending_report tool handler respects its merchant filter argument', async () => {
+ const result = await spendingReportDef.handler({ merchant: 'other.example' });
+ assert.equal(result.ok, true);
+ assert.equal(result.totalCalls, 1);
+ assert.equal(result.byMerchant[0].merchant, 'other.example');
+});
+
+test('readEntries returns an empty array when the ledger file does not exist yet', async () => {
+ const unusedPath = path.join(dir, 'never-written.jsonl');
+ const original = process.env.X402_MCP_LEDGER_PATH;
+ process.env.X402_MCP_LEDGER_PATH = unusedPath;
+ try {
+ // readEntries reads LEDGER_PATH captured at import time, not the live env
+ // var, so this exercises the ENOENT branch directly against that path.
+ const fresh = await import(`../src/lib/ledger.js?probe=${Date.now()}`);
+ const entries = await fresh.readEntries();
+ assert.deepEqual(entries, []);
+ } finally {
+ process.env.X402_MCP_LEDGER_PATH = original;
+ }
+});
diff --git a/packages/x402-mcp/test/named-services.test.mjs b/packages/x402-mcp/test/named-services.test.mjs
new file mode 100644
index 000000000..344bda3c3
--- /dev/null
+++ b/packages/x402-mcp/test/named-services.test.mjs
@@ -0,0 +1,127 @@
+// Named commerce tools (order 521): one MCP tool per entry in ../src/tools.json,
+// built by ../src/tools/named-services.js. These tests run offline: schema
+// validation never touches the network, and the "dry run" test stubs
+// globalThis.fetch so no real HTTP call and no signing happens.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { z } from 'zod';
+
+import { NAMED_SERVICE_TOOLS } from '../src/tools/named-services.js';
+import { jsonSchemaToZodShape } from '../src/lib/json-schema-to-zod.js';
+import registry from '../src/tools.json' with { type: 'json' };
+
+test('every registry entry became a named tool, 1:1', () => {
+ assert.equal(NAMED_SERVICE_TOOLS.length, registry.tools.length);
+ assert.deepEqual(
+ new Set(NAMED_SERVICE_TOOLS.map((t) => t.name)),
+ new Set(registry.tools.map((e) => e.name)),
+ );
+});
+
+test('every named tool has a title, a price-stating description, a schema and a handler', () => {
+ for (const tool of NAMED_SERVICE_TOOLS) {
+ assert.equal(typeof tool.title, 'string', `${tool.name} is missing a title`);
+ assert.match(tool.description, /^\[\$\d+(\.\d+)? USDC per call\]/, `${tool.name} description must state its price`);
+ assert.ok(tool.inputSchema && typeof tool.inputSchema === 'object', `${tool.name} is missing inputSchema`);
+ assert.equal(typeof tool.handler, 'function', `${tool.name} is missing a handler`);
+ }
+});
+
+test('named tools are execution tools: openWorldHint true, destructiveHint explicit', () => {
+ for (const tool of NAMED_SERVICE_TOOLS) {
+ assert.equal(tool.annotations.openWorldHint, true, `${tool.name} must set openWorldHint (pays a real external-feeling endpoint)`);
+ assert.equal(tool.annotations.readOnlyHint, false, `${tool.name} spends money, not read-only`);
+ assert.equal(tool.annotations.destructiveHint, true, `${tool.name} must set destructiveHint explicitly`);
+ }
+});
+
+test('every entry\'s inputSchema converts to a valid zod shape that accepts its own required fields', () => {
+ for (const entry of registry.tools) {
+ const shape = jsonSchemaToZodShape(entry.inputSchema);
+ const schema = z.object(shape);
+ const sample = sampleFor(entry.inputSchema);
+ const parsed = schema.safeParse(sample);
+ assert.ok(parsed.success, `${entry.name}: sample args ${JSON.stringify(sample)} should validate, got ${JSON.stringify(parsed.error?.issues)}`);
+ }
+});
+
+test('a required field missing from the input fails validation', () => {
+ for (const entry of registry.tools) {
+ const required = entry.inputSchema.required || [];
+ if (!required.length) continue;
+ const shape = jsonSchemaToZodShape(entry.inputSchema);
+ const schema = z.object(shape);
+ const sample = sampleFor(entry.inputSchema);
+ delete sample[required[0]];
+ const parsed = schema.safeParse(sample);
+ assert.equal(parsed.success, false, `${entry.name}: dropping required field "${required[0]}" should fail validation`);
+ }
+});
+
+test('dry run: calling a named tool without confirm:true prices it and pays nothing (no fetch beyond the probe)', async () => {
+ const originalFetch = globalThis.fetch;
+ let fetchCalls = 0;
+ try {
+ for (const entry of registry.tools) {
+ const tool = NAMED_SERVICE_TOOLS.find((t) => t.name === entry.name);
+ const atomics = String(Math.round(entry.priceUsd * 1_000_000));
+ globalThis.fetch = async () => {
+ fetchCalls += 1;
+ return new Response(
+ JSON.stringify({
+ x402Version: 2,
+ accepts: [
+ {
+ scheme: 'exact',
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ amount: atomics,
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ extra: { name: 'USDC', decimals: 6 },
+ },
+ ],
+ }),
+ { status: 402, headers: { 'content-type': 'application/json' } },
+ );
+ };
+
+ const before = fetchCalls;
+ const result = await tool.handler({ ...sampleFor(entry.inputSchema), secret: 'dry-run-not-a-real-key' });
+
+ assert.equal(result.ok, false, `${entry.name}: dry run should refuse without confirm`);
+ assert.equal(result.error, 'confirm_required', `${entry.name}: dry run should ask for confirm`);
+ assert.match(result.message, new RegExp(`\\$${entry.priceUsd}`), `${entry.name}: dry run must state the price $${entry.priceUsd}`);
+ assert.equal(fetchCalls, before + 1, `${entry.name}: dry run should make exactly one probe call, no payment`);
+ }
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+/** Minimal valid arguments for a JSON Schema object, covering every required field. */
+function sampleFor(schema) {
+ const sample = {};
+ for (const [key, prop] of Object.entries(schema.properties || {})) {
+ if (!(schema.required || []).includes(key)) continue;
+ sample[key] = sampleValue(prop);
+ }
+ return sample;
+}
+
+function sampleValue(prop) {
+ if (Array.isArray(prop.enum)) return prop.enum[0];
+ switch (prop.type) {
+ case 'string':
+ return 'example';
+ case 'integer':
+ return prop.minimum ?? 1;
+ case 'number':
+ return prop.minimum ?? 1;
+ case 'boolean':
+ return true;
+ case 'array':
+ return [sampleValue(prop.items || { type: 'string' })];
+ default:
+ return 'example';
+ }
+}
diff --git a/packages/x402-mcp/test/registration.test.mjs b/packages/x402-mcp/test/registration.test.mjs
index 4df5c90fd..102e18642 100644
--- a/packages/x402-mcp/test/registration.test.mjs
+++ b/packages/x402-mcp/test/registration.test.mjs
@@ -10,15 +10,17 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import { TOOLS, buildServer } from '../src/index.js';
+import registry from '../src/tools.json' with { type: 'json' };
-const READ_ONLY_TOOLS = new Set(['x402_wallet', 'find_services', 'inspect_endpoint']);
-const EXECUTION_TOOLS = new Set(['pay_and_call']);
+const NAMED_SERVICE_NAMES = registry.tools.map((entry) => entry.name);
+const READ_ONLY_TOOLS = new Set(['x402_wallet', 'find_services', 'inspect_endpoint', 'spending_report']);
+const EXECUTION_TOOLS = new Set(['pay_and_call', ...NAMED_SERVICE_NAMES]);
test('exactly the expected tools are registered', () => {
- assert.equal(TOOLS.length, 4);
+ assert.equal(TOOLS.length, 5 + NAMED_SERVICE_NAMES.length);
assert.deepEqual(
new Set(TOOLS.map((t) => t.name)),
- new Set(['x402_wallet', 'find_services', 'inspect_endpoint', 'pay_and_call']),
+ new Set(['x402_wallet', 'find_services', 'inspect_endpoint', 'pay_and_call', 'spending_report', ...NAMED_SERVICE_NAMES]),
);
});
@@ -36,22 +38,32 @@ test('every tool has a title, description, input schema and complete annotations
}
});
-test('the read tools advertise readOnlyHint and openWorldHint', () => {
+test('the read tools advertise readOnlyHint', () => {
for (const name of READ_ONLY_TOOLS) {
const tool = TOOLS.find((t) => t.name === name);
assert.ok(tool, `${name} must exist`);
assert.equal(tool.annotations.readOnlyHint, true, `${name} should be read-only`);
+ }
+});
+
+test('the live-service read tools advertise openWorldHint; the local-only ledger tool does not', () => {
+ for (const name of ['x402_wallet', 'find_services', 'inspect_endpoint']) {
+ const tool = TOOLS.find((t) => t.name === name);
assert.equal(tool.annotations.openWorldHint, true, `${name} talks to a live service`);
}
+ const spendingReport = TOOLS.find((t) => t.name === 'spending_report');
+ assert.equal(spendingReport.annotations.openWorldHint, false, 'spending_report only reads a local file');
});
-test('pay_and_call is the only destructive execution tool (spends real USDC)', () => {
+test('pay_and_call and the named service tools are the only destructive execution tools (spend real USDC)', () => {
const destructive = TOOLS.filter((t) => t.annotations.destructiveHint === true).map((t) => t.name);
assert.deepEqual(new Set(destructive), EXECUTION_TOOLS);
- const pay = TOOLS.find((t) => t.name === 'pay_and_call');
- assert.equal(pay.annotations.readOnlyHint, false);
- assert.equal(pay.annotations.destructiveHint, true);
- assert.equal(pay.annotations.idempotentHint, false);
+ for (const name of EXECUTION_TOOLS) {
+ const tool = TOOLS.find((t) => t.name === name);
+ assert.equal(tool.annotations.readOnlyHint, false, `${name} should not be read-only`);
+ assert.equal(tool.annotations.destructiveHint, true, `${name} should be destructive`);
+ assert.equal(tool.annotations.idempotentHint, false, `${name} should not be idempotent`);
+ }
});
test('non-read-only tools set destructiveHint explicitly (spec default is TRUE when omitted)', () => {