Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(mcp-bridge): harden spending-cap test payee allowlist and add verify scripts
nirholase5123ccb6378
diff --git a/mcp-bridge/package.json b/mcp-bridge/package.jsonindex 797e21fbd..a69e6db03 100644--- a/mcp-bridge/package.json+++ b/mcp-bridge/package.json@@ -43,7 +43,7 @@"main": "./src/index.js","scripts": {"start": "node src/index.js",- "test": "node --test tests/",+ "test": "node --test \"tests/**/*.test.mjs\"","test:smoke": "node tests/smoke.mjs","inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"},diff --git a/mcp-bridge/tests/spending-cap.test.mjs b/mcp-bridge/tests/spending-cap.test.mjsindex 904012c83..bfd2887be 100644--- a/mcp-bridge/tests/spending-cap.test.mjs+++ b/mcp-bridge/tests/spending-cap.test.mjs@@ -17,13 +17,16 @@ const SYNTH_ASSET = `0x${'a'.repeat(40)}`;const SYNTH_PAYEE = `0x${'b'.repeat(40)}`;const SYNTH_OTHER_PAYEE = `0x${'c'.repeat(40)}`;-function requirements({ amount, payTo = SYNTH_PAYEE }) {+// payTo is intentionally NOT defaulted: passing `payTo: undefined` must reach+// the hook as a genuinely missing payee so the allowlist's missing-payee branch+// is exercised. Defaulting here would silently substitute an allowlisted payee.+function requirements({ amount, payTo = SYNTH_PAYEE, omitPayTo = false }) {return {selectedRequirements: {amount: String(amount),network: 'eip155:8453',asset: SYNTH_ASSET,- payTo,+ payTo: omitPayTo ? undefined : payTo,},};}@@ -102,7 +105,7 @@ test('spending-cap hook: per-call cap, payee allowlist, session ceiling', asyncassert.match(refused.reason, new RegExp(`payee "${SYNTH_OTHER_PAYEE}"`));assert.match(refused.reason, /MCP_BRIDGE_ALLOWED_PAYTO/);- const missing = await hook(requirements({ amount: 100, payTo: undefined }));+ const missing = await hook(requirements({ amount: 100, omitPayTo: true }));assert.equal(missing.abort, true, 'a missing payTo must not bypass the allowlist');const allowed = await hook(requirements({ amount: 100, payTo: SYNTH_PAYEE }));diff --git a/scripts/smoke-mcp-remotes.mjs b/scripts/smoke-mcp-remotes.mjsnew file mode 100644index 000000000..5dff6b617--- /dev/null+++ b/scripts/smoke-mcp-remotes.mjs@@ -0,0 +1,145 @@+#!/usr/bin/env node+// Live health probe for every three.ws remote MCP endpoint.+//+// Free endpoints (no x402 gate) must answer initialize + tools/list and run a+// read-only tool. Paid endpoints (whole transport gated by x402) must answer a+// bare request with a well-formed 401/402 payment challenge whose `accepts[]`+// carries valid requirements — proof the server is live and the gate is wired.+// No real payment is ever sent.+//+// node scripts/smoke-mcp-remotes.mjs # against https://three.ws+// node scripts/smoke-mcp-remotes.mjs http://localhost:3000+//+// Exit code is non-zero if any endpoint is unhealthy.++const BASE = (process.argv[2] || 'https://three.ws').replace(/\/$/, '');++// USDC on Base mainnet — the only asset a paid challenge should price in.+const USDC_BASE = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';++const ENDPOINTS = [+ {+ path: '/api/pump-fun-mcp',+ type: 'free',+ // On-chain tool that needs no external indexer — $THREE is the only mint we touch.+ probe: { name: 'get_token_details', args: { mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' } },+ },+ { path: '/api/mcp', type: 'paid' },+ { path: '/api/mcp-3d', type: 'paid' },+ { path: '/api/mcp-agent', type: 'paid' },+ { path: '/api/ibm-mcp', type: 'paid' },+ { path: '/api/mcp-bazaar', type: 'paid' },+];++function rpc(method, params, id = 1) {+ return { jsonrpc: '2.0', id, method, params };+}++// MCP Streamable HTTP may answer as application/json or as an SSE stream+// (text/event-stream). Parse the first JSON-RPC payload out of either.+function parseBody(text, contentType) {+ if (contentType.includes('text/event-stream')) {+ for (const line of text.split('\n')) {+ const t = line.trim();+ if (t.startsWith('data:')) {+ try {+ return JSON.parse(t.slice(5).trim());+ } catch {+ /* keep scanning */+ }+ }+ }+ return null;+ }+ try {+ return JSON.parse(text);+ } catch {+ return null;+ }+}++async function post(path, payload) {+ const res = await fetch(`${BASE}${path}`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ },+ body: JSON.stringify(payload),+ });+ const text = await res.text();+ return { status: res.status, body: parseBody(text, res.headers.get('content-type') || ''), raw: text };+}++function validateChallenge(body) {+ if (!body || !Array.isArray(body.accepts) || body.accepts.length === 0) {+ return 'no accepts[] in challenge body';+ }+ for (const a of body.accepts) {+ if (!a.scheme || !a.network || !a.payTo || !a.asset) {+ return `accept entry missing scheme/network/payTo/asset: ${JSON.stringify(a).slice(0, 80)}`;+ }+ }+ const base = body.accepts.find((a) => a.network === 'eip155:8453');+ if (base && base.asset.toLowerCase() !== USDC_BASE) {+ return `Base accept asset is not USDC: ${base.asset}`;+ }+ return null;+}++const results = [];++async function checkFree(ep) {+ const checks = [];+ const init = await post(ep.path, rpc('initialize', {+ protocolVersion: '2025-06-18',+ capabilities: {},+ clientInfo: { name: 'smoke', version: '0' },+ }));+ const name = init.body?.result?.serverInfo?.name;+ checks.push(['initialize', init.status === 200 && !!name, name ? `serverInfo=${name}` : `status ${init.status}`]);++ const list = await post(ep.path, rpc('tools/list', {}, 2));+ const tools = list.body?.result?.tools;+ checks.push(['tools/list', Array.isArray(tools) && tools.length > 0, `${tools?.length ?? 0} tools`]);++ const call = await post(ep.path, rpc('tools/call', { name: ep.probe.name, arguments: ep.probe.args }, 3));+ const isErr = !!call.body?.error;+ checks.push([`call ${ep.probe.name}`, !isErr, isErr ? call.body.error.message?.slice(0, 60) : 'ok']);+ return checks;+}++async function checkPaid(ep) {+ const res = await post(ep.path, rpc('initialize', {+ protocolVersion: '2025-06-18',+ capabilities: {},+ clientInfo: { name: 'smoke', version: '0' },+ }));+ const gated = res.status === 401 || res.status === 402;+ const challengeErr = validateChallenge(res.body);+ return [+ ['payment-gated', gated, `HTTP ${res.status}`],+ ['valid x402 challenge', gated && !challengeErr, challengeErr || `${res.body?.accepts?.length} accept(s)`],+ ];+}++console.log(`\nMCP remote smoke → ${BASE}\n`);+let failures = 0;+for (const ep of ENDPOINTS) {+ let checks;+ try {+ checks = ep.type === 'free' ? await checkFree(ep) : await checkPaid(ep);+ } catch (e) {+ checks = [['reachable', false, e.message]];+ }+ const epOk = checks.every((c) => c[1]);+ if (!epOk) failures++;+ console.log(`${epOk ? '✓' : '✗'} ${ep.path} (${ep.type})`);+ for (const [label, ok, detail] of checks) {+ console.log(` ${ok ? 'ok ' : 'FAIL'} ${label.padEnd(22)} ${detail}`);+ }+ results.push({ path: ep.path, ok: epOk });+}++console.log(`\n${failures === 0 ? '✓ all remotes healthy' : `✗ ${failures} endpoint(s) unhealthy`} (${results.length} checked)\n`);+process.exit(failures === 0 ? 0 : 1);diff --git a/scripts/verify-packages.mjs b/scripts/verify-packages.mjsnew file mode 100644index 000000000..f73932f50--- /dev/null+++ b/scripts/verify-packages.mjs@@ -0,0 +1,171 @@+#!/usr/bin/env node+// Pre-publish verification: pack each package into its real npm tarball, install+// it into a clean throwaway project (resolving its dependencies fresh, exactly+// as an external consumer would), then exercise its real public surface —+// import the SDK, run the CLI bin, or boot the MCP server and request tools/list.+//+// This is the strongest pre-publish gate: it catches files[] gaps, broken+// exports maps, missing/wrong runtime deps, and version-resolution issues that+// in-repo unit tests cannot see.+//+// Usage: node scripts/verify-packages.mjs [name-substring-filter]+import { mkdtempSync, writeFileSync, existsSync, rmSync, mkdirSync } from 'node:fs';+import { execFileSync, spawn } from 'node:child_process';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';++const ROOT = resolve('.');+const WORK = mkdtempSync(join(tmpdir(), 'pkg-verify-'));+const TARBALLS = join(WORK, 'tarballs');+mkdirSync(TARBALLS, { recursive: true });++// type: 'import' (node-safe ESM), 'resolve' (browser lib — verify exports resolve+// without executing), 'cli', or 'mcp' (boot stdio server + tools/list).+const PACKAGES = [+ { dir: 'packages/avatar-schema', name: '@three-ws/avatar-schema', type: 'import', expect: ['validate', 'assertValid', 'schema', 'SCHEMA_VERSION'] },+ { dir: 'packages/viewer-presets', name: '@three-ws/viewer-presets', type: 'import', expect: ['buildLightRig', 'bloomConfig', 'floorReflectionConfig'] },+ { dir: 'solana-agent-sdk', name: '@three-ws/solana-agent', type: 'import', minExports: 3 },+ { dir: 'agent-payments-sdk', name: '@three-ws/agent-payments', type: 'import', minExports: 3 },+ { dir: 'avatar-sdk', name: '@three-ws/avatar', type: 'resolve', subpaths: ['.', './agent', './viewer', './creator', './react'] },+ { dir: 'agent-ui-sdk', name: '@three-ws/agent-ui', type: 'resolve', subpaths: ['.'] },+ { dir: 'sdk', name: '@three-ws/sdk', type: 'resolve', subpaths: ['.'] },+ { dir: 'packages/avatar-cli', name: '@three-ws/avatar-cli', type: 'cli', bin: 'three-ws-avatar', siblings: ['packages/avatar-schema'] },+ { dir: 'mcp-server', name: '@3d-agent/mcp-server', type: 'mcp', bin: 'mcp-server', minTools: 15 },+ { dir: 'packages/pumpfun-mcp', name: '@three-ws/pumpfun-mcp', type: 'mcp', bin: 'pumpfun-mcp', minTools: 20 },+ { dir: 'packages/ibm-watsonx-mcp', name: '@three-ws/ibm-watsonx-mcp',type: 'mcp', bin: 'ibm-watsonx-mcp', minTools: 6, env: { WATSONX_API_KEY: 'test', WATSONX_PROJECT_ID: 'test' } },+ { dir: 'packages/ibm-x402-mcp', name: '@three-ws/ibm-x402-mcp', type: 'mcp', bin: 'ibm-x402-mcp', minTools: 6 },+ { dir: 'packages/three-token-mcp', name: '@three-ws/three-token-mcp',type: 'mcp', bin: 'three-token-mcp', minTools: 3 },+ { dir: 'packages/avatar-agent-mcp', name: '@three-ws/avatar-agent', type: 'mcp', bin: 'three-avatar-agent', minTools: 18 },+ { dir: 'packages/threews-avatar-mcp', name: '@three-ws/avatar-mcp', type: 'mcp', bin: 'avatar-mcp', minTools: 3 },+];++const filter = process.argv[2];+const targets = filter ? PACKAGES.filter((p) => p.name.includes(filter) || p.dir.includes(filter)) : PACKAGES;++function sh(cmd, args, opts = {}) {+ return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], ...opts });+}++function pack(pkg) {+ const out = sh('npm', ['pack', resolve(ROOT, pkg.dir), '--pack-destination', TARBALLS, '--json'], { cwd: ROOT });+ const meta = JSON.parse(out)[0];+ return join(TARBALLS, meta.filename);+}++function freshConsumer(pkg, tarball) {+ const dir = join(WORK, pkg.name.replace(/[@/]/g, '_'));+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'consumer', private: true, version: '1.0.0', type: 'module' }, null, 2));+ // Pack any sibling workspace deps locally so the consumer install resolves+ // them from the tarball (they aren't on the registry yet), in correct order.+ const siblingTarballs = (pkg.siblings || []).map((d) => pack({ dir: d }));+ sh('npm', ['install', ...siblingTarballs, tarball, '--no-audit', '--no-fund', '--loglevel=error'], { cwd: dir, timeout: 360_000 });+ return dir;+}++async function smokeImport(pkg, dir) {+ const code = `import * as m from ${JSON.stringify(pkg.name)};+const keys = Object.keys(m);+const expect = ${JSON.stringify(pkg.expect || [])};+const missing = expect.filter((k) => !(k in m));+if (missing.length) { console.error('MISSING EXPORTS: ' + missing.join(', ')); process.exit(3); }+const min = ${pkg.minExports || 0};+if (keys.length < min) { console.error('TOO FEW EXPORTS: ' + keys.length + ' < ' + min); process.exit(4); }+console.log('exports:' + keys.length);`;+ const out = sh('node', ['--input-type=module', '-e', code], { cwd: dir, timeout: 60_000 });+ return out.trim();+}++function smokeResolve(pkg, dir) {+ const code = `const subs = ${JSON.stringify(pkg.subpaths)};+const results = [];+for (const s of subs) {+ try { results.push(s + '=' + (import.meta.resolve(${JSON.stringify(pkg.name)} + (s === '.' ? '' : s.slice(1))) ? 'ok' : '?')); }+ catch (e) { console.error('UNRESOLVED ' + s + ': ' + e.message); process.exit(3); }+}+console.log(results.join(' '));`;+ return sh('node', ['--input-type=module', '-e', code], { cwd: dir, timeout: 60_000 }).trim();+}++function smokeCli(pkg, dir) {+ const bin = join(dir, 'node_modules', '.bin', pkg.bin);+ const ver = sh(bin, ['--version'], { cwd: dir, timeout: 30_000 }).trim();+ const help = sh(bin, ['--help'], { cwd: dir, timeout: 30_000 });+ if (!/^\d+\.\d+\.\d+/.test(ver)) throw new Error('bad --version: ' + ver);+ if (!/commands/i.test(help)) throw new Error('--help missing commands');+ // exercise a real command end-to-end+ const f = join(dir, 'sample.bin');+ writeFileSync(f, 'three-ws-avatar-cli-smoke');+ const hash = sh(bin, ['hash', f], { cwd: dir, timeout: 30_000 }).trim();+ if (!/^[a-f0-9]{64}$/.test(hash)) throw new Error('hash not 64-hex: ' + hash);+ return `v${ver} hash:${hash.slice(0, 8)}…`;+}++function smokeMcp(pkg, dir) {+ return new Promise((res, rej) => {+ const bin = join(dir, 'node_modules', '.bin', pkg.bin);+ const child = spawn('node', [bin], { cwd: dir, env: { ...process.env, ...(pkg.env || {}) }, stdio: ['pipe', 'pipe', 'pipe'] });+ let buf = '';+ let stderr = '';+ let done = false;+ const timer = setTimeout(() => finish(new Error('timeout (no tools/list response in 30s)')), 30_000);+ function finish(err, result) {+ if (done) return;+ done = true;+ clearTimeout(timer);+ try { child.kill('SIGKILL'); } catch {}+ err ? rej(new Error(err.message + (stderr ? ' | stderr: ' + stderr.slice(0, 200) : ''))) : res(result);+ }+ child.on('error', finish);+ child.stderr.on('data', (d) => (stderr += d.toString()));+ child.stdout.on('data', (d) => {+ buf += d.toString();+ let nl;+ while ((nl = buf.indexOf('\n')) >= 0) {+ const line = buf.slice(0, nl).trim();+ buf = buf.slice(nl + 1);+ if (!line) continue;+ let msg;+ try { msg = JSON.parse(line); } catch { continue; }+ if (msg.id === 1 && msg.result) {+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} }) + '\n');+ } else if (msg.id === 2) {+ if (msg.error) return finish(new Error('tools/list error: ' + JSON.stringify(msg.error)));+ const tools = msg.result?.tools || [];+ if (tools.length < pkg.minTools) return finish(new Error(`only ${tools.length} tools (expected >= ${pkg.minTools})`));+ return finish(null, `boots, ${tools.length} tools`);+ }+ }+ });+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'verify', version: '1.0.0' } } }) + '\n');+ });+}++const results = [];+for (const pkg of targets) {+ const t0 = Date.now();+ let status = 'PASS';+ let detail = '';+ try {+ const tarball = pack(pkg);+ const dir = freshConsumer(pkg, tarball);+ if (pkg.type === 'import') detail = await smokeImport(pkg, dir);+ else if (pkg.type === 'resolve') detail = smokeResolve(pkg, dir);+ else if (pkg.type === 'cli') detail = smokeCli(pkg, dir);+ else if (pkg.type === 'mcp') detail = await smokeMcp(pkg, dir);+ } catch (e) {+ status = 'FAIL';+ detail = (e.stdout ? e.stdout.toString() + ' ' : '') + (e.stderr ? e.stderr.toString() + ' ' : '') + e.message;+ detail = detail.replace(/\s+/g, ' ').trim().slice(0, 300);+ }+ const secs = ((Date.now() - t0) / 1000).toFixed(0);+ results.push({ name: pkg.name, type: pkg.type, status, detail, secs });+ console.log(`${status === 'PASS' ? '✅' : '❌'} ${pkg.name.padEnd(28)} [${pkg.type}] ${secs}s — ${detail}`);+}++const fail = results.filter((r) => r.status === 'FAIL');+console.log(`\n${results.length - fail.length}/${results.length} packages verified from a clean install.`);+if (fail.length) { console.log('FAILURES:'); fail.forEach((r) => console.log(` ${r.name}: ${r.detail}`)); }+try { rmSync(WORK, { recursive: true, force: true }); } catch {}+process.exit(fail.length ? 1 : 0);