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(x402): a paid call that fails after settlement says paid and retry-safe and re-runs on the same payment, POST bodies join the idempotency hash, MCP docs gain tool-call use cases
nirholas353a5a177845
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.jsindex ab1ef5908..5fcd1786b 100644--- a/api/_lib/x402-paid-endpoint.js+++ b/api/_lib/x402-paid-endpoint.js@@ -29,7 +29,7 @@// helper. Missing keys fall back to env (so a single override doesn't// disable the other networks).-import { cors, error, respondError, rateLimited, wrap } from './http.js';+import { cors, error, readBody, respondError, rateLimited, wrap } from './http.js';import { env } from './env.js';import { clientIp, limits } from './rate-limit.js';import { logPaymentEvent } from './x402/audit-log.js';@@ -75,7 +75,15 @@ import { normalizeBazaarEntry } from './x402/bazaar-helpers.js';import { buildOffersExtension, buildReceiptExtension } from './x402/offer-receipt-server.js';import { signReceipt } from './x402-offer-receipt.js';import { recordReceipt } from './x402/receipt-storage.js';-import { claimSpentPayment, isPaymentSpent, writeReplayed } from './x402/spent-payments.js';+import {+ claimPaidRetry,+ claimSpentPayment,+ isPaymentSpent,+ markDelivered,+ markFailedAfterSettle,+ paidFailureFields,+ writeReplayed,+} from './x402/spent-payments.js';import {authenticateAuthHintsRequest,declareAuthHintsExtension,@@ -291,6 +299,66 @@ export function buildRequirements({ priceAtomics, networks, resourceUrl, payToOvreturn out;}+/**+ * The request body for the idempotency hash. GET and HEAD carry none. The Cloud+ * Run server pre-parses bodies onto `req.rawBody` or `req.body`; when neither is+ * set the stream is read here and parked on `req.rawBody`, which the handler's+ * own `readJson` consults first, so hashing never starves it of its body.+ */+async function bodyForHash(req) {+ if (req.method === 'GET' || req.method === 'HEAD') return null;+ if (Buffer.isBuffer(req.rawBody)) return req.rawBody;+ if (req.body !== undefined) return req.body;+ const buf = await readBody(req, 2_000_000);+ req.rawBody = buf;+ return buf;+}++/**+ * Answer a failure that happened AFTER the buyer's payment settled. Records the+ * failure against the spent proof (so the same X-PAYMENT header may re-run the+ * work instead of answering 409) and tells the client plainly that it paid and+ * whether retrying is safe: `paid`, `retry_safe`, the settlement transaction and+ * a sentence a human can act on.+ *+ * @param {import('node:http').ServerResponse} res+ * @param {object} args+ * @param {string|null} args.paymentHash Hash of the signed X-PAYMENT proof.+ * @param {object} args.settlement Stored blob: { transaction, network, settled, requirement, payer, header }.+ * @param {Error & { status?: number, code?: string }} args.err+ * @param {{ endpoint: string, amountAtomics: string|number|null }} [args.claim]+ * Pass when no spent row exists yet (the failure came before the claim), so+ * one is written as `failed_after_settle`.+ */+async function respondFailedAfterSettle(res, { paymentHash, settlement, err, claim }) {+ const lastError = err?.message || String(err);+ if (claim) {+ await claimSpentPayment({+ paymentHash,+ endpoint: claim.endpoint,+ amountAtomics: claim.amountAtomics,+ outcome: 'failed_after_settle',+ settlement,+ lastError,+ });+ }+ const { retriesLeft, retryUntil } = await markFailedAfterSettle({ paymentHash, settlement, lastError });+ const status = err?.status >= 400 && err?.status < 600 ? err.status : 500;+ const code = err?.code || (status === 502 ? 'siwx_record_failed' : 'internal_error');+ console.error(`[x402] failure after settlement (${code}, tx ${settlement?.transaction ?? 'unknown'}):`, lastError);+ res.statusCode = status;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('cache-control', 'no-store');+ res.end(+ JSON.stringify({+ error: code,+ error_description:+ status < 500 && err?.message ? err.message : 'the paid work failed after your payment settled',+ ...paidFailureFields({ settlement, retriesLeft, retryUntil }),+ }),+ );+}+// `spec.bazaar` is the v2 discoverable extension shape: { discoverable: true,// info: { input, output }, schema }. See model-check.js for a worked example.// `spec.handler({ req, res, requirement, payer })` is called only AFTER the@@ -872,15 +940,20 @@ export function paidEndpoint(spec) {throw err;}- // USE-15: deduplicate before /verify. Hashing the request URL is enough- // for our GET-only paid endpoints — none of them read request bodies.- // When/if a POST endpoint joins the family, the handler can buffer- // `req.body` and pass it in here.+ // USE-15: deduplicate before /verify. The hash covers method, URL and the+ // request body, so two different POST bodies sent under one payment+ // identifier never share a cached response. GET and HEAD carry no body.const clientPaymentId = extractIdFromHeader(paymentHeader);+ let requestBody = null;+ try {+ requestBody = await bodyForHash(req);+ } catch (err) {+ return error(res, err.status || 400, 'invalid_body', err.message);+ }const payloadHash = hashRequestPayload({method: req.method,url: req.url,- body: null,+ body: requestBody,});// Bind the idempotency cache to the signed payment proof so a stolen or// guessed payment-identifier can't redeem a prior paid response for free.@@ -952,10 +1025,77 @@ export function paidEndpoint(spec) {// the concurrent-race window runs at the end of settlement below. Fails// OPEN on a DB outage — see api/_lib/x402/spent-payments.js for why this// control's failure policy is the inverse of settle-credit's.+ // Re-run the work for a proof that settled but failed. `stored` is the+ // settlement blob written when the failure was recorded.+ async function runPaidRetry(stored) {+ const settled = stored.settled || { transaction: stored.transaction, network: stored.network };+ const retryRequirement = stored.requirement || null;+ const retryPayer = stored.payer || settled.payer || null;+ const header = stored.header || encodePaymentResponseHeader(settled);+ try {+ if (siwx && retryPayer && retryRequirement) {+ await recordSiwxPayment({+ resourceUrl,+ payer: normalizeAddress(retryRequirement.network, retryPayer),+ network: retryRequirement.network,+ ttlSeconds: siwx.ttlSeconds ?? null,+ });+ }+ if (streaming) {+ res.setHeader('x-payment-response', header);+ res.setHeader('cache-control', 'no-store');+ }+ const retried = await handler({+ req,+ res,+ requirement: retryRequirement,+ payer: retryPayer,+ ...(streaming ? { settled } : {}),+ });+ if (ownsReservation) await releaseSlot({ route, paymentId });+ if (!res.writableEnded) {+ const contentType = `${mimeType}; charset=utf-8`;+ const retryBody = typeof retried === 'string' ? retried : JSON.stringify(retried);+ res.setHeader('x-payment-response', header);+ res.setHeader('cache-control', 'no-store');+ res.setHeader('content-type', contentType);+ res.end(retryBody);+ }+ await markDelivered(paymentHash);+ } catch (err) {+ if (ownsReservation) await releaseSlot({ route, paymentId });+ if (res.writableEnded) return;+ return await respondFailedAfterSettle(res, { paymentHash, settlement: stored, err });+ }+ }+if (paymentHash) {let spent = await isPaymentSpent(paymentHash);const legacyHash = legacyPaymentProofHash(paymentHeader);if (!spent.spent && legacyHash && legacyHash !== paymentHash) spent = await isPaymentSpent(legacyHash);+ // Charged but not served: the work failed after this proof settled. Re-run+ // it for the same header, with no second verify or settle (the payment is+ // already on chain), a bounded number of times inside the retry window.+ if (spent.spent && spent.retryable && spent.endpoint === route) {+ const retry = await claimPaidRetry({ paymentHash, endpoint: route });+ if (retry.granted) {+ return await runPaidRetry(retry.settlement || {});+ }+ }+ if (spent.spent && spent.outcome === 'failed_after_settle') {+ if (ownsReservation) await releaseSlot({ route, paymentId });+ res.statusCode = 409;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('cache-control', 'no-store');+ res.setHeader('x-x402-idempotent', 'replayed');+ return res.end(+ JSON.stringify({+ error: 'payment_retries_exhausted',+ route,+ ...paidFailureFields({ settlement: spent.settlement, retriesLeft: 0 }),+ }),+ );+ }if (spent.spent) {logPaymentEvent({eventType: 'payment_replay_rejected',@@ -1032,6 +1172,22 @@ export function paidEndpoint(spec) {// runs; deliver-then-settle calls it after the handler returned a value.// On any settle/SIWX fault it writes the error response and returns null,// and the caller returns immediately.+ // What a retry needs once the payment has settled: the settlement for+ // the x-payment-response header and the context the handler ran with.+ let settledForRetry = null;+ let headerForRetry = null;+ function settlementBlob() {+ const settled = settledForRetry;+ return {+ transaction: settled?.transaction ?? null,+ network: settled?.network ?? verified.requirement?.network ?? null,+ settled,+ requirement: verified.requirement,+ payer: verified.payer || null,+ header: headerForRetry,+ };+ }+async function settleAndBuildResponse() {let settled;try {@@ -1064,6 +1220,8 @@ export function paidEndpoint(spec) {return null;}+ settledForRetry = settled;+// Record the SIWX grant so the wallet can re-access via signature next// time. siwx-storage.recordPayment is idempotent (upsert on PK), so a// retried settle is safe. The on-chain payment is final; if Neon@@ -1087,7 +1245,15 @@ export function paidEndpoint(spec) {metadata: { ttlSeconds: siwx.ttlSeconds ?? null },});} catch (err) {- respondError(res, 502, 'siwx_record_failed', err);+ // The buyer's money moved. Record the proof as charged-but-unserved+ // so the same header can retry, and say so in the response.+ if (ownsReservation) await releaseSlot({ route, paymentId });+ await respondFailedAfterSettle(res, {+ paymentHash,+ settlement: settlementBlob(),+ err: Object.assign(new Error(err.message), { status: 502, code: 'siwx_record_failed' }),+ claim: { endpoint: route, amountAtomics: verified.requirement?.amount ?? null },+ });return null;}}@@ -1206,6 +1372,7 @@ export function paidEndpoint(spec) {}const paymentResponseHeader = encodePaymentResponseHeader(settled, responseExtensions);+ headerForRetry = paymentResponseHeader;return { settled, paymentResponseHeader };}@@ -1299,10 +1466,14 @@ export function paidEndpoint(spec) {recordSettledSuccess(settled);return;}- if (err instanceof X402Error && err.status === 402) {- return await send402(res, { ...challenge, error: err.message });- }- return respondError(res, err.status || 500, err.code || 'internal_error', err);+ // Charged and not served: record it against the spent proof so the+ // same header may retry, and tell the buyer they paid. Even a handler+ // 402 lands here; asking someone who just paid to pay again is the bug.+ return await respondFailedAfterSettle(res, {+ paymentHash,+ settlement: settlementBlob(),+ err,+ });}if (ownsReservation) await releaseSlot({ route, paymentId });diff --git a/data/changelog.json b/data/changelog.jsonindex 32ddbfe23..0ae987676 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -29188,6 +29188,13 @@"summary": "pump.fun's October program update changed where creator rewards land: newer trades leave the creator fee on the coin's bonding curve or pool until someone sweeps it into the creator's vault. Without handling that, those rewards were invisible to a claim and read as already claimed on coin pages. Every claim on three.ws now sweeps your coins first and collects everything in the same transaction, from your wallet, an agent wallet or the automatic claimer. Reward balances, coin pages and earnings history count the held fees as unclaimed, fee-sharing changes and distributions no longer fail on unswept fees, and the biggest buy a coin ever sees (the one that completes its curve) is now reported at its full size in trade feeds and whale alerts. The automatic claimer for agent sniper wallets also had a bug that stopped every claim; that is fixed.","tags": ["improvement", "fix"],"link": "/launch"+ },+ {+ "date": "2026-10-09",+ "title": "A paid call that fails after payment now tells you to retry, not to pay again",+ "summary": "If a paid x402 call fails after your payment has already settled, the response now says so: paid, retry safe, the settlement transaction, and how many retries are left. Repeat the exact same request with the same payment and the server re-runs the work without charging you again, instead of answering that the payment was already used. Paid POST routes also now tell apart two different request bodies sent under one payment identifier. The MCP docs gained a Use cases section that spells out every guided prompt as the ordered tool calls it makes, with the steps that spend money marked, and a test keeps it in step with the real tools.",+ "tags": ["improvement", "docs"],+ "link": "/docs/x402"}]}diff --git a/docs/api-reference.md b/docs/api-reference.mdindex b6e522bde..2b928c1d3 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -8544,6 +8544,9 @@ Session cookie required; writes must be same-site. `POST` answers `201` with `{| `forbidden` | 403 | write from another origin || `not_found` | 404 | token or agent is not the caller's || `too_many_tokens` | 409 | 12 live tokens already |+| `payment_replayed` | 409 | An x402 payment proof that already bought its result is being used again | No | Pay again to buy it a second time; to re-read a result you already paid for, use the receipt or sign in with the paying wallet |+| any code, with `paid: true` and `retry_safe: true` | 500, 502 | An x402 call failed AFTER your payment settled. You were charged and the work was not delivered. The body carries `settlement.transaction`, `retries_left` and `retry_until` | Yes, with the same payment | Repeat the exact request with the same `X-PAYMENT` header. Do not pay again ([x402](/docs/x402)) |+| `payment_retries_exhausted`, or `paid: true` with `retry_safe: false` | 409, 5xx | A paid call kept failing and the proof used up its retries | No | Contact support with `settlement.transaction`; you were charged and it will be made right || `rate_limited` | 429 | over the per-account write limit |## Trading guidance APIdiff --git a/docs/mcp.md b/docs/mcp.mdindex e2c8e28e5..62188bf1f 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -1086,6 +1086,175 @@ Every prompt that can move funds ends with the same rules: show the recipient, a---+## Use cases++Each guided prompt is a workflow written as the calls an agent makes, in order. Read it as a script: the goal in one line, then the exact tool calls (`name()`) and resource reads (`three://...`) the prompt drives. A step marked **spends money** moves funds or bills credits, and always waits for an explicit yes from you first. Every other step is read-only or creates a record without moving funds. The tool names here are checked against the live `tools/list` of all four servers by `tests/mcp-use-cases-doc.test.js`, so this section cannot name a tool that no longer exists.++Where a flow's executing venue (swaps, launches, perps, lending, predictions) is not enabled on the MCP server yet, the prompt does the research with the tools that exist and sends you to the web page where you confirm the action yourself.++### `get-started`++Goal: learn what a server does and pick the best next step. Server: all four (the first call is the same everywhere).++1. `getting_started()` to summarize what the server can do.+2. Read `three://me`. If you are not signed in, connect with OAuth or an API key from `/dashboard/api-keys`, then stop.+3. Read `three://agents` to list your agents with their Solana addresses.+4. Pick a next prompt from the ones the server lists.++### `create-agent`++Goal: create an agent with a persona and model, then give it a body. Server: `mcp`.++1. Read `three://models` and confirm the model you want is available.+2. `identity_check()` to catch a look-alike of an existing public agent.+3. Review the name, persona and model with the user.+4. `create_agent()` to create the agent with a custodial Solana wallet. Moves no funds.+5. Read `three://agents/{agentId}` for the new agent's page URL and Solana address.+6. `list_my_avatars()`, then `attach_avatar_to_agent()` with the avatar you pick.++### `setup-wallet`++Goal: provision, review and fund an agent's Solana wallet. Server: `mcp-agent`.++1. Read `three://agents/{agentId}/wallet`.+2. `provision_wallet()` if the wallet has no address yet. Moves no funds.+3. `wallet_status()` for the address, SOL and USDC balances and the spending caps.+4. Review the guard settings (daily and per-transaction limits, withdraw allowlist, freeze switch) on the wallet page.+5. Fund it by sending SOL or USDC on Solana to the address yourself. The agent never sends funds from here.+6. Subscribe to `three://agents/{agentId}/wallet` with `resources/subscribe` to be notified of transfers.++### `trade`++Goal: research a Solana token and decide whether to trade it. Server: `mcp`. Swap execution is not enabled on MCP yet: the last step sends you to the wallet page, where you confirm the swap yourself.++1. `token_snapshot()` for price, liquidity, market cap and holders.+2. `pumpfun_token_intel()` for creator history and risk flags.+3. `oracle_coin()` for the conviction score and its reasons.+4. Read `three://agents/{agentId}/wallet` for the balance, trade limits and freeze state.+5. Summarize the risks and the case for and against before any trade talk.++### `launch-token`++Goal: plan a token launch grounded in current data. Server: `mcp`. Launching from MCP is not enabled yet: you review and sign the launch on `/launch`.++1. Read `three://launches` to see what the account launched before and flag a repeated name or symbol.+2. `pumpfun_recent_graduations()` to see what recently graduated launches have in common.+3. Read `three://agents/{agentId}/wallet` and check there is enough SOL for the launch fee.+4. Show the name, symbol, description, image, launching wallet and cost, and wait for the yes.+5. Confirm on the launch page, then read `three://launches` again to see it landed.++### `hire-agent`++Goal: find an agent or paid service for a task and pay for it with a capped call. Servers: `mcp-agent` (full flow), `mcp` and `mcp-bazaar` (find, then hand off).++On `mcp-agent`:++1. `find_services()` with the task, three best matches with price and network, Solana first.+2. `wallet_status()` to confirm the balance and caps cover the price.+3. Show the service, resource URL, exact price and paying wallet, and wait for the yes.+4. `pay_and_call()` with the resource URL and `max_usd` set to the quoted price. **Spends money.**+5. Show the result and the payment receipt.++On `mcp`: read `three://marketplace`, pick a fit, then `call_agent()` with the agent id and a brief. **Spends money** when the agent is priced or the trial is used up. On `mcp-bazaar`: `search_services()`, then `get_service()` for the exact price, networks and input schema, then hand off to `mcp-agent` to pay.++### `sell-a-skill`++Goal: price a capability and publish it as a paid service. Server: `mcp-agent`.++1. Read `three://agents/{agentId}` for its skills and existing prices.+2. Read `three://marketplace` to see what comparable skills charge.+3. Read `three://agents/{agentId}/wallet` to confirm which wallet receives revenue.+4. Agree on name, description, price per call in USDC, the https endpoint and the network.+5. `monetize_endpoint()` to publish the listing. Moves no funds; buyers pay per call.++### `review-costs`++Goal: find the single biggest saving in an agent's monthly spend. Server: `mcp`.++1. Read `three://agents/{agentId}/usage` for LLM calls, tokens and cost per model, tool calls and the credit balance.+2. Read `three://models` for current prices per million tokens.+3. Read `three://me` for the daily MCP quota and what is left.+4. Show a model, calls, tokens and cost table and name the one change that saves the most.++### `setup-automations`++Goal: put an agent on autopilot with every automation simulated first. Server: `mcp`.++1. Read `three://agents/{agentId}/intents` and `three://agents/{agentId}/orders` to start from what is running.+2. Read `three://agents/{agentId}/wallet` for the balance, limits and freeze state.+3. `oracle_watch_status()`, then `oracle_arm_watch()` in simulate mode so it only logs what it would buy. Live mode **spends money**: show the per-trade cap and daily budget and wait for the yes.+4. `trader_leaderboard()` to pick a leader, then `copy_subscribe()` with a per-trade cap and daily budget. Non-custodial: it creates intents you act on from the dashboard.+5. Standing wallet intents are created on the wallet page, where you confirm each one.++### `setup-dca`++Goal: start a recurring buy of a token. Servers: `mcp` (with research), `mcp-agent`.++1. Read `three://agents/{agentId}/dca` for plans already running.+2. Read `three://agents/{agentId}/wallet` for the balance and limits.+3. `token_snapshot()` on the token to accumulate (on `mcp`).+4. Propose an amount and period and show the total committed over three months.+5. Start the plan on `/recurring`, where you sign the spending permission yourself, then read `three://agents/{agentId}/dca` to confirm it is active. **Spends money** once the plan runs.++### `explore-marketplace`++Goal: browse paid skills and services with prices and trials. Servers: `mcp`, `mcp-agent`, `mcp-bazaar`.++1. Read `three://marketplace`.+2. Group the skills by what they do and show the best options with price and trial uses.+3. List agent-to-agent services by completion count and rating.+4. On `mcp`, offer `call_agent()` for a short test request. **Spends money** unless a free trial covers it.++### `explore-x402`++Goal: find an x402 service for a capability and see exactly how to pay. Servers: `mcp-bazaar`, `mcp-agent`, `mcp`.++On `mcp-bazaar`: `search_services()` with the capability, Solana first, then `get_service()` for the price, networks, recipient and input schema. On `mcp-agent`: `find_services()`, show the pick with its exact price, wait for the yes, then `pay_and_call()` with `max_usd` set to the quoted price. **Spends money.** On `mcp`: read `three://x402/services` and hand off to `mcp-agent` to pay.++### `earn-yield`++Goal: find yield for idle agent funds. Server: `mcp`. Lending is not enabled on MCP yet, so nothing moves from here.++1. Read `three://agents/{agentId}/wallet` and show what is idle.+2. `crypto_data()` with the DefiLlama provider to compare pool APYs for the assets held, Solana first.+3. Summarize the two best options and their risks.++### `perps`++Goal: research a perpetual futures setup. Server: `mcp`. Perps are not enabled on MCP yet, so no position opens from here.++1. Read `three://agents/{agentId}/wallet` for collateral and limits.+2. `crypto_data()` for spot price and recent volatility, and `token_snapshot()` for Solana tokens.+3. Summarize the setup, the liquidation risk at 2x and 5x, and what would invalidate it.++### `predictions`++Goal: research a prediction-market question. Server: `mcp`. Prediction markets are not enabled on MCP yet, so no position is placed from here.++1. Read `three://agents/{agentId}/wallet` for the balance and limits.+2. `crypto_data()` for the data behind the question, then give a probability estimate with reasoning.++### `embed-avatar`++Goal: put an agent's live 3D avatar on a website. Server: `mcp`.++1. Read `three://agents/{agentId}` and check it has an avatar; if not, `list_my_avatars()` and `attach_avatar_to_agent()`.+2. `get_embed_code()` with the agent id, choosing a size and autorotate.+3. `render_avatar()` to preview it in chat.+4. Paste the snippet and check it with the embed doctor at `/embed-doctor`.++### `generate-3d`++Goal: turn a text prompt into a textured, optionally rigged model saved to your library. Server: `mcp-3d`.++1. `direct_prompt()` to sharpen the idea into a generation prompt.+2. `text_to_3d()` with the prompt. **Spends money** at the tier price shown in `tools/list`; state it first.+3. `generation_status()` with the job id until a GLB comes back.+4. `auto_rig_model()` for characters so they can be animated.+5. `save_avatar()` with the GLB URL and a name, then read `three://assets/{id}` for the saved asset.++---+## Rate limits| Scope | Limit |diff --git a/docs/x402.md b/docs/x402.mdindex ad6a10a2d..ea21bf36c 100644--- a/docs/x402.md+++ b/docs/x402.md@@ -145,6 +145,36 @@ For idempotency (don't double-charge on network retry), pass an`Idempotency-Key` header — implementations are free to dedupe beforeconsuming the intent. Not yet enforced server-side.+## A paid call that fails never asks the buyer to pay twice++The paid HTTP routes under `/api/x402/*` run the work before settling, so a+handler that fails charges nothing. Two cases remain where the payment has+already settled when something goes wrong: a streaming route (which settles+first so the body can stream) whose handler throws, and a failure recording the+wallet's Sign-In-With-X grant. For both, the response says so and the same+payment can be reused:++```json+{+ "error": "internal_error",+ "paid": true,+ "retry_safe": true,+ "settlement": { "transaction": "5Kd...", "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d" },+ "retries_left": 3,+ "retry_until": "2026-10-10T03:00:00.000Z",+ "message": "You were charged; repeat this exact request with the same payment to get your result."+}+```++What a buyer's client should do:++- `paid: true` means the settlement transaction landed. Never build a second payment for this request.+- `retry_safe: true`: repeat the exact request with the same `X-PAYMENT` (or `PAYMENT-SIGNATURE`) header. The server skips verify and settle, re-runs the work, and answers with the original `x-payment-response` header. A body that differs from the original is a different request, so resend it unchanged.+- `retry_safe: false`: the proof used up its retries (`X402_PAID_RETRY_MAX`, default 3) or the window closed (`X402_PAID_RETRY_WINDOW_SECONDS`, default 24 hours). The next attempt answers 409 `payment_retries_exhausted`. Contact support with `settlement.transaction`.+- A call that completed is different: replaying its proof answers 409 `payment_replayed`, and buying the result again needs a new payment.++When a request carries a `payment-identifier`, the idempotency hash covers the HTTP method, URL and request body, so two different POST bodies under one identifier never share a cached response.+## Differences from x402 mainline- We bind intents to `(agent, skill, payer)` server-side: the manifest'sdiff --git a/tests/api/x402-spent-payments.test.js b/tests/api/x402-spent-payments.test.jsindex df25c2c0a..cd8a46a90 100644--- a/tests/api/x402-spent-payments.test.js+++ b/tests/api/x402-spent-payments.test.js@@ -86,6 +86,12 @@ vi.mock('../../api/_lib/db.js', async (importActual) => {return { ...actual, sql: fakeSql };});+const recordSiwxPayment = vi.fn();+vi.mock('../../api/_lib/siwx-server.js', async (importActual) => {+ const actual = await importActual();+ return { ...actual, recordSiwxPayment };+});+vi.mock('@coinbase/x402', () => ({ createCdpAuthHeaders: vi.fn(async () => ({})) }));let paidEndpoint;@@ -105,7 +111,7 @@ const HANDLER_BAZAAR = {schema: { type: 'object' },};-function mockReqRes({ method = 'GET', headers = {}, url = ROUTE } = {}) {+function mockReqRes({ method = 'GET', headers = {}, url = ROUTE, body = null } = {}) {const lowerHeaders = {};for (const [k, v] of Object.entries(headers)) lowerHeaders[k.toLowerCase()] = v;const req = Object.assign(new Readable({ read() {} }), {@@ -115,6 +121,10 @@ function mockReqRes({ method = 'GET', headers = {}, url = ROUTE } = {}) {connection: { remoteAddress: '127.0.0.1' },socket: { remoteAddress: '127.0.0.1' },});+ if (body !== null) {+ req.rawBody = Buffer.from(JSON.stringify(body));+ req.body = body;+ }req.push(null);const chunks = [];const resHeaders = {};@@ -144,8 +154,9 @@ function mockReqRes({ method = 'GET', headers = {}, url = ROUTE } = {}) {return { req, res };}-function paymentHeader({ salt = 'a' } = {}) {+function paymentHeader({ salt = 'a', paymentId = null } = {}) {const payload = {+ ...(paymentId ? { extensions: { 'payment-identifier': { info: { required: false, id: paymentId } } } } : {}),x402Version: 2,scheme: 'exact',network: BASE,@@ -197,6 +208,8 @@ beforeEach(() => {auditEvents.length = 0;verifyPayment.mockReset();settlePayment.mockReset();+ recordSiwxPayment.mockReset();+ recordSiwxPayment.mockResolvedValue(undefined);verifyPayment.mockImplementation(async () => ({paymentPayload: {},requirement: {@@ -321,3 +334,145 @@ describe('paidEndpoint() durable spent-payment guard', () => {expect(res.getHeader('x-payment-response')).toBeTruthy();});});++describe('paidEndpoint() failure after settlement', () => {+ const streamOnce = () => {+ let calls = 0;+ return {+ calls: () => calls,+ handler: async ({ res }) => {+ calls++;+ if (calls === 1) throw new Error('upstream exploded');+ res.setHeader('content-type', 'application/octet-stream');+ res.write('GOOD');+ res.end();+ },+ };+ };++ it('tells a buyer they were charged and may retry, then serves the retry without a second charge', async () => {+ const h = streamOnce();+ const failed = await callPaid(h.handler, { spec: { streaming: true } });++ expect(failed.statusCode).toBe(500);+ const body = JSON.parse(failed.body);+ expect(body).toMatchObject({+ paid: true,+ retry_safe: true,+ settlement: { transaction: '0xdeadbeef', network: BASE },+ });+ expect(body.message).toBe(+ 'You were charged; repeat this exact request with the same payment to get your result.',+ );+ expect([...spentRows.values()][0].outcome).toBe('failed_after_settle');++ cacheMod._resetMemoryStore();+ verifyPayment.mockClear();+ settlePayment.mockClear();+ const retried = await callPaid(h.handler, { spec: { streaming: true } });++ expect(retried.statusCode).toBe(200);+ expect(retried.body).toBe('GOOD');+ expect(retried.getHeader('x-payment-response')).toBeTruthy();+ expect(h.calls()).toBe(2);+ expect(verifyPayment).not.toHaveBeenCalled();+ expect(settlePayment).not.toHaveBeenCalled();+ expect([...spentRows.values()][0].outcome).toBe('delivered');+ });++ it('still answers 409 for a call that completed, even after a failed attempt was retried', async () => {+ const h = streamOnce();+ await callPaid(h.handler, { spec: { streaming: true } });+ cacheMod._resetMemoryStore();+ await callPaid(h.handler, { spec: { streaming: true } });++ cacheMod._resetMemoryStore();+ const replay = await callPaid(h.handler, { spec: { streaming: true } });+ expect(replay.statusCode).toBe(409);+ expect(JSON.parse(replay.body)).toMatchObject({ error: 'payment_replayed' });+ expect(h.calls()).toBe(2);+ });++ it('stops offering retries once they are used up and says to contact support', async () => {+ let calls = 0;+ const alwaysFails = async () => {+ calls++;+ throw new Error('still broken');+ };+ let last;+ for (let i = 0; i < 4; i++) {+ cacheMod._resetMemoryStore();+ last = await callPaid(alwaysFails, { spec: { streaming: true } });+ }+ expect(calls).toBe(4);+ expect(JSON.parse(last.body)).toMatchObject({ paid: true, retry_safe: false });++ cacheMod._resetMemoryStore();+ const after = await callPaid(alwaysFails, { spec: { streaming: true } });+ expect(calls).toBe(4);+ expect(after.statusCode).toBe(409);+ expect(JSON.parse(after.body)).toMatchObject({+ error: 'payment_retries_exhausted',+ paid: true,+ retry_safe: false,+ });+ });++ it('marks siwx_record_failed as paid and retry-safe, and the retry succeeds', async () => {+ recordSiwxPayment.mockRejectedValueOnce(new Error('neon hiccup'));+ const spec = { siwx: { statement: 'Access the paid good' } };+ const failed = await callPaid(async () => ({ ok: true }), { spec });++ expect(failed.statusCode).toBe(502);+ expect(JSON.parse(failed.body)).toMatchObject({+ error: 'siwx_record_failed',+ paid: true,+ retry_safe: true,+ settlement: { transaction: '0xdeadbeef' },+ });++ cacheMod._resetMemoryStore();+ settlePayment.mockClear();+ const retried = await callPaid(async () => ({ ok: true }), { spec });+ expect(retried.statusCode).toBe(200);+ expect(JSON.parse(retried.body)).toMatchObject({ ok: true });+ expect(settlePayment).not.toHaveBeenCalled();+ });+});++describe('paidEndpoint() idempotency over POST bodies', () => {+ async function callPost(body, handler) {+ const endpoint = makeEndpoint(handler, { method: 'POST' });+ const { req, res } = mockReqRes({+ method: 'POST',+ body,+ headers: { 'x-payment': paymentHeader({ paymentId: 'pay_post_body_00000001' }), 'content-type': 'application/json' },+ });+ await endpoint(req, res);+ return res;+ }++ it('does not serve one body\'s cached response to a different body under the same payment identifier', async () => {+ let ran = 0;+ const handler = async ({ req }) => ({ ran: ++ran, echo: req.body });+ const first = await callPost({ q: 'one' }, handler);+ expect(first.statusCode).toBe(200);++ const second = await callPost({ q: 'two' }, handler);+ expect(second.statusCode).toBe(409);+ expect(second.getHeader('x-x402-idempotent')).toBe('conflict');+ expect(second.body).not.toContain('"one"');+ expect(ran).toBe(1);+ });++ it('still replays the cached response for the identical body', async () => {+ let ran = 0;+ const handler = async () => ({ ran: ++ran });+ const first = await callPost({ q: 'same' }, handler);+ const again = await callPost({ q: 'same' }, handler);++ expect(first.statusCode).toBe(200);+ expect(again.statusCode).toBe(200);+ expect(ran).toBe(1);+ });+});diff --git a/tests/mcp-use-cases-doc.test.js b/tests/mcp-use-cases-doc.test.jsnew file mode 100644index 000000000..4f0391933--- /dev/null+++ b/tests/mcp-use-cases-doc.test.js@@ -0,0 +1,80 @@+// docs/mcp.md "Use cases" section: each guided prompt written as the ordered+// tool and resource calls it drives. This suite keeps that section true.+//+// - Every prompt in api/_mcp/prompts.js has a section.+// - Every `tool()` the section names is published by at least one hosted+// server, so removing or renaming a tool turns this red.+// - Every three:// resource it names is served by at least one hosted server.+// - Every tool a prompt actually renders is named in that prompt's section,+// so a new step added to a prompt cannot go undocumented.++import { readFileSync } from 'node:fs';+import { describe, it, expect } from 'vitest';++const { PROMPTS, promptsFor, renderPrompt } = await import('../api/_mcp/prompts.js');+const { matchResource } = await import('../api/_mcp/resources.js');+const { TOOL_CATALOG: mainCatalog } = await import('../api/_mcp/catalog.js');+const { TOOL_CATALOG: agentCatalog } = await import('../api/_mcpagent/catalog.js');+const { TOOL_CATALOG: studioCatalog } = await import('../api/_mcp3d/catalog.js');+const { TOOL_CATALOG: bazaarCatalog } = await import('../api/_mcpbazaar/catalog.js');++const SERVERS = { mcp: mainCatalog, 'mcp-agent': agentCatalog, 'mcp-3d': studioCatalog, 'mcp-bazaar': bazaarCatalog };+const ALL_TOOLS = new Set(Object.values(SERVERS).flatMap((c) => c.map((t) => t.name)));+const AGENT = '33333333-3333-4333-8333-333333333333';++const doc = readFileSync(new URL('../docs/mcp.md', import.meta.url), 'utf8');++function useCaseSections() {+ const start = doc.indexOf('\n## Use cases\n');+ if (start < 0) return new Map();+ const rest = doc.slice(start + 1);+ const end = rest.indexOf('\n## ', 1);+ const body = end < 0 ? rest : rest.slice(0, end);+ const sections = new Map();+ for (const chunk of body.split(/\n### /).slice(1)) {+ const name = chunk.match(/^`([a-z0-9-]+)`/)?.[1];+ if (name) sections.set(name, chunk);+ }+ return sections;+}++const sections = useCaseSections();+const toolRefs = (text) => [...text.matchAll(/`([a-z][a-z0-9_]*)\(\)`/g)].map((m) => m[1]);+const resourceRefs = (text) => [...text.matchAll(/`(three:\/\/[^`\s]+)`/g)].map((m) => m[1]);++describe('docs/mcp.md use cases', () => {+ it('has a Use cases section', () => {+ expect(sections.size).toBeGreaterThan(0);+ });++ it('covers every guided prompt', () => {+ for (const p of PROMPTS) expect([...sections.keys()], p.name).toContain(p.name);+ });++ it('names only tools a hosted server publishes', () => {+ for (const [prompt, text] of sections) {+ for (const tool of toolRefs(text)) expect(ALL_TOOLS, `${prompt} names ${tool}()`).toContain(tool);+ }+ });++ it('names only resources a hosted server serves', () => {+ for (const [prompt, text] of sections) {+ for (const uri of resourceRefs(text)) {+ const concrete = uri.replace('{agentId}', AGENT).replace('{id}', AGENT);+ const served = Object.keys(SERVERS).some((s) => matchResource(s, concrete));+ expect(served, `${prompt} names ${uri}`).toBe(true);+ }+ }+ });++ it('names every tool its prompt renders', () => {+ for (const [server, catalog] of Object.entries(SERVERS)) {+ for (const prompt of promptsFor(server, catalog)) {+ const args = Object.fromEntries(prompt.arguments.map((a) => [a.name, a.name === 'agentId' ? AGENT : 'sample']));+ const used = renderPrompt(server, catalog, prompt.name, args).tools.filter((t) => t !== 'read_resource');+ const named = new Set(toolRefs(sections.get(prompt.name) || ''));+ for (const tool of used) expect(named, `${prompt.name} on ${server} drives ${tool}()`).toContain(tool);+ }+ }+ });+});