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
feat: add gate inventory and tripwire proof for MCP tool contracts
nrpo60d8c1991935
diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.jsindex fa13925a8..92fee10fa 100644--- a/api/_lib/solana/connection.js+++ b/api/_lib/solana/connection.js@@ -244,6 +244,13 @@ export function solanaRpcEndpoints(network = 'mainnet', url = null) {// keyless), so this set is curated to ones that actually respond — re-verify// any that start cooling persistently in the failover logs.'https://api.tatum.io/v3/blockchain/node/solana-mainnet',+ // MagicBlock + Tatum's gateway host — two more keyless lanes verified live+ // (getLatestBlockhash + sendTransaction enabled) on 2026-07-04 when the free+ // pool was re-probed after a Helius plan lapsed mid-cycle. They deepen the+ // keyless chain precisely for the "every paid key is exhausted" case; the+ // classifyRpcBody guard still fails them over if either returns garbage.+ 'https://rpc.magicblock.app/mainnet',+ 'https://solana-mainnet.gateway.tatum.io','https://solana.therpc.io',PUBLIC_MAINNET,// .filter(isHttpUrl) is the hard guarantee: only a value `new Connection`diff --git a/api/_lib/solana/hedged-send.js b/api/_lib/solana/hedged-send.jsnew file mode 100644index 000000000..83749ba32--- /dev/null+++ b/api/_lib/solana/hedged-send.js@@ -0,0 +1,72 @@+// Hedged Solana transaction broadcast.+//+// A signed Solana transaction has a fixed signature, so re-broadcasting the SAME+// signed bytes to many RPCs only ever lands ONCE (the cluster dedupes by+// signature). That makes it safe — and, for the free/public RPC tier where+// `sendTransaction` is the flaky, rate-limited, sometimes-throttled method — much+// faster and more reliable to fire the send at EVERY healthy endpoint at once and+// take the first that accepts it, instead of trying them one at a time.+//+// This complements the sequential `RpcFallback` (rpc-fallback.js): use the+// fallback for reads (quote, blockhash, confirm), use this to get the buy/sell tx+// onto the chain with the best land-rate the free tier can give.+//+// import { hedgedBroadcast } from './hedged-send.js';+// const { signature, landed } = await hedgedBroadcast(rawTxBase64, endpoints);+//+// Pure over an injectable `fetchImpl` so it unit-tests without a network.++/**+ * @param {string} rawTxBase64 the fully-signed transaction, base64-encoded.+ * @param {string[]} endpoints RPC URLs to race the send across.+ * @param {object} [opts]+ * @param {boolean} [opts.skipPreflight=true] skip node-side simulation (we pre-simulate ourselves).+ * @param {number} [opts.perEndpointTimeoutMs=8000] abort a single endpoint after this.+ * @param {typeof fetch} [opts.fetchImpl=fetch] injectable for tests.+ * @returns {Promise<{ signature: string, endpoint: string, accepted: number, errors: string[] }>}+ */+export async function hedgedBroadcast(rawTxBase64, endpoints, {+ skipPreflight = true,+ perEndpointTimeoutMs = 8000,+ fetchImpl = fetch,+} = {}) {+ const urls = [...new Set((endpoints || []).filter(Boolean))];+ if (!rawTxBase64 || typeof rawTxBase64 !== 'string') throw new Error('hedgedBroadcast: rawTxBase64 required');+ if (urls.length === 0) throw new Error('hedgedBroadcast: no endpoints');++ const body = JSON.stringify({+ jsonrpc: '2.0', id: 1, method: 'sendTransaction',+ params: [rawTxBase64, { encoding: 'base64', skipPreflight, maxRetries: 0 }],+ });++ const errors = [];+ let accepted = 0;+ const attempt = (url) => {+ const ac = new AbortController();+ const timer = setTimeout(() => ac.abort(), perEndpointTimeoutMs);+ return Promise.resolve()+ .then(() => fetchImpl(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body, signal: ac.signal }))+ .then(async (res) => {+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const j = await res.json();+ if (j && typeof j.result === 'string') { accepted += 1; return { signature: j.result, endpoint: url }; }+ throw new Error(j?.error?.message ? String(j.error.message).slice(0, 80) : 'no result');+ })+ .catch((e) => { errors.push(`${maskHost(url)}: ${e?.message || e}`); throw e; })+ .finally(() => clearTimeout(timer));+ };++ // Promise.any resolves with the FIRST endpoint that accepts the tx; rejects only+ // if every endpoint fails. All accepters return the same signature (signed bytes+ // are identical), so whichever wins the race is authoritative.+ try {+ const win = await Promise.any(urls.map(attempt));+ return { signature: win.signature, endpoint: win.endpoint, accepted, errors };+ } catch {+ throw new Error(`hedgedBroadcast: all ${urls.length} endpoints rejected the send — ${errors.join(' | ')}`);+ }+}++function maskHost(url) {+ try { return new URL(url).host; } catch { return String(url).slice(0, 24); }+}diff --git a/avatar-sdk/src/viewer.js b/avatar-sdk/src/viewer.jsindex 97949a35f..6fb0636ac 100644--- a/avatar-sdk/src/viewer.js+++ b/avatar-sdk/src/viewer.js@@ -28,6 +28,17 @@ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';const TAG = 'three-ws-viewer';+// three.ws-served GLBs (and any gltf-transform-optimized asset) may carry+// EXT_meshopt_compression; without a decoder GLTFLoader throws before parsing.+// Lazy + memoized so uncompressed-only consumers never pay for the wasm init.+let _meshoptPromise = null;+function getMeshoptDecoder() {+ if (!_meshoptPromise) {+ _meshoptPromise = import('three/addons/libs/meshopt_decoder.module.js').then((m) => m.MeshoptDecoder);+ }+ return _meshoptPromise;+}+class ThreeWsViewerElement extends HTMLElement {static get observedAttributes() {return ['src', 'alt', 'background', 'wallet', 'agent-id', 'api-base'];@@ -154,6 +165,7 @@ class ThreeWsViewerElement extends HTMLElement {const token = ++this._loadToken;const loader = new GLTFLoader();try {+ loader.setMeshoptDecoder(await getMeshoptDecoder());const gltf = await loader.loadAsync(url);if (token !== this._loadToken || !this._scene) return;if (this._model) { this._scene.remove(this._model); this._disposeModel(this._model); }diff --git a/docs/internal/MAINNET-TEST-2026-07-03.md b/docs/internal/MAINNET-TEST-2026-07-03.mdindex ca4eeb1ba..254ca7f5b 100644--- a/docs/internal/MAINNET-TEST-2026-07-03.md+++ b/docs/internal/MAINNET-TEST-2026-07-03.md@@ -25,7 +25,42 @@ Running log, newest last. ✅ pass · ❌ fail · ⚠ degraded/blocked (with rea**Test is BLOCKED at authentication.** No SOL spent beyond the inbound funding. Burner holds 0.759860663 SOL (recoverable in full minus a sweep fee).-## Active production bug: wallet sign-in is down+## ⛔ CORRECTED ROOT CAUSE — not the DB. Two production secrets are wrong, and 458 custodial wallets are locked.++The owner supplied the prod `DATABASE_URL`. Direct inspection **disproved** the missing-tables hypothesis below and found the real cause:++- `siws_nonces` / `siwe_nonces` **exist** on the prod DB, schema correct, and a direct `INSERT` **succeeds**. Not a DB/migration problem.+- Vercel runtime logs for the 500 show the actual error:+ `Error: Missing required env var: JWT_SECRET` at `get JWT_SECRET` → `handleNonce`.+- Vercel env inspection (v9 API): **`JWT_SECRET` is present but EMPTY** (targets preview+production, type sensitive). The nonce handler calls `hmacSha256(env.JWT_SECRET, …)` for CSRF; the env getter treats empty as missing and throws → 500. Read endpoints that never touch `JWT_SECRET` keep working, which is why only auth broke.+- **`WALLET_ENCRYPTION_KEY` is ABSENT** from prod env entirely. Custodial secret decryption ([api/_lib/secret-box.js](../../api/_lib/secret-box.js)) uses it for the v2 scheme and falls back to `JWT_SECRET` for v1 — but `JWT_SECRET` is empty too, so **both schemes are currently broken**.++### Blast radius (verified read-only against prod DB + mainnet RPC)++- **458 custodial agent wallets** hold an encrypted secret: **294 v1** (keyed off `JWT_SECRET`) + **164 v2** (keyed off `WALLET_ENCRYPTION_KEY`).+- Right now **all 458 are undecryptable** → no agent can trade, withdraw, or pay.+- **88 of them hold funds: 3.2428 SOL total** locked (native SOL only; SPL tokens/USDC/$THREE not counted, so true value is higher). Largest single: 0.320 SOL.++### ⚠️ The dangerous part — do NOT set these to new values++`JWT_SECRET` and `WALLET_ENCRYPTION_KEY` must be restored to their **exact original values**. Setting either to a freshly-generated secret makes the wallets encrypted under the old key **permanently undecryptable — the 3.24+ SOL is lost forever.** This is why I did not set them myself, and cannot: I don't have the originals, and guessing is catastrophic.++Per the account-migration memo these two were restored from the old-account pull on 2026-07-03; they have since regressed (JWT_SECRET → empty, WALLET_ENCRYPTION_KEY → removed). Something overwrote them after that restore.++### Fix (owner-only — needs the original secret values)++1. Restore the **original** `JWT_SECRET` value to prod+preview (currently empty).+2. Re-add the **original** `WALLET_ENCRYPTION_KEY` to prod (currently absent).+3. Redeploy (env changes need a new deployment to take effect).+4. Verify: `curl https://three.ws/api/auth/siws/nonce` → expect **200**.++The DB and the site are otherwise healthy — this is purely the two secrets. Once restored, this test can run end-to-end with no further changes.++---++## (SUPERSEDED — kept for the record) Original hypothesis: missing nonce tables++The reasoning below was my first hypothesis before I had DB access. **It was wrong** — the tables exist and inserts work. Left here to show the diagnostic path.`GET /api/auth/siws/nonce` and `GET /api/auth/siwe/nonce` both 500 on their `INSERT INTO {siws,siwe}_nonces`. This blocks **every wallet login on production** (Solana and Ethereum), not just this test.diff --git a/docs/roadmap/00-README.md b/docs/roadmap/00-README.mdindex 090f4aaff..df7e90b16 100644--- a/docs/roadmap/00-README.md+++ b/docs/roadmap/00-README.md@@ -29,8 +29,13 @@ three.ws is a large, live, single monorepo (see `STRUCTURE.md` for the full surfnpm run gate```This alias (added to `package.json`) runs the **offline-safe** checks only:-`test:gate` (curated money/auth unit tests) + `audit:mcp` + `audit:routes` +-`audit:handlers` + `audit:pages` + `audit:hidden-guard`. It is intentionally the+`test:gate` (curated money/auth unit tests) + `test:gate-3d` (glb-canonicalize /+animation-retarget / viewer-framing contract tests — the universal shared 3D+cores) + `audit:mcp` + `audit:mcp-golden` (golden-snapshot tripwire over every+hosted MCP tool contract; on an *intentional* contract change run+`node scripts/audit-mcp-golden.mjs --update` and commit the fixture) ++`audit:routes` + `audit:handlers` + `audit:pages` + `audit:hidden-guard` ++`audit:x402-catalog` + `audit:tokens`. It is intentionally the*offline* subset — the project doctrine (see `scripts/test-gate.mjs`) keepscatalog/handler-heavy and browser specs in `npm test`, because importing a hostedMCP catalog pulls in DB/RPC clients that **block without live credentials** (andiff --git a/docs/roadmap/_generated/01/gate-after.txt b/docs/roadmap/_generated/01/gate-after.txtnew file mode 100644index 000000000..c87240e71--- /dev/null+++ b/docs/roadmap/_generated/01/gate-after.txt@@ -0,0 +1,45 @@++> [email protected] audit:mcp-golden+> node scripts/audit-mcp-golden.mjs++[audit:mcp-golden] 73 hosted MCP tool contracts match the golden fixture++> [email protected] audit:routes+> node scripts/verify-routes.mjs++Route verify — 268 catalog pages, 1031 main routes, 1 post-filesystem routes.+ modeled dist files: 1479 · canonical-covered: 268 · literal page routes checked for shadows: 421+ filesystem boundary (handle:filesystem) present: yes++ℹ 1 advisory note(s):+ TRAILSLASH /payments/ → notfound (lands on designed 404)++✓ static checks pass: every catalog page reachable, unknown paths → designed 404, no shadowed page routes.++> [email protected] audit:handlers+> node scripts/audit-empty-handlers.mjs++✓ audit-empty-handlers: all API handlers export a body (1413 checked)++> [email protected] audit:pages+> node scripts/audit-page-index.mjs++Route audit: 137 auditable page routes, 268 documented in pages.json.+✓ Every auditable page route is documented.++ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.++> [email protected] audit:hidden-guard+> node scripts/audit-hidden-guard.mjs++✓ audit-hidden-guard: all 243 pages resolve the [hidden] guard++> [email protected] audit:x402-catalog+> node scripts/audit-x402-catalog.mjs++✓ audit-x402-catalog: all 53 x402 endpoints are documented++> [email protected] audit:tokens+> node scripts/audit-token-drift.mjs++✓ token drift unchanged: 0 hardcoded token-hex(es) (baseline 0).diff --git a/docs/roadmap/_generated/01/gate-before.txt b/docs/roadmap/_generated/01/gate-before.txtindex b5e6550b7..3889ce6b1 100644--- a/docs/roadmap/_generated/01/gate-before.txt+++ b/docs/roadmap/_generated/01/gate-before.txt@@ -1,11 +1,64 @@++> [email protected] gate+> npm run test:gate && npm run audit:mcp && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens+++> [email protected] test:gate+> node scripts/test-gate.mjs+[test-gate] running 7 critical-path test files…- RUN v4.1.7 /workspaces/three.ws+ RUN v4.1.9 /workspaces/three.wsTest Files 7 passed (7)Tests 79 passed (79)- Start at 23:00:17- Duration 6.31s (transform 3.43s, setup 0ms, import 10.15s, tests 1.46s, environment 6ms)+ Start at 01:13:13+ Duration 2.17s (transform 1.28s, setup 0ms, import 4.48s, tests 409ms, environment 1ms)[test-gate] ✓ all critical-path tests passed++> [email protected] audit:mcp+> node scripts/audit-mcp-manifests.mjs++[audit:mcp] 15 MCP manifests consistent++> [email protected] audit:routes+> node scripts/verify-routes.mjs++Route verify — 268 catalog pages, 1031 main routes, 1 post-filesystem routes.+ modeled dist files: 1477 · canonical-covered: 268 · literal page routes checked for shadows: 421+ filesystem boundary (handle:filesystem) present: yes++ℹ 1 advisory note(s):+ TRAILSLASH /payments/ → notfound (lands on designed 404)++✓ static checks pass: every catalog page reachable, unknown paths → designed 404, no shadowed page routes.++> [email protected] audit:handlers+> node scripts/audit-empty-handlers.mjs++✓ audit-empty-handlers: all API handlers export a body (1413 checked)++> [email protected] audit:pages+> node scripts/audit-page-index.mjs++Route audit: 137 auditable page routes, 268 documented in pages.json.+✓ Every auditable page route is documented.++ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.++> [email protected] audit:hidden-guard+> node scripts/audit-hidden-guard.mjs++✓ audit-hidden-guard: all 243 pages resolve the [hidden] guard++> [email protected] audit:x402-catalog+> node scripts/audit-x402-catalog.mjs++✓ audit-x402-catalog: all 53 x402 endpoints are documented++> [email protected] audit:tokens+> node scripts/audit-token-drift.mjs++✓ token drift unchanged: 0 hardcoded token-hex(es) (baseline 0).diff --git a/docs/roadmap/_generated/01/gate-inventory.md b/docs/roadmap/_generated/01/gate-inventory.mdnew file mode 100644index 000000000..e338775d7--- /dev/null+++ b/docs/roadmap/_generated/01/gate-inventory.md@@ -0,0 +1,48 @@+# Gate inventory — roadmap 01 (2026-07-04)++State of every check behind `npm run gate`, what it protects, and what changed+in this pass. Baseline: `gate-before.txt` (all green). Post-change: `gate-after.txt`.++## Checks, before this pass++| Check | Script | Protects | Status |+|---|---|---|---|+| `test:gate` | `scripts/test-gate.mjs` (7 files, 79 tests) | Money paths: tx confirmation, HTTP cache boundary, custody/spend guards, vanity flow, x402 verify, holder snapshot, healthz | green |+| `audit:mcp` | `scripts/audit-mcp-manifests.mjs` | 15 MCP registry manifests valid (publish-time rules, offline) | green |+| `audit:routes` | `scripts/verify-routes.mjs` | 1031 routes: every catalog page reachable, unknown → designed 404, no shadowed routes | green (1 advisory: `/payments/` trailing slash → 404) |+| `audit:handlers` | `scripts/audit-empty-handlers.mjs` | 1413 API handlers export a body | green |+| `audit:pages` | `scripts/audit-page-index.mjs` | Every auditable page route documented in `data/pages.json` | green (6 legacy pages lack `added` dates — advisory) |+| `audit:hidden-guard` | `scripts/audit-hidden-guard.mjs` | 243 pages resolve the `[hidden]` guard | green |+| `audit:x402-catalog` | `scripts/audit-x402-catalog.mjs` | All 53 x402 endpoints documented | green |+| `audit:tokens` | `scripts/audit-token-drift.mjs` | Design-token drift | green |++## Added in this pass (both offline, deterministic, additive)++| Check | Script | Protects |+|---|---|---|+| `test:gate-3d` | `vitest run` over `tests/glb-canonicalize.test.js`, `tests/animation-retarget.test.js`, `tests/animation-retarget-rest-pollution.test.js`, `tests/viewer-framing.test.js` (243 tests, <1s) | The universal shared 3D cores every avatar surface depends on: rig-convention → canonical-skeleton mapping, retarget correctness (incl. the michelle.glb rest-pollution regression), viewer framing/scene-graph path (headless, no WebGL needed — satisfies task 4 to the draw-call boundary) |+| `audit:mcp-golden` | `scripts/audit-mcp-golden.mjs` + fixture `tests/fixtures/mcp-golden-tools.json` | Public MCP tool contracts: 73 statically-declared tools across 15 source files (`api/_mcp/tools/*`, `api/_mcp3d/tools/*`, `api/_mcp-studio/tools.js`, `api/_mcpagent/tools.js`, `api/_mcpbazaar/tools.js`, `api/_mcpibm/tools.js`). Captures name, description hash, annotations, input-schema hash via acorn AST — **never imports catalogs** (doctrine: catalog imports block offline). Intentional change → `--update` + commit fixture. |++Tripwire proven live: see `tripwire-proof.txt` (rename of `list_my_avatars` →+exit 1 with exact diagnosis; revert → green).++## Deliberate scope decisions++- **Deploy gate (`scripts/test-gate.mjs` GATE_TESTS) untouched.** It runs inside+ the Vercel build, which sits at ~34 min against a 45-min ceiling, and every+ GATE_TESTS entry needs a matching `.vercelignore` re-include (a mismatch fails+ the deploy with a cryptic "No test files found"). Adding the 3D/golden checks+ there is an owner decision to make with build-minute headroom, not a default.+ The new checks run in the *local* `npm run gate` used at the start/end of+ every roadmap prompt — which is where the protection was missing.+- **Dynamically-built MCP tools** (e.g. `buildGettingStartedTool`) are invisible+ to static parsing and out of golden scope; they're covered by the live-server+ paths (`npm run test:mcp`, `smoke:mcp`).+- **Full-WebGL render smoke** stays in `npm test` (Playwright, browser-real via+ SwiftShader) per the offline-gate doctrine; `viewer-framing` covers the+ loader → scene-graph → framing path offline.++## Pre-existing advisories (not fixed here, per prompt 01 hand-off rules)++1. `TRAILSLASH /payments/` lands on the designed 404 (route audit advisory).+2. 6 manifest pages missing `added` dates (omitted from /changelog).diff --git a/docs/roadmap/_generated/01/tripwire-proof.txt b/docs/roadmap/_generated/01/tripwire-proof.txtnew file mode 100644index 000000000..0e25fc89c--- /dev/null+++ b/docs/roadmap/_generated/01/tripwire-proof.txt@@ -0,0 +1,10 @@+# Tripwire proof — 2026-07-04+# Temporarily renamed list_my_avatars -> list_my_avatars_RENAMED in api/_mcp/tools/avatars.js,+# ran the audit (exit code 1), reverted, re-ran (exit 0). Output while broken:++[audit:mcp-golden] api/_mcp/tools/avatars.js: tool REMOVED or renamed: list_my_avatars+[audit:mcp-golden] api/_mcp/tools/avatars.js: tool ADDED: list_my_avatars_RENAMED++[audit:mcp-golden] 2 contract change(s) vs golden fixture.+ If every change above is INTENTIONAL (reviewed as a public-contract change),+ refresh the fixture: node scripts/audit-mcp-golden.mjs --updatediff --git a/package.json b/package.jsonindex 82515e837..818676f38 100644--- a/package.json+++ b/package.json@@ -129,7 +129,9 @@"audit:routes": "node scripts/verify-routes.mjs","audit:handlers": "node scripts/audit-empty-handlers.mjs","audit:x402-catalog": "node scripts/audit-x402-catalog.mjs",- "gate": "npm run test:gate && npm run audit:mcp && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens",+ "gate": "npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens",+ "test:gate-3d": "vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js",+ "audit:mcp-golden": "node scripts/audit-mcp-golden.mjs","audit:hidden-guard": "node scripts/audit-hidden-guard.mjs","audit:tokens": "node scripts/audit-token-drift.mjs","guard:hidden": "node scripts/inject-hidden-guard.mjs --write",diff --git a/scripts/audit-mcp-golden.mjs b/scripts/audit-mcp-golden.mjsnew file mode 100644index 000000000..39a790df6--- /dev/null+++ b/scripts/audit-mcp-golden.mjs@@ -0,0 +1,166 @@+#!/usr/bin/env node+// Golden-snapshot tripwire for hosted MCP tool contracts (roadmap 01, task 2).+//+// The public contract of every hosted MCP server — tool names, descriptions,+// annotations, input schemas — is what external agents integrate against. An+// accidental rename, deletion, or schema change breaks those integrations+// silently. This audit catches that drift OFFLINE by statically parsing the+// tool-definition sources with acorn and comparing against a committed golden+// fixture. It never imports the catalog modules: project doctrine (see+// docs/roadmap/00-README.md) forbids that — importing a hosted catalog pulls+// in DB/RPC clients that block without live credentials.+//+// What it captures per statically-declared tool def (an object literal with+// `name` + `description` + `inputSchema`/`annotations` properties):+// - name (the wire-visible tool identifier)+// - descHead + descHash (first line fragment + sha256-12 of the full text)+// - annotations (boolean hints when literal, or the referenced const's name)+// - schemaHash (sha256-12 of the whitespace-normalized inputSchema source)+// Tools built dynamically (e.g. buildGettingStartedTool) are invisible to+// static parsing and are intentionally out of scope — verify those against a+// running server (`npm run test:mcp` / `smoke:mcp`).+//+// Run: node scripts/audit-mcp-golden.mjs → compare, exit 1 on drift+// node scripts/audit-mcp-golden.mjs --update → regenerate the fixture+import { readFileSync, writeFileSync, readdirSync } from 'node:fs';+import { createHash } from 'node:crypto';+import { resolve, dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { parse } from 'acorn';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const FIXTURE = join(ROOT, 'tests', 'fixtures', 'mcp-golden-tools.json');++// Every hosted MCP server's tool-definition sources. A new hosted server MUST+// be added here (and the fixture regenerated) or its contract is unguarded.+const SOURCES = [+ ...readdirSync(join(ROOT, 'api/_mcp/tools')).map((f) => `api/_mcp/tools/${f}`),+ ...readdirSync(join(ROOT, 'api/_mcp3d/tools')).map((f) => `api/_mcp3d/tools/${f}`),+ 'api/_mcp-studio/tools.js',+ 'api/_mcpagent/tools.js',+ 'api/_mcpbazaar/tools.js',+ 'api/_mcpibm/tools.js',+].filter((f) => f.endsWith('.js')).sort();++const sha12 = (text) => createHash('sha256').update(text).digest('hex').slice(0, 12);++function templateText(node) {+ // Cooked template text with `${…}` marking interpolations — stable across+ // formatting changes, sensitive to wording changes.+ return node.quasis.map((q) => q.value.cooked ?? '').join('${…}');+}++function stringValue(node) {+ if (!node) return null;+ if (node.type === 'Literal' && typeof node.value === 'string') return node.value;+ if (node.type === 'TemplateLiteral') return templateText(node);+ return null;+}++function annotationsValue(node) {+ if (!node) return undefined;+ if (node.type === 'Identifier') return `ref:${node.name}`;+ if (node.type !== 'ObjectExpression') return 'dynamic';+ const out = {};+ for (const p of node.properties) {+ if (p.type !== 'Property' || p.computed) { out['…'] = 'dynamic'; continue; }+ const key = p.key.name ?? p.key.value;+ out[key] = p.value.type === 'Literal' ? p.value.value+ : p.value.type === 'Identifier' ? `ref:${p.value.name}`+ : 'dynamic';+ }+ return out;+}++function extractTools(file) {+ const src = readFileSync(join(ROOT, file), 'utf8');+ const ast = parse(src, { ecmaVersion: 'latest', sourceType: 'module' });+ const tools = [];++ (function walk(node) {+ if (!node || typeof node.type !== 'string') return;+ if (node.type === 'ObjectExpression') {+ const props = new Map();+ for (const p of node.properties) {+ if (p.type === 'Property' && !p.computed) props.set(p.key.name ?? p.key.value, p.value);+ }+ const name = stringValue(props.get('name'));+ const hasContract = props.has('description') && (props.has('inputSchema') || props.has('annotations'));+ if (name && hasContract) {+ const desc = stringValue(props.get('description'));+ const schemaNode = props.get('inputSchema');+ tools.push({+ name,+ descHead: desc ? desc.split('\n')[0].slice(0, 72) : 'dynamic',+ descHash: desc ? sha12(desc) : 'dynamic',+ annotations: annotationsValue(props.get('annotations')),+ schemaHash: !schemaNode ? undefined+ : schemaNode.type === 'Identifier' ? `ref:${schemaNode.name}`+ : sha12(src.slice(schemaNode.start, schemaNode.end).replace(/\s+/g, ' ')),+ });+ }+ }+ for (const key of Object.keys(node)) {+ const v = node[key];+ if (Array.isArray(v)) v.forEach(walk);+ else if (v && typeof v.type === 'string') walk(v);+ }+ })(ast);++ tools.sort((a, b) => a.name.localeCompare(b.name));+ return tools;+}++const current = {};+for (const file of SOURCES) {+ const tools = extractTools(file);+ if (tools.length) current[file] = tools;+}++if (process.argv.includes('--update')) {+ writeFileSync(FIXTURE, `${JSON.stringify(current, null, '\t')}\n`);+ const count = Object.values(current).reduce((n, t) => n + t.length, 0);+ console.log(`[audit:mcp-golden] fixture updated: ${count} tool contracts across ${Object.keys(current).length} files`);+ process.exit(0);+}++let golden;+try {+ golden = JSON.parse(readFileSync(FIXTURE, 'utf8'));+} catch {+ console.error(`[audit:mcp-golden] missing/unreadable fixture ${FIXTURE}`);+ console.error(' bootstrap it: node scripts/audit-mcp-golden.mjs --update');+ process.exit(1);+}++let drift = 0;+const complain = (msg) => { drift += 1; console.error(`[audit:mcp-golden] ${msg}`); };++for (const file of new Set([...Object.keys(golden), ...Object.keys(current)])) {+ const before = new Map((golden[file] ?? []).map((t) => [t.name, t]));+ const after = new Map((current[file] ?? []).map((t) => [t.name, t]));+ for (const name of before.keys()) {+ if (!after.has(name)) complain(`${file}: tool REMOVED or renamed: ${name}`);+ }+ for (const [name, tool] of after) {+ const prev = before.get(name);+ if (!prev) { complain(`${file}: tool ADDED: ${name}`); continue; }+ for (const field of ['descHash', 'schemaHash']) {+ if (JSON.stringify(prev[field]) !== JSON.stringify(tool[field])) {+ complain(`${file}: ${name}.${field.replace('Hash', '')} changed (was "${prev.descHead}")`);+ }+ }+ if (JSON.stringify(prev.annotations) !== JSON.stringify(tool.annotations)) {+ complain(`${file}: ${name}.annotations changed`);+ }+ }+}++const count = Object.values(current).reduce((n, t) => n + t.length, 0);+if (drift) {+ console.error(`\n[audit:mcp-golden] ${drift} contract change(s) vs golden fixture.`);+ console.error(' If every change above is INTENTIONAL (reviewed as a public-contract change),');+ console.error(' refresh the fixture: node scripts/audit-mcp-golden.mjs --update');+ process.exit(1);+}+console.log(`[audit:mcp-golden] ${count} hosted MCP tool contracts match the golden fixture`);diff --git a/tests/fixtures/mcp-golden-tools.json b/tests/fixtures/mcp-golden-tools.jsonnew file mode 100644index 000000000..64b997f6f--- /dev/null+++ b/tests/fixtures/mcp-golden-tools.json@@ -0,0 +1,658 @@+{+ "api/_mcp-studio/tools.js": [+ {+ "name": "forge_avatar",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:GEN_ANNOTATIONS",+ "schemaHash": "d0b27741c3cf"+ },+ {+ "name": "forge_free",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:GEN_ANNOTATIONS",+ "schemaHash": "324b0832b9e2"+ },+ {+ "name": "mesh_forge",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:GEN_ANNOTATIONS",+ "schemaHash": "8282c22b2dc6"+ },+ {+ "name": "rig_mesh",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:GEN_ANNOTATIONS",+ "schemaHash": "69bf89c0d2be"+ },+ {+ "name": "text_to_avatar",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:GEN_ANNOTATIONS",+ "schemaHash": "dfba7138f9a1"+ }+ ],+ "api/_mcp/tools/agents.js": [+ {+ "name": "call_agent",+ "descHead": "Send a message to another three.ws agent and get its response. Use this ",+ "descHash": "3d9116ed9950",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "944e8f9d1ef7"+ },+ {+ "name": "identity_check",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "4b32993a5276"+ },+ {+ "name": "register_agent",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "a5ae268bcb2d"+ }+ ],+ "api/_mcp/tools/animations.js": [+ {+ "name": "apply_animation",+ "descHead": "Retarget a curated animation preset onto a caller-supplied rigged humano",+ "descHash": "e42328286a5c",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "ae2a6528b1ba"+ },+ {+ "name": "list_animations",+ "descHead": "List the curated, retargetable animation presets in the three.ws library",+ "descHash": "97f136897e7b",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "schemaHash": "1f6841da513b"+ },+ {+ "name": "text_to_animation",+ "descHead": "Generate a brand-new motion from a natural-language prompt (e.g. \"waving",+ "descHash": "e69992039d1a",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "a72f659ddf98"+ }+ ],+ "api/_mcp/tools/avatars.js": [+ {+ "name": "delete_avatar",+ "descHead": "Soft-delete an avatar you own. Requires avatars:delete scope.",+ "descHash": "7e867ad19f8c",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "15b6f07fa18e"+ },+ {+ "name": "get_avatar",+ "descHead": "Fetch a single avatar by id or by owner+slug. Returns metadata and a mod",+ "descHash": "7d13b04e4e9a",+ "annotations": "ref:READ_ANNOTATIONS",+ "schemaHash": "613746a8df6f"+ },+ {+ "name": "list_my_avatars",+ "descHead": "List the authenticated user's avatars. Returns id, name, slug, size, vis",+ "descHash": "63b8ad84489b",+ "annotations": "ref:READ_ANNOTATIONS",+ "schemaHash": "9e46bf1d5ddb"+ },+ {+ "name": "render_avatar",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:READ_ANNOTATIONS",+ "schemaHash": "f6112443c499"+ },+ {+ "name": "render_avatar_image",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "37a7804715a6"+ },+ {+ "name": "search_public_avatars",+ "descHead": "Search the public avatar gallery. Useful for finding characters to rende",+ "descHash": "50269f56daf0",+ "annotations": "ref:READ_ANNOTATIONS",+ "schemaHash": "5d9b231c5a24"+ }+ ],+ "api/_mcp/tools/embed.js": [+ {+ "name": "get_embed_code",+ "descHead": "Return a ready-to-paste <iframe> embed snippet (plus shareable URL, oEmb",+ "descHash": "757acd12b3f0",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "19fef9f6debc"+ }+ ],+ "api/_mcp/tools/memory.js": [+ {+ "name": "forget",+ "descHead": "Delete a memory you own by its id.",+ "descHash": "c7a3d36e6024",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "755f21dddd24"+ },+ {+ "name": "recall",+ "descHead": "Retrieve the most relevant memories for a query from one of your agents.",+ "descHash": "2f63c3847d9b",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "ff6704725285"+ },+ {+ "name": "remember",+ "descHead": "Store a long-term memory for one of your agents. Use for durable facts: ",+ "descHash": "ae6892ef85bb",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "8033e83ac438"+ }+ ],+ "api/_mcp/tools/models.js": [+ {+ "name": "inspect_model",+ "descHead": "Parse a remote GLB or glTF and return structural stats: scene/node/mesh ",+ "descHash": "b8209ee26651",+ "annotations": "ref:INSPECTION_ANNOTATIONS",+ "schemaHash": "508ba4931749"+ },+ {+ "name": "optimize_model",+ "descHead": "Inspect the model and return actionable suggestions for reducing size an",+ "descHash": "6aae82cc8273",+ "annotations": "ref:INSPECTION_ANNOTATIONS",+ "schemaHash": "508ba4931749"+ },+ {+ "name": "validate_model",+ "descHead": "Run the Khronos glTF-Validator against a remote GLB or glTF URL. Returns",+ "descHash": "1ad7ca463dbe",+ "annotations": "ref:INSPECTION_ANNOTATIONS",+ "schemaHash": "ec4de14d2fb0"+ }+ ],+ "api/_mcp/tools/oracle.js": [+ {+ "name": "oracle_arm_watch",+ "descHead": "Arm your agent to automatically act on Oracle conviction signals. Once a",+ "descHash": "d659c5146b5d",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "schemaHash": "2fd3f728039c"+ },+ {+ "name": "oracle_coin",+ "descHead": "Get Oracle's full conviction verdict for a specific pump.fun coin by min",+ "descHash": "b2e49ba1236a",+ "annotations": "ref:LIVE_ANNOTATIONS",+ "schemaHash": "e49439fea65e"+ },+ {+ "name": "oracle_top_plays",+ "descHead": "Get the current top pump.fun launches ranked by Oracle conviction score.",+ "descHash": "61cecaf86ed6",+ "annotations": "ref:LIVE_ANNOTATIONS",+ "schemaHash": "e6121e0129f6"+ },+ {+ "name": "oracle_watch_status",+ "descHead": "Check your agent's current Oracle watch configuration and its realized t",+ "descHash": "9edf65c96476",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "schemaHash": "7187ef4e7b09"+ }+ ],+ "api/_mcp/tools/pumpfun.js": [+ {+ "name": "pumpfun_creator_intel",+ "descHead": "Reputation profile for a pump.fun creator wallet: prior launches, gradua",+ "descHash": "11009779c558",+ "annotations": "ref:LIVE_FEED_ANNOTATIONS",+ "schemaHash": "d70ded99f0a8"+ },+ {+ "name": "pumpfun_recent_claims",+ "descHead": "Fetch the most recent pump.fun GitHub social-fee claim events with full ",+ "descHash": "cb6200c9fb5a",+ "annotations": "ref:LIVE_FEED_ANNOTATIONS",+ "schemaHash": "167128e5fd74"+ },+ {+ "name": "pumpfun_recent_graduations",+ "descHead": "Tokens that recently graduated from the bonding curve to PumpAMM, with c",+ "descHash": "caf218a6cdd6",+ "annotations": "ref:LIVE_FEED_ANNOTATIONS",+ "schemaHash": "167128e5fd74"+ },+ {+ "name": "pumpfun_token_intel",+ "descHead": "Full intel on a pump.fun token: graduation status, bonding-curve progres",+ "descHash": "d1119e50045e",+ "annotations": "ref:LIVE_FEED_ANNOTATIONS",+ "schemaHash": "f98dc82b28e7"+ }+ ],+ "api/_mcp/tools/solana.js": [+ {+ "name": "solana_agent_attestations",+ "descHead": "List recent on-chain attestations about a Solana-registered agent (feedb",+ "descHash": "2c83176df84d",+ "annotations": "ref:ATTESTATION_READ_ANNOTATIONS",+ "schemaHash": "19470067c940"+ },+ {+ "name": "solana_agent_passport",+ "descHead": "Full discovery card for a Solana agent: identity (Metaplex Core asset), ",+ "descHash": "6320bafe75df",+ "annotations": "ref:ATTESTATION_READ_ANNOTATIONS",+ "schemaHash": "dab5747d2c2b"+ },+ {+ "name": "solana_agent_reputation",+ "descHead": "Computed reputation summary for a Solana-registered three.ws agent. Retu",+ "descHash": "5c3aa420b75e",+ "annotations": "ref:ATTESTATION_READ_ANNOTATIONS",+ "schemaHash": "72791cf29a31"+ }+ ],+ "api/_mcp/tools/trader.js": [+ {+ "name": "copy_status",+ "descHead": "List all your active copy-trading subscriptions, with sizing config, exe",+ "descHash": "d18378cae20d",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "schemaHash": "e478f4f47bac"+ },+ {+ "name": "copy_subscribe",+ "descHead": "Set up non-custodial copy-trading: mirror a leader agent's future pump.f",+ "descHash": "d4c0a89a60dd",+ "annotations": "ref:WRITE",+ "schemaHash": "4371f009b2b2"+ },+ {+ "name": "trader_leaderboard",+ "descHead": "Get the top pump.fun traders on three.ws ranked by composite TraderScore",+ "descHash": "51e91774fd99",+ "annotations": "ref:LIVE",+ "schemaHash": "ab27ab6634a8"+ },+ {+ "name": "trader_profile",+ "descHead": "Get the full, verifiable track record for a specific pump.fun agent trad",+ "descHash": "aaff472b3eae",+ "annotations": "ref:LIVE",+ "schemaHash": "4dc84b2cce04"+ }+ ],+ "api/_mcp3d/tools/studio.js": [+ {+ "name": "auto_rig_model",+ "descHead": "Turn a static GLB mesh into an animation-ready character: adds a humanoi",+ "descHash": "832b32ab5642",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "7009c009db7d"+ },+ {+ "name": "capture_scene",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "dc76eb022976"+ },+ {+ "name": "create_agent_persona",+ "descHead": "Turn a generated GLB into a NAMED, persistent agent body — a \"persona\" t",+ "descHash": "716809d092b0",+ "annotations": "ref:PERSONA_CREATE_ANNOTATIONS",+ "schemaHash": "7d650a9be810"+ },+ {+ "name": "direct_prompt",+ "descHead": "Rewrite a rough idea into an optimized text_to_3d prompt using IBM Grani",+ "descHash": "1e1c7ac5025f",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "2d5958c4b914"+ },+ {+ "name": "generate_material",+ "descHead": "Generate a physically-based (PBR) glTF 2.0 material from a text descript",+ "descHash": "50c812e688fc",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "e146204d56d4"+ },+ {+ "name": "generation_status",+ "descHead": "Poll a text_to_3d or image_to_3d job by its job_id. While running it rep",+ "descHash": "2fdc15375822",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "2d3db883d926"+ },+ {+ "name": "get_agent_persona",+ "descHead": "Bring back a previously minted persona by its persona_id — the SAME body",+ "descHash": "04388b6c47b0",+ "annotations": "ref:PERSONA_READ_ANNOTATIONS",+ "schemaHash": "b8451da964a3"+ },+ {+ "name": "image_to_3d",+ "descHead": "Reconstruct a textured 3D model (GLB) from a reference image using the t",+ "descHash": "cf4145f4d88b",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "02b319a19d1c"+ },+ {+ "name": "persona_say",+ "descHead": "Make a persona PERFORM a reply: the body lip-syncs the text and shows th",+ "descHash": "7ce7c147f8f6",+ "annotations": "ref:PERSONA_SAY_ANNOTATIONS",+ "schemaHash": "497937ffa9cc"+ },+ {+ "name": "pose_model",+ "descHead": "Map a natural-language pose description to a deterministic pose-studio s",+ "descHash": "f90f437e72b1",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "schemaHash": "5659e1a9db1c"+ },+ {+ "name": "preview_3d",+ "descHead": "Render any public GLB URL as an inline <model-viewer> HTML artifact — or",+ "descHash": "ed4b123a6d3e",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true+ },+ "schemaHash": "ad6b903dc3c5"+ },+ {+ "name": "remesh_model",+ "descHead": "Process an existing GLB/OBJ/STL/PLY mesh: fix holes and degenerate geome",+ "descHash": "47b083320257",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "c0c577c37614"+ },+ {+ "name": "remove_background",+ "descHead": "Strip the background from a photo or illustration with the three.ws back",+ "descHash": "3334882948e5",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "137e26fac1e6"+ },+ {+ "name": "retexture_model",+ "descHead": "Generate a fresh texture for an untextured or poorly-textured GLB with t",+ "descHash": "6cc85e4e6fb7",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "43f9aed91920"+ },+ {+ "name": "retexture_region",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "b7bf7bb6cf9e"+ },+ {+ "name": "save_avatar",+ "descHead": "Persist a generated GLB (e.g. the glb_url returned by generation_status)",+ "descHash": "de0ef1a0a729",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "ae4e2c32ab4f"+ },+ {+ "name": "segment_model",+ "descHead": "Segment a GLB/OBJ/STL/PLY mesh into meaningful parts with clean boundari",+ "descHash": "be034074eec2",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "0bf100913339"+ },+ {+ "name": "stylize_model",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "4fd28829ddac"+ },+ {+ "name": "text_to_3d",+ "descHead": "Turn a text description into a textured 3D model (GLB). Runs a fast text",+ "descHash": "8d96a3f07c0f",+ "annotations": "ref:GENERATIVE_ANNOTATIONS",+ "schemaHash": "764012918b1c"+ }+ ],+ "api/_mcpagent/tools.js": [+ {+ "name": "find_services",+ "descHead": "Search the live x402 facilitator network for paid services (HTTP APIs an",+ "descHash": "10b9605cf0c4",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "c2ce8b0c47c9"+ },+ {+ "name": "monetize_endpoint",+ "descHead": "Put a price on an upstream API your agent already serves and publish it ",+ "descHash": "43e54e8d4142",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "ba14c8f9eb27"+ },+ {+ "name": "pay_and_call",+ "descHead": "Call a paid x402 endpoint and settle the USDC payment automatically from",+ "descHash": "590dd66c69e6",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "9c9654820288"+ },+ {+ "name": "provision_wallet",+ "descHead": "Create (or return) the custodial Solana wallet for one of your agents so",+ "descHash": "aea787e2cec2",+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "575d608cdcde"+ },+ {+ "name": "wallet_status",+ "descHead": "Show the signed-in user's three.ws agent wallet: address, SOL and USDC b",+ "descHash": "e8cef61875a7",+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true+ },+ "schemaHash": "b3761fba59a0"+ }+ ],+ "api/_mcpbazaar/tools.js": [+ {+ "name": "bazaar_service_details",+ "descHead": "Resolve the current live price of a single x402 service by its resource ",+ "descHash": "32ef6c0a06fd",+ "annotations": "ref:DISCOVERY_ANNOTATIONS",+ "schemaHash": "8b343836306d"+ },+ {+ "name": "browse_services",+ "descHead": "List paid agent services from the live x402 facilitator network without ",+ "descHash": "5f4946b4f7d3",+ "annotations": "ref:DISCOVERY_ANNOTATIONS",+ "schemaHash": "24d42c431f67"+ },+ {+ "name": "get_service",+ "descHead": "Resolve a single x402 service by its resource URL (and tool_name for MCP",+ "descHash": "b38eb5052ab1",+ "annotations": "ref:DISCOVERY_ANNOTATIONS",+ "schemaHash": "8b343836306d"+ },+ {+ "name": "search_services",+ "descHead": "Ranked search across the live x402 facilitator network for paid agent se",+ "descHash": "7e71185f12b2",+ "annotations": "ref:DISCOVERY_ANNOTATIONS",+ "schemaHash": "b9757f337ea2"+ }+ ],+ "api/_mcpibm/tools.js": [+ {+ "name": "ibm_granite_analyze",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:generativeAnnotations",+ "schemaHash": "d52c3000def8"+ },+ {+ "name": "ibm_granite_chat",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:generativeAnnotations",+ "schemaHash": "ddda8f410a4c"+ },+ {+ "name": "ibm_granite_code",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:generativeAnnotations",+ "schemaHash": "727fb084f050"+ },+ {+ "name": "ibm_granite_embed",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:deterministicAnnotations",+ "schemaHash": "dab504ead530"+ },+ {+ "name": "ibm_granite_forecast",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "ref:generativeAnnotations",+ "schemaHash": "ca5737f97470"+ },+ {+ "name": "ibm_granite_getting_started",+ "descHead": "dynamic",+ "descHash": "dynamic",+ "annotations": "dynamic",+ "schemaHash": "77bf1a795265"+ }+ ]+}diff --git a/tests/hedged-send.test.js b/tests/hedged-send.test.jsnew file mode 100644index 000000000..7210900ef--- /dev/null+++ b/tests/hedged-send.test.js@@ -0,0 +1,61 @@+import { describe, it, expect } from 'vitest';+import { hedgedBroadcast } from '../api/_lib/solana/hedged-send.js';++// A fake fetch factory: map url → behavior. `ok` returns a signature, `slow`+// resolves after a delay, `fail` returns an RPC error, `http` a non-200.+function makeFetch(behaviors) {+ return (url, _opts) => {+ const b = behaviors[url];+ if (!b) return Promise.reject(new Error('unmocked ' + url));+ if (b.type === 'fail') return Promise.resolve({ ok: true, json: async () => ({ error: { message: b.message || 'rpc error' } }) });+ if (b.type === 'http') return Promise.resolve({ ok: false, status: b.status || 429 });+ if (b.type === 'reject') return Promise.reject(new Error(b.message || 'network'));+ // ok / slow+ const resp = { ok: true, json: async () => ({ result: b.signature || 'SIG_' + url.slice(-4) }) };+ if (b.type === 'slow') return new Promise((r) => setTimeout(() => r(resp), b.delay ?? 50));+ return Promise.resolve(resp);+ };+}++const E = ['https://a.rpc', 'https://b.rpc', 'https://c.rpc'];++describe('hedgedBroadcast', () => {+ it('returns the first endpoint that accepts the tx', async () => {+ const fetchImpl = makeFetch({+ 'https://a.rpc': { type: 'slow', delay: 80, signature: 'SIG_A' },+ 'https://b.rpc': { type: 'ok', signature: 'SIG_WIN' },+ 'https://c.rpc': { type: 'fail', message: '429 max usage' },+ });+ const r = await hedgedBroadcast('AQAB', E, { fetchImpl });+ expect(r.signature).toBe('SIG_WIN');+ expect(r.endpoint).toBe('https://b.rpc');+ });++ it('still lands when SOME endpoints 403/429/error — free-tier reality', async () => {+ const fetchImpl = makeFetch({+ 'https://a.rpc': { type: 'http', status: 403 },+ 'https://b.rpc': { type: 'reject', message: 'ECONNRESET' },+ 'https://c.rpc': { type: 'ok', signature: 'SIG_C' },+ });+ const r = await hedgedBroadcast('AQAB', E, { fetchImpl });+ expect(r.signature).toBe('SIG_C');+ expect(r.accepted).toBe(1);+ });++ it('throws only when EVERY endpoint rejects, aggregating reasons', async () => {+ const fetchImpl = makeFetch({+ 'https://a.rpc': { type: 'http', status: 429 },+ 'https://b.rpc': { type: 'fail', message: 'blockhash not found' },+ 'https://c.rpc': { type: 'reject', message: 'timeout' },+ });+ await expect(hedgedBroadcast('AQAB', E, { fetchImpl })).rejects.toThrow(/all 3 endpoints rejected/);+ });++ it('dedupes endpoints and rejects empty / bad input', async () => {+ const fetchImpl = makeFetch({ 'https://a.rpc': { type: 'ok', signature: 'SIG_A' } });+ const r = await hedgedBroadcast('AQAB', ['https://a.rpc', 'https://a.rpc'], { fetchImpl });+ expect(r.signature).toBe('SIG_A');+ await expect(hedgedBroadcast('', E, { fetchImpl })).rejects.toThrow(/rawTxBase64 required/);+ await expect(hedgedBroadcast('AQAB', [], { fetchImpl })).rejects.toThrow(/no endpoints/);+ });+});