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(mcp-agent): add pay_quote so pay_and_call can run behind a user-approved price

nirholas2cc2908d7a0d
diff --git a/api/_mcpagent/discovery.js b/api/_mcpagent/discovery.js
index 118febcc7..ac3dbd2fb 100644
--- a/api/_mcpagent/discovery.js
+++ b/api/_mcpagent/discovery.js
@@ -16,7 +16,8 @@ import { withService } from '../_lib/x402/bazaar-helpers.js';
export const RESOURCE_DESCRIPTION =
'three.ws Agent MCP: Streamable HTTP (MCP 2025-06-18) that gives an assistant a real on-chain ' +
'wallet on the x402 network: wallet_status (address, USDC and SOL balance, spend caps), ' +
- 'find_services (search the live facilitator network for paid services), pay_and_call (call a ' +
+ 'find_services (search the live facilitator network for paid services), pay_quote (read what a ' +
+ 'paid endpoint charges without paying), pay_and_call (call a ' +
'paid x402 endpoint and settle the USDC payment from the signed-in user own three.ws agent ' +
'wallet, bounded by their caps), provision_wallet, monetize_endpoint (list your own paid ' +
'service), and read_resource (live three:// wallet, spend limit and service data). The agent ' +
@@ -82,7 +83,7 @@ function agentBazaarExtension() {
params: {
type: 'object',
description:
- 'For tools/call: { name, arguments }. Tool names: getting_started (free), wallet_status, find_services, pay_and_call, provision_wallet, monetize_endpoint, see tools/list.',
+ 'For tools/call: { name, arguments }. Tool names: getting_started (free), wallet_status, find_services, pay_quote, pay_and_call, provision_wallet, monetize_endpoint, see tools/list.',
},
},
};
diff --git a/api/_mcpagent/dispatch.js b/api/_mcpagent/dispatch.js
index 2b8e2715d..e0d818011 100644
--- a/api/_mcpagent/dispatch.js
+++ b/api/_mcpagent/dispatch.js
@@ -11,11 +11,13 @@ export { isPublicTool } from '../_lib/mcp-getting-started.js';
const INSTRUCTIONS = [
'three.ws Agent gives this assistant a real on-chain wallet on the x402 network.',
'wallet_status shows the balance and spending caps; provision_wallet creates a custodial wallet',
- 'for one of your agents; find_services discovers paid services; pay_and_call(resource_url) calls a',
- "paid x402 endpoint and settles the USDC payment from the user's own three.ws agent wallet, within",
- 'caps; monetize_endpoint publishes one of your agent endpoints as a priced x402 service so other',
- 'agents can pay it and you earn USDC. Always check wallet_status before spending, and confirm the',
- 'price with the user when it is non-trivial.',
+ 'for one of your agents; find_services discovers paid services; pay_quote(resource_url) reads what',
+ 'an x402 endpoint charges without paying; pay_and_call(resource_url) calls it and settles the USDC',
+ "payment from the user's own three.ws agent wallet, within caps. pay_and_call moves funds: call",
+ 'pay_quote first, show the user the price and pay-to, wait for a clear yes, then call pay_and_call',
+ 'with its quote_id and confirm_payment: true. monetize_endpoint publishes one of your agent',
+ 'endpoints as a priced x402 service so other agents can pay it and you earn USDC. Always check',
+ 'wallet_status before spending.',
'The agent marketplace tools buy, sell and bid on whole agents with USDC escrow on Solana:',
'browse_marketplace, get_listing, place_bid, buy_now, accept_marketplace_bid and friends. Every',
'financial one needs preview_marketplace_action first: show the user its table (recipient, amount,',
diff --git a/api/_mcpagent/tools.js b/api/_mcpagent/tools.js
index 27aa6dd5d..16434d04f 100644
--- a/api/_mcpagent/tools.js
+++ b/api/_mcpagent/tools.js
@@ -1,9 +1,10 @@
// threews-agent MCP: "add a wallet to Claude."
//
-// Three tools turn a Claude (or any MCP client) into an autonomous economic
+// These tools turn a Claude (or any MCP client) into an autonomous economic
// agent on the live x402 network:
// * wallet_status what the agent's wallet holds and is allowed to spend
// * find_services discover paid services it can call
+// * pay_quote read an endpoint's price and pay-to without paying
// * pay_and_call pay an x402 endpoint in USDC from the user's own wallet
// and return the result, bounded by spending caps
//
@@ -33,6 +34,7 @@ import {
MonetizeError,
} from '../_lib/agent-paid-services.js';
import { currentSignatureFor, agreementRequirement } from '../_lib/real-funds-agreement.js';
+import { fetchSafePublicUrlPinned, SsrfBlockedError } from '../_lib/ssrf-guard.js';
import { readResourceToolResult } from '../_mcp/resources.js';
function rpcError(code, message, data) {
@@ -103,6 +105,67 @@ async function agreementRequired(userId, resource) {
};
}
+// ── pay_quote: read an x402 challenge without paying ─────────────────────────
+// pay_and_call is a financial tool: the tool policy (@three-ws/mcp-policy) only
+// lets it run with a fresh pay_quote preview for the same resource_url. The
+// quote is one unpaid request to the endpoint; its 402 challenge names every
+// accepted network, asset, price and pay-to address, which is what the user
+// approves before any USDC moves. The probe is DNS-resolved, IP-pinned and
+// size-capped, so a caller cannot aim it at an internal address.
+const QUOTE_TIMEOUT_MS = 15_000;
+const QUOTE_MAX_BYTES = 256 * 1024;
+
+function parseJsonText(text) {
+ try {
+ return text ? JSON.parse(text) : null;
+ } catch {
+ return null;
+ }
+}
+
+// x402 v2 servers carry the challenge in a base64 `payment-required` header;
+// v1 servers put it in the 402 body. Read both.
+function readChallenge(headers, bodyText) {
+ const fromBody = parseJsonText(bodyText);
+ if (Array.isArray(fromBody?.accepts)) return fromBody;
+ const header = headers.get('payment-required');
+ if (!header) return null;
+ try {
+ const decoded = JSON.parse(Buffer.from(header, 'base64').toString('utf8'));
+ return Array.isArray(decoded?.accepts) ? decoded : null;
+ } catch {
+ return null;
+ }
+}
+
+// One accepts[] entry in the shape a person approves. v2 names the atomic charge
+// `amount`, v1 `maxAmountRequired`, and some servers a bare `price`.
+function describeAccept(a) {
+ const atomic = a.amount ?? a.maxAmountRequired ?? a.price ?? null;
+ const decimals = Number(a.extra?.decimals);
+ const assetName = String(a.extra?.name ?? '').trim();
+ const display =
+ atomic != null && Number.isFinite(decimals)
+ ? `${Number(atomic) / 10 ** decimals}${assetName ? ` ${assetName}` : ''}`
+ : null;
+ return {
+ scheme: a.scheme ?? null,
+ network: a.network ?? null,
+ price_atomic: atomic != null ? String(atomic) : null,
+ price_display: display,
+ asset: a.asset ?? a.extra?.asset ?? null,
+ pay_to: a.payTo ?? null,
+ };
+}
+
+function quoteFailed(reason, text, resource) {
+ return {
+ content: [{ type: 'text', text }],
+ structuredContent: { ok: false, reason, resource },
+ isError: true,
+ };
+}
+
// Scope is enforced inside the handler (not via the dispatcher's tool.scope) so
// the null-userId x402 path gets the friendly signInRequired() message first,
// and an authenticated-but-under-scoped token gets a clear, designed error
@@ -283,6 +346,116 @@ export const toolDefs = [
};
},
},
+ {
+ name: 'pay_quote',
+ title: 'Quote an x402 service before paying',
+ // One unpaid request that reads the payment challenge: no funds move.
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: true,
+ },
+ description:
+ 'Read what a paid x402 endpoint charges WITHOUT paying: every accepted network, asset, price and pay-to address from its 402 challenge. Show the user this quote and get a clear yes before pay_and_call; pay_and_call needs the quote_id this returns for the same resource_url.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ resource_url: {
+ type: 'string',
+ format: 'uri',
+ description: 'The x402 endpoint to quote.',
+ },
+ method: { type: 'string', enum: ['GET', 'POST'], default: 'GET' },
+ body: { type: 'object', description: 'JSON body for a POST endpoint.' },
+ },
+ required: ['resource_url'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(limits.mcpAgent, auth);
+ const resource = args.resource_url;
+ const method = args.method === 'POST' ? 'POST' : 'GET';
+
+ let res;
+ try {
+ res = await fetchSafePublicUrlPinned(
+ resource,
+ {
+ method,
+ headers: {
+ accept: 'application/json',
+ ...(args.body != null ? { 'content-type': 'application/json' } : {}),
+ },
+ ...(args.body != null ? { body: JSON.stringify(args.body) } : {}),
+ signal: AbortSignal.timeout(QUOTE_TIMEOUT_MS),
+ },
+ { maxBytes: QUOTE_MAX_BYTES },
+ );
+ } catch (err) {
+ if (err instanceof SsrfBlockedError) {
+ return quoteFailed('blocked_url', 'That resource URL is not a permitted public https endpoint.', resource);
+ }
+ const timedOut = err?.name === 'TimeoutError' || err?.name === 'AbortError';
+ return quoteFailed(
+ timedOut ? 'timeout' : 'unreachable',
+ timedOut
+ ? `${resource} did not answer within ${QUOTE_TIMEOUT_MS / 1000} seconds.`
+ : `Could not reach ${resource}: ${err?.message || err}`,
+ resource,
+ );
+ }
+
+ const bodyText = await res.text();
+ if (res.status !== 402) {
+ return {
+ content: [
+ {
+ type: 'text',
+ text: `${resource} answered ${res.status} without asking for payment, so pay_and_call would call it for free.`,
+ },
+ ],
+ structuredContent: { ok: true, resource, method, paywalled: false, status: res.status, accepts: [] },
+ };
+ }
+
+ const challenge = readChallenge(res.headers, bodyText);
+ if (!challenge) {
+ return quoteFailed(
+ 'invalid_challenge',
+ `${resource} answered 402 but sent no readable x402 payment requirements.`,
+ resource,
+ );
+ }
+ const accepts = challenge.accepts.map(describeAccept);
+ const payable = accepts.some((a) => String(a.network || '').startsWith('solana'));
+ const lines = accepts.map(
+ (a) => `- ${a.price_display ?? `${a.price_atomic ?? '?'} atomic`} on ${a.network ?? 'an unnamed network'} to ${a.pay_to ?? 'an unnamed address'}`,
+ );
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `${resource} asks for payment:\n${lines.join('\n')}\n` +
+ (payable
+ ? 'Your three.ws agent wallet settles the Solana option.'
+ : 'None of these settle on Solana, so your three.ws agent wallet cannot pay this endpoint.'),
+ },
+ ],
+ structuredContent: {
+ ok: true,
+ resource,
+ method,
+ paywalled: true,
+ x402_version: challenge.x402Version ?? null,
+ accepts,
+ payable_with_agent_wallet: payable,
+ pay_link: payLink(resource),
+ },
+ };
+ },
+ },
{
name: 'pay_and_call',
title: 'Pay an x402 service and return its result',
diff --git a/data/changelog.json b/data/changelog.json
index 6307d3c83..e24855b85 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-10-08",
+ "title": "Agent Wallet MCP: quote an x402 service before your assistant pays it",
+ "summary": "The Agent Wallet MCP server has a new pay_quote tool. It reads what a paid x402 endpoint charges (price, network and the address that gets paid) without spending anything. pay_and_call now works end to end once you turn it on for a connection: your assistant quotes first, shows you the price, and pays only after you say yes, using that quote. Paying a different endpoint than the one quoted, or paying with an expired quote, is refused before any USDC moves.",
+ "tags": ["feature", "security"],
+ "link": "/docs/mcp-agent"
+ },
{
"date": "2026-10-08",
"title": "Your own free 3D quota when you connect through Grok Bot or another cloud agent",
diff --git a/docs/mcp-agent.md b/docs/mcp-agent.md
index c548bd01b..b3935e54f 100644
--- a/docs/mcp-agent.md
+++ b/docs/mcp-agent.md
@@ -18,10 +18,29 @@ Registered with the MCP Registry as **`io.github.nirholas/threews-agent`**.
| `getting_started` | none (free, no sign-in) | Overview of the server and its tools. The one tool an unauthenticated client can call. |
| `wallet_status` | `wallet:read` (or `wallet:write`) | Read-only: the user's agent wallet address, SOL + USDC balance, spending caps, and whether spend is enabled. Never moves funds. |
| `find_services(query, type?, network?, max_price_usdc?, limit?)` | none beyond sign-in | Search the live x402 facilitator network for paid services to call. `max_price_usdc` accepts 0 to 1,000,000. |
-| `pay_and_call(resource_url, method?, body?, max_usd?)` | `wallet:write` | Call a paid x402 endpoint and auto-settle the USDC payment from the user's wallet, within caps. Returns the service response. |
+| `pay_quote(resource_url, method?, body?)` | none beyond sign-in | Read what a paid x402 endpoint charges without paying: every accepted network, asset, price and pay-to address from its 402 challenge. Returns the `quote_id` that `pay_and_call` needs. Never moves funds. |
+| `pay_and_call(resource_url, method?, body?, max_usd?, quote_id, confirm_payment)` | `wallet:write` | Call a paid x402 endpoint and auto-settle the USDC payment from the user's wallet, within caps. Returns the service response. Financial: off until the connection turns it on (see below). |
| `provision_wallet(agent_id, cluster?, airdrop?)` | `wallet:write` | Create (or return) the custodial Solana wallet for one of your own agents. Idempotent. `airdrop` is devnet only and never fires on mainnet. |
| `monetize_endpoint(agent_id, name, description, price_usdc, target_url, method?, input_schema?, network?)` | `services:write` | Publish an upstream API you already serve as a priced x402 endpoint. Buyers' USDC settles to your agent's own wallet. |
+## Turning on pay_and_call
+
+`pay_and_call` moves real USDC, so the tool policy ([`@three-ws/mcp-policy`](../packages/mcp-policy/README.md)) keeps it
+off for every connection until the user turns it on, and even then it runs only
+against a fresh quote the user approved:
+
+1. Turn it on for the connection: `npx three-ws tools`, the toggles on
+ [/settings/mcp-tools](https://three.ws/settings/mcp-tools), or the header
+ `X-Three-Tools: default,pay_and_call` (`default,x402` turns on the whole x402
+ group). Until then `tools/list` hides it and a call answers
+ `{ "reason": "tool_disabled" }` with those same instructions.
+2. Call `pay_quote(resource_url)`. Its result names the price, network and
+ pay-to address, and carries a `quote_id` valid for a few minutes.
+3. Show the user that quote. Only after a clear yes, call
+ `pay_and_call(resource_url, quote_id, confirm_payment: true)` with the same
+ `resource_url`. A missing flag, a stale or foreign `quote_id`, or a different
+ `resource_url` is refused before any payment is attempted.
+
## Scopes
Every tool above that reads or moves an agent wallet is gated on an OAuth scope,
diff --git a/tests/api/mcp-agent-catalog.test.js b/tests/api/mcp-agent-catalog.test.js
index 3b228bbd8..46e1a332d 100644
--- a/tests/api/mcp-agent-catalog.test.js
+++ b/tests/api/mcp-agent-catalog.test.js
@@ -10,17 +10,59 @@ import { describe, it, expect } from 'vitest';
import { TOOL_CATALOG, TOOLS } from '../../api/_mcpagent/catalog.js';
describe('agent-wallet MCP catalog', () => {
- it('leads with the free getting_started tool, then the wallet toolset', () => {
+ it('leads with the free getting_started tool, then the wallet, marketplace and prediction toolsets', () => {
expect(TOOL_CATALOG.map((t) => t.name)).toEqual([
'getting_started',
+ // wallet + x402 (api/_mcpagent/tools.js)
'wallet_status',
'find_services',
+ 'pay_quote',
'pay_and_call',
'provision_wallet',
'monetize_endpoint',
+ 'read_resource',
+ // agent marketplace (api/_mcpagent/marketplace-tools.js)
+ 'browse_marketplace',
+ 'browse_public_agents',
+ 'get_listing',
+ 'get_marketplace_history',
+ 'preview_marketplace_action',
+ 'create_marketplace_listing',
+ 'delist_marketplace_listing',
+ 'place_bid',
+ 'buy_now',
+ 'get_my_bids',
+ 'get_received_bids',
+ 'accept_marketplace_bid',
+ 'reject_marketplace_bid',
+ 'withdraw_marketplace_bid',
+ 'get_agent_transfer',
+ 'resume_agent_transfer',
+ // prediction markets (api/_mcpagent/predictions-tools.js)
+ 'predictions_events',
+ 'predictions_event',
+ 'predictions_positions',
+ 'predictions_open_preview',
+ 'predictions_open',
+ 'predictions_close_preview',
+ 'predictions_close',
+ 'predictions_redeem_preview',
+ 'predictions_redeem',
+ 'predictions_watch',
]);
});
+ it('ships the preview tool every financial tool in the policy table names', async () => {
+ // A financial tool whose preview tool is missing can never be called: the
+ // policy refuses it for want of a preview no tool can issue.
+ const { POLICY } = await import('@three-ws/mcp-policy');
+ const names = new Set(TOOL_CATALOG.map((t) => t.name));
+ for (const name of names) {
+ const row = POLICY['threews-agent'][name];
+ if (row?.tier === 'financial' && row.previewTool) expect(names.has(row.previewTool), `${name} needs ${row.previewTool}`).toBe(true);
+ }
+ });
+
it('gives every catalog entry a handler in the dispatch map', () => {
for (const tool of TOOL_CATALOG) {
expect(typeof TOOLS[tool.name]?.handler).toBe('function');
diff --git a/tests/api/mcp-agent.test.js b/tests/api/mcp-agent.test.js
index c6322da56..92e7e992a 100644
--- a/tests/api/mcp-agent.test.js
+++ b/tests/api/mcp-agent.test.js
@@ -33,7 +33,8 @@ vi.mock('../../api/_lib/x402/bazaar-client.js', async (orig) => {
// ── Rate limits ──────────────────────────────────────────────────────────────
const rl = { agent: { success: true, reset: 0 }, pay: { success: true, reset: 0 } };
-vi.mock('../../api/_lib/rate-limit.js', () => ({
+vi.mock('../../api/_lib/rate-limit.js', async (importOriginal) => ({
+ ...(await importOriginal()),
limits: {
mcpAgent: vi.fn(async () => rl.agent),
mcpAgentPay: vi.fn(async () => rl.pay),
@@ -41,6 +42,31 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
clientIp: vi.fn(() => '203.0.113.5'),
}));
+// ── pay_quote's unpaid probe ─────────────────────────────────────────────────
+// The quote goes out through the DNS-resolving, IP-pinned fetch, which cannot
+// reach the offline `.test` hosts below; it answers from quoteState instead.
+// Pinning and redirect re-validation are covered in tests/ssrf-hardening-guards.test.js.
+const SOLANA_ACCEPT = {
+ scheme: 'exact',
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ amount: '10000',
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ payTo: 'THREEsynthetic1111111111111111111111111111',
+ extra: { name: 'USDC', decimals: 6 },
+};
+const quoteState = { status: 402, body: { x402Version: 2, accepts: [SOLANA_ACCEPT] }, headers: {}, error: null };
+const quoteFetch = vi.fn(async () => {
+ if (quoteState.error) throw quoteState.error;
+ return new Response(JSON.stringify(quoteState.body), {
+ status: quoteState.status,
+ headers: { 'content-type': 'application/json', ...quoteState.headers },
+ });
+});
+vi.mock('../../api/_lib/ssrf-guard.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ fetchSafePublicUrlPinned: (...a) => quoteFetch(...a),
+}));
+
vi.mock('../../api/_lib/usage.js', () => ({
recordEvent: vi.fn(),
logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),
@@ -56,8 +82,22 @@ const READONLY = { userId: 'user-1', rateKey: 'user-1', scope: 'wallet:read', so
// A token from a client that was never granted anything wallet-shaped, e.g. a
// dynamically-registered client holding the default avatars:read.
const NOSCOPE = { userId: 'user-1', rateKey: 'user-1', scope: 'avatars:read', source: 'bearer' };
-const call = (name, args, auth = USER) =>
- dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, auth);
+// A connection's tool settings arrive as the X-Three-Tools header (what
+// `npx three-ws tools` writes). DEFAULT_SESSION is the platform default (read
+// and write on, financial off); PAY_ON adds the one financial tool.
+const DEFAULT_SESSION = { headers: { 'x-three-tools': 'default' } };
+const PAY_ON = { headers: { 'x-three-tools': 'default,pay_and_call' } };
+const call = (name, args, auth = USER, req = DEFAULT_SESSION) =>
+ dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, auth, { ...req });
+
+// The approved flow for a financial call: quote, then pay with the quote's
+// quote_id and confirm_payment: true, on a connection that turned it on.
+async function quoteThenPay(args, auth = USER) {
+ const quote = await call('pay_quote', { resource_url: args.resource_url }, auth, PAY_ON);
+ const quoteId = quote.result?._meta?.['three.ws/preview']?.quote_id;
+ expect(typeof quoteId).toBe('string');
+ return call('pay_and_call', { ...args, quote_id: quoteId, confirm_payment: true }, auth, PAY_ON);
+}
beforeEach(() => {
payerState.spendEnabled = true;
@@ -67,23 +107,111 @@ beforeEach(() => {
payer.payExternalX402.mockClear();
payer.getUserWalletStatus.mockClear();
bazState.search.mockClear();
+ quoteFetch.mockClear();
+ quoteState.status = 402;
+ quoteState.body = { x402Version: 2, accepts: [SOLANA_ACCEPT] };
+ quoteState.headers = {};
+ quoteState.error = null;
rl.agent = { success: true, reset: 0 };
rl.pay = { success: true, reset: 0 };
});
describe('threews-agent MCP', () => {
- it('lists the wallet toolset behind a free getting_started tool', async () => {
- const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, USER);
+ it('lists the wallet toolset behind a free getting_started tool, financial tools off by default', async () => {
+ const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, USER, { ...DEFAULT_SESSION });
expect(r.result.tools.map((t) => t.name)).toEqual([
'getting_started',
'wallet_status',
'find_services',
- 'pay_and_call',
+ 'pay_quote',
'provision_wallet',
'monetize_endpoint',
+ 'read_resource',
+ 'browse_marketplace',
+ 'browse_public_agents',
+ 'get_listing',
+ 'get_marketplace_history',
+ 'preview_marketplace_action',
+ 'get_my_bids',
+ 'get_received_bids',
+ 'reject_marketplace_bid',
+ 'get_agent_transfer',
+ 'resume_agent_transfer',
+ 'predictions_events',
+ 'predictions_event',
+ 'predictions_positions',
+ 'predictions_open_preview',
+ 'predictions_close_preview',
+ 'predictions_redeem_preview',
+ 'predictions_watch',
]);
});
+ it('lists pay_and_call with its confirm flag and quote argument once the connection turns it on', async () => {
+ const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, USER, { ...PAY_ON });
+ const pay = r.result.tools.find((t) => t.name === 'pay_and_call');
+ expect(pay).toBeDefined();
+ expect(Object.keys(pay.inputSchema.properties)).toEqual(
+ expect.arrayContaining(['resource_url', 'confirm_payment', 'quote_id']),
+ );
+ expect(pay._meta['three.ws/policy']).toMatchObject({ tier: 'financial', previewTool: 'pay_quote' });
+ });
+
+ it('refuses pay_and_call on a connection that has not turned it on, before any payment call', async () => {
+ const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' });
+ expect(r.result.isError).toBe(true);
+ expect(r.result.structuredContent).toMatchObject({ reason: 'tool_disabled', group: 'x402', tier: 'financial' });
+ expect(payer.payExternalX402).not.toHaveBeenCalled();
+ });
+
+ it('refuses pay_and_call without a pay_quote preview for the same resource', async () => {
+ const noPreview = await call('pay_and_call', { resource_url: 'https://paid.test/x', confirm_payment: true }, USER, PAY_ON);
+ expect(noPreview.result.structuredContent.reason).toBe('preview_required');
+
+ const quote = await call('pay_quote', { resource_url: 'https://paid.test/cheap' }, USER, PAY_ON);
+ const quoteId = quote.result._meta['three.ws/preview'].quote_id;
+ const swapped = await call(
+ 'pay_and_call',
+ { resource_url: 'https://paid.test/expensive', quote_id: quoteId, confirm_payment: true },
+ USER,
+ PAY_ON,
+ );
+ expect(swapped.result.structuredContent.reason).toBe('preview_mismatch');
+ expect(payer.payExternalX402).not.toHaveBeenCalled();
+ });
+
+ it('pay_quote reads the price and pay-to from the 402 challenge without paying', async () => {
+ const r = await call('pay_quote', { resource_url: 'https://paid.test/weather' });
+ expect(quoteFetch).toHaveBeenCalledTimes(1);
+ expect(quoteFetch.mock.calls[0][0]).toBe('https://paid.test/weather');
+ expect(payer.payExternalX402).not.toHaveBeenCalled();
+ expect(r.result.isError).toBeUndefined();
+ expect(r.result.structuredContent).toMatchObject({
+ paywalled: true,
+ payable_with_agent_wallet: true,
+ accepts: [{ network: SOLANA_ACCEPT.network, price_atomic: '10000', price_display: '0.01 USDC', pay_to: SOLANA_ACCEPT.payTo }],
+ });
+ expect(r.result._meta['three.ws/preview'].unlocks).toEqual(['pay_and_call']);
+ });
+
+ it('pay_quote reads a v2 challenge carried in the payment-required header', async () => {
+ quoteState.body = {};
+ quoteState.headers = {
+ 'payment-required': Buffer.from(JSON.stringify({ x402Version: 2, accepts: [SOLANA_ACCEPT] })).toString('base64'),
+ };
+ const r = await call('pay_quote', { resource_url: 'https://paid.test/weather' });
+ expect(r.result.structuredContent.accepts[0].price_display).toBe('0.01 USDC');
+ });
+
+ it('pay_quote refuses an internal address without issuing a preview', async () => {
+ const { SsrfBlockedError } = await import('../../api/_lib/ssrf-guard.js');
+ quoteState.error = new SsrfBlockedError('host resolves to a blocked range');
+ const r = await call('pay_quote', { resource_url: 'https://internal.test/x' });
+ expect(r.result.isError).toBe(true);
+ expect(r.result.structuredContent.reason).toBe('blocked_url');
+ expect(r.result._meta?.['three.ws/preview']).toBeUndefined();
+ });
+
it('getting_started is free and callable with no sign-in', async () => {
expect(isPublicTool('getting_started')).toBe(true);
expect(isPublicTool('pay_and_call')).toBe(false);
@@ -159,21 +287,21 @@ describe('threews-agent MCP', () => {
it('pay_and_call degrades to a pay link when spend is disabled', async () => {
payerState.spendEnabled = false;
- const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' });
+ const r = await quoteThenPay({ resource_url: 'https://paid.test/x' });
expect(payer.payExternalX402).not.toHaveBeenCalled();
expect(r.result.structuredContent).toMatchObject({ paid: false, reason: 'spend_disabled' });
expect(r.result.structuredContent.pay_link).toContain('https://three.ws/pay?resource=');
});
it('pay_and_call degrades to auth handoff for anon callers', async () => {
- const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' }, ANON);
+ const r = await quoteThenPay({ resource_url: 'https://paid.test/x' }, ANON);
expect(payer.payExternalX402).not.toHaveBeenCalled();
expect(r.result.structuredContent.reason).toBe('auth_required');
});
it('pay_and_call pays and returns the result when enabled', async () => {
payerState.payResult = { ok: true, payer: 'SoLaddr', result: { temp: 72 }, receipt: { tx: 'sig' } };
- const r = await call('pay_and_call', { resource_url: 'https://paid.test/weather', max_usd: 0.05 });
+ const r = await quoteThenPay({ resource_url: 'https://paid.test/weather', max_usd: 0.05 });
expect(payer.payExternalX402).toHaveBeenCalledWith({
userId: 'user-1',
url: 'https://paid.test/weather',
@@ -186,14 +314,14 @@ describe('threews-agent MCP', () => {
it('pay_and_call surfaces payer errors with a friendly message + pay link', async () => {
payerState.payError = Object.assign(new Error('boom'), { code: 'no_solana_wallet' });
- const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' });
+ const r = await quoteThenPay({ resource_url: 'https://paid.test/x' });
expect(r.result.isError).toBe(true);
expect(r.result.content[0].text).toContain('no Solana wallet');
expect(r.result.structuredContent.reason).toBe('no_solana_wallet');
});
it('refuses to spend for a read-only token, before any payment call', async () => {
- const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' }, READONLY);
+ const r = await quoteThenPay({ resource_url: 'https://paid.test/x' }, READONLY);
expect(payer.payExternalX402).not.toHaveBeenCalled();
expect(r.result.isError).toBe(true);
expect(r.result.structuredContent).toMatchObject({
@@ -204,7 +332,7 @@ describe('threews-agent MCP', () => {
it('still hands a read-only token the manual pay link when spend is off', async () => {
payerState.spendEnabled = false;
- const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' }, READONLY);
+ const r = await quoteThenPay({ resource_url: 'https://paid.test/x' }, READONLY);
expect(r.result.structuredContent).toMatchObject({ paid: false, reason: 'spend_disabled' });
expect(r.result.structuredContent.pay_link).toContain('https://three.ws/pay?resource=');
});
@@ -218,7 +346,7 @@ describe('threews-agent MCP', () => {
it('enforces the pay rate limit before spending', async () => {
rl.pay = { success: false, reset: Date.now() + 30000 };
- const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' });
+ const r = await quoteThenPay({ resource_url: 'https://paid.test/x' });
expect(r.error.code).toBe(-32000);
expect(payer.payExternalX402).not.toHaveBeenCalled();
});