Skip to content

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

fix(x402): send a self-valid v2 Bazaar block on every paid route's 402, and add a probe that runs the marketplace checklist

nirholas6d123d953600
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 215fe692c..1965a90ca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-09-18
- **Granite Guardian now answers on three.ws, not just in the docs**: The governance check that screens what an agent is asked to do, and vetoes it when the request is a jailbreak, harmful, or fraudulent, runs on IBM Granite Guardian. It was built to call IBM's hosted watsonx.ai service, so on our live site it answered with a not-configured error, and the new agent identity check quietly skipped itself for the same reason. IBM publishes Granite Guardian's weights openly, so we now run the model ourselves on a dedicated GPU as a second lane: watsonx still leads wherever it is set up, and our own copy answers whenever it is not. Every verdict now says which model and which lane produced it. The identity check also compares a new agent against existing ones using the site's regular embedding service when Granite embeddings are unavailable; it lists the look-alikes it finds but only scores them on Granite, because that is what its thresholds were tuned on. (`/docs/ibm`) `[fix, infra]`
+- **Paid endpoints now describe themselves the way marketplaces expect**: When an agent or a marketplace asks one of our paid endpoints what it costs, the answer also explains how to call it and what comes back. Around sixty endpoints were sending that explanation in an older layout, or in one that did not match its own rules, which is enough for a marketplace to skip the listing without saying why. Every paid endpoint now sends it in the current standard layout, checked against its own rules. We also added a tool that tests our endpoints with the same checklist a marketplace validator uses, so a listing problem shows up on our side first. (`/docs/x402-dev-tools`) `[improvement, fix]`
- **Paid x402 endpoints are answering again**: For several hours on September 18, nearly every paid endpoint on three.ws, the x402 discovery document at /.well-known/x402, the payment facilitator and the MCP server answered with a server error instead of a price. A routine update to the library behind wallet sign-in changed what it needs at startup, and our code tripped over it the moment it loaded, before any request could be served. Agents and marketplace validators that probed us saw a broken seller. The sign-in code now supplies what the library expects, returning buyers can sign back in to what they already paid for exactly as before, and the deploy checks now refuse to ship when the tested dependencies differ from the ones the live site will run, which is how this got past us. (`/docs/x402`) `[fix, infra]`
## 2026-09-17
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index 0d100abd1..5cb568ebb 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -70,6 +70,7 @@ import {
} from './x402/payment-identifier-server.js';
import { authenticateSiwx, declareSiwxExtensionFor, recordSiwxPayment } from './siwx-server.js';
import { normalizeAddress } from './siwx-storage.js';
+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';
@@ -418,6 +419,9 @@ export function paidEndpoint(spec) {
if (!route) throw new Error('paidEndpoint: route is required');
if (!description) throw new Error('paidEndpoint: description is required');
if (!bazaar) throw new Error('paidEndpoint: bazaar discovery extension is required');
+ // Legacy flat blocks become the v2 `{ info, schema }` entry here, once, so the
+ // live 402 matches what the discovery document already advertises.
+ const bazaarEntry = normalizeBazaarEntry(bazaar, { method });
if (typeof handler !== 'function') throw new Error('paidEndpoint: handler must be a function');
if (accessControl != null && typeof accessControl !== 'function') {
throw new Error('paidEndpoint: accessControl must be a function when provided');
@@ -619,7 +623,7 @@ export function paidEndpoint(spec) {
accepts: requirements,
description,
mimeType,
- bazaar,
+ bazaar: bazaarEntry,
extensions: extraExtensions,
...(service?.serviceName ? { serviceName: service.serviceName } : {}),
...(Array.isArray(service?.tags) && service.tags.length ? { tags: service.tags } : {}),
diff --git a/api/_lib/x402/bazaar-helpers.js b/api/_lib/x402/bazaar-helpers.js
index 4dd080a01..0521ffa92 100644
--- a/api/_lib/x402/bazaar-helpers.js
+++ b/api/_lib/x402/bazaar-helpers.js
@@ -22,6 +22,8 @@
// Spec: /tmp/x402-docs/specs/extensions/bazaar.md
// /tmp/x402-docs/docs/extensions/bazaar.mdx
+import Ajv2020 from 'ajv/dist/2020.js';
+import addFormats from 'ajv-formats';
import { declareDiscoveryExtension } from '@x402/extensions';
import { buildBazaarSchema } from '../x402-spec.js';
@@ -123,17 +125,22 @@ export function declareHttpDiscovery({
// `additionalProperties` placement — running through buildBazaarSchema
// guarantees the exact shape that has been validated against the CDP
// Bazaar's discovery probe.
+ const info = sdkInner?.info || {};
+ const inputInfo = info.input || {};
+
+ // The meta-schema closes `input` to additional properties, so it has to
+ // describe `queryParams` whenever info carries them. A route that gives
+ // example params but no param schema used to get an info block its own
+ // schema rejected, which is the mismatch CDP drops a listing for.
+ const queryParamsSchema = inputSchema || (inputInfo.queryParams !== undefined ? {} : undefined);
const schema = buildBazaarSchema({
method: upper,
- queryParamsSchema: isBody ? undefined : inputSchema,
+ queryParamsSchema: isBody ? undefined : queryParamsSchema,
bodyType: isBody ? bodyType || 'json' : undefined,
bodySchema: isBody ? inputSchema : undefined,
outputSchema: output?.schema,
});
- const info = sdkInner?.info || {};
- const inputInfo = info.input || {};
-
// Surface the response example/schema in the same shape buildBazaarSchema
// expects. The SDK already nests these under info.output but only when an
// `output` arg was passed; we re-normalize so consumers can rely on the
@@ -204,6 +211,65 @@ export function declareMcpDiscovery({
return { ...sdkInner, discoverable: true };
}
+// Bring whatever a route passed as `bazaar` to a canonical v2 entry,
+// `{ discoverable, info: { input, output }, schema }`, whose info validates
+// against its own schema. That self-validation is the strict check CDP runs
+// before it catalogs a resource, and marketplace validators read it off the
+// live 402, so it is the pass-through test here too.
+//
+// Three shapes reach this point that fail it:
+// - flat, pre-v2: `{ description, useCases, input: { type: 'query' | 'json',
+// example, schema }, output }`, with no `info` block at all;
+// - hybrid: an `info` wrapper around that same legacy input;
+// - v2 by hand, but drifted from its schema (no `bodyType`, stray keys).
+// paidEndpoint() used to forward all of them verbatim. The discovery document
+// rebuilds its own entries and looked fine, which hid it. Each is rebuilt from
+// its parts through declareHttpDiscovery; a valid entry, and any MCP entry
+// (built by declareMcpDiscovery), passes through untouched.
+const bazaarAjv = new Ajv2020({ allErrors: false, strict: false });
+addFormats(bazaarAjv);
+
+function infoMatchesSchema(entry) {
+ if (!entry?.info?.input || !entry.schema) return false;
+ try {
+ return bazaarAjv.compile(entry.schema)(entry.info) === true;
+ } catch {
+ return false;
+ }
+}
+
+export function normalizeBazaarEntry(bazaar, { method = 'GET' } = {}) {
+ const entry = bazaar || {};
+ const input = entry.info?.input ?? entry.input ?? {};
+ if (input.type === 'mcp' || infoMatchesSchema(entry)) return entry;
+
+ const upper = String(input.method || method).toUpperCase();
+ const isBody = ['POST', 'PUT', 'PATCH'].includes(upper);
+ const isV2Input = input.type === 'http';
+ const part = isBody ? 'body' : 'queryParams';
+ // Some hand-written blocks carry the example as `bodyExample`, a key the v2
+ // schema does not define, so it counts as the example rather than as drift.
+ const example = isV2Input ? input[part] ?? input.bodyExample ?? input.example : input.example;
+ const inputSchema = isV2Input ? entry.schema?.properties?.input?.properties?.[part] : input.schema;
+ const hasExample = example && typeof example === 'object' && Object.keys(example).length > 0;
+
+ const declaredOutput = entry.info?.output ?? entry.output;
+ const outputSchema = isV2Input ? undefined : declaredOutput?.schema;
+ const output =
+ declaredOutput && (declaredOutput.example !== undefined || outputSchema)
+ ? { example: declaredOutput.example, schema: outputSchema }
+ : undefined;
+
+ const rebuilt = declareHttpDiscovery({
+ method: upper,
+ input: hasExample || isBody ? example : undefined,
+ inputSchema,
+ output,
+ bodyType: isBody ? input.bodyType || 'json' : undefined,
+ });
+ return entry.discoverable === false ? { ...rebuilt, discoverable: false } : rebuilt;
+}
+
// Convenience: returns the full extensions block `{ bazaar: <inner> }` for
// callers that want to spread it straight into a payment-wrapper config.
// Matches the v2 SDK call signature ({ method, input, inputSchema, output, … })
diff --git a/api/x402/knock.js b/api/x402/knock.js
index 35b081713..569674914 100644
--- a/api/x402/knock.js
+++ b/api/x402/knock.js
@@ -81,7 +81,7 @@ const OUTPUT_EXAMPLE = {
announced: true,
importance: 74,
paid: '$0.05',
- receipt_url: 'https://three.ws/api/knock/reply?id=c1b0a2d4-7e33-4f01-9a55-2b7c1d0e9f4a&token=…',
+ receipt_url: 'https://three.ws/api/knock/reply?id=c1b0a2d4-7e33-4f01-9a55-2b7c1d0e9f4a&token=THREEsyntheticReplyToken',
duplicate: false,
};
diff --git a/api/x402/wallet-connect.js b/api/x402/wallet-connect.js
index 6d5b5b4ef..296c16f57 100644
--- a/api/x402/wallet-connect.js
+++ b/api/x402/wallet-connect.js
@@ -136,7 +136,7 @@ const OUTPUT_EXAMPLE = {
const BAZAAR = {
discoverable: true,
info: {
- input: { type: 'http', method: 'POST', bodySchema: INPUT_SCHEMA },
+ input: { type: 'http', method: 'POST', bodyType: 'json', body: { mode: 'health' } },
output: { type: 'json', example: OUTPUT_EXAMPLE },
},
schema: buildBazaarSchema({ method: 'POST', bodySchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),
diff --git a/data/changelog.json b/data/changelog.json
index 391f82300..605a191d7 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$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. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-09-18",
+ "title": "Paid endpoints now describe themselves the way marketplaces expect",
+ "summary": "When an agent or a marketplace asks one of our paid endpoints what it costs, the answer also explains how to call it and what comes back. Around sixty endpoints were sending that explanation in an older layout, or in one that did not match its own rules, which is enough for a marketplace to skip the listing without saying why. Every paid endpoint now sends it in the current standard layout, checked against its own rules. We also added a tool that tests our endpoints with the same checklist a marketplace validator uses, so a listing problem shows up on our side first.",
+ "tags": [
+ "improvement",
+ "fix"
+ ],
+ "link": "/docs/x402-dev-tools"
+ },
{
"date": "2026-09-18",
"title": "Paid x402 endpoints are answering again",
diff --git a/docs/x402-dev-tools.md b/docs/x402-dev-tools.md
index 6bd43decb..452b6a2f3 100644
--- a/docs/x402-dev-tools.md
+++ b/docs/x402-dev-tools.md
@@ -197,6 +197,54 @@ implementation against a live server.
4. After a successful call, `POST /api/x402/verify-receipt` to confirm the
attestation and settlement.
+## Checking our own endpoints the way a marketplace does
+
+The tools above debug a buyer's call. This one checks the seller side: whether
+the paid routes three.ws lists would pass the checklist a marketplace validator
+(Agentic Market's Seller Tools, the CDP Bazaar crawler) runs before it catalogs
+a resource. It sends the same unpaid request an indexer sends, so it costs
+nothing.
+
+```bash
+npm run x402:probe # every listed route on https://three.ws
+npm run x402:probe -- --only=/api/x402/forge # routes whose path contains the text
+npm run x402:probe -- --base=http://localhost:8080 # a local or preview server
+npm run x402:probe -- --url=https://three.ws/api/x402/model-check
+npm run x402:probe -- --json # machine-readable report
+```
+
+It reads `/.well-known/x402.json`, takes one sample per route (the datapoint
+catalog lists thousands of parameterised URLs behind a few handlers), and fails
+a route when any of these is false:
+
+| Group | Checks |
+|---|---|
+| Transport | HTTPS, reachable, body at most 65,536 bytes, HTTP 402, valid JSON, `resource` object present |
+| Payment | `x402Version` 2, a `PAYMENT-REQUIRED` header that decodes, `accepts[]` present and well formed, known scheme, CAIP-2 network, asset, USDC price at least $0.001, `payTo`, `maxTimeoutSeconds` |
+| Bazaar | extension present, `info` block, input type and method, `schema`, and `info` validating against that `schema` |
+
+Two readings to know:
+
+- **"No x402 setup detected" with a body over 65,536 bytes** means the URL is
+ not a paid route. A page or the discovery document answers 200 with a large
+ body, the validator truncates it, and every later check is skipped. Validate a
+ route from the catalog, with the method the catalog lists for it.
+- **HTTP 500 on every route** is a handler that throws while loading, not a
+ payment problem. `npm run check:api-imports` finds it locally in under a
+ minute, and it gates `deploy:gcp:submit`.
+
+With `--base`, catalog URLs are rebased onto that host, so a local run never
+quietly tests production. A local server without the production settlement
+configuration advertises fewer payment options than production does; an empty
+`accepts[]` there is a local artifact, so confirm it with `--url` against
+production before treating it as a defect.
+
+Every route's Bazaar block is normalized in one place,
+`normalizeBazaarEntry` in `api/_lib/x402/bazaar-helpers.js`, which
+`paidEndpoint()` applies to whatever a handler declares. A handler may still
+declare the older flat `{ input: { type, example, schema }, output }` block; the
+live 402 carries the v2 `{ info, schema }` entry either way.
+
## Related
- [x402 Protocol](/docs/x402) - the challenge / verify / settle mechanics.
diff --git a/package.json b/package.json
index d6fd79b0b..7c4d01062 100644
--- a/package.json
+++ b/package.json
@@ -212,6 +212,7 @@
"guard:esbuild:all": "node scripts/guard-esbuild-bundles.mjs --all",
"verify:solana": "node scripts/verify-solana-parity.mjs",
"verify:onchain": "node scripts/verify-onchain-parity.mjs",
+ "x402:probe": "node scripts/probe-x402-live.mjs",
"verify:x402": "node scripts/build-x402-catalog.mjs --out=/tmp/x402-catalog.json && node scripts/verify-x402-discovery.mjs --file=/tmp/x402-catalog.json",
"smoke:x402-facilitator": "node scripts/x402-facilitator-smoke-test.mjs",
"preview:x402scan-registration": "node scripts/x402scan-registration-gap.mjs",
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index cce23f1c4..1b59fc148 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,11 +1,11 @@
{
- "generated_at": "2026-09-18T07:13:35.035Z",
+ "generated_at": "2026-09-18T07:48:36.343Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 3703,
+ "total": 3704,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
@@ -20,6 +20,17 @@
"infra"
]
},
+ {
+ "date": "2026-09-18",
+ "type": "update",
+ "title": "Paid endpoints now describe themselves the way marketplaces expect",
+ "summary": "When an agent or a marketplace asks one of our paid endpoints what it costs, the answer also explains how to call it and what comes back. Around sixty endpoints were sending that explanation in an older layout, or in one that did not match its own rules, which is enough for a marketplace to skip the listing without saying why. Every paid endpoint now sends it in the current standard layout, checked against its own rules. We also added a tool that tests our endpoints with the same checklist a marketplace validator uses, so a listing problem shows up on our side first.",
+ "link": "/docs/x402-dev-tools",
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
{
"date": "2026-09-18",
"type": "update",
@@ -1609,17 +1620,6 @@
"fix",
"improvement"
]
- },
- {
- "date": "2026-09-08",
- "type": "update",
- "title": "The agent vitals endpoint answers again, and eight documented API examples now say what they really return",
- "summary": "GET /api/agents/vitals, the operator view that reports whether each autonomous agent can actually act, had been unreachable: a broader routing rule for agent profiles was catching the request first and answering with an agent lookup instead. It resolves to its own handler again. Separately, every runnable curl sample in the documentation was replayed against the live API, and the ones whose example used a placeholder id or needed a signed-in session now say so above the snippet rather than looking like a call that should have worked.",
- "link": "/docs/agent-vitals",
- "tags": [
- "fix",
- "docs"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index bca648cfd..6ac5dca4d 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-18T07:13:35.000Z",
+ "generated_at": "2026-09-18T07:48:36.274Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -17,6 +17,17 @@
"infra"
]
},
+ {
+ "date": "2026-09-18",
+ "type": "update",
+ "title": "Paid endpoints now describe themselves the way marketplaces expect",
+ "summary": "When an agent or a marketplace asks one of our paid endpoints what it costs, the answer also explains how to call it and what comes back. Around sixty endpoints were sending that explanation in an older layout, or in one that did not match its own rules, which is enough for a marketplace to skip the listing without saying why. Every paid endpoint now sends it in the current standard layout, checked against its own rules. We also added a tool that tests our endpoints with the same checklist a marketplace validator uses, so a listing problem shows up on our side first.",
+ "link": "/docs/x402-dev-tools",
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
{
"date": "2026-09-18",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 78716f955..0ad21abb5 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>fix</category>
<description>The governance check that screens what an agent is asked to do, and vetoes it when the request is a jailbreak, harmful, or fraudulent, runs on IBM Granite Guardian. It was built to call IBM's hosted watsonx.ai service, so on our live site it answered with a not-configured error, and the new agent identity check quietly skipped itself for the same reason. IBM publishes Granite Guardian's weights openly, so we now run the model ourselves on a dedicated GPU as a second lane: watsonx still leads wherever it is set up, and our own copy answers whenever it is not. Every verdict now says which model and which lane produced it. The identity check also compares a new agent against existing ones using the site's regular embedding service when Granite embeddings are unavailable; it lists the look-alikes it finds but only scores them on Granite, because that is what its thresholds were tuned on.</description>
</item>
+ <item>
+ <title>Paid endpoints now describe themselves the way marketplaces expect</title>
+ <link>https://three.ws/docs/x402-dev-tools</link>
+ <guid isPermaLink="false">2026-09-18:Paid endpoints now describe themselves the way marketplaces expect</guid>
+ <pubDate>Fri, 18 Sep 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>When an agent or a marketplace asks one of our paid endpoints what it costs, the answer also explains how to call it and what comes back. Around sixty endpoints were sending that explanation in an older layout, or in one that did not match its own rules, which is enough for a marketplace to skip the listing without saying why. Every paid endpoint now sends it in the current standard layout, checked against its own rules. We also added a tool that tests our endpoints with the same checklist a marketplace validator uses, so a listing problem shows up on our side first.</description>
+ </item>
<item>
<title>Paid x402 endpoints are answering again</title>
<link>https://three.ws/docs/x402</link>
diff --git a/public/features.json b/public/features.json
index 73aa446ae..8a238196c 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-18T07:13:34.969Z",
+ "generated_at": "2026-09-18T07:48:36.227Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/probe-x402-live.mjs b/scripts/probe-x402-live.mjs
new file mode 100644
index 000000000..cdcfac249
--- /dev/null
+++ b/scripts/probe-x402-live.mjs
@@ -0,0 +1,282 @@
+#!/usr/bin/env node
+/**
+ * Live x402 probe: would a marketplace validator accept our paid endpoints?
+ *
+ * Why this exists
+ * ---------------
+ * `verify:x402` validates the discovery DOCUMENT. It says nothing about whether
+ * the routes that document lists actually answer an unpaid request with a valid
+ * 402. On 2026-09-18 the document was the least of it: a dependency bump made
+ * every paid route throw on import, so each one answered 500, and the first
+ * sign was Agentic Market's seller validator reporting "No x402 Setup Detected".
+ *
+ * This sends the same unpaid request a buyer or indexer sends and applies the
+ * checklist Agentic Market's validator (agentic.market, Seller Tools) publishes:
+ *
+ * Transport https, reachable, body <= 65536 bytes, HTTP 402, valid JSON,
+ * resource object present
+ * Payment x402Version 2, PAYMENT-REQUIRED header that decodes, accepts[]
+ * present and well-formed, known scheme, CAIP-2 network, asset,
+ * USDC price >= $0.001, payTo, maxTimeoutSeconds
+ * Bazaar extension present, info block, input type + method, schema,
+ * and info validating against that schema (the strict check CDP
+ * runs before cataloging); output metadata and example are
+ * advisory
+ *
+ * It costs nothing: no request carries a payment.
+ *
+ * Usage:
+ * node scripts/probe-x402-live.mjs # https://three.ws, one sample per route
+ * node scripts/probe-x402-live.mjs --base=http://localhost:3000
+ * node scripts/probe-x402-live.mjs --only=/api/x402/forge # routes whose path contains the text
+ * node scripts/probe-x402-live.mjs --url=https://three.ws/api/x402/forge --method=POST
+ * node scripts/probe-x402-live.mjs --json # machine-readable report
+ *
+ * Exit code 0 when every probed route passes, 1 when any fails, 2 when the
+ * discovery document itself cannot be loaded.
+ */
+
+import Ajv2020 from 'ajv/dist/2020.js';
+import addFormats from 'ajv-formats';
+
+const ajv = new Ajv2020({ allErrors: true, strict: false });
+addFormats(ajv);
+
+const args = process.argv.slice(2);
+const flag = (name) => args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3) ?? null;
+const base = (flag('base') || 'https://three.ws').replace(/\/$/, '');
+const only = flag('only');
+const singleUrl = flag('url');
+const singleMethod = (flag('method') || 'GET').toUpperCase();
+const concurrency = Math.max(1, Number(flag('concurrency')) || 4);
+const asJson = args.includes('--json');
+
+// The validator truncates anything larger and then skips every other check.
+const MAX_BODY_BYTES = 65536;
+const MIN_USDC_ATOMIC = 1000n; // $0.001 at 6 decimals
+const KNOWN_SCHEMES = new Set(['exact', 'upto']);
+const CAIP2 = /^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,64}$/;
+const REQUEST_TIMEOUT_MS = 30_000;
+
+/**
+ * The datapoint catalog lists thousands of parameterised URLs behind a handful
+ * of handlers (/api/x402/d/<family>/...). One sample per handler is what tells
+ * us whether the route works; the rest would only hammer the probe rate limit.
+ */
+export function routeKey(url) {
+ const parts = new URL(url).pathname.split('/').filter(Boolean);
+ if (parts[0] === 'api' && parts[1] === 'x402' && parts[2] === 'd') return `/${parts.slice(0, 4).join('/')}`;
+ return `/${parts.join('/')}`;
+}
+
+/**
+ * The catalog always prints canonical production URLs, whatever host served it.
+ * Probing a --base (a local server, a preview) has to hit THAT host, or the run
+ * quietly tests production instead.
+ */
+export function rebase(url, onto) {
+ const source = new URL(url);
+ return new URL(`${source.pathname}${source.search}`, onto).href;
+}
+
+export function sampleRoutes(resources, { onto = null } = {}) {
+ const byRoute = new Map();
+ for (const r of resources) {
+ if (!r?.url) continue;
+ const key = routeKey(r.url);
+ if (!byRoute.has(key)) byRoute.set(key, r);
+ }
+ return [...byRoute.entries()].map(([route, r]) => ({
+ route,
+ url: onto ? rebase(r.url, onto) : r.url,
+ method: String(r.method || r.extensions?.bazaar?.info?.input?.method || 'GET').toUpperCase(),
+ body: r.extensions?.bazaar?.info?.input?.body ?? null,
+ }));
+}
+
+function decodePaymentRequiredHeader(value) {
+ try {
+ return JSON.parse(Buffer.from(String(value), 'base64').toString('utf8'));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Applies the validator's checklist to one response. Returns
+ * `{ failures: [...], advisories: [...] }`; an empty failures list is a pass.
+ */
+export function checkResponse({ url, status, bodyBytes, bodyText, paymentRequiredHeader }) {
+ const failures = [];
+ const advisories = [];
+
+ if (new URL(url).protocol !== 'https:' && !/^http:\/\/(localhost|127\.0\.0\.1)/.test(url)) {
+ failures.push('resource URL does not use HTTPS');
+ }
+ if (bodyBytes > MAX_BODY_BYTES) {
+ failures.push(`response body is ${bodyBytes} bytes, over the ${MAX_BODY_BYTES}-byte limit (the validator truncates it and skips every other check)`);
+ return { failures, advisories };
+ }
+ if (status !== 402) {
+ failures.push(`HTTP ${status}, expected 402 for an unpaid request`);
+ return { failures, advisories };
+ }
+
+ let body;
+ try {
+ body = JSON.parse(bodyText);
+ } catch {
+ failures.push('402 body is not valid JSON');
+ return { failures, advisories };
+ }
+
+ if (!body.resource || typeof body.resource !== 'object' || !body.resource.url) failures.push('resource object missing or has no url');
+ if (body.x402Version !== 2) failures.push(`x402Version is ${JSON.stringify(body.x402Version)}, expected 2`);
+
+ if (!paymentRequiredHeader) {
+ failures.push('PAYMENT-REQUIRED header missing (v2 delivers PaymentRequired there)');
+ } else if (!decodePaymentRequiredHeader(paymentRequiredHeader)?.accepts) {
+ failures.push('PAYMENT-REQUIRED header does not decode to a PaymentRequired object');
+ }
+
+ const accepts = Array.isArray(body.accepts) ? body.accepts : [];
+ if (!accepts.length) failures.push('accepts[] missing or empty');
+ accepts.forEach((a, i) => {
+ for (const field of ['scheme', 'network', 'asset', 'amount', 'payTo']) {
+ if (a?.[field] == null || a[field] === '') failures.push(`accepts[${i}] missing ${field}`);
+ }
+ if (a?.scheme && !KNOWN_SCHEMES.has(a.scheme)) failures.push(`accepts[${i}].scheme "${a.scheme}" is not a known scheme`);
+ if (a?.network && !CAIP2.test(a.network)) failures.push(`accepts[${i}].network "${a.network}" is not a CAIP-2 id`);
+ if (!(Number(a?.maxTimeoutSeconds) > 0)) failures.push(`accepts[${i}].maxTimeoutSeconds is not set`);
+ if (a?.extra?.name === 'USDC' && /^\d+$/.test(String(a.amount)) && BigInt(a.amount) < MIN_USDC_ATOMIC) {
+ failures.push(`accepts[${i}] prices ${a.amount} atomic USDC, under the $0.001 minimum`);
+ }
+ });
+
+ const bazaar = body.extensions?.bazaar;
+ if (!bazaar) {
+ failures.push('bazaar extension missing (will not be cataloged)');
+ } else {
+ if (!bazaar.info) failures.push('bazaar.info missing');
+ const input = bazaar.info?.input;
+ if (!input) failures.push('bazaar.info.input missing');
+ else {
+ if (!input.type) failures.push('bazaar.info.input.type missing');
+ if (!input.method && input.type === 'http') failures.push('bazaar.info.input.method missing');
+ }
+ if (!bazaar.schema) failures.push('bazaar.schema missing');
+ else if (bazaar.info) {
+ try {
+ const validate = ajv.compile(bazaar.schema);
+ if (!validate(bazaar.info)) {
+ const detail = (validate.errors || []).slice(0, 3).map((e) => `${e.instancePath || '/'} ${e.message}`).join('; ');
+ failures.push(`bazaar.info fails its own schema, so CDP rejects the listing: ${detail}`);
+ }
+ } catch (err) {
+ failures.push(`bazaar.schema does not compile: ${err.message}`);
+ }
+ }
+ if (!bazaar.info?.output) advisories.push('no output metadata');
+ else if (bazaar.info.output.example == null) advisories.push('no output example');
+ }
+
+ return { failures, advisories };
+}
+
+async function probe({ route, url, method, body }) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
+ try {
+ const hasBody = method !== 'GET' && method !== 'HEAD';
+ const res = await fetch(url, {
+ method,
+ headers: { accept: 'application/json', ...(hasBody ? { 'content-type': 'application/json' } : {}) },
+ body: hasBody ? JSON.stringify(body ?? {}) : undefined,
+ redirect: 'manual',
+ signal: controller.signal,
+ });
+ const buf = Buffer.from(await res.arrayBuffer());
+ const verdict = checkResponse({
+ url,
+ status: res.status,
+ bodyBytes: buf.length,
+ bodyText: buf.toString('utf8'),
+ paymentRequiredHeader: res.headers.get('payment-required'),
+ });
+ return { route, url, method, status: res.status, bytes: buf.length, ...verdict };
+ } catch (err) {
+ const reason = err?.name === 'AbortError' ? `no response within ${REQUEST_TIMEOUT_MS / 1000}s` : err?.message || String(err);
+ return { route, url, method, status: 0, bytes: 0, failures: [`endpoint is not reachable: ${reason}`], advisories: [] };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+async function runPool(items, worker, size) {
+ const results = new Array(items.length);
+ let next = 0;
+ await Promise.all(
+ Array.from({ length: Math.min(size, items.length) }, async () => {
+ while (next < items.length) {
+ const index = next++;
+ results[index] = await worker(items[index]);
+ }
+ }),
+ );
+ return results;
+}
+
+async function loadTargets() {
+ if (singleUrl) return [{ route: routeKey(singleUrl), url: singleUrl, method: singleMethod, body: null }];
+ const docUrl = `${base}/.well-known/x402.json`;
+ let res;
+ try {
+ res = await fetch(docUrl, { headers: { accept: 'application/json' } });
+ } catch (err) {
+ console.error(`[x402:probe] cannot reach ${docUrl}: ${err.message}`);
+ process.exit(2);
+ }
+ if (!res.ok) {
+ console.error(`[x402:probe] ${docUrl} answered HTTP ${res.status}. The discovery document is down, so nothing listed in it can be indexed. Probe a route directly with --url=<paid route>.`);
+ process.exit(2);
+ }
+ const doc = await res.json();
+ const targets = sampleRoutes(doc.resources || doc.items || [], { onto: base });
+ return only ? targets.filter((t) => t.route.includes(only)) : targets;
+}
+
+async function main() {
+ const targets = await loadTargets();
+ if (!targets.length) {
+ console.error('[x402:probe] no routes to probe (empty discovery document, or --only matched nothing)');
+ process.exit(2);
+ }
+ const results = await runPool(targets, probe, concurrency);
+ const failing = results.filter((r) => r.failures.length);
+
+ if (asJson) {
+ console.log(JSON.stringify({ base, probed: results.length, failing: failing.length, results }, null, 2));
+ process.exit(failing.length ? 1 : 0);
+ }
+
+ for (const r of failing) {
+ console.log(`FAIL ${r.method} ${r.route} (HTTP ${r.status}, ${r.bytes} bytes)`);
+ for (const f of r.failures) console.log(` ${f}`);
+ }
+ const advised = results.filter((r) => !r.failures.length && r.advisories.length);
+ for (const r of advised) console.log(`note ${r.method} ${r.route}: ${r.advisories.join('; ')}`);
+
+ const largest = results.reduce((max, r) => Math.max(max, r.bytes), 0);
+ console.log(
+ `\n[x402:probe] ${results.length - failing.length}/${results.length} route(s) pass the marketplace checklist at ${singleUrl ? singleUrl : base}; largest response ${largest} of ${MAX_BODY_BYTES} bytes`,
+ );
+ process.exit(failing.length ? 1 : 0);
+}
+
+const isMain = process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href;
+if (isMain) {
+ main().catch((err) => {
+ console.error(`[x402:probe] ${err?.stack || err}`);
+ process.exit(2);
+ });
+}
diff --git a/tests/api/bazaar-normalize.test.js b/tests/api/bazaar-normalize.test.js
new file mode 100644
index 000000000..156c13446
--- /dev/null
+++ b/tests/api/bazaar-normalize.test.js
@@ -0,0 +1,98 @@
+// paidEndpoint() normalizes whatever a route declares as `bazaar` into a v2
+// entry whose info validates against its own schema. That self-validation is
+// the strict check CDP runs before cataloging, and marketplace validators read
+// it off the live 402. Before this, 48 routes shipped a flat pre-v2 block with
+// no `info` at all and 12 more shipped an info their own schema rejected.
+
+import { describe, it, expect } from 'vitest';
+import Ajv2020 from 'ajv/dist/2020.js';
+import addFormats from 'ajv-formats';
+import { declareHttpDiscovery, declareMcpDiscovery, normalizeBazaarEntry } from '../../api/_lib/x402/bazaar-helpers.js';
+
+const ajv = new Ajv2020({ allErrors: true, strict: false });
+addFormats(ajv);
+
+function expectSelfValid(entry) {
+ const validate = ajv.compile(entry.schema);
+ const ok = validate(entry.info);
+ expect(validate.errors || []).toEqual([]);
+ expect(ok).toBe(true);
+}
+
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const MINT_SCHEMA = { type: 'object', properties: { mint: { type: 'string' } }, required: ['mint'] };
+
+describe('normalizeBazaarEntry', () => {
+ it('lifts a flat query block into a self-valid v2 entry', () => {
+ const entry = normalizeBazaarEntry(
+ {
+ description: 'token intel',
+ useCases: ['signal'],
+ input: { type: 'query', example: { mint: MINT }, schema: MINT_SCHEMA },
+ output: { type: 'json', example: { symbol: 'THREE' } },
+ },
+ { method: 'GET' },
+ );
+ expect(Object.keys(entry).sort()).toEqual(['discoverable', 'info', 'schema']);
+ expect(entry.info.input).toEqual({ type: 'http', method: 'GET', queryParams: { mint: MINT } });
+ expect(entry.info.output).toEqual({ type: 'json', example: { symbol: 'THREE' } });
+ expectSelfValid(entry);
+ });
+
+ it('lifts a flat json block on a POST route into a body entry', () => {
+ const entry = normalizeBazaarEntry(
+ { input: { type: 'json', example: { report: 'clubs' }, schema: { type: 'object' } }, output: { type: 'json', example: { ok: true } } },
+ { method: 'POST' },
+ );
+ expect(entry.info.input).toEqual({ type: 'http', method: 'POST', bodyType: 'json', body: { report: 'clubs' } });
+ expectSelfValid(entry);
+ });
+
+ it('rebuilds a hybrid entry whose info wraps the legacy input', () => {
+ const valid = declareHttpDiscovery({ method: 'POST', input: {}, inputSchema: { type: 'object' } });
+ const hybrid = { ...valid, info: { input: { type: 'json', method: 'POST', example: { mode: 'canary' } }, output: { type: 'json', example: { ok: true } } } };
+ const entry = normalizeBazaarEntry(hybrid, { method: 'POST' });
+ expect(entry.info.input.type).toBe('http');
+ expect(entry.info.input.body).toEqual({ mode: 'canary' });
+ expect(entry.info.output.example).toEqual({ ok: true });
+ expectSelfValid(entry);
+ });
+
+ it('repairs a hand-written v2 entry that drifted from its schema', () => {
+ const valid = declareHttpDiscovery({ method: 'POST', input: { url: 'https://three.ws/avatars/cesium-man.glb' }, inputSchema: { type: 'object' } });
+ const drifted = structuredClone(valid);
+ delete drifted.info.input.bodyType;
+ const entry = normalizeBazaarEntry(drifted, { method: 'POST' });
+ expect(entry.info.input.bodyType).toBe('json');
+ expect(entry.info.input.body).toEqual({ url: 'https://three.ws/avatars/cesium-man.glb' });
+ expectSelfValid(entry);
+ });
+
+ it('returns an already-valid v2 entry untouched', () => {
+ const valid = declareHttpDiscovery({ method: 'GET', input: { mint: MINT }, inputSchema: MINT_SCHEMA, output: { example: { ok: true } } });
+ expect(normalizeBazaarEntry(valid, { method: 'GET' })).toBe(valid);
+ });
+
+ it('never rebuilds an MCP entry as HTTP', () => {
+ const mcp = declareMcpDiscovery({ toolName: 'validate_model', inputSchema: { type: 'object' } });
+ expect(normalizeBazaarEntry(mcp, { method: 'POST' })).toBe(mcp);
+ });
+
+ it('keeps a route that opted out of discovery opted out', () => {
+ const entry = normalizeBazaarEntry({ discoverable: false, input: { type: 'query', example: { mint: MINT } } }, { method: 'GET' });
+ expect(entry.discoverable).toBe(false);
+ expectSelfValid(entry);
+ });
+
+ it('gives an empty block a minimal self-valid entry', () => {
+ const entry = normalizeBazaarEntry({}, { method: 'GET' });
+ expect(entry.info.input).toMatchObject({ type: 'http', method: 'GET' });
+ expectSelfValid(entry);
+ });
+});
+
+describe('declareHttpDiscovery', () => {
+ it('describes queryParams in the schema whenever info carries them, even with no param schema', () => {
+ expectSelfValid(declareHttpDiscovery({ method: 'GET', input: { mint: MINT } }));
+ });
+});
diff --git a/tests/probe-x402-live.test.js b/tests/probe-x402-live.test.js
new file mode 100644
index 000000000..9a97bc9a7
--- /dev/null
+++ b/tests/probe-x402-live.test.js
@@ -0,0 +1,108 @@
+// The live x402 probe applies the checklist a marketplace validator runs against
+// an unpaid request. These cases pin the verdicts that matter: a non-402 answer
+// (what the 2026-09-18 import outage looked like from outside), an oversized
+// body, and a 402 whose Bazaar block a catalog would reject.
+
+import { describe, it, expect } from 'vitest';
+import { routeKey, sampleRoutes, rebase, checkResponse } from '../scripts/probe-x402-live.mjs';
+import { declareHttpDiscovery } from '../api/_lib/x402/bazaar-helpers.js';
+
+const URL_ = 'https://three.ws/api/x402/token-intel';
+
+function challenge(overrides = {}) {
+ return {
+ x402Version: 2,
+ resource: { url: URL_, description: 'token intel', mimeType: 'application/json' },
+ accepts: [
+ {
+ scheme: 'exact',
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ amount: '10000',
+ payTo: 'THREEsynthetic11111111111111111111111111111',
+ maxTimeoutSeconds: 60,
+ extra: { name: 'USDC', decimals: 6 },
+ },
+ ],
+ extensions: { bazaar: declareHttpDiscovery({ method: 'GET', input: { mint: 'abc' }, output: { example: { ok: true } } }) },
+ ...overrides,
+ };
+}
+
+function respond(body, { status = 402, header = true } = {}) {
+ const bodyText = typeof body === 'string' ? body : JSON.stringify(body);
+ return checkResponse({
+ url: URL_,
+ status,
+ bodyBytes: Buffer.byteLength(bodyText),
+ bodyText,
+ paymentRequiredHeader: header ? Buffer.from(bodyText).toString('base64') : null,
+ });
+}
+
+describe('route sampling', () => {
+ it('collapses the parameterised datapoint catalog to one sample per handler', () => {
+ expect(routeKey('https://three.ws/api/x402/d/coin/bitcoin?x=1')).toBe('/api/x402/d/coin');
+ expect(routeKey('https://three.ws/api/x402/forge')).toBe('/api/x402/forge');
+ const targets = sampleRoutes([
+ { url: 'https://three.ws/api/x402/d/coin/bitcoin', method: 'GET' },
+ { url: 'https://three.ws/api/x402/d/coin/ethereum', method: 'GET' },
+ { url: 'https://three.ws/api/mcp', method: 'POST', extensions: { bazaar: { info: { input: { body: { jsonrpc: '2.0' } } } } } },
+ ]);
+ expect(targets.map((t) => t.route)).toEqual(['/api/x402/d/coin', '/api/mcp']);
+ expect(targets[1]).toMatchObject({ method: 'POST', body: { jsonrpc: '2.0' } });
+ });
+
+ it('rebases catalog URLs onto the probed host so a local run never tests production', () => {
+ expect(rebase('https://three.ws/api/x402/d/coin/bitcoin?x=1', 'http://localhost:8080')).toBe('http://localhost:8080/api/x402/d/coin/bitcoin?x=1');
+ const [target] = sampleRoutes([{ url: URL_, method: 'GET' }], { onto: 'http://localhost:8080' });
+ expect(target.url).toBe('http://localhost:8080/api/x402/token-intel');
+ });
+});
+
+describe('checkResponse', () => {
+ it('passes a well-formed v2 challenge', () => {
+ expect(respond(challenge())).toEqual({ failures: [], advisories: [] });
+ });
+
+ it('fails a route that answers 500, the shape of a handler that throws on import', () => {
+ const verdict = respond({ error: 'internal_error' }, { status: 500 });
+ expect(verdict.failures).toEqual(['HTTP 500, expected 402 for an unpaid request']);
+ });
+
+ it('fails an oversized body before anything else, as the validator does', () => {
+ const verdict = respond('x'.repeat(70000), { status: 200 });
+ expect(verdict.failures).toHaveLength(1);
+ expect(verdict.failures[0]).toMatch(/over the 65536-byte limit/);
+ });
+
+ it('fails a 402 with no PAYMENT-REQUIRED header', () => {
+ expect(respond(challenge(), { header: false }).failures).toEqual(['PAYMENT-REQUIRED header missing (v2 delivers PaymentRequired there)']);
+ });
+
+ it('fails a flat pre-v2 bazaar block, which has no info for a catalog to read', () => {
+ const flat = { description: 'x', input: { type: 'query', example: {} }, output: { type: 'json', example: {} }, schema: {} };
+ const verdict = respond(challenge({ extensions: { bazaar: flat } }));
+ expect(verdict.failures).toContain('bazaar.info missing');
+ expect(verdict.failures).toContain('bazaar.info.input missing');
+ });
+
+ it('fails an info block its own schema rejects', () => {
+ const bazaar = declareHttpDiscovery({ method: 'POST', input: {}, inputSchema: { type: 'object' } });
+ delete bazaar.info.input.bodyType;
+ const verdict = respond(challenge({ extensions: { bazaar } }));
+ expect(verdict.failures.join('\n')).toMatch(/fails its own schema/);
+ });
+
+ it('fails a USDC price under the marketplace minimum and an empty accepts list', () => {
+ const cheap = challenge();
+ cheap.accepts[0].amount = '500';
+ expect(respond(cheap).failures).toEqual(['accepts[0] prices 500 atomic USDC, under the $0.001 minimum']);
+ expect(respond(challenge({ accepts: [] })).failures).toContain('accepts[] missing or empty');
+ });
+
+ it('reports a missing output example as advisory, not a failure', () => {
+ const bazaar = declareHttpDiscovery({ method: 'GET', input: { mint: 'abc' } });
+ expect(respond(challenge({ extensions: { bazaar } }))).toEqual({ failures: [], advisories: ['no output metadata'] });
+ });
+});