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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(mcp-agent): add the pay_quote preview the spend policy requires, so pay_and_call can run once enabled
nirholasbde8f717e210
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 12b248d17..91d9ef85d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-10-09+- **Agent MCP: price an x402 payment with pay_quote before pay_and_call spends it**: The Agent MCP server now has a pay_quote tool. It asks a paid x402 endpoint what it charges without paying, and shows who gets paid, how much, in which token and on which chain, which wallet pays, the per-call limit, and anything that would stop the payment. pay_and_call needs the quote_id it returns plus an explicit confirm_payment, so an assistant always shows you the price before your agent wallet pays. One approval pays one call. Before this, turning pay_and_call on still left it refusing every call, because the quote step it requires did not exist. `[feature, fix]`- **Funding an agent's inference from its wallet now needs the signed real-funds agreements**: Topping up an agent's inference credits, switching on its automatic top-up, and provisioning an inference API key all send real USDC out of the agent's wallet. They now ask for the same signed Terms of Service, Risk Disclosure and Agent Wallet Agreement as every other real-funds action, on the page and on the API alike. Previews and switching the automatic top-up off stay open, since nothing moves. `[security]`- **The desktop companion, CLI and MCP server now work with just the bridge token**: The companion bridge token is the one credential the desktop app, the companion command line and its MCP server are given, but the feed, marking a message as spoken, replying, reading contacts and checking sources all refused it, so pasting the token into the desktop app said it was wrong and an agent asking what you had heard got turned away. Those calls now accept the bridge token and only ever show the messages and contacts of the person it belongs to. It still cannot connect sources, edit contacts, change settings or rotate itself; those stay behind your signed-in account, and they now say so plainly instead of answering as if the token were wrong. (`/companion`) `[fix]`diff --git a/api/_mcpagent/discovery.js b/api/_mcpagent/discovery.jsindex 29be135d7..28c7cd0d9 100644--- a/api/_mcpagent/discovery.js+++ b/api/_mcpagent/discovery.js@@ -16,11 +16,20 @@ 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 ' +- 'paid x402 endpoint and settle the USDC payment from the signed-in user own three.ws agent ' +- 'wallet, bounded by their caps), provision_wallet, and monetize_endpoint (list your own paid ' +- 'service). Connect with a three.ws account (OAuth) or pay per call in USDC on Base or Solana ' +- 'mainnet, no API key. Operated by three.ws.';+ 'find_services (search the live facilitator network for paid services), pay_quote (price a paid ' ++ 'endpoint 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:// resources). ' ++ 'An agent marketplace with USDC escrow on Solana: 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 and ' ++ 'resume_agent_transfer. Prediction markets settled in USDC on Solana: predictions_events, ' ++ 'predictions_event, predictions_positions, predictions_open_preview, predictions_open, ' ++ 'predictions_close_preview, predictions_close, predictions_redeem_preview, predictions_redeem and ' ++ 'predictions_watch. Every money-moving tool needs its preview first and an explicit confirm flag. ' ++ 'Connect with a three.ws account (OAuth) or pay per call in USDC on Base or Solana mainnet, no ' ++ 'API key. Operated by three.ws.';// Endpoint-level v2 bazaar discovery entry, shaped exactly like the validator// expects (see api/_lib/x402-spec.js, bazaarExtension). The advertised example@@ -75,7 +84,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, read_resource, plus the marketplace and prediction-market tools, see tools/list.',},},};diff --git a/api/_mcpagent/dispatch.js b/api/_mcpagent/dispatch.jsindex 2b8e2715d..efaed3021 100644--- a/api/_mcpagent/dispatch.js+++ b/api/_mcpagent/dispatch.js@@ -11,11 +11,15 @@ 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) prices one',+ 'without paying (recipient, amount, token, chain, and anything blocking it); 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, show the user the',+ 'pay_quote table, wait for a clear yes, then call pay_and_call with its quote_id and',+ 'confirm_payment: true. pay_and_call is off until the session turns on the x402 group.',+ 'read_resource reads live three:// resources (wallets, agents, usage, orders, launches, the',+ 'marketplace and x402 services); omit uri to list them.','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.jsindex 27aa6dd5d..691615fad 100644--- a/api/_mcpagent/tools.js+++ b/api/_mcpagent/tools.js@@ -1,9 +1,12 @@// 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 price one paid endpoint without paying: the confirmation+// table (recipient, amount, token, chain) and anything+// that would block the payment// * pay_and_call pay an x402 endpoint in USDC from the user's own wallet// and return the result, bounded by spending caps//@@ -11,6 +14,10 @@// the agent spends THAT user's wallet, and it is hard-gated by// THREEWS_AGENT_PAY_ENABLED on the server. When spend is disabled it degrades// to returning the exact payment requirements + a pay link rather than failing.+// The tool policy (@three-ws/mcp-policy, row `pay_and_call`) also keeps it off+// until the session enables the x402 group, and then refuses it without the+// quote_id pay_quote returned for the same resource_url plus+// confirm_payment: true, so the user sees the price before anything is signed.import { limits } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';import { sql } from '../_lib/db.js';@@ -33,6 +40,7 @@ import {MonetizeError,} from '../_lib/agent-paid-services.js';import { currentSignatureFor, agreementRequirement } from '../_lib/real-funds-agreement.js';+import { probePrice, selectRail } from '../_lib/pay/probe.js';import { readResourceToolResult } from '../_mcp/resources.js';function rpcError(code, message, data) {@@ -171,6 +179,50 @@ async function requestDevnetAirdrop(address) {}}+function chainLabel(network) {+ if (typeof network !== 'string') return 'unknown chain';+ if (network.startsWith('solana')) return `Solana (${network})`;+ if (network === 'eip155:8453' || network === 'base') return `Base (${network})`;+ return network;+}++function quoteRefusal(resource, reason, text, extra = {}) {+ return {+ content: [{ type: 'text', text: `${text} Nothing was paid.` }],+ structuredContent: { ok: false, reason, resource, ...extra },+ isError: true,+ };+}++// What would stop pay_and_call from settling this price automatically. `hard`+// blockers make pay_and_call fail after the user approves, so the quote itself+// fails and no preview id is issued for a payment that cannot happen. A signed-+// out caller or a server with spend off is not a hard blocker: pay_and_call+// answers both with the manual pay link, which the quote already carries.+function payBlockers({ auth, spendEnabled, wallet, priceUsd, perCallLimit }) {+ if (!auth.userId) {+ return [{ code: 'auth_required', hard: false, message: 'Sign in to three.ws to pay from your agent wallet; until then use the pay link.' }];+ }+ if (!spendEnabled) {+ return [{ code: 'spend_disabled', hard: false, message: 'Autonomous spending is not enabled on this server; use the pay link to pay manually.' }];+ }+ const out = [];+ if (!hasScope(auth.scope, 'wallet:write')) {+ out.push({ code: 'insufficient_scope', hard: true, message: 'This connection lacks the wallet:write scope. Re-authorize with it granted.' });+ }+ if (wallet && !wallet.provisioned) {+ out.push({ code: 'no_wallet', hard: true, message: 'No agent wallet is provisioned for this account. Run provision_wallet first.' });+ }+ if (perCallLimit != null && priceUsd > perCallLimit) {+ out.push({ code: 'over_per_call_limit', hard: true, message: `The price $${priceUsd} is above the per-call limit of $${perCallLimit}.` });+ }+ const usdc = wallet?.balances?.usdc;+ if (typeof usdc === 'number' && priceUsd > usdc) {+ out.push({ code: 'insufficient_usdc', hard: true, message: `The wallet holds ${usdc} USDC, less than the $${priceUsd} price.` });+ }+ return out;+}+export const toolDefs = [{name: 'wallet_status',@@ -231,7 +283,7 @@ export const toolDefs = [openWorldHint: true,},description:- 'Search the live x402 facilitator network for paid services (HTTP APIs and MCP tools). Returns each match with its price and resource URL. Feed a resource into pay_and_call to actually use it.',+ 'Search the live x402 facilitator network for paid services (HTTP APIs and MCP tools). Returns each match with its price and resource URL. To use one, price it with pay_quote, show the user the result, then pay with pay_and_call.',inputSchema: {type: 'object',properties: {@@ -283,6 +335,118 @@ export const toolDefs = [};},},+ {+ name: 'pay_quote',+ title: 'Price an x402 payment without paying',+ // Probes the endpoint for its 402 challenge and reads the wallet; never+ // signs or moves anything. Prices can change between calls.+ annotations: {+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: true,+ },+ description:+ "Price a paid x402 endpoint WITHOUT paying: asks the resource for its payment challenge and returns the confirmation table pay_and_call would settle from the signed-in user's agent wallet (recipient, amount, token, chain), the per-call limit that applies, the wallet balance, and anything that would block the payment. Show the table to the user; pay_and_call needs the quote_id this returns, for the same resource_url, and confirm_payment: true after a clear yes.",+ inputSchema: {+ type: 'object',+ properties: {+ resource_url: {+ type: 'string',+ format: 'uri',+ description: 'The x402 endpoint you intend to pay with pay_and_call.',+ },+ method: { type: 'string', enum: ['GET', 'POST'], default: 'GET' },+ body: { type: 'object', description: 'JSON body for POST requests, as pay_and_call will send it.' },+ max_usd: {+ type: 'number',+ minimum: 0,+ description: 'The ceiling you will pass to pay_and_call, so the quote checks the price against it.',+ },+ },+ required: ['resource_url'],+ additionalProperties: false,+ },+ async handler(args, auth) {+ await enforce(limits.mcpAgent, auth);+ const resource = args.resource_url;+ const method = args.method || 'GET';++ const probe = await probePrice(resource, { method, body: args.body ?? null });+ if (probe.kind === 'error') {+ return quoteRefusal(resource, probe.code, `Could not price ${resource}: ${probe.message}.`);+ }+ // The payer signs Solana exact-scheme payments only, so the Solana rail+ // is the one this quote has to describe.+ const rail = probe.kind === 'priced' ? selectRail(probe.rails, 'solana') : null;+ if (probe.kind === 'priced' && !rail) {+ const offered = [...new Set(probe.rails.map((r) => r.network).filter(Boolean))];+ return quoteRefusal(+ resource,+ 'no_solana_rail',+ `${resource} does not accept payment on Solana (it offers ${offered.join(', ') || 'no readable network'}), and the three.ws agent wallet pays on Solana.`,+ { networks: offered },+ );+ }+ if (rail && rail.amount_usd == null) {+ return quoteRefusal(resource, 'unreadable_price', `${resource} sent a payment challenge whose amount could not be read.`);+ }+ const priceUsd = rail ? rail.amount_usd : 0;++ const canReadWallet =+ Boolean(auth.userId) && (hasScope(auth.scope, 'wallet:read') || hasScope(auth.scope, 'wallet:write'));+ const wallet = canReadWallet ? await getUserWalletStatus(auth.userId) : null;+ const capPerCall = wallet?.caps?.max_per_call_usdc ?? null;+ const callerCap = typeof args.max_usd === 'number' && args.max_usd > 0 ? args.max_usd : null;+ const limitsKnown = [capPerCall, callerCap].filter((v) => v != null);+ const perCallLimit = limitsKnown.length ? Math.min(...limitsKnown) : null;+ const spendEnabled = resolveSpendEnabled();+ const blockers = payBlockers({ auth, spendEnabled, wallet, priceUsd, perCallLimit });+ const hard = blockers.filter((b) => b.hard);++ const token = rail ? (rail.usdc ? 'USDC' : String(rail.asset ?? 'unknown token')) : null;+ const lines = [`Payment preview for ${method} ${resource} (nothing was paid):`];+ if (rail) {+ lines.push(+ ` Recipient: ${rail.pay_to ?? 'not stated by the service'}`,+ ` Amount: ${priceUsd} ${token}`,+ ` Token: ${token}${rail.asset ? ` (${rail.asset})` : ''}`,+ ` Chain: ${chainLabel(rail.network)}`,+ );+ } else {+ lines.push(' This endpoint did not ask for payment, so pay_and_call would call it and pay nothing.');+ }+ if (wallet?.provisioned) {+ lines.push(` From: ${wallet.address} (${wallet.balances?.usdc ?? '?'} USDC)`);+ }+ if (perCallLimit != null) lines.push(` Per-call limit: $${perCallLimit}`);+ for (const b of blockers) lines.push(` ${b.hard ? 'Blocked' : 'Note'}: ${b.message}`);+ if (!auth.userId || !spendEnabled) lines.push(` Pay manually: ${payLink(resource)}`);++ return {+ content: [{ type: 'text', text: lines.join('\n') }],+ structuredContent: {+ ok: hard.length === 0,+ resource,+ method,+ free: !rail,+ recipient: rail?.pay_to ?? null,+ amount_usd: priceUsd,+ amount_atomics: rail?.amount_atomics ?? '0',+ token,+ asset: rail?.asset ?? null,+ network: rail?.network ?? null,+ from: wallet?.provisioned ? wallet.address : null,+ balance_usdc: wallet?.balances?.usdc ?? null,+ per_call_limit_usd: perCallLimit,+ spend_enabled: spendEnabled,+ blockers: blockers.map(({ code, message }) => ({ code, message })),+ ...(!auth.userId || !spendEnabled ? { pay_link: payLink(resource) } : {}),+ },+ ...(hard.length ? { isError: true } : {}),+ };+ },+ },{name: 'pay_and_call',title: 'Pay an x402 service and return its result',@@ -294,7 +458,7 @@ export const toolDefs = [openWorldHint: true,},description:- "Call a paid x402 endpoint and settle the USDC payment automatically from the signed-in user's three.ws agent wallet, bounded by spending caps. Returns the service's response. Requires sign-in. If the per-call price exceeds max_usd (or the caps), the call is refused before any money moves.",+ "Call a paid x402 endpoint and settle the USDC payment automatically from the signed-in user's three.ws agent wallet, bounded by spending caps. Returns the service's response. Requires sign-in. Call pay_quote for the same resource_url first and pay only after the user approves its table. If the per-call price exceeds max_usd (or the caps), the call is refused before any money moves.",inputSchema: {type: 'object',properties: {diff --git a/data/changelog.json b/data/changelog.jsonindex f4be04f6d..f6be23f7b 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$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-09",+ "title": "Agent MCP: price an x402 payment with pay_quote before pay_and_call spends it",+ "summary": "The Agent MCP server now has a pay_quote tool. It asks a paid x402 endpoint what it charges without paying, and shows who gets paid, how much, in which token and on which chain, which wallet pays, the per-call limit, and anything that would stop the payment. pay_and_call needs the quote_id it returns plus an explicit confirm_payment, so an assistant always shows you the price before your agent wallet pays. One approval pays one call. Before this, turning pay_and_call on still left it refusing every call, because the quote step it requires did not exist.",+ "tags": [+ "feature",+ "fix"+ ]+ },{"date": "2026-10-09","title": "Funding an agent's inference from its wallet now needs the signed real-funds agreements",diff --git a/docs/mcp-agent.md b/docs/mcp-agent.mdindex c548bd01b..b43286fd8 100644--- a/docs/mcp-agent.md+++ b/docs/mcp-agent.md@@ -2,7 +2,10 @@The first MCP server where the assistant can **transact real value**: discover,pay for, and call paid x402 services in USDC — settled on-chain from the-signed-in user's own three.ws agent wallet, bounded by spending caps.+signed-in user's own three.ws agent wallet, bounded by spending caps. The same+server also buys, sells, and bids on whole agents in the escrowed agent+marketplace, and trades USDC prediction markets on Solana, every money-moving+call behind a preview and a named confirm flag.Registered with the MCP Registry as **`io.github.nirholas/threews-agent`**.@@ -18,9 +21,54 @@ 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?, max_usd?)` | none (reads the wallet with `wallet:read`) | Price a paid endpoint without paying: the confirmation table `pay_and_call` would settle (recipient, amount, token, chain), the per-call limit, the wallet balance, and anything that would block the payment. Returns the `quote_id` `pay_and_call` needs. |+| `pay_and_call(resource_url, method?, body?, max_usd?, quote_id, confirm_payment)` | `wallet:write` | Financial tier. Call a paid x402 endpoint and auto-settle the USDC payment from the user's wallet, within caps. Needs the `quote_id` from `pay_quote` for the same `resource_url` and `confirm_payment: true`. Returns the service response. || `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. |+| `read_resource(uri?, format?)` | the resource's own scope | Read a `three://` resource (account, agents, wallets, launches, marketplace, x402 catalog) as a tool call, for clients that do not render MCP resources. Omit `uri` to list what you can read. |++### Agent marketplace++Buy, sell, and bid on whole agents (identity, persona, skills, history, and+optionally the wallet balance) with USDC held in per-listing escrow on Solana.+The tools are thin adapters over `api/_lib/agent-market/service.js`, the layer+the REST API and the `/marketplace/agents` pages use.++| Tool | Tier | Scope | What it does |+|------|------|-------|--------------|+| `browse_marketplace`, `browse_public_agents`, `get_listing`, `get_marketplace_history` | read | none (an x402 payer needs no account) | Listings, public agents with their sale state, one listing in full, and the marketplace event log with on-chain signatures. |+| `preview_marketplace_action(action, ...)` | read | `agents:read` | Builds the confirmation table (recipient, amount, token, chain, fees, warnings) for `create_listing`, `delist`, `place_bid`, `buy_now`, `accept_bid`, or `withdraw_bid` and returns a `preview_id` valid for ten minutes, one use. |+| `get_my_bids`, `get_received_bids`, `get_agent_transfer` | read | `agents:read` | Your open bids, bids on your listings, and the settlement progress of a sold agent. |+| `reject_marketplace_bid`, `resume_agent_transfer` | write | `agents:write` | Decline a bid; resume a stalled post-sale transfer. |+| `create_marketplace_listing` / `delist_marketplace_listing` / `accept_marketplace_bid` | financial | `agents:write` | Confirm flags `confirm_listing`, `confirm_delist`, `confirm_accept`. |+| `place_bid` / `buy_now` / `withdraw_marketplace_bid` | financial | `wallet:write` | Confirm flags `confirm_bid`, `confirm_payment`, `confirm_withdraw`. Pay from one of your agents (`funding_source: agent_wallet`) or get a transaction to sign in a browser wallet (`connected_wallet`). |++Every financial marketplace call needs its confirm flag set to `true` and the+`preview_id` that `preview_marketplace_action` issued to the same user for the+same action and arguments; different terms than the preview are refused.++### Prediction markets++USDC prediction markets on Solana, over the same engine (`api/_lib/predictions/`)+as the `/api/v1/agents/:id/predictions/*` routes and the `/predictions` pages.++| Tool | Tier | Scope | What it does |+|------|------|-------|--------------|+| `predictions_events`, `predictions_event` | read | none (an x402 payer needs no account) | Search live events; one event with every market's prices, history, and resolution rules. |+| `predictions_positions(agent_id)` | read | `wallet:read` | An agent's open and settled positions, PnL, claimable payouts, recent fills. |+| `predictions_open_preview`, `predictions_close_preview`, `predictions_redeem_preview` | read | `wallet:read` | Price the trade and return a `preview_id` (ten minutes). Moves nothing. |+| `predictions_open`, `predictions_close`, `predictions_redeem` | financial | `wallet:write` | Execute with `agent_id`, the `preview_id`, and `confirm_trade: true`. |+| `predictions_watch` | write | `wallet:write` | Alert when an outcome's probability crosses a threshold, in-app and optionally to Telegram or a webhook. Moves no funds. |++### Resources and prompts++This server also answers `resources/*` and `prompts/*`: the `three://` resources+(your account, agents, wallets with balances and spend limits, per-agent usage,+runs, orders, DCA plans, intents, launches, the skill marketplace, and the x402+catalog) and guided prompts such as `setup-wallet`, `hire-agent`, `sell-a-skill`,+and `setup-dca`. The full tables, with the scope each resource needs, are in+[MCP resources](./mcp.md#resources) and [guided prompts](./mcp.md#guided-prompts).+The manifest lists them under `_meta` in [`server-agent.json`](../server-agent.json).## Scopes@@ -33,7 +81,8 @@ the scope it needs, not a bare JSON-RPC error:{ "ok": false, "reason": "insufficient_scope", "required": "wallet:write" }```-The three scopes (`wallet:read`, `wallet:write`, `services:write`) are advertised+The marketplace tools also use `agents:read` and `agents:write` (see the+tables above). The three wallet scopes (`wallet:read`, `wallet:write`, `services:write`) are advertisedin [`/.well-known/oauth-authorization-server`](https://three.ws/.well-known/oauth-authorization-server),may be requested by any client (including dynamically-registered ones), and areapproved by name on the consent screen. Ask for them in the `scope` parameter of@@ -47,8 +96,66 @@ and every `accepts[].resource` read `https://three.ws/api/mcp-agent`, under theservice name `three.ws Agent MCP`. Facilitators (CDP Bazaar, agentic.market,x402scan) index it from that same envelope, whose `extensions.bazaar` example isthe read-only `find_services` call, so a crawler probing the documented shape can-never move a caller's funds. `initialize`, `tools/list`, `ping`, and-`getting_started` stay free for plain clients and crawlers.+never move a caller's funds. `initialize`, `tools/list`, `ping`, resource and+prompt discovery (`resources/list`, `resources/templates/list`, `resources/read`+of the public resources, `prompts/list`, `prompts/get`), and `getting_started`+stay free for plain clients and crawlers.++## Tool policy: financial tools are off by default++The server runs the shared [`@three-ws/mcp-policy`](../packages/mcp-policy/README.md)+table. Every tool has a tier: `read` and `write` tools are listed by default, while+`financial` tools (`pay_and_call` and the money-moving marketplace and prediction+tools) are hidden from `tools/list` and refused with `tool_disabled` until the+connection turns them on. Each financial tool's description and its+`_meta['three.ws/policy']` entry name its confirm flag and the preview tool that+must run first.++Turn them on per connection with the `X-Three-Tools` header or the `tools` query+parameter, using the policy grammar: `default,financial` adds every financial+tool, `default,marketplace` adds one whole group, and a bare list of tool names is+an exact allow list.++```bash+curl -s https://three.ws/api/mcp-agent \+ -H "authorization: Bearer $TOKEN" \+ -H "content-type: application/json" \+ -H "X-Three-Tools: default,predictions" \+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'+```++### Paying an x402 endpoint: quote, approve, pay++`pay_and_call` is in the `x402` group, so a connection turns it on with+`X-Three-Tools: default,x402` (or `default,financial`). Once on, it only runs+after a quote the user has seen:++1. Call `pay_quote` with the `resource_url` (and the `method`, `body` and+ `max_usd` you intend to pay with). It asks the endpoint for its 402+ challenge and pays nothing. The result is the table to show the user+ (recipient, amount, token, chain, the wallet it pays from, the per-call+ limit) plus a `quote_id` valid for five minutes.+2. Wait for the user's clear yes.+3. Call `pay_and_call` with the same `resource_url`, the `quote_id`, and+ `confirm_payment: true`.++The policy refuses `pay_and_call` without the flag (`confirmation_required`),+without a quote (`preview_required`), with an expired or already spent one+(`preview_unknown`, `preview_stale`), or with a quote for a different+`resource_url` or a different account (`preview_mismatch`). A quote is spent by+the payment it authorized, so one approval pays one call. `pay_quote` issues no+`quote_id` when the payment could not succeed anyway: a price over the per-call+limit, too little USDC, no provisioned wallet, a token without `wallet:write`,+or an endpoint with no Solana payment option. A signed-out caller, or a server+with spend off, still gets a quote and the manual `/pay` link.++```bash+curl -s https://three.ws/api/mcp-agent \+ -H "authorization: Bearer $TOKEN" \+ -H "content-type: application/json" \+ -H "X-Three-Tools: default,x402" \+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"pay_quote","arguments":{"resource_url":"https://three.ws/api/x402/market-global"}}}'+```## How payment works@@ -71,6 +178,14 @@ Autonomous spending is **off** unless `THREEWS_AGENT_PAY_ENABLED=1`. While off,`pay_and_call` returns the exact payment details and a `/pay` link instead ofmoving funds. `wallet_status` and `find_services` work regardless.+Real funds also move only for an account that has signed the current real-funds+agreements (Terms of Service, Risk Disclosure, Agent Wallet Agreement). An+unsigned account gets `reason: "risk_ack_required"` with a `sign_url` pointing at+[`/legal/agreements`](https://three.ws/legal/agreements), and nothing is sent; if+the signature lookup fails, the call fails closed with `agreement_check_unavailable`.+The same check guards the prediction-market trades and the marketplace's listing,+bid, buy-now, and accept calls.+**Before enabling spend in production:** run a funded-wallet integration testagainst a live x402 endpoint (confirm a real USDC settlement + cap enforcement +rollback on failure). Do not enable the flag for the public until that passes.diff --git a/packages/home-mcp/tests/registration.test.js b/packages/home-mcp/tests/registration.test.jsindex cb7337ab8..c465315c7 100644--- a/packages/home-mcp/tests/registration.test.js+++ b/packages/home-mcp/tests/registration.test.js@@ -18,6 +18,9 @@ const EXPECTED = {list_entities: { write: false },list_macros: { write: false },call_service: { write: true },+ // run_macro's dry run as its own read-only tool: the preview the policy+ // requires before run_macro, so it stays callable while run_macro is off.+ preview_macro: { write: false },run_macro: { write: true },};@@ -50,8 +53,9 @@ describe('the tool surface', () => {if (expected.write) {expect(tool.annotations.destructiveHint, `${tool.name} moves a physical object`).toBe(true);} else {- // The spec ignores destructiveHint when readOnlyHint is true.- expect(tool.annotations.destructiveHint, `${tool.name} is read-only`).toBeUndefined();+ // The spec ignores destructiveHint when readOnlyHint is true, so a+ // read tool may omit it or state false, but never claim true.+ expect(tool.annotations.destructiveHint, `${tool.name} is read-only`).not.toBe(true);}}});diff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex 55a6cae09..30ff77891 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,14 +1,25 @@{- "generated_at": "2026-10-09T03:00:46.444Z",+ "generated_at": "2026-10-09T03:05:50.446Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 3838,+ "total": 3839,"complete": false,"full_feed": "/changelog.json","entries": [+ {+ "date": "2026-10-09",+ "type": "update",+ "title": "Agent MCP: price an x402 payment with pay_quote before pay_and_call spends it",+ "summary": "The Agent MCP server now has a pay_quote tool. It asks a paid x402 endpoint what it charges without paying, and shows who gets paid, how much, in which token and on which chain, which wallet pays, the per-call limit, and anything that would stop the payment. pay_and_call needs the quote_id it returns plus an explicit confirm_payment, so an assistant always shows you the price before your agent wallet pays. One approval pays one call. Before this, turning pay_and_call on still left it refusing every call, because the quote step it requires did not exist.",+ "link": null,+ "tags": [+ "feature",+ "fix"+ ]+ },{"date": "2026-10-09","type": "update",@@ -1548,17 +1559,6 @@"feature","fix"]- },- {- "date": "2026-09-17",- "type": "update",- "title": "Sign the real-funds agreements once before using real money",- "summary": "three.ws is experimental technology, and agent wallets are custodial software, not bank accounts. Before you deposit into an agent wallet, trade, send, withdraw, arm autopilot, or pay with real funds, you now sign three agreements in one step: the Terms of Service, the Risk Disclosure, and the new Agent Wallet Agreement. You tick each one, confirm you are eligible and that you understand funds can be lost for any reason with nothing insured, and type your name as your signature. An agent's deposit address now appears only after signing, and every deposit is covered by the Agent Wallet Agreement. When you are signed in, the signature is saved to your account and the servers refuse real-funds actions from unsigned accounts, including through the API, so it cannot be skipped. You can review every signature you have made at /legal/agreements. Devnet stays free of this step.",- "link": "/legal/agreements",- "tags": [- "security",- "feature"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex 8b1ca9882..19b3f242e 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,22 @@{- "generated_at": "2026-10-09T03:00:46.418Z",+ "generated_at": "2026-10-09T03:05:50.422Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-10-09",+ "type": "update",+ "title": "Agent MCP: price an x402 payment with pay_quote before pay_and_call spends it",+ "summary": "The Agent MCP server now has a pay_quote tool. It asks a paid x402 endpoint what it charges without paying, and shows who gets paid, how much, in which token and on which chain, which wallet pays, the per-call limit, and anything that would stop the payment. pay_and_call needs the quote_id it returns plus an explicit confirm_payment, so an assistant always shows you the price before your agent wallet pays. One approval pays one call. Before this, turning pay_and_call on still left it refusing every call, because the quote step it requires did not exist.",+ "link": null,+ "tags": [+ "feature",+ "fix"+ ]+ },{"date": "2026-10-09","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 7f733cb6a..7ba785ea0 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws: features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Agent MCP: price an x402 payment with pay_quote before pay_and_call spends it</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-10-09:Agent MCP: price an x402 payment with pay_quote before pay_and_call spends it</guid>+ <pubDate>Fri, 09 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The Agent MCP server now has a pay_quote tool. It asks a paid x402 endpoint what it charges without paying, and shows who gets paid, how much, in which token and on which chain, which wallet pays, the per-call limit, and anything that would stop the payment. pay_and_call needs the quote_id it returns plus an explicit confirm_payment, so an assistant always shows you the price before your agent wallet pays. One approval pays one call. Before this, turning pay_and_call on still left it refusing every call, because the quote step it requires did not exist.</description>+ </item><item><title>Funding an agent's inference from its wallet now needs the signed real-funds agreements</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex adb715cee..49ff5ff48 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-09T03:00:46.403Z",+ "generated_at": "2026-10-09T03:05:50.411Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/mcp-catalog.json b/public/mcp-catalog.jsonindex 9ef05cb5a..a8e6e2a99 100644--- a/public/mcp-catalog.json+++ b/public/mcp-catalog.json@@ -2,15 +2,15 @@"$comment": "Generated by scripts/build-mcp-catalog.mjs from the tool definitions and price maps in this repo. Do not edit by hand: npm run build:mcp-catalog regenerates it and npm run audit:mcp-catalog fails the build when it is stale.","docs": "https://three.ws/docs/mcp-safety","counts": {- "tools": 368,+ "tools": 369,"servers": 42,- "free": 340,+ "free": 341,"paid": 28,- "read": 247,+ "read": 248,"write": 89,"irreversible": 32,- "withSchema": 368,- "withArguments": 342+ "withSchema": 369,+ "withArguments": 343},"servers": [{@@ -299,7 +299,7 @@"endpoint": "/api/mcp-agent","transport": "remote","auth": "oauth-or-x402",- "tools": 6+ "tools": 7},{"id": "threews-pumpfun",@@ -17571,7 +17571,7 @@{"name": "find_services","title": "Find paid services the agent can call",- "description": "Search the live x402 facilitator network for paid services (HTTP APIs and MCP tools). Returns each match with its price and resource URL. Feed a resource into pay_and_call to actually use it.",+ "description": "Search the live x402 facilitator network for paid services (HTTP APIs and MCP tools). Returns each match with its price and resource URL. To use one, price it with pay_quote, show the user the result, then pay with pay_and_call.","server": {"id": "threews-agent","title": "Agent Wallet",@@ -17712,7 +17712,7 @@{"name": "pay_and_call","title": "Pay an x402 service and return its result",- "description": "Call a paid x402 endpoint and settle the USDC payment automatically from the signed-in user's three.ws agent wallet, bounded by spending caps. Returns the service's response. Requires sign-in. If the per-call price exceeds max_usd (or the caps), the call is refused before any money moves.",+ "description": "Call a paid x402 endpoint and settle the USDC payment automatically from the signed-in user's three.ws agent wallet, bounded by spending caps. Returns the service's response. Requires sign-in. Call pay_quote for the same resource_url first and pay only after the user approves its table. If the per-call price exceeds max_usd (or the caps), the call is refused before any money moves.","server": {"id": "threews-agent","title": "Agent Wallet",@@ -17764,6 +17764,61 @@},"source": "api/_mcpagent/tools.js"},+ {+ "name": "pay_quote",+ "title": "Price an x402 payment without paying",+ "description": "Price a paid x402 endpoint WITHOUT paying: asks the resource for its payment challenge and returns the confirmation table pay_and_call would settle from the signed-in user's agent wallet (recipient, amount, token, chain), the per-call limit that applies, the wallet balance, and anything that would block the payment. Show the table to the user; pay_and_call needs the quote_id this returns, for the same resource_url, and confirm_payment: true after a clear yes.",+ "server": {+ "id": "threews-agent",+ "title": "Agent Wallet",+ "endpoint": "/api/mcp-agent",+ "transport": "remote",+ "auth": "oauth-or-x402"+ },+ "safety": "read",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "price": {+ "usd": 0,+ "free": true+ },+ "inputSchema": {+ "type": "object",+ "properties": {+ "resource_url": {+ "type": "string",+ "format": "uri",+ "description": "The x402 endpoint you intend to pay with pay_and_call."+ },+ "method": {+ "type": "string",+ "enum": [+ "GET",+ "POST"+ ],+ "default": "GET"+ },+ "body": {+ "type": "object",+ "description": "JSON body for POST requests, as pay_and_call will send it."+ },+ "max_usd": {+ "type": "number",+ "minimum": 0,+ "description": "The ceiling you will pass to pay_and_call, so the quote checks the price against it."+ }+ },+ "required": [+ "resource_url"+ ],+ "additionalProperties": false+ },+ "source": "api/_mcpagent/tools.js"+ },{"name": "provision_wallet","title": "Create the agent's wallet",diff --git a/tests/agora-mcp-tools.test.js b/tests/agora-mcp-tools.test.jsindex ae45002a8..33edcfcda 100644--- a/tests/agora-mcp-tools.test.js+++ b/tests/agora-mcp-tools.test.js@@ -4,7 +4,7 @@* node:test suites (packages/agora-mcp/test/*.test.mjs) for the write-tool* early-reject paths; this suite complements them with:*- * 1. the tool-surface contract for ALL nine tools (name/title/description/+ * 1. the tool-surface contract for ALL eleven tools (name/title/description/* inputSchema/handler + read-only vs write annotations), and* 2. the READ tools' real shaping/filtering logic, driven with `apiRequest`* mocked at the HTTP boundary (never a mock in shipped code) so profession /@@ -28,14 +28,19 @@ import { def as passport } from '../packages/agora-mcp/src/tools/passport.js';import { def as pulse } from '../packages/agora-mcp/src/tools/pulse.js';import { def as citizens } from '../packages/agora-mcp/src/tools/citizens.js';-const READ_TOOLS = new Set(['agora_board', 'agora_pulse', 'agora_citizens', 'agora_passport', 'agora_professions']);+// agora_quote_register and agora_quote_task are the previews the spend tools+// (agora_register, agora_post_task) are gated on: read-only, nothing signed.+const READ_TOOLS = new Set([+ 'agora_board', 'agora_pulse', 'agora_citizens', 'agora_passport', 'agora_professions',+ 'agora_quote_register', 'agora_quote_task',+]);const WRITE_TOOLS = new Set(['agora_register', 'agora_claim_task', 'agora_complete_task', 'agora_post_task']);beforeEach(() => {vi.mocked(apiRequest).mockReset();});-describe('tool surface — all nine tools', () => {+describe('tool surface: all eleven tools', () => {it('exposes exactly the expected tool names', () => {const names = TOOLS.map((t) => t.name).sort();expect(names).toEqual(diff --git a/tests/api/mcp-agent-catalog.test.js b/tests/api/mcp-agent-catalog.test.jsindex 3b228bbd8..20d5932bc 100644--- a/tests/api/mcp-agent-catalog.test.js+++ b/tests/api/mcp-agent-catalog.test.js@@ -10,17 +10,56 @@ 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 and 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('quotes with the same arguments pay_and_call spends with', () => {+ const quote = { resource_url: 'https://a.test/x', method: 'POST', body: { q: 1 }, max_usd: 0.05 };+ expect(TOOLS.pay_quote.validate({ ...quote })).toBe(true);+ expect(TOOLS.pay_and_call.validate({ ...quote })).toBe(true);+ expect(TOOLS.pay_quote.validate({ resource_url: 'not a url' })).toBe(false);+ expect(TOOLS.pay_quote.validate({})).toBe(false);+ });+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.jsindex c6322da56..6b04b73e6 100644--- a/tests/api/mcp-agent.test.js+++ b/tests/api/mcp-agent.test.js@@ -31,6 +31,15 @@ vi.mock('../../api/_lib/x402/bazaar-client.js', async (orig) => {return { ...real, Bazaar: class { search(...a) { return bazState.search(...a); } } };});+// ── x402 price probe (the network boundary pay_quote reads) ─────────────────+// probePrice is the only call that leaves the process; selectRail and the rest+// of the module stay real so the quote picks its rail the way production does.+const probeState = { result: null };+vi.mock('../../api/_lib/pay/probe.js', async (orig) => {+ const real = await orig();+ return { ...real, probePrice: vi.fn(async () => probeState.result) };+});+// ── Rate limits ──────────────────────────────────────────────────────────────const rl = { agent: { success: true, reset: 0 }, pay: { success: true, reset: 0 } };vi.mock('../../api/_lib/rate-limit.js', () => ({@@ -47,8 +56,20 @@ vi.mock('../../api/_lib/usage.js', () => ({}));const payer = await import('../../api/_lib/x402-user-payer.js');+const probe = await import('../../api/_lib/pay/probe.js');const { dispatch, isPublicTool } = await import('../../api/_mcpagent/dispatch.js');+// A synthetic seller: one Solana USDC accept for one cent.+const SELLER = 'THREEsyntheticSe11er1111111111111111111111';+function pricedAt(amountAtomics, network = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp') {+ return {+ kind: 'priced',+ status: 402,+ description: null,+ rails: [probe.describeRail({ network, asset: probe.USDC_SOLANA_MINT, payTo: SELLER, amount: String(amountAtomics) })],+ };+}+const ANON = { userId: null, rateKey: 'x402:anon', scope: '', source: 'x402' };const USER = { userId: 'user-1', rateKey: 'user-1', scope: 'wallet:read wallet:write', source: 'bearer' };// Read grant only: may look at the wallet, may never spend from it.@@ -56,8 +77,24 @@ 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);+// Each request names its tool enablement in X-Three-Tools, the way a client+// does, so no test depends on saved settings. `default` is the platform base+// (read and write on, financial off); `x402` turns on the x402 group, which is+// what lets pay_and_call exist for the session at all.+const reqWith = (tools) => ({ url: '/api/mcp-agent', headers: tools ? { 'x-three-tools': tools } : {} });+const PAY_ON = 'default,x402';+const call = (name, args, auth = USER, tools = PAY_ON) =>+ dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, auth, reqWith(tools));++// The full spend path a model has to walk: pay_quote, then pay_and_call with+// the quote_id it returned and confirm_payment: true. `quoteAuth` lets a test+// quote as one token and pay as another for the same account.+async function quoteThenPay(args, auth = USER, { quoteAuth = auth } = {}) {+ const quote = await call('pay_quote', { resource_url: args.resource_url }, quoteAuth);+ const quoteId = quote.result._meta?.['three.ws/preview']?.quote_id;+ expect(quoteId, 'pay_quote issued a quote_id').toMatch(/^q_/);+ return call('pay_and_call', { ...args, quote_id: quoteId, confirm_payment: true }, auth);+}beforeEach(() => {payerState.spendEnabled = true;@@ -67,21 +104,48 @@ beforeEach(() => {payer.payExternalX402.mockClear();payer.getUserWalletStatus.mockClear();bazState.search.mockClear();+ probeState.result = pricedAt(10_000);+ probe.probePrice.mockClear();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);- expect(r.result.tools.map((t) => t.name)).toEqual([+ it('lists the wallet toolset behind a free getting_started tool, with spend tools off by default', async () => {+ const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, USER, reqWith('default'));+ const names = r.result.tools.map((t) => t.name);+ expect(names.slice(0, 8)).toEqual(['getting_started','wallet_status','find_services',- 'pay_and_call',+ 'pay_quote','provision_wallet','monetize_endpoint',+ 'read_resource',+ 'browse_marketplace',]);+ // Every tool that moves funds is financial tier: hidden until the session+ // turns its group on, so a default connection can never spend.+ for (const spend of ['pay_and_call', 'buy_now', 'place_bid', 'accept_marketplace_bid', 'predictions_open', 'predictions_redeem']) {+ expect(names, spend).not.toContain(spend);+ }+ // Every preview a money-moving tool depends on stays visible.+ expect(names).toEqual(expect.arrayContaining(['pay_quote', 'preview_marketplace_action', 'predictions_open_preview']));+ });++ it('shows pay_and_call, with its confirm flag and quote_id, once the x402 group is on', async () => {+ const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, USER, reqWith(PAY_ON));+ const pay = r.result.tools.find((t) => t.name === 'pay_and_call');+ expect(pay).toBeDefined();+ expect(pay._meta['three.ws/policy']).toMatchObject({+ group: 'x402',+ tier: 'financial',+ confirmFlag: 'confirm_payment',+ previewTool: 'pay_quote',+ previewArg: 'quote_id',+ });+ expect(Object.keys(pay.inputSchema.properties)).toEqual(expect.arrayContaining(['confirm_payment', 'quote_id']));+ expect(pay.description).toContain('Call pay_quote first');});it('getting_started is free and callable with no sign-in', async () => {@@ -157,23 +221,104 @@ describe('threews-agent MCP', () => {expect(r.result.structuredContent.services[0]).toMatchObject({ resource: 'https://svc.test', price: '$0.01' });});+ it('pay_quote prices the endpoint without paying and issues a quote_id', async () => {+ payerState.walletStatus = {+ provisioned: true,+ address: 'SoLaddr',+ balances: { sol: 0.2, usdc: 5 },+ spend_enabled: true,+ caps: { max_per_call_usdc: 0.1, max_per_hour_usdc: 1, max_per_day_usdc: 10 },+ };+ const r = await call('pay_quote', { resource_url: 'https://paid.test/weather' });+ expect(probe.probePrice).toHaveBeenCalledWith('https://paid.test/weather', { method: 'GET', body: null });+ expect(payer.payExternalX402).not.toHaveBeenCalled();+ expect(r.result.isError).toBeUndefined();+ expect(r.result.structuredContent).toMatchObject({+ ok: true,+ recipient: SELLER,+ amount_usd: 0.01,+ token: 'USDC',+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ from: 'SoLaddr',+ per_call_limit_usd: 0.1,+ blockers: [],+ });+ const text = r.result.content.map((c) => c.text).join('\n');+ expect(text).toContain(`Recipient: ${SELLER}`);+ expect(text).toContain('Amount: 0.01 USDC');+ expect(text).toContain('Chain: Solana');+ expect(r.result._meta['three.ws/preview']).toMatchObject({ unlocks: ['pay_and_call'] });+ });++ it('pay_quote refuses, and issues no quote_id, for a price over the per-call limit', async () => {+ probeState.result = pricedAt(250_000);+ const r = await call('pay_quote', { resource_url: 'https://paid.test/x', max_usd: 0.05 });+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent.blockers.map((b) => b.code)).toContain('over_per_call_limit');+ expect(r.result._meta?.['three.ws/preview']).toBeUndefined();+ });++ it('pay_quote refuses an endpoint that cannot be paid on Solana', async () => {+ probeState.result = pricedAt(10_000, 'eip155:8453');+ const r = await call('pay_quote', { resource_url: 'https://paid.test/x' });+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent).toMatchObject({ reason: 'no_solana_rail', networks: ['eip155:8453'] });+ expect(r.result._meta?.['three.ws/preview']).toBeUndefined();+ });++ it('pay_quote passes an unreachable endpoint through as a designed refusal', async () => {+ probeState.result = { kind: 'error', code: 'blocked_url', message: 'Target URL is not a reachable public endpoint' };+ const r = await call('pay_quote', { resource_url: 'https://paid.test/x' });+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent.reason).toBe('blocked_url');+ expect(r.result.content[0].text).toContain('Nothing was paid.');+ });++ it('pay_and_call is turned off until the session enables the x402 group', async () => {+ const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' }, USER, 'default');+ expect(payer.payExternalX402).not.toHaveBeenCalled();+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent).toMatchObject({ reason: 'tool_disabled', tool: 'pay_and_call', group: 'x402', tier: 'financial' });+ expect(r.result.content[0].text).toContain('X-Three-Tools: x402');+ });++ it('pay_and_call refuses without confirm_payment, then without a quote, before any payment call', async () => {+ const noConfirm = await call('pay_and_call', { resource_url: 'https://paid.test/x' });+ expect(noConfirm.result.structuredContent).toMatchObject({ reason: 'confirmation_required', confirm_flag: 'confirm_payment', preview_tool: 'pay_quote' });+ const noQuote = await call('pay_and_call', { resource_url: 'https://paid.test/x', confirm_payment: true });+ expect(noQuote.result.structuredContent).toMatchObject({ reason: 'preview_required', preview_arg: 'quote_id' });+ const unknown = await call('pay_and_call', { resource_url: 'https://paid.test/x', confirm_payment: true, quote_id: 'q_aaaaaaaaaaaaaaaaaaaaaaaa' });+ expect(unknown.result.structuredContent.reason).toBe('preview_unknown');+ expect(payer.payExternalX402).not.toHaveBeenCalled();+ });++ it('pay_and_call refuses a quote_id issued for a different resource', async () => {+ const quote = await call('pay_quote', { resource_url: 'https://paid.test/cheap' });+ const quoteId = quote.result._meta['three.ws/preview'].quote_id;+ const r = await call('pay_and_call', { resource_url: 'https://paid.test/other', quote_id: quoteId, confirm_payment: true });+ expect(r.result.structuredContent).toMatchObject({ reason: 'preview_mismatch' });+ expect(payer.payExternalX402).not.toHaveBeenCalled();+ });+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 });+ // The policy-only arguments (quote_id, confirm_payment) never reach the payer.+ expect(payer.payExternalX402).toHaveBeenCalledTimes(1);expect(payer.payExternalX402).toHaveBeenCalledWith({userId: 'user-1',url: 'https://paid.test/weather',@@ -184,16 +329,40 @@ describe('threews-agent MCP', () => {expect(r.result.structuredContent).toMatchObject({ paid: true, payer: 'SoLaddr', result: { temp: 72 } });});+ it('spends a quote_id once: one approval pays one call', async () => {+ payerState.payResult = { ok: true, payer: 'SoLaddr', result: { temp: 72 }, receipt: { tx: 'sig' } };+ const quote = await call('pay_quote', { resource_url: 'https://paid.test/weather' });+ const args = {+ resource_url: 'https://paid.test/weather',+ quote_id: quote.result._meta['three.ws/preview'].quote_id,+ confirm_payment: true,+ };+ const first = await call('pay_and_call', args);+ expect(first.result.structuredContent.paid).toBe(true);+ const replay = await call('pay_and_call', args);+ expect(replay.result.structuredContent.reason).toBe('preview_unknown');+ expect(payer.payExternalX402).toHaveBeenCalledTimes(1);+ });+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('pay_quote tells a read-only token it cannot spend and issues it no quote_id', async () => {+ const r = await call('pay_quote', { resource_url: 'https://paid.test/x' }, READONLY);+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent.blockers.map((b) => b.code)).toContain('insufficient_scope');+ expect(r.result._meta?.['three.ws/preview']).toBeUndefined();+ });+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);+ // Same account, so a quote issued to its full-scope token passes the+ // policy gate; the handler's own wallet:write check must still refuse.+ const r = await quoteThenPay({ resource_url: 'https://paid.test/x' }, READONLY, { quoteAuth: USER });expect(payer.payExternalX402).not.toHaveBeenCalled();expect(r.result.isError).toBe(true);expect(r.result.structuredContent).toMatchObject({@@ -204,7 +373,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=');});@@ -217,8 +386,13 @@ describe('threews-agent MCP', () => {});it('enforces the pay rate limit before spending', async () => {+ const quote = await call('pay_quote', { resource_url: 'https://paid.test/x' });rl.pay = { success: false, reset: Date.now() + 30000 };- const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' });+ const r = await call('pay_and_call', {+ resource_url: 'https://paid.test/x',+ quote_id: quote.result._meta['three.ws/preview'].quote_id,+ confirm_payment: true,+ });expect(r.error.code).toBe(-32000);expect(payer.payExternalX402).not.toHaveBeenCalled();});diff --git a/tests/api/mcp-bazaar-challenge.test.js b/tests/api/mcp-bazaar-challenge.test.jsindex d9310e5d3..eed7a3d53 100644--- a/tests/api/mcp-bazaar-challenge.test.js+++ b/tests/api/mcp-bazaar-challenge.test.js@@ -145,6 +145,8 @@ describe('POST /api/mcp-bazaar: free discovery for plain clients', () => {'browse_services','get_service','bazaar_service_details',+ // Live three:// resources (three://x402/services and friends), read-only.+ 'read_resource',]);});diff --git a/tests/api/mcp-bazaar.test.js b/tests/api/mcp-bazaar.test.jsindex 4e3d3bed5..731b6f0e5 100644--- a/tests/api/mcp-bazaar.test.js+++ b/tests/api/mcp-bazaar.test.js@@ -92,6 +92,8 @@ describe('x402 Bazaar MCP', () => {'browse_services','get_service','bazaar_service_details',+ // Live three:// resources (three://x402/services and friends), read-only.+ 'read_resource',]);});diff --git a/tests/api/mcp-memory.test.js b/tests/api/mcp-memory.test.jsindex 255d14593..edf4b4f13 100644--- a/tests/api/mcp-memory.test.js+++ b/tests/api/mcp-memory.test.js@@ -180,12 +180,20 @@ function makeRes() {};}-async function call(name, args, { scope = 'memory:read memory:write' } = {}) {+// Every request names its tool enablement in X-Three-Tools, the way a client+// does, so the policy never reads saved settings through the queued sql mock+// above. `default` is the platform base: read and write on, financial off.+// forget deletes a memory for good, so the policy keeps it financial tier: off+// until named, and refused without confirm_delete and a fresh preview_id from+// recall for the same agent.+const FORGET_ON = 'default,forget';++async function call(name, args, { scope = 'memory:read memory:write', tools = 'default' } = {}) {authState.extracted = 'valid-token';authState.bearer = { userId: 'user-1', scope, source: 'oauth' };const req = makeReq({body: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } },- headers: { authorization: 'Bearer valid-token' },+ headers: { authorization: 'Bearer valid-token', 'x-three-tools': tools },});const res = makeRes();await handler(req, res);@@ -195,6 +203,19 @@ async function call(name, args, { scope = 'memory:read memory:write' } = {}) {const AGENT_ID = '11111111-1111-4111-8111-111111111111';const MEM_ID = '22222222-2222-4222-8222-222222222222';+// recall is forget's preview: the caller sees what is stored, then deletes one+// memory with the preview_id recall returned. Queues the two recall queries+// (ownsAgent, candidates) and hands back that id.+async function recallPreviewId() {+ sqlState.queue = [[{ user_id: 'user-1' }], []];+ const { body } = await call('recall', { agent_id: AGENT_ID, query: 'anything' }, { tools: FORGET_ON });+ const previewId = body.result._meta?.['three.ws/preview']?.preview_id;+ expect(previewId, 'recall issued a preview_id').toMatch(/^p_/);+ return previewId;+}++const forgetArgs = (previewId) => ({ memory_id: MEM_ID, agent_id: AGENT_ID, preview_id: previewId, confirm_delete: true });+beforeEach(() => {authState.extracted = null;authState.bearer = null;@@ -270,10 +291,43 @@ describe('ownership', () => {});it('forget refuses a memory owned by another user', async () => {+ const previewId = await recallPreviewId();sqlState.queue = [[{ id: MEM_ID, user_id: 'someone-else' }]];- const { body } = await call('forget', { memory_id: MEM_ID });+ sqlState.calls = [];+ const { body } = await call('forget', forgetArgs(previewId), { tools: FORGET_ON });expect(body.result.isError).toBe(true);expect(body.result.content[0].text).toMatch(/does not belong to you/i);+ expect(sqlState.calls.some((c) => /DELETE/i.test(c.query))).toBe(false);+ });+});++// ── The forget policy gate ───────────────────────────────────────────────────+describe('forget policy gate', () => {+ it('is turned off for a default connection and touches no row', async () => {+ const { body } = await call('forget', { memory_id: MEM_ID, agent_id: AGENT_ID });+ expect(body.result.isError).toBe(true);+ expect(body.result.structuredContent).toMatchObject({ reason: 'tool_disabled', tool: 'forget', tier: 'financial' });+ expect(sqlState.calls).toEqual([]);+ });++ it('refuses without confirm_delete, then without a preview, before any query', async () => {+ const noConfirm = await call('forget', { memory_id: MEM_ID, agent_id: AGENT_ID }, { tools: FORGET_ON });+ expect(noConfirm.body.result.structuredContent).toMatchObject({ reason: 'confirmation_required', confirm_flag: 'confirm_delete', preview_tool: 'recall' });+ const noPreview = await call('forget', { memory_id: MEM_ID, agent_id: AGENT_ID, confirm_delete: true }, { tools: FORGET_ON });+ expect(noPreview.body.result.structuredContent).toMatchObject({ reason: 'preview_required' });+ expect(sqlState.calls).toEqual([]);+ });++ it('refuses a preview_id recall issued for a different agent', async () => {+ const previewId = await recallPreviewId();+ sqlState.calls = [];+ const { body } = await call(+ 'forget',+ { ...forgetArgs(previewId), agent_id: '33333333-3333-4333-8333-333333333333' },+ { tools: FORGET_ON },+ );+ expect(body.result.structuredContent).toMatchObject({ reason: 'preview_mismatch' });+ expect(sqlState.calls).toEqual([]);});});@@ -356,13 +410,17 @@ describe('round trip', () => {});it('forgets a memory the caller owns', async () => {+ const previewId = await recallPreviewId();sqlState.queue = [[{ id: MEM_ID, user_id: 'user-1' }], // ownership join[], // DELETE];- const { body } = await call('forget', { memory_id: MEM_ID });+ const { body } = await call('forget', forgetArgs(previewId), { tools: FORGET_ON });expect(body.error).toBeUndefined();expect(body.result.structuredContent).toEqual({ ok: true, id: MEM_ID });expect(body.result.content[0].text).toContain(MEM_ID);+ // The preview authorized one deletion and is spent now.+ const replay = await call('forget', forgetArgs(previewId), { tools: FORGET_ON });+ expect(replay.body.result.structuredContent.reason).toBe('preview_unknown');});});diff --git a/tests/fixtures/mcp-golden-tools.json b/tests/fixtures/mcp-golden-tools.jsonindex e9baccc62..d791adbf4 100644--- a/tests/fixtures/mcp-golden-tools.json+++ b/tests/fixtures/mcp-golden-tools.json@@ -1305,7 +1305,7 @@"name": "find_services","title": "Find paid services the agent can call","descHead": "Search the live x402 facilitator network for paid services (HTTP APIs an",- "descHash": "0a3c1fdcaf27",+ "descHash": "96a31531545e","annotations": {"readOnlyHint": true,"destructiveHint": false,@@ -1331,7 +1331,7 @@"name": "pay_and_call","title": "Pay an x402 service and return its result","descHead": "Call a paid x402 endpoint and settle the USDC payment automatically from",- "descHash": "590dd66c69e6",+ "descHash": "a0fb0d23ab91","annotations": {"readOnlyHint": false,"destructiveHint": true,@@ -1340,6 +1340,19 @@},"schemaHash": "9c9654820288"},+ {+ "name": "pay_quote",+ "title": "Price an x402 payment without paying",+ "descHead": "Price a paid x402 endpoint WITHOUT paying: asks the resource for its pay",+ "descHash": "169881373481",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "b61b0648b6a8"+ },{"name": "provision_wallet","title": "Create the agent's wallet",diff --git a/tests/mcp-remote-annotations.test.js b/tests/mcp-remote-annotations.test.jsindex ec2980e0b..15ef4a6fa 100644--- a/tests/mcp-remote-annotations.test.js+++ b/tests/mcp-remote-annotations.test.js@@ -9,30 +9,46 @@ import { TOOL_CATALOG as studioCatalog } from '../api/_mcp3d/catalog.js';import { TOOL_CATALOG as agentCatalog } from '../api/_mcpagent/catalog.js';import { TOOL_CATALOG as ibmCatalog } from '../api/_mcpibm/catalog.js';import { TOOL_CATALOG as bazaarCatalog } from '../api/_mcpbazaar/catalog.js';+import { POLICY } from '../packages/mcp-policy/src/table.js';+// [label, catalog, @three-ws/mcp-policy server id]const CATALOGS = [- ['three.ws main (/api/mcp)', mainCatalog],- ['3D Studio (/api/mcp-3d)', studioCatalog],- ['Agent (/api/agent-mcp)', agentCatalog],- ['IBM Granite (/api/ibm-mcp)', ibmCatalog],- ['x402 Bazaar (/api/bazaar-mcp)', bazaarCatalog],+ ['three.ws main (/api/mcp)', mainCatalog, 'three.ws'],+ ['3D Studio (/api/mcp-3d)', studioCatalog, 'threews-3d-studio'],+ ['Agent (/api/agent-mcp)', agentCatalog, 'threews-agent'],+ ['IBM Granite (/api/ibm-mcp)', ibmCatalog, 'ibm-x402-mcp-remote'],+ ['x402 Bazaar (/api/bazaar-mcp)', bazaarCatalog, 'threews-x402-bazaar'],];// The ONLY tools across all five hosted servers allowed to advertise-// destructiveHint: true. Everything else must set it explicitly to false —+// destructiveHint: true. Everything else must set it explicitly to false;// the MCP spec defaults destructiveHint to TRUE when omitted, so an absent// hint silently marks a tool destructive.-// delete_avatar — permanently removes a user's avatar-// forget — deletes a stored agent memory-// pay_and_call — spends the user's USDC (irreversible transfer)-// persona_tip — spends a persona's own USDC (irreversible transfer)-// persona_send - spends a persona's own USDC (irreversible transfer)-// home_activate - runs a scene or script in a real house, which moves locks,-// covers and alarms in the physical world-// home_call - calls an arbitrary Home Assistant service, so it can unlock a-// door or open a garage-// delete_custom_skill - permanently removes a skill an owner may have written-// by hand; gated on confirm_delete+//+// Deleting what cannot be regenerated:+// delete_avatar permanently removes a user's avatar+// forget deletes a stored agent memory+// delete_custom_skill permanently removes a skill an owner may have written+// by hand; gated on confirm_delete+// Moving money (an irreversible transfer or an on-chain transaction):+// pay_and_call spends the user's USDC on an x402 endpoint+// persona_tip, persona_send spend a persona's own USDC+// agent_card_create buys a card or gift card with the agent's funds+// agent_card_reveal exposes a card's secret number or code, once+// agent_card_cancel, agent_card_withdraw close a card or pull its funds+// paired_launch launches a coin and its opening buy on Robinhood Chain+// paired_claim_fees signs and broadcasts the fee-collection transaction on+// Robinhood Chain (marked destructive on 2026-10-09)+// create_marketplace_listing, delist_marketplace_listing, place_bid,+// buy_now, accept_marketplace_bid, withdraw_marketplace_bid+// commit an agent or move USDC through marketplace escrow+// predictions_open, predictions_close, predictions_redeem+// trade or settle prediction-market positions in USDC+// Acting on the physical world:+// home_activate runs a scene or script in a real house, which moves+// locks, covers and alarms+// home_call calls an arbitrary Home Assistant service, so it can+// unlock a door or open a garage//// The two home tools are the reason this list is not just about money. Marking// them non-destructive would tell every MCP client that opening someone's front@@ -41,15 +57,28 @@ const CATALOGS = [// future home tool is genuinely read-only it belongs outside this set; anything// that reaches an actuator belongs inside it.const DESTRUCTIVE_TOOLS = new Set([- 'delete_avatar', 'forget', 'pay_and_call', 'persona_tip', 'persona_send',- 'home_activate', 'home_call', 'delete_custom_skill',+ 'delete_avatar', 'forget', 'delete_custom_skill',+ 'pay_and_call', 'persona_tip', 'persona_send',+ 'agent_card_create', 'agent_card_reveal', 'agent_card_cancel', 'agent_card_withdraw',+ 'paired_launch', 'paired_claim_fees',+ 'create_marketplace_listing', 'delist_marketplace_listing', 'place_bid', 'buy_now',+ 'accept_marketplace_bid', 'withdraw_marketplace_bid',+ 'predictions_open', 'predictions_close', 'predictions_redeem',+ 'home_activate', 'home_call',]);+// Destructive tools the policy deliberately leaves in the write tier (on by+// default, no confirm flag). paired_claim_fees collects fees into the agent's+// own wallet, so nothing leaves the owner's control. Every other destructive+// tool must be financial tier: off until the session enables it, and refused+// without its confirm flag.+const DESTRUCTIVE_WRITE_TIER = new Set(['paired_claim_fees']);+// Internal/spec-only fields that must never leak into the tools/list wire// payload.const FORBIDDEN_WIRE_FIELDS = ['handler', 'scope', 'example', 'output'];-describe.each(CATALOGS)('%s — tools/list catalog', (label, catalog) => {+describe.each(CATALOGS)('%s: tools/list catalog', (label, catalog, serverId) => {it('is a non-empty array', () => {expect(Array.isArray(catalog)).toBe(true);expect(catalog.length).toBeGreaterThan(0);@@ -101,6 +130,27 @@ describe.each(CATALOGS)('%s — tools/list catalog', (label, catalog) => {}});+ it('gates every destructive tool behind the financial policy tier', () => {+ const rows = POLICY[serverId];+ for (const tool of catalog) {+ if (tool.annotations?.destructiveHint !== true || DESTRUCTIVE_WRITE_TIER.has(tool.name)) continue;+ const row = rows[tool.name];+ expect(row?.tier, `${tool.name}: policy tier`).toBe('financial');+ expect(row?.confirmFlag, `${tool.name}: confirm flag`).toMatch(/^confirm_/);+ }+ });++ it('serves the preview tool every financial tool is gated on', () => {+ // The policy refuses a financial tool without a fresh id from its preview+ // tool, so a preview this server does not serve leaves the tool+ // uncallable (pay_and_call once named a pay_quote nobody registered).+ const names = new Set(catalog.map((t) => t.name));+ for (const [name, row] of Object.entries(POLICY[serverId])) {+ if (!names.has(name) || !row.previewTool) continue;+ expect(names.has(row.previewTool), `${name} needs ${row.previewTool}`).toBe(true);+ }+ });+it('never leaks internal fields onto the wire', () => {for (const tool of catalog) {for (const field of FORBIDDEN_WIRE_FIELDS) {@@ -111,7 +161,7 @@ describe.each(CATALOGS)('%s — tools/list catalog', (label, catalog) => {});describe('destructive set across all five servers', () => {- it('is exactly { delete_avatar, forget, pay_and_call, persona_tip, persona_send }', () => {+ it('is exactly the pinned DESTRUCTIVE_TOOLS set', () => {const destructive = new Set();for (const [, catalog] of CATALOGS) {for (const tool of catalog) {