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): stop registering Bazaar tools the spending cap will always refuse
nirholas77fb42662664
diff --git a/mcp-bridge/src/bazaar-discover.js b/mcp-bridge/src/bazaar-discover.jsindex 4565fd231..087f98f37 100644--- a/mcp-bridge/src/bazaar-discover.js+++ b/mcp-bridge/src/bazaar-discover.js@@ -102,8 +102,9 @@ function summarizeAccepts(accepts) {}function affordable(accepts) {- const cap = maxPriceAtomic({ strict: false });- if (cap === null) return true;+ // Same effective cap the spending-cap hook enforces (including its default):+ // a tool the hook would always refuse must never be registered.+ const cap = maxPriceAtomic();return accepts.some((a) => {try {return BigInt(a.amount) <= cap;diff --git a/mcp-bridge/src/index.js b/mcp-bridge/src/index.jsindex cde638878..dd204e498 100755--- a/mcp-bridge/src/index.js+++ b/mcp-bridge/src/index.js@@ -15,6 +15,7 @@// Transport: stdio. Claude Desktop launches the bridge with this server file// as `command` and reads/writes JSON-RPC frames over stdin/stdout.+import { createRequire } from 'node:module';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';import { z } from 'zod';@@ -24,8 +25,10 @@ import { discoverBazaarTools } from './bazaar-discover.js';import { assertPayableUrl } from './url-guard.js';import { asTextContent, asErrorContent } from './content.js';-const BRIDGE_NAME = '3d-agent-x402-bridge';-const BRIDGE_VERSION = '1.0.0';+const BRIDGE_NAME = 'three-ws-x402-bridge';+// Version is read from package.json so serverInfo can never drift from the+// published package version (tests/bridge-boot.test.mjs asserts they match).+const BRIDGE_VERSION = createRequire(import.meta.url)('../package.json').version;const log = (...args) => {// MCP stdio: stdout is reserved for protocol frames. Diagnostics MUST godiff --git a/mcp-bridge/src/url-guard.js b/mcp-bridge/src/url-guard.jsindex 804bf9d06..8a27a8f5c 100644--- a/mcp-bridge/src/url-guard.js+++ b/mcp-bridge/src/url-guard.js@@ -23,17 +23,15 @@ import net from 'node:net';const DEFAULT_MAX_PRICE_ATOMIC = 100_000n; // $0.10 USDC// ----------------------------------------------------------------------------// Shared spend-limit parsing (de-duplicated from x402-axios-client.js and-// bazaar-discover.js, which previously defined this with differing semantics).-//-// `strict: true` → throw on a negative value, return the default when unset-// (used by the spending-cap hook, which needs a real number).-// `strict: false` → return null when unset (used by bazaar discovery, which-// treats "no cap configured" as "show every tool").+// Shared spend-limit parsing: the single source of truth for the effective+// per-call cap. The spending-cap hook and Bazaar discovery MUST read the same+// value; when they disagree, discovery registers tools whose every call the+// hook then refuses. The cap always exists (default when unset), because the+// hook enforces the default even when no env var is configured.// ----------------------------------------------------------------------------export function maxPriceAtomic({ strict = true } = {}) {+export function maxPriceAtomic() {const raw = process.env.MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC;- if (!raw) return strict ? DEFAULT_MAX_PRICE_ATOMIC : null;+ if (!raw) return DEFAULT_MAX_PRICE_ATOMIC;let v;try {v = BigInt(raw);diff --git a/mcp-bridge/tests/bridge-boot.test.mjs b/mcp-bridge/tests/bridge-boot.test.mjsnew file mode 100644index 000000000..3900973be--- /dev/null+++ b/mcp-bridge/tests/bridge-boot.test.mjs@@ -0,0 +1,222 @@+// Hermetic tests for the bridge's core path: Bazaar tool naming and the+// stdio boot of the main export (src/index.js).+//+// Tool naming exercises the pure functions in bazaar-discover.js directly.+// The boot test spawns the real server with a throwaway in-process EVM key and+// MCP_BRIDGE_DISCOVER_LIMIT=0, so no network request leaves the process and no+// real keys or funds are ever involved.++import test from 'node:test';+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { mkdtempSync, rmSync } from 'node:fs';+import { createRequire } from 'node:module';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { generatePrivateKey } from 'viem/accounts';++import { deriveToolName, specsFromItems } from '../src/bazaar-discover.js';++const pkg = createRequire(import.meta.url)('../package.json');+const SERVER_PATH = join(import.meta.dirname, '..', 'src', 'index.js');++// Synthetic accepts entry, well under the default per-call cap. No real+// mints, payees, or networks-with-funds appear anywhere in these fixtures.+const CHEAP_ACCEPT = {+ scheme: 'exact',+ network: 'eip155:8453',+ amount: '1000',+ asset: `0x${'a'.repeat(40)}`,+ payTo: `0x${'b'.repeat(40)}`,+};++test('deriveToolName: URL path, generic-segment skipping, description fallback', () => {+ assert.equal(+ deriveToolName({ resource: 'https://api.vendor.example/api/v1/weather-report' }),+ 'paid_weather_report',+ 'uses the last meaningful path segment, snake_cased',+ );+ assert.equal(+ deriveToolName({ resource: 'https://vendor.example/x402/api/v2/quote/tools' }),+ 'paid_quote',+ 'skips generic segments (api, tools, vN, x402) from the right',+ );+ assert.equal(+ deriveToolName({ resource: 'not a url', description: 'Vendor · get quote' }),+ 'paid_get_quote',+ 'falls back to the description after the publisher prefix',+ );+ assert.equal(+ deriveToolName({ resource: 'not a url', description: '' }),+ 'paid_tool',+ 'falls back to a generic name when nothing usable exists',+ );+ const long = deriveToolName({ resource: `https://vendor.example/${'segment'.repeat(20)}` });+ assert.ok(long.length <= 'paid_'.length + 48, 'sanitized names are length-capped');+});++test('specsFromItems: dedupe suffixes, affordability filter, malformed-item resilience', () => {+ const items = [+ { resource: 'https://a.example/quote', description: 'quote A', accepts: [CHEAP_ACCEPT] },+ { resource: 'https://b.example/quote', description: 'quote B', accepts: [CHEAP_ACCEPT] },+ { resource: 'https://c.example/quote', description: 'quote C', accepts: [CHEAP_ACCEPT] },+ // Every accepts entry above the default 100000 cap: filtered out.+ {+ resource: 'https://d.example/pricey',+ description: 'too expensive',+ accepts: [{ ...CHEAP_ACCEPT, amount: '100001' }],+ },+ // No accepts at all: filtered out.+ { resource: 'https://e.example/free', description: 'no accepts' },+ // Malformed entry must not take the whole discovery down.+ null,+ ];+ const specs = specsFromItems(items);+ assert.deepEqual(+ specs.map((s) => s.name),+ ['paid_quote', 'paid_quote_1', 'paid_quote_2'],+ 'name collisions get numeric suffixes; unaffordable and accept-less items are dropped',+ );+ const first = specs[0];+ assert.equal(first.resource, 'https://a.example/quote');+ assert.equal(first.method, 'GET');+ assert.match(first.description, /Auto-paid via x402/);+ assert.match(first.acceptSummary, /exact@eip155:8453 1000/);+});++// Minimal JSON-RPC-over-stdio client for the boot test.+function bootBridge(env) {+ const child = spawn('node', [SERVER_PATH], {+ stdio: ['pipe', 'pipe', 'pipe'],+ env,+ });+ let buf = '';+ let stderr = '';+ let nextId = 1;+ const pending = new Map();+ child.stdout.on('data', (chunk) => {+ buf += chunk.toString('utf8');+ let nl;+ while ((nl = buf.indexOf('\n')) !== -1) {+ const line = buf.slice(0, nl);+ buf = buf.slice(nl + 1);+ if (!line.trim()) continue;+ let msg;+ try {+ msg = JSON.parse(line);+ } catch {+ continue;+ }+ if (msg.id && pending.has(msg.id)) {+ pending.get(msg.id)(msg);+ pending.delete(msg.id);+ }+ }+ });+ child.stderr.on('data', (chunk) => {+ stderr += chunk.toString('utf8');+ });+ const send = (method, params) => {+ const id = nextId++;+ const p = new Promise((resolve, reject) => {+ pending.set(id, resolve);+ setTimeout(() => {+ if (pending.has(id)) {+ pending.delete(id);+ reject(new Error(`timeout waiting for ${method}#${id}; stderr:\n${stderr}`));+ }+ }, 15_000);+ });+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');+ return p;+ };+ const stop = () => {+ child.kill('SIGTERM');+ return new Promise((r) => child.once('exit', r));+ };+ return { child, send, stop, getStderr: () => stderr };+}++// Strip any key/cap material inherited from the invoking shell so the boot is+// deterministic regardless of the developer's environment.+function hermeticEnv(extra) {+ const env = {};+ for (const [k, v] of Object.entries(process.env)) {+ if (k.startsWith('MCP_BRIDGE_') || k.startsWith('RPC_URL_')) continue;+ if (k === 'EVM_PRIVATE_KEY' || k === 'SVM_PRIVATE_KEY') continue;+ env[k] = v;+ }+ return { ...env, ...extra };+}++test('stdio boot: static tools registered with honest annotations, version matches package.json', async () => {+ const tmpRoot = mkdtempSync(join(tmpdir(), 'x402-bridge-boot-'));+ const bridge = bootBridge(+ hermeticEnv({+ MCP_BRIDGE_EVM_PRIVATE_KEY: generatePrivateKey(),+ MCP_BRIDGE_DISCOVER_LIMIT: '0',+ X402_MCP_BRIDGE_CHANNELS_DIR: join(tmpRoot, 'channels'),+ }),+ );+ try {+ const init = await bridge.send('initialize', {+ protocolVersion: '2025-03-26',+ clientInfo: { name: 'bridge-boot-test', version: '0.0.1' },+ capabilities: {},+ });+ assert.equal(init.result.serverInfo.name, 'three-ws-x402-bridge');+ assert.equal(+ init.result.serverInfo.version,+ pkg.version,+ 'serverInfo.version must track package.json, never a hardcoded copy',+ );+ bridge.child.stdin.write(+ JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n',+ );++ const listed = await bridge.send('tools/list', {});+ const byName = new Map(listed.result.tools.map((t) => [t.name, t]));+ assert.deepEqual(+ [...byName.keys()].sort(),+ ['call_paid_endpoint', 'list_bazaar_tools', 'refresh_bazaar'],+ 'with discovery disabled, exactly the three static tools are registered',+ );++ const paid = byName.get('call_paid_endpoint');+ assert.equal(paid.annotations.readOnlyHint, false);+ assert.equal(paid.annotations.idempotentHint, false);+ assert.equal(paid.annotations.openWorldHint, true);+ assert.match(paid.description, /SPENDS REAL MONEY/);++ const list = byName.get('list_bazaar_tools');+ assert.equal(list.annotations.readOnlyHint, true);+ assert.equal(list.annotations.idempotentHint, true);+ assert.equal(list.annotations.openWorldHint, false);++ const call = await bridge.send('tools/call', { name: 'list_bazaar_tools', arguments: {} });+ assert.equal(call.result.isError, undefined, 'cache read must not error');+ assert.deepEqual(+ JSON.parse(call.result.content[0].text),+ [],+ 'discovery disabled leaves an empty bazaar cache',+ );+ } finally {+ await bridge.stop();+ rmSync(tmpRoot, { recursive: true, force: true });+ }+});++test('stdio boot: refuses to start without any signer, naming both key env vars', async () => {+ const child = spawn('node', [SERVER_PATH], {+ stdio: ['ignore', 'ignore', 'pipe'],+ env: hermeticEnv({}),+ });+ let stderr = '';+ child.stderr.on('data', (chunk) => {+ stderr += chunk.toString('utf8');+ });+ const code = await new Promise((r) => child.once('exit', r));+ assert.equal(code, 1, 'boot without keys must exit non-zero');+ assert.match(stderr, /MCP_BRIDGE_EVM_PRIVATE_KEY/);+ assert.match(stderr, /MCP_BRIDGE_SVM_PRIVATE_KEY/);+});diff --git a/mcp-bridge/tests/smoke.mjs b/mcp-bridge/tests/smoke.mjsindex cdab7df44..17531d8a2 100644--- a/mcp-bridge/tests/smoke.mjs+++ b/mcp-bridge/tests/smoke.mjs@@ -4,15 +4,18 @@// real funds at risk — the bridge never tries to settle, we only exercise// the start-up path, tool listing, and the spending-cap abort).//-// Test flow:-// 1. Boot the bridge, send initialize/tools/list — assert call_paid_endpoint,-// list_bazaar_tools, refresh_bazaar exist + at least one paid_* dynamic tool.-// 2. Call call_paid_endpoint on a real x402-paid resource with-// MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC=1 — assert the response carries-// the cap-exceeded error string.-// 3. Re-launch the bridge and confirm ~/.x402-mcp-bridge/channels exists-// (storage directory survives restart). The channel file itself only-// writes after a real settlement, so we only assert the directory.+// Test flow (two boots, because the per-call cap is also the discovery+// filter: a cap of 1 atomic unit correctly hides every Bazaar tool, so the+// discovery assertions and the cap-block assertion need different caps):+// 1. Boot with the DEFAULT cap: assert call_paid_endpoint,+// list_bazaar_tools, refresh_bazaar exist + at least one paid_* dynamic+// tool, and extract a live resource URL from one.+// 2. Re-boot with MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC=1 and discovery+// disabled: call call_paid_endpoint on that URL and assert the response+// carries the cap-exceeded error string.+// 3. The second boot also proves the channels directory survives a restart.+// The channel file itself only writes after a real settlement, so we+// only assert the directory.import { spawn } from 'node:child_process';import { existsSync, mkdtempSync, rmSync } from 'node:fs';@@ -101,32 +104,47 @@ function assert(cond, msg) {const tmpRoot = mkdtempSync(join(tmpdir(), 'x402-bridge-smoke-'));const channelsDir = join(tmpRoot, 'channels');-const env = {- // Burner EVM key so the bridge can boot. We never make real settlements- // in this test, just exercise the start-up + cap-abort paths.- MCP_BRIDGE_EVM_PRIVATE_KEY: generatePrivateKey(),+// Burner EVM key so the bridge can boot. We never make real settlements+// in this test, just exercise the start-up + cap-abort paths.+const burnerKey = generatePrivateKey();++const discoveryEnv = {+ MCP_BRIDGE_EVM_PRIVATE_KEY: burnerKey,+ MCP_BRIDGE_DISCOVER_LIMIT: '20',+ X402_MCP_BRIDGE_CHANNELS_DIR: channelsDir,+};++const cappedEnv = {+ MCP_BRIDGE_EVM_PRIVATE_KEY: burnerKey,MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC: '1', // 1 atomic unit = effectively zero- MCP_BRIDGE_DISCOVER_LIMIT: '5',+ MCP_BRIDGE_DISCOVER_LIMIT: '0',X402_MCP_BRIDGE_CHANNELS_DIR: channelsDir,};try {- await withBridge(env, async ({ send }) => {+ // Boot 1 (default cap): discovery registers affordable Bazaar tools.+ let resourceUrl = null;+ await withBridge(discoveryEnv, async ({ send }) => {const tools = await send('tools/list', {});- const names = (tools.result?.tools || []).map((t) => t.name);+ const all = tools.result?.tools || [];+ const names = all.map((t) => t.name);console.log(' registered tools:', names.slice(0, 8).join(', '), '…');assert(names.includes('call_paid_endpoint'), 'call_paid_endpoint registered');assert(names.includes('list_bazaar_tools'), 'list_bazaar_tools registered');assert(names.includes('refresh_bazaar'), 'refresh_bazaar registered');assert(names.some((n) => n.startsWith('paid_')), 'at least one dynamic paid_* tool');- // Spending-cap check: call any real x402-paid endpoint with cap=1.- // The bridge SHOULD return an isError tool result mentioning the cap.- // We pick one of the discovered tools so the URL is guaranteed live.- const dynamicTool = (tools.result?.tools || []).find((t) => t.name.startsWith('paid_'));- const resourceUrl = dynamicTool ? dynamicTool.description.match(/Resource: (\S+)/)?.[1] : null;+ // Pick a discovered tool so the URL is guaranteed live; prefer a GET+ // endpoint so the request reaches the 402 payment step.+ const dynamic = all.filter((t) => t.name.startsWith('paid_'));+ const getTool = dynamic.find((t) => /Method: GET\./.test(t.description)) || dynamic[0];+ resourceUrl = getTool ? getTool.description.match(/Resource: (\S+)/)?.[1] : null;assert(!!resourceUrl, 'extracted resource URL from a dynamic tool description');+ });+ // Boot 2 (cap=1): the same URL must be refused by the spending cap before+ // any payment is signed. This restart also proves channel-dir persistence.+ await withBridge(cappedEnv, async ({ send }) => {const call = await send('tools/call', {name: 'call_paid_endpoint',arguments: { url: resourceUrl, method: 'GET' },@@ -137,15 +155,10 @@ try {JSON.stringify(call);assert(call.result?.isError === true, 'call_paid_endpoint returned isError for cap-blocked call');assert(- /exceeds spending cap|cap (1|of)/i.test(text) || /aborted/i.test(text),+ /exceeds per-call cap|exceeds spending cap|cap (1|of)/i.test(text) || /aborted/i.test(text),'error text mentions the spending cap',);});-- // Second boot: prove the channels directory survives.- await withBridge(env, async ({ send }) => {- await send('tools/list', {});- });assert(existsSync(channelsDir), 'channels directory persists across bridge restarts');assert(existsSync(join(channelsDir, 'client')), 'channels/client subdir created by FileClientChannelStorage');} finally {diff --git a/mcp-bridge/tests/url-guard.test.mjs b/mcp-bridge/tests/url-guard.test.mjsindex 316998ae5..a1ecacb21 100644--- a/mcp-bridge/tests/url-guard.test.mjs+++ b/mcp-bridge/tests/url-guard.test.mjs@@ -108,24 +108,22 @@ async function main() {// --- maxPriceAtomic shared helper ---await withEnv({ MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC: undefined }, () => {- if (maxPriceAtomic({ strict: true }) !== 100_000n)- fail('maxPriceAtomic strict default should be 100_000n');- if (maxPriceAtomic({ strict: false }) !== null)- fail('maxPriceAtomic non-strict unset should be null');+ if (maxPriceAtomic() !== 100_000n)+ fail('maxPriceAtomic default should be 100_000n even when unset');});await withEnv({ MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC: '250000' }, () => {- if (maxPriceAtomic({ strict: false }) !== 250_000n)+ if (maxPriceAtomic() !== 250_000n)fail('maxPriceAtomic should parse env value');});await withEnv({ MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC: '-5' }, () => {try {- maxPriceAtomic({ strict: true });+ maxPriceAtomic();fail('maxPriceAtomic should reject negative');} catch {/* expected */}});- pass('maxPriceAtomic strict/non-strict semantics');+ pass('maxPriceAtomic effective-cap semantics');console.log(`\nAll ${passed} url-guard checks passed.`);}