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
docs(mcp): document the agent server's scope gating and full tool roster, pinned by catalog tests
nichc025476b8dd2
diff --git a/docs/mcp-agent.md b/docs/mcp-agent.mdindex 6fab7c319..2e65f0e7a 100644--- a/docs/mcp-agent.md+++ b/docs/mcp-agent.md@@ -8,16 +8,36 @@ Registered with the MCP Registry as **`io.github.nirholas/threews-agent`**.- **Endpoint:** `https://three.ws/api/mcp-agent`- **Transport:** Streamable HTTP (MCP `2025-06-18`)-- **Auth:** OAuth 2.1 (same three.ws authorization server as `/api/mcp`)+- **Auth:** OAuth 2.1 (same three.ws authorization server as `/api/mcp`), plus the wallet scopes below- **Money rail:** Solana USDC via the x402 `exact` scheme (`@x402/svm`)## Tools-| Tool | What it does |-|------|--------------|-| `wallet_status` | Read-only: the user's agent wallet address, SOL + USDC balance, spending caps, and whether spend is enabled. Never moves funds. |-| `find_services(query, …)` | Search the live x402 facilitator network for paid services to call. |-| `pay_and_call(resource_url, method?, body?, max_usd?)` | Call a paid x402 endpoint and auto-settle the USDC payment from the user's wallet, within caps. Returns the service response. |+| Tool | Scope required | What it does |+|------|----------------|--------------|+| `getting_started` | none (free, no sign-in) | Overview of the server and its tools. The one tool an unauthenticated client can call. |+| `wallet_status` | `wallet:read` (or `wallet:write`) | Read-only: the user's agent wallet address, SOL + USDC balance, spending caps, and whether spend is enabled. Never moves funds. |+| `find_services(query, type?, network?, max_price_usdc?, limit?)` | none beyond sign-in | Search the live x402 facilitator network for paid services to call. `max_price_usdc` accepts 0 to 1,000,000. |+| `pay_and_call(resource_url, method?, body?, max_usd?)` | `wallet:write` | Call a paid x402 endpoint and auto-settle the USDC payment from the user's wallet, within caps. Returns the service response. |+| `provision_wallet(agent_id, cluster?, airdrop?)` | `wallet:write` | Create (or return) the custodial Solana wallet for one of your own agents. Idempotent. `airdrop` is devnet only and never fires on mainnet. |+| `monetize_endpoint(agent_id, name, description, price_usdc, target_url, method?, input_schema?, network?)` | `services:write` | Publish an upstream API you already serve as a priced x402 endpoint. Buyers' USDC settles to your agent's own wallet. |++## Scopes++Every tool above that reads or moves an agent wallet is gated on an OAuth scope,+so a token minted for something else (an avatar client, say) can never read a+balance or spend a cent. An under-scoped call returns a designed result naming+the scope it needs, not a bare JSON-RPC error:++```json+{ "ok": false, "reason": "insufficient_scope", "required": "wallet:write" }+```++The three scopes (`wallet:read`, `wallet:write`, `services:write`) are advertised+in [`/.well-known/oauth-authorization-server`](https://three.ws/.well-known/oauth-authorization-server),+may be requested by any client (including dynamically-registered ones), and are+approved by name on the consent screen. Ask for them in the `scope` parameter of+the authorization request; re-authorize an existing connection to add one.## How payment worksdiff --git a/public/mcp-catalog.json b/public/mcp-catalog.jsonindex ffe9127e0..50b2b1a80 100644--- a/public/mcp-catalog.json+++ b/public/mcp-catalog.json@@ -12465,7 +12465,8 @@},"max_price_usdc": {"type": "number",- "minimum": 0+ "minimum": 0,+ "maximum": 1000000},"limit": {"type": "integer",diff --git a/tests/api/mcp-agent-catalog.test.js b/tests/api/mcp-agent-catalog.test.jsnew file mode 100644index 000000000..3b228bbd8--- /dev/null+++ b/tests/api/mcp-agent-catalog.test.js@@ -0,0 +1,92 @@+// api/_mcpagent/catalog.js — the wire contract + argument validators behind the+// agent-wallet MCP server (/api/mcp-agent). The catalog module is what turns a+// tool definition into (a) the tools/list payload external agents integrate+// against and (b) the compiled Ajv validator every tools/call argument set has+// to pass before a handler can touch a wallet. Both are asserted here directly;+// handler behaviour lives in mcp-agent.test.js.++import { describe, it, expect } from 'vitest';++import { TOOL_CATALOG, TOOLS } from '../../api/_mcpagent/catalog.js';++describe('agent-wallet MCP catalog', () => {+ it('leads with the free getting_started tool, then the wallet toolset', () => {+ expect(TOOL_CATALOG.map((t) => t.name)).toEqual([+ 'getting_started',+ 'wallet_status',+ 'find_services',+ 'pay_and_call',+ 'provision_wallet',+ 'monetize_endpoint',+ ]);+ });++ it('gives every catalog entry a handler in the dispatch map', () => {+ for (const tool of TOOL_CATALOG) {+ expect(typeof TOOLS[tool.name]?.handler).toBe('function');+ }+ // And nothing extra: the dispatch map and the wire catalog are one list.+ expect(Object.keys(TOOLS).sort()).toEqual(TOOL_CATALOG.map((t) => t.name).sort());+ });++ it('compiles a validator for each tool that declares an input schema', () => {+ for (const tool of TOOL_CATALOG) {+ if (!tool.inputSchema) continue;+ expect(typeof TOOLS[tool.name].validate).toBe('function');+ }+ });++ // ── validators: the accept path ──────────────────────────────────────────+ it('fills schema defaults into the arguments the handler will read', () => {+ const args = { query: 'weather' };+ expect(TOOLS.find_services.validate(args)).toBe(true);+ // Ajv runs with useDefaults, so the handler sees the declared defaults+ // instead of having to re-derive them.+ expect(args).toMatchObject({ query: 'weather', type: 'http', limit: 15 });++ const monetize = {+ agent_id: '11111111-1111-1111-1111-111111111111',+ name: 'Weather API',+ description: 'Live weather',+ price_usdc: 0.01,+ target_url: 'https://api.example.com/weather',+ };+ expect(TOOLS.monetize_endpoint.validate(monetize)).toBe(true);+ // Base is the default payout rail; a solana default here would have sent+ // every default-network call down the wrong payout path.+ expect(monetize).toMatchObject({ method: 'POST', network: 'base' });+ });++ // ── validators: the reject path ──────────────────────────────────────────+ it('rejects arguments that would otherwise reach a wallet', () => {+ // Unknown property: additionalProperties is closed on every tool.+ expect(TOOLS.pay_and_call.validate({ resource_url: 'https://a.test/x', evil: 1 })).toBe(+ false,+ );+ // Missing the one required argument.+ expect(TOOLS.pay_and_call.validate({})).toBe(false);+ // Not a URI.+ expect(TOOLS.pay_and_call.validate({ resource_url: 'not a url' })).toBe(false);+ // Not a uuid: provision_wallet would otherwise query agent_identities with junk.+ expect(TOOLS.provision_wallet.validate({ agent_id: 'nope' })).toBe(false);+ // A price the atomic conversion cannot express in integer notation.+ expect(TOOLS.find_services.validate({ query: 'x', max_price_usdc: 1e21 })).toBe(false);+ // A free service is not a service: price must be above zero.+ expect(+ TOOLS.monetize_endpoint.validate({+ agent_id: '11111111-1111-1111-1111-111111111111',+ name: 'Svc',+ description: 'desc',+ price_usdc: 0,+ target_url: 'https://api.example.com/x',+ }),+ ).toBe(false);+ });++ it('reports why an argument set failed so the dispatcher can quote it', () => {+ TOOLS.pay_and_call.validate({ resource_url: 123 });+ expect(TOOLS.pay_and_call.validate.errors?.[0]).toMatchObject({+ instancePath: '/resource_url',+ });+ });+});diff --git a/tests/api/mcp-agent.test.js b/tests/api/mcp-agent.test.jsindex de292c99b..e0b73264c 100644--- a/tests/api/mcp-agent.test.js+++ b/tests/api/mcp-agent.test.js@@ -44,7 +44,12 @@ const payer = await import('../../api/_lib/x402-user-payer.js');const { dispatch, isPublicTool } = await import('../../api/_mcpagent/dispatch.js');const ANON = { userId: null, rateKey: 'x402:anon', scope: '', source: 'x402' };-const USER = { userId: 'user-1', rateKey: 'user-1', scope: 'wallet:read', source: 'bearer' };+const USER = { userId: 'user-1', rateKey: 'user-1', scope: 'wallet:read wallet:write', source: 'bearer' };+// Read grant only: may look at the wallet, may never spend from it.+const READONLY = { userId: 'user-1', rateKey: 'user-1', scope: 'wallet:read', source: 'bearer' };+// A token from a client that was never granted anything wallet-shaped, e.g. a+// dynamically-registered client holding the default avatars:read.+const NOSCOPE = { userId: 'user-1', rateKey: 'user-1', scope: 'avatars:read', source: 'bearer' };const call = (name, args, auth = USER) =>dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, auth);@@ -110,6 +115,32 @@ describe('threews-agent MCP', () => {expect(r.result.content[0].text).toContain('5 USDC');});+ it('wallet_status refuses a token with no wallet grant', async () => {+ const r = await call('wallet_status', {}, NOSCOPE);+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent).toMatchObject({+ reason: 'insufficient_scope',+ required: 'wallet:read',+ });+ expect(payer.getUserWalletStatus).not.toHaveBeenCalled();+ });++ it('wallet_status accepts wallet:write as proof of read access', async () => {+ payerState.walletStatus = {+ provisioned: false,+ balances: {},+ caps: {},+ spend_enabled: false,+ };+ const r = await call(+ 'wallet_status',+ {},+ { userId: 'user-1', rateKey: 'user-1', scope: 'wallet:write', source: 'bearer' },+ );+ expect(r.result.isError).toBeUndefined();+ expect(r.result.structuredContent.signed_in).toBe(true);+ });+it('find_services searches the live bazaar', async () => {bazState.search.mockResolvedValue({resources: [{ resource: 'https://svc.test', serviceName: 'Svc', minPriceLabel: '$0.01', networks: ['solana:*'], toolName: '' }],@@ -155,6 +186,30 @@ describe('threews-agent MCP', () => {expect(r.result.structuredContent.reason).toBe('no_solana_wallet');});+ it('refuses to spend for a read-only token, before any payment call', async () => {+ const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' }, READONLY);+ expect(payer.payExternalX402).not.toHaveBeenCalled();+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent).toMatchObject({+ reason: 'insufficient_scope',+ required: 'wallet:write',+ });+ });++ it('still hands a read-only token the manual pay link when spend is off', async () => {+ payerState.spendEnabled = false;+ const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' }, READONLY);+ expect(r.result.structuredContent).toMatchObject({ paid: false, reason: 'spend_disabled' });+ expect(r.result.structuredContent.pay_link).toContain('https://three.ws/pay?resource=');+ });++ it('rejects an out-of-range max_price_usdc as invalid params, not an internal error', async () => {+ const r = await call('find_services', { query: 'weather', max_price_usdc: 1e21 });+ expect(r.error.code).toBe(-32602);+ expect(r.error.message).toContain('max_price_usdc');+ expect(bazState.search).not.toHaveBeenCalled();+ });+it('enforces the pay rate limit before spending', async () => {rl.pay = { success: false, reset: Date.now() + 30000 };const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' });diff --git a/tests/api/mcp-bazaar.test.js b/tests/api/mcp-bazaar.test.jsindex 567440023..26f9041a6 100644--- a/tests/api/mcp-bazaar.test.js+++ b/tests/api/mcp-bazaar.test.js@@ -164,6 +164,43 @@ describe('x402 Bazaar MCP', () => {expect(miss.result.structuredContent.count).toBe(0);});+ // A cap large enough that Number to String flips to exponential ("1e+21")+ // used to reach parseAtomicAmount as a non-integer string and throw a+ // TypeError out of filterByMaxPrice, failing the whole tool call.+ it('search_services treats an oversized max_price_usdc as no cap', async () => {+ bazState.search.mockResolvedValue({ resources: [item()], sources: [], errors: [] });+ const r = await call('search_services', { query: 'x', max_price_usdc: 1e21 });+ expect(r.error).toBeUndefined();+ expect(r.result.isError).toBeUndefined();+ expect(r.result.structuredContent.services).toHaveLength(1);+ });++ it('search_services caps at a large but representable price without erroring', async () => {+ bazState.search.mockResolvedValue({ resources: [item()], sources: [], errors: [] });+ const r = await call('search_services', { query: 'x', max_price_usdc: 1e15 });+ expect(r.result.structuredContent.services).toHaveLength(1);+ });++ // `network` is a user-supplied wildcard pattern compiled to a RegExp. A bare+ // "?" used to compile to /^?$/ and throw "Nothing to repeat"; a pattern that+ // matches no network must return no services, not an error.+ it('search_services returns no matches for a regex-metacharacter network', async () => {+ bazState.search.mockResolvedValue({ resources: [item()], sources: [], errors: [] });+ const r = await call('search_services', { query: 'x', network: '?' });+ expect(r.error).toBeUndefined();+ expect(r.result.isError).toBeUndefined();+ expect(r.result.structuredContent.count).toBe(0);+ });++ it('search_services still honors the * wildcard in a network filter', async () => {+ bazState.search.mockResolvedValue({ resources: [item()], sources: [], errors: [] });+ const hit = await call('search_services', { query: 'x', network: 'eip155:*' });+ expect(hit.result.structuredContent.count).toBe(1);+ bazState.search.mockResolvedValue({ resources: [item()], sources: [], errors: [] });+ const miss = await call('search_services', { query: 'x', network: 'solana:*' });+ expect(miss.result.structuredContent.count).toBe(0);+ });+it('browse_services lists without a query', async () => {bazState.list.mockResolvedValue({ items: [item()], sources: [], errors: [] });const r = await call('browse_services', {});diff --git a/tests/api/mcp-wallet-provision.test.js b/tests/api/mcp-wallet-provision.test.jsindex b53e1eab5..2a73ef50c 100644--- a/tests/api/mcp-wallet-provision.test.js+++ b/tests/api/mcp-wallet-provision.test.js@@ -153,6 +153,8 @@ describe('agent-wallet MCP — provisioning + earning', () => {// No airdrop attempted, no fabricated balance.expect(r.result.structuredContent.airdrop).toBeUndefined();expect(r.result.structuredContent.sol_balance).toBe(0.5);+ // Say so rather than dropping the argument in silence.+ expect(r.result.content[0].text).toContain('Airdrop skipped');});it('enforces the wallet:write scope', async () => {diff --git a/tests/fixtures/mcp-golden-tools.json b/tests/fixtures/mcp-golden-tools.jsonindex 04e67836b..a1b41d844 100644--- a/tests/fixtures/mcp-golden-tools.json+++ b/tests/fixtures/mcp-golden-tools.json@@ -861,7 +861,7 @@"idempotentHint": false,"openWorldHint": true},- "schemaHash": "c2ce8b0c47c9"+ "schemaHash": "85a78b392826"},{"name": "monetize_endpoint",