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(agent): wallet provisioning, pump bounties detail, mcpagent dispatch
nirholas47fb067867be
diff --git a/api/_lib/agent-paid-services.js b/api/_lib/agent-paid-services.jsindex e44e09dae..d04471f00 100644--- a/api/_lib/agent-paid-services.js+++ b/api/_lib/agent-paid-services.js@@ -165,7 +165,7 @@ export async function listBazaarServices({ limit = 200 } = {}) {const capped = Math.min(Math.max(1, limit | 0 || 200), 500);const rows = await sql`SELECT slug, name, description, price_atomics, target_method,- input_schema, network+ input_schema, network, payout_addressFROM agent_paid_servicesWHERE archived_at IS NULL AND bazaar_listed = trueORDER BY created_at DESCdiff --git a/api/_lib/pump-go.js b/api/_lib/pump-go.jsindex 1e67a6fbd..8cdaf98fc 100644--- a/api/_lib/pump-go.js+++ b/api/_lib/pump-go.js@@ -81,6 +81,7 @@ export function normalizeTask(t) {amount: fromAtomic(l.amountAtomic, l.decimalsSnapshot),remaining: fromAtomic(l.remainingAmountAtomic, l.decimalsSnapshot),amountAtomic: l.amountAtomic,+ remainingAtomic: l.remainingAmountAtomic ?? null,isSol: l.mintAddress === WSOL_MINT,vault: l.rewardVaultAddress,usd: legUsd(legsUsd, l.mintAddress),@@ -185,4 +186,85 @@ export async function getSubmissions(taskId, { limit = 30 } = {}) {};}+// ── On-chain escrow verification ───────────────────────────────────────────────+//+// Each reward leg names its on-chain RewardVault (an SPL token account owned by+// the bounty PDA). The REST listing is just content — to prove the reward is real+// we read the vault's token balance straight from the chain and check it covers+// the remaining reward. This is trustless: it doesn't rely on pump.fun's API+// being honest, only on a Solana RPC.++const RPC_URL =+ process.env.SOLANA_RPC_URL ||+ process.env.SOLANA_MAINNET_RPC ||+ 'https://api.mainnet-beta.solana.com';++// Pure: given a leg's expected remaining atomic amount and the on-chain atomic+// balance, decide whether the escrow covers it. Exported for unit testing.+export function legFunded(expectedAtomic, onChainAtomic) {+ if (onChainAtomic == null) return false;+ let have, need;+ try {+ have = BigInt(onChainAtomic);+ need = BigInt(expectedAtomic ?? 0);+ } catch {+ return false;+ }+ return have >= need && have > 0n;+}++async function getTokenAccountBalanceAtomic(vault) {+ const res = await fetch(RPC_URL, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'getTokenAccountBalance',+ params: [vault, { commitment: 'confirmed' }],+ }),+ signal: AbortSignal.timeout(TIMEOUT_MS),+ });+ if (!res.ok) throw new PumpGoError(`solana rpc ${res.status}`, 502);+ const data = await res.json();+ // A closed/nonexistent vault errors here — surface as null (unfunded), not a throw.+ if (data.error) return null;+ return data.result?.value?.amount ?? null;+}++// Verify every reward leg's vault on-chain. Returns a per-leg report plus an+// overall `verified` (true only when every leg with a positive remaining reward+// is covered by its vault balance).+export async function verifyEscrow(bounty) {+ const legs = (bounty?.reward?.legs || []).filter((l) => l.vault);+ if (!legs.length) {+ return { verified: false, checkedAt: null, legs: [], reason: 'no_vaults' };+ }+ const reports = await Promise.all(+ legs.map(async (l) => {+ let onChainAtomic = null;+ let error = null;+ try {+ onChainAtomic = await getTokenAccountBalanceAtomic(l.vault);+ } catch (e) {+ error = e?.message || 'rpc_error';+ }+ const expectedAtomic = l.remainingAtomic ?? l.amountAtomic ?? '0';+ return {+ mint: l.mint,+ isSol: l.isSol,+ vault: l.vault,+ decimals: l.decimals,+ expectedAtomic: String(expectedAtomic),+ onChainAtomic: onChainAtomic != null ? String(onChainAtomic) : null,+ funded: error ? false : legFunded(expectedAtomic, onChainAtomic),+ error,+ };+ }),+ );+ const anyError = reports.some((r) => r.error);+ const verified = reports.length > 0 && reports.every((r) => r.funded);+ return { verified, checkedAt: null, degraded: anyError, legs: reports };+}+export { REST_BASE, PROGRAM_ID, WSOL_MINT };diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.jsindex f2eef0d4d..348604e0d 100644--- a/api/_mcp3d/tools/studio.js+++ b/api/_mcp3d/tools/studio.js@@ -1613,10 +1613,9 @@ export const toolDefs = [? args.visibility: 'unlisted';const name = String(args.name).trim().slice(0, 80);- const slug = `studio-${createHash('sha256')- .update(`${auth.userId}|${name}|${args.glb_url}`)- .digest('hex')- .slice(0, 8)}`;+ // Random suffix (matches the reconstruct pipeline) so re-saving the same+ // model never collides on the per-owner unique slug constraint.+ const slug = `studio-${Math.random().toString(36).slice(2, 8)}`;const storageKey = storageKeyFor({ userId: auth.userId, slug });await putObject({diff --git a/api/_mcpagent/dispatch.js b/api/_mcpagent/dispatch.jsindex a6fd0625b..6d50759d4 100644--- a/api/_mcpagent/dispatch.js+++ b/api/_mcpagent/dispatch.js@@ -9,10 +9,12 @@ export { PROTOCOL_VERSION };const INSTRUCTIONS = ['three.ws Agent gives this assistant a real on-chain wallet on the x402 network.',- 'wallet_status shows the balance and spending caps; find_services discovers paid services;',- 'pay_and_call(resource_url) calls a paid x402 endpoint and settles the USDC payment from the',- "user's own three.ws agent wallet, within caps. Always check wallet_status before spending, and",- 'confirm the price with the user when it is non-trivial.',+ 'wallet_status shows the balance and spending caps; provision_wallet creates a custodial wallet',+ 'for one of your agents; find_services discovers paid services; pay_and_call(resource_url) calls a',+ "paid x402 endpoint and settles the USDC payment from the user's own three.ws agent wallet, within",+ 'caps; monetize_endpoint publishes one of your agent endpoints as a priced x402 service so other',+ 'agents can pay it and you earn USDC. Always check wallet_status before spending, and confirm the',+ 'price with the user when it is non-trivial.',].join(' ');export const dispatch = makeDispatcher({diff --git a/api/_mcpagent/tools.js b/api/_mcpagent/tools.jsindex 5f6075ad0..36d469374 100644--- a/api/_mcpagent/tools.js+++ b/api/_mcpagent/tools.js@@ -14,6 +14,7 @@import { limits } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';import { sql } from '../_lib/db.js';+import { hasScope } from '../_lib/auth.js';import { Bazaar, filterByMaxPrice, filterByNetwork } from '../_lib/x402/bazaar-client.js';import {getUserWalletStatus,@@ -56,6 +57,81 @@ function payLink(resource) {return u.toString();}+// Designed "sign in" result for the null x402 path — these tools write to the+// user's own account, so an anonymous pay-per-call caller can never use them.+function signInRequired(text) {+ return {+ content: [{ type: 'text', text }],+ structuredContent: { signed_in: false },+ isError: true,+ };+}++// Scope is enforced inside the handler (not via the dispatcher's tool.scope) so+// the null-userId x402 path gets the friendly signInRequired() message first,+// and an authenticated-but-under-scoped token gets a clear, designed error+// rather than a bare JSON-RPC code.+function scopeRequired(scope) {+ return {+ content: [+ { type: 'text', text: `This action needs the ${scope} scope. Re-authorize with it granted.` },+ ],+ structuredContent: { ok: false, reason: 'insufficient_scope', required: scope },+ isError: true,+ };+}++// Load an agent the caller owns. Returns { row } on success or { error } with a+// designed not-found / forbidden result so handlers stay flat.+async function loadOwnedAgent(agentId, auth) {+ const [row] = await sql`+ SELECT id, user_id, meta, wallet_address+ FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ LIMIT 1+ `;+ if (!row) {+ return {+ error: {+ content: [{ type: 'text', text: `No agent found with id ${agentId}.` }],+ structuredContent: { ok: false, reason: 'agent_not_found' },+ isError: true,+ },+ };+ }+ if (row.user_id !== auth.userId) {+ return {+ error: {+ content: [{ type: 'text', text: "That agent isn't on your account." }],+ structuredContent: { ok: false, reason: 'forbidden' },+ isError: true,+ },+ };+ }+ return { row };+}++// Request a 1 SOL devnet airdrop for a freshly provisioned wallet. Devnet only;+// never called on mainnet. Returns the signature or a reason on failure — an+// unavailable faucet must not fail the whole provision call.+async function requestDevnetAirdrop(address) {+ const { solanaConnection } = await import('../_lib/agent-pumpfun.js');+ const { PublicKey, LAMPORTS_PER_SOL } = await import('@solana/web3.js');+ try {+ const conn = solanaConnection('devnet');+ const signature = await conn.requestAirdrop(new PublicKey(address), LAMPORTS_PER_SOL);+ await conn.confirmTransaction(signature, 'confirmed');+ return { ok: true, signature, sol: 1 };+ } catch (err) {+ const rateLimited = /429|limit/i.test(err?.message || '');+ return {+ ok: false,+ reason: rateLimited ? 'faucet_rate_limited' : 'faucet_unavailable',+ message: err?.message || 'devnet airdrop failed',+ };+ }+}+export const toolDefs = [{name: 'wallet_status',@@ -224,4 +300,189 @@ export const toolDefs = [}},},+ {+ name: 'provision_wallet',+ title: "Create the agent's wallet",+ description:+ "Create (or return) the custodial Solana wallet for one of your agents so it can hold and earn USDC. Idempotent — if the agent already has a wallet, its address and live SOL/USDC balances are returned unchanged. On devnet you can request a 1 SOL airdrop for testing; mainnet wallets are never airdropped. Requires sign-in; you can only provision wallets for agents on your own account.",+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: { type: 'string', format: 'uuid', description: 'The agent to provision a wallet for.' },+ cluster: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },+ airdrop: {+ type: 'boolean',+ default: false,+ description: 'Devnet only — request a 1 SOL faucet airdrop after provisioning.',+ },+ },+ required: ['agent_id'],+ additionalProperties: false,+ },+ async handler(args, auth) {+ await enforce(limits.mcpAgent, auth);+ if (!auth.userId) {+ return signInRequired('Sign in to three.ws to provision an agent wallet.');+ }+ if (!hasScope(auth.scope, 'wallet:write')) return scopeRequired('wallet:write');++ const cluster = args.cluster === 'devnet' ? 'devnet' : 'mainnet';+ const owned = await loadOwnedAgent(args.agent_id, auth);+ if (owned.error) return owned.error;++ const { address, created } = await getOrCreateAgentSolanaWallet(args.agent_id);++ // Airdrop is devnet-only and best-effort — never on mainnet, never+ // fabricated. A faucet failure is surfaced as a note, not an error.+ let airdrop = null;+ if (cluster === 'devnet' && args.airdrop) {+ airdrop = await requestDevnetAirdrop(address);+ }++ const balances = await getSolanaAddressBalances(address, cluster);++ const lines = [+ `${created ? 'Provisioned' : 'Wallet already exists for'} agent ${args.agent_id}`,+ `Address: ${address}`,+ `Cluster: ${cluster}`,+ `Balance: ${balances.sol ?? '?'} SOL, ${balances.usdc ?? '?'} USDC`,+ ];+ if (airdrop) {+ lines.push(+ airdrop.ok+ ? `Airdropped 1 SOL on devnet (sig ${airdrop.signature}).`+ : `Devnet airdrop unavailable: ${airdrop.reason}.`,+ );+ }++ return {+ content: [{ type: 'text', text: lines.join('\n') }],+ structuredContent: {+ ok: true,+ agent_id: args.agent_id,+ address,+ cluster,+ sol_balance: balances.sol,+ usdc_balance: balances.usdc,+ created,+ ...(airdrop ? { airdrop } : {}),+ },+ };+ },+ },+ {+ name: 'monetize_endpoint',+ title: 'Publish a paid endpoint to earn USDC',+ description:+ "Put a price on an upstream API your agent already serves and publish it as an x402 endpoint other agents can pay to call. three.ws hosts the paywall, settles each buyer's USDC to your agent's own wallet, and proxies the call to your target_url. The listing becomes discoverable via find_services / the bazaar and callable by pay_and_call. Requires a provisioned wallet for the chosen network — run provision_wallet first if you haven't. Requires sign-in; you can only monetize agents on your own account.",+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: { type: 'string', format: 'uuid' },+ name: { type: 'string', minLength: 1, maxLength: 120 },+ description: { type: 'string', minLength: 1, maxLength: 2000 },+ price_usdc: { type: 'number', exclusiveMinimum: 0, description: 'Price per call in USDC.' },+ target_url: {+ type: 'string',+ format: 'uri',+ description: 'The public https upstream you already serve, called after payment settles.',+ },+ method: { type: 'string', enum: ['GET', 'POST'], default: 'POST' },+ input_schema: { type: 'object', description: 'Optional JSON Schema for the request body.' },+ network: { type: 'string', enum: ['base', 'solana'], default: 'base' },+ },+ required: ['agent_id', 'name', 'description', 'price_usdc', 'target_url'],+ additionalProperties: false,+ },+ async handler(args, auth) {+ await enforce(limits.mcpAgent, auth);+ if (!auth.userId) {+ return signInRequired('Sign in to three.ws to monetize an endpoint.');+ }+ if (!hasScope(auth.scope, 'services:write')) return scopeRequired('services:write');++ const network = args.network === 'solana' ? 'solana' : 'base';+ const owned = await loadOwnedAgent(args.agent_id, auth);+ if (owned.error) return owned.error;++ // Validate price early so an invalid value never reaches SSRF / DNS.+ let priceAtomics;+ try {+ priceAtomics = usdcToAtomics(args.price_usdc);+ } catch (err) {+ return {+ content: [{ type: 'text', text: err.message }],+ structuredContent: { ok: false, reason: err.code || 'invalid_price' },+ isError: true,+ };+ }++ // The agent must already have a payout wallet for this network.+ const payoutAddress = resolvePayoutAddress({ network, agentRow: owned.row });+ if (!payoutAddress) {+ const need = network === 'solana' ? 'a Solana wallet' : 'an EVM wallet';+ const hint =+ network === 'solana'+ ? `Run provision_wallet for this agent to create ${need}, then monetize.`+ : `This agent needs ${need} (registered at agent creation) before it can earn on Base.`;+ return {+ content: [+ { type: 'text', text: `This agent has no payout wallet on ${network}. ${hint}` },+ ],+ structuredContent: { ok: false, reason: 'no_payout_wallet', network },+ isError: true,+ };+ }++ // SSRF-guard the upstream before we persist anything.+ let targetUrl;+ try {+ targetUrl = await validateTargetUrl(args.target_url);+ } catch (err) {+ const message = err instanceof MonetizeError ? err.message : `target_url rejected: ${err?.message || err}`;+ return {+ content: [{ type: 'text', text: message }],+ structuredContent: { ok: false, reason: 'invalid_target_url' },+ isError: true,+ };+ }++ const row = await createPaidService({+ ownerUserId: auth.userId,+ agentId: args.agent_id,+ name: args.name,+ description: args.description,+ priceUsdc: args.price_usdc,+ targetUrl,+ method: args.method || 'POST',+ inputSchema: args.input_schema || null,+ network,+ payoutAddress,+ });++ const resourceUrl = serviceResourceUrl(row.slug);+ const priceUsdc = atomicsToUsdc(priceAtomics);+ return {+ content: [+ {+ type: 'text',+ text: [+ `Published "${row.name}" — $${priceUsdc} USDC per call on ${network}.`,+ `Resource: ${resourceUrl}`,+ `Payouts settle to ${payoutAddress}.`,+ 'Other agents can now find it via find_services and pay it with pay_and_call.',+ ].join('\n'),+ },+ ],+ structuredContent: {+ ok: true,+ service_id: row.id,+ resource_url: resourceUrl,+ price_usdc: priceUsdc,+ network,+ bazaar_listed: row.bazaar_listed,+ },+ };+ },+ },];diff --git a/api/pump-bounties/[id]/verify.js b/api/pump-bounties/[id]/verify.jsnew file mode 100644index 000000000..e1de9a981--- /dev/null+++ b/api/pump-bounties/[id]/verify.js@@ -0,0 +1,49 @@+// GET /api/pump-bounties/:id/verify — trustless on-chain escrow check.+//+// Reads each reward leg's RewardVault balance straight from a Solana RPC and+// confirms it covers the remaining reward. Independent of pump.fun's API being+// honest. Lazy-loaded by the detail page so the page paints first, then the+// "escrow funded" badge resolves. Cached briefly — vault balances rarely change.++import { cors, json, error, wrap, method } from '../../_lib/http.js';+import { cacheGet, cacheSet } from '../../_lib/cache.js';+import { isUuid } from '../../_lib/validate.js';+import { getBounty, verifyEscrow, PumpGoError } from '../../_lib/pump-go.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const id = req.query?.id;+ if (!id || !isUuid(id)) return error(res, 400, 'bad_request', 'valid bounty taskId required');++ const cacheKey = `pumpgo:verify:${id}`;+ const cached = await cacheGet(cacheKey).catch(() => null);+ if (cached) {+ res.setHeader('cache-control', 'public, s-maxage=45, stale-while-revalidate=180');+ return json(res, 200, cached);+ }++ let bounty;+ try {+ bounty = await getBounty(id);+ } catch (e) {+ if (e instanceof PumpGoError) return error(res, e.status, e.code, e.message);+ throw e;+ }+ if (!bounty) return error(res, 404, 'not_found', 'bounty not found');++ const result = await verifyEscrow(bounty);+ const payload = {+ ...result,+ checkedAt: new Date().toISOString(),+ programId: bounty.onChain.programId,+ bountyId: bounty.onChain.bountyId,+ };++ // Only cache a clean (non-degraded) verdict, so a transient RPC error doesn't+ // stick for the full TTL.+ if (!payload.degraded) await cacheSet(cacheKey, payload, 45).catch(() => {});+ res.setHeader('cache-control', 'public, s-maxage=45, stale-while-revalidate=180');+ return json(res, 200, payload);+});diff --git a/api/wk.js b/api/wk.jsindex 782bc1cbd..ebad6151b 100644--- a/api/wk.js+++ b/api/wk.js@@ -18,6 +18,7 @@ import {import { declareMcpDiscovery, withService } from './_lib/x402/bazaar-helpers.js';import { TOOL_CATALOG } from './_mcp/catalog.js';import { priceFor } from './_lib/pump-pricing.js';+import { listBazaarServices, serviceResourceUrl } from './_lib/agent-paid-services.js';// ── agent-attestation-schemas ─────────────────────────────────────────────────@@ -140,6 +141,11 @@ function handleOauthAuthServer(req, res) {// Bearer-token bypass via the auth-hints extension.'read:agent-reputation','x402:bypass',+ // Agent wallet MCP (api/mcp-agent): read status, provision a wallet,+ // and publish a paid endpoint to earn USDC.+ 'wallet:read',+ 'wallet:write',+ 'services:write',],service_documentation: `${base}/docs/mcp`,ui_locales_supported: ['en'],@@ -352,7 +358,88 @@ function exampleArgsForTool(tool) {return out;}-function handleX402Discovery(req, res) {+// Agent-published paid services (the `monetize_endpoint` tool). Each active,+// bazaar-listed row in agent_paid_services becomes a discovery catalog entry so+// facilitators — and therefore find_services / the bazaar — index the agent's+// endpoint the moment it's published. The advertised payTo is the agent's OWN+// payout wallet, mirroring the live 402 that api/x402/service.js serves.+//+// Never throws: a DB hiccup (or no DB, as in unit tests) yields an empty list so+// the static catalog still renders. Capped by listBazaarServices().+async function buildAgentServiceItems(origin) {+ let rows;+ try {+ rows = await listBazaarServices({ limit: 200 });+ } catch (err) {+ console.error('[wk/x402-discovery] agent services unavailable', err?.message || err);+ return [];+ }++ const items = [];+ for (const row of rows) {+ const url = serviceResourceUrl(row.slug);+ const price = RAW_AMOUNT_TO_USDC(row.price_atomics);+ const accepts = [];+ if (row.network === 'base' && row.payout_address && env.X402_ASSET_ADDRESS_BASE) {+ pushAcceptWithPermit2Sibling(accepts, {+ scheme: 'exact',+ network: NETWORK_BASE_MAINNET,+ network_label: 'base-mainnet',+ amount: String(row.price_atomics),+ price,+ payTo: row.payout_address,+ asset: env.X402_ASSET_ADDRESS_BASE,+ asset_symbol: 'USDC',+ maxTimeoutSeconds: 60,+ resource: url,+ extra: { name: 'USD Coin', version: '2', decimals: 6 },+ });+ } else if (+ row.network === 'solana' &&+ row.payout_address &&+ env.X402_ASSET_MINT_SOLANA &&+ env.X402_FEE_PAYER_SOLANA+ ) {+ accepts.push({+ scheme: 'exact',+ network: NETWORK_SOLANA_MAINNET,+ network_label: 'solana-mainnet',+ amount: String(row.price_atomics),+ price,+ payTo: row.payout_address,+ asset: env.X402_ASSET_MINT_SOLANA,+ asset_symbol: 'USDC',+ maxTimeoutSeconds: 60,+ resource: url,+ extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },+ });+ }+ // No advertisable accept (missing payout / env for this network) → skip,+ // matching the live 402 which would also refuse to advertise it.+ if (!accepts.length) continue;++ const inputSchema = row.input_schema || { type: 'object', additionalProperties: true };+ items.push({+ path: `/api/x402/service/${row.slug}`,+ url,+ method: row.target_method,+ description: row.description,+ mimeType: 'application/json',+ serviceName: row.name,+ tags: ['agent', 'monetized', row.network],+ accepts,+ extensions: extensionsForAccepts(accepts, {+ method: row.target_method,+ discoverable: true,+ input: {},+ inputSchema,+ }),+ });+ }+ return items;+}++async function handleX402Discovery(req, res) {const origin = env.APP_ORIGIN;const mcpUrl = `${origin}/api/mcp`;const modelCheckUrl = `${origin}/api/x402/model-check`;@@ -550,6 +637,9 @@ function handleX402Discovery(req, res) {// requires a pricing entry; the discovery shape follows automatically.const mcpToolItems = buildMcpToolItems({ mcpUrl, mcpAccepts, mcpService: routeMeta.mcp });+ // Agent-published paid services — dynamic, one entry per active listing.+ const agentServiceItems = await buildAgentServiceItems(origin);+return json(res,200,@@ -1307,6 +1397,9 @@ function handleX402Discovery(req, res) {// `/api/mcp` resource above is the transport entry; these are// the individual paid tools facilitators index by toolName....mcpToolItems,+ // Agent-published paid endpoints (monetize_endpoint). Dynamic —+ // one entry per active agent_paid_services listing.+ ...agentServiceItems,].filter(Boolean),},{ 'cache-control': 'public, max-age=300' },diff --git a/server-agent.json b/server-agent.jsonindex 15d746f5b..8d9eb650f 100644--- a/server-agent.json+++ b/server-agent.json@@ -1,7 +1,7 @@{"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name": "io.github.nirholas/threews-agent",- "description": "Give your AI agent a wallet: discover, pay for, and call x402 services in USDC. By three.ws.",+ "description": "Give your AI agent a wallet on the x402 network: provision a custodial wallet, discover and pay for services in USDC, and monetize your own endpoint to earn USDC from other agents. By three.ws.","repository": {"url": "https://github.com/nirholas/three.ws","source": "github"diff --git a/src/game/npc/npc-catalog.js b/src/game/npc/npc-catalog.jsindex 47e792f10..20df59785 100644--- a/src/game/npc/npc-catalog.js+++ b/src/game/npc/npc-catalog.js@@ -54,7 +54,7 @@ export function npcCatalogFor(world) {range: 5,prompt: 'Pull market intel',onInteract: ({ npc, ui }) => {- npc.say('Reading the feed — narratives and momentum, live.');+ npc.say('What do you want to see? Movers, narratives, the macro read, or a token scan.');npc.emote('av-call-me');openAixbtTerminal(npc, { ui });},diff --git a/tests/api/mcp-agent.test.js b/tests/api/mcp-agent.test.jsindex 3d78814e7..a31a66b0d 100644--- a/tests/api/mcp-agent.test.js+++ b/tests/api/mcp-agent.test.js@@ -63,7 +63,13 @@ beforeEach(() => {describe('threews-agent MCP', () => {it('lists the wallet toolset', async () => {const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, USER);- expect(r.result.tools.map((t) => t.name)).toEqual(['wallet_status', 'find_services', 'pay_and_call']);+ expect(r.result.tools.map((t) => t.name)).toEqual([+ 'wallet_status',+ 'find_services',+ 'pay_and_call',+ 'provision_wallet',+ 'monetize_endpoint',+ ]);});it('wallet_status requires sign-in', async () => {diff --git a/tests/api/mcp-wallet-provision.test.js b/tests/api/mcp-wallet-provision.test.jsnew file mode 100644index 000000000..64b765cd9--- /dev/null+++ b/tests/api/mcp-wallet-provision.test.js@@ -0,0 +1,265 @@+// provision_wallet + monetize_endpoint — the two-sided wallet tools on the+// agent-wallet MCP server (api/mcp-agent). We test orchestration: ownership,+// scope, idempotency, the mainnet-airdrop refusal, SSRF rejection of a private+// target_url, and the "no wallet → provision first" designed error. The wallet+// custody, registry DB, and SSRF resolver layers are mocked — we assert the+// tool wiring, not fund movement or real network I/O.++import { describe, it, expect, beforeEach, vi } from 'vitest';++process.env.PUBLIC_APP_ORIGIN ||= 'https://three.ws';++// ── DB (registry + agent lookup) ─────────────────────────────────────────────+const dbState = { agentRow: null, insertRow: null };+vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings) => {+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);+ if (q.includes('INSERT INTO agent_paid_services')) return [dbState.insertRow];+ if (q.includes('agent_identities')) return dbState.agentRow ? [dbState.agentRow] : [];+ return [];+ }),+}));++// ── Wallet custody layer ─────────────────────────────────────────────────────+const walletState = { address: 'SoLagentAddr1111', created: true, sol: 0.5, usdc: 0 };+vi.mock('../../api/_lib/agent-wallet.js', () => ({+ getOrCreateAgentSolanaWallet: vi.fn(async () => ({+ address: walletState.address,+ created: walletState.created,+ })),+ getSolanaAddressBalances: vi.fn(async () => ({ sol: walletState.sol, usdc: walletState.usdc })),+}));++// ── SSRF resolver — deterministic, no real DNS ───────────────────────────────+vi.mock('../../api/_lib/ssrf.js', () => {+ class SsrfError extends Error {+ constructor(message, code = 'blocked') {+ super(message);+ this.name = 'SsrfError';+ this.code = code;+ }+ }+ return {+ SsrfError,+ assertPublicHttpsUrl: vi.fn(async (rawUrl) => {+ if (/localhost|127\.0\.0\.1|169\.254|(^|\/\/)10\.|internal\b/.test(rawUrl)) {+ throw new SsrfError('host resolves to private address', 'private_address');+ }+ return rawUrl;+ }),+ };+});++// ── Imported-but-unused-here money core (must resolve) ───────────────────────+vi.mock('../../api/_lib/x402-user-payer.js', () => ({+ resolveSpendEnabled: () => true,+ getUserWalletStatus: vi.fn(async () => null),+ payExternalX402: vi.fn(async () => null),+}));++// ── Rate limits + usage ──────────────────────────────────────────────────────+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { mcpAgent: vi.fn(async () => ({ success: true, reset: 0 })) },+ clientIp: vi.fn(() => '203.0.113.9'),+}));+vi.mock('../../api/_lib/usage.js', () => ({+ recordEvent: vi.fn(),+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),+}));++const { dispatch } = 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 wallet:write services:write',+ source: 'bearer',+};+const READONLY = { userId: 'user-1', rateKey: 'user-1', scope: 'wallet:read', source: 'bearer' };++const AGENT_ID = '11111111-1111-1111-1111-111111111111';++const call = (name, args, auth = USER) =>+ dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, auth);++function ownedAgent(extra = {}) {+ return { id: AGENT_ID, user_id: 'user-1', meta: {}, wallet_address: null, ...extra };+}++beforeEach(() => {+ dbState.agentRow = ownedAgent();+ dbState.insertRow = null;+ walletState.created = true;+ walletState.sol = 0.5;+ walletState.usdc = 0;+});++describe('agent-wallet MCP — provisioning + earning', () => {+ it('exposes provision_wallet and monetize_endpoint in the catalog', async () => {+ const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, USER);+ const names = r.result.tools.map((t) => t.name);+ expect(names).toContain('provision_wallet');+ expect(names).toContain('monetize_endpoint');+ });++ // ── provision_wallet ────────────────────────────────────────────────────────++ it('provisions a wallet and returns address + balances', async () => {+ const r = await call('provision_wallet', { agent_id: AGENT_ID });+ expect(r.result.structuredContent).toMatchObject({+ ok: true,+ agent_id: AGENT_ID,+ address: 'SoLagentAddr1111',+ cluster: 'mainnet',+ created: true,+ sol_balance: 0.5,+ usdc_balance: 0,+ });+ expect(r.result.structuredContent.airdrop).toBeUndefined();+ });++ it('is idempotent — a second call returns the existing wallet (created:false)', async () => {+ walletState.created = false;+ const r = await call('provision_wallet', { agent_id: AGENT_ID });+ expect(r.result.structuredContent).toMatchObject({ ok: true, created: false, address: 'SoLagentAddr1111' });+ });++ it('rejects the anonymous x402 path with a designed sign-in error', async () => {+ const r = await call('provision_wallet', { agent_id: AGENT_ID }, ANON);+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent.signed_in).toBe(false);+ });++ it("refuses an agent the caller doesn't own", async () => {+ dbState.agentRow = ownedAgent({ user_id: 'someone-else' });+ const r = await call('provision_wallet', { agent_id: AGENT_ID });+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent.reason).toBe('forbidden');+ });++ it('reports a missing agent', async () => {+ dbState.agentRow = null;+ const r = await call('provision_wallet', { agent_id: AGENT_ID });+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent.reason).toBe('agent_not_found');+ });++ it('NEVER airdrops on mainnet, even when airdrop:true', async () => {+ const r = await call('provision_wallet', { agent_id: AGENT_ID, cluster: 'mainnet', airdrop: true });+ expect(r.result.structuredContent.cluster).toBe('mainnet');+ // No airdrop attempted, no fabricated balance.+ expect(r.result.structuredContent.airdrop).toBeUndefined();+ expect(r.result.structuredContent.sol_balance).toBe(0.5);+ });++ it('enforces the wallet:write scope', async () => {+ const r = await call('provision_wallet', { agent_id: AGENT_ID }, READONLY);+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent).toMatchObject({ reason: 'insufficient_scope', required: 'wallet:write' });+ });++ // ── monetize_endpoint ────────────────────────────────────────────────────────++ it('publishes a priced, bazaar-listed endpoint (happy path)', async () => {+ dbState.agentRow = ownedAgent({ wallet_address: '0xAgentEvmWallet' });+ dbState.insertRow = {+ id: 'svc-1',+ slug: 'weather-api-abcd1234',+ name: 'Weather API',+ description: 'Live weather',+ price_atomics: '10000',+ network: 'base',+ bazaar_listed: true,+ };+ const r = await call('monetize_endpoint', {+ agent_id: AGENT_ID,+ name: 'Weather API',+ description: 'Live weather',+ price_usdc: 0.01,+ target_url: 'https://api.example.com/weather',+ });+ expect(r.result.structuredContent).toMatchObject({+ ok: true,+ service_id: 'svc-1',+ resource_url: 'https://three.ws/api/x402/service/weather-api-abcd1234',+ price_usdc: 0.01,+ network: 'base',+ bazaar_listed: true,+ });+ });++ it('refuses to list without a payout wallet — tells the caller to provision first', async () => {+ // Base network, agent has no EVM wallet_address.+ dbState.agentRow = ownedAgent({ wallet_address: null });+ const r = await call('monetize_endpoint', {+ agent_id: AGENT_ID,+ name: 'Svc',+ description: 'desc',+ price_usdc: 0.05,+ target_url: 'https://api.example.com/x',+ network: 'solana',+ });+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent.reason).toBe('no_payout_wallet');+ expect(dbState.insertRow).toBeNull(); // nothing half-created+ });++ it('rejects a non-public (SSRF) target_url', async () => {+ dbState.agentRow = ownedAgent({ wallet_address: '0xAgentEvmWallet' });+ const r = await call('monetize_endpoint', {+ agent_id: AGENT_ID,+ name: 'Svc',+ description: 'desc',+ price_usdc: 0.05,+ target_url: 'https://169.254.169.254/latest/meta-data',+ });+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent.reason).toBe('invalid_target_url');+ });++ it('rejects a non-positive price before any DNS / DB work', async () => {+ dbState.agentRow = ownedAgent({ wallet_address: '0xAgentEvmWallet' });+ const r = await call('monetize_endpoint', {+ agent_id: AGENT_ID,+ name: 'Svc',+ description: 'desc',+ price_usdc: 0,+ target_url: 'https://api.example.com/x',+ });+ // price_usdc: 0 fails the schema (exclusiveMinimum) → -32602 invalid params.+ expect(r.error?.code).toBe(-32602);+ });++ it('requires sign-in for monetize_endpoint', async () => {+ const r = await call(+ 'monetize_endpoint',+ {+ agent_id: AGENT_ID,+ name: 'Svc',+ description: 'desc',+ price_usdc: 0.05,+ target_url: 'https://api.example.com/x',+ },+ ANON,+ );+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent.signed_in).toBe(false);+ });++ it('enforces the services:write scope', async () => {+ const r = await call(+ 'monetize_endpoint',+ {+ agent_id: AGENT_ID,+ name: 'Svc',+ description: 'desc',+ price_usdc: 0.05,+ target_url: 'https://api.example.com/x',+ },+ READONLY,+ );+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent).toMatchObject({ reason: 'insufficient_scope', required: 'services:write' });+ });+});diff --git a/tests/api/x402-discovery-parity.test.js b/tests/api/x402-discovery-parity.test.jsindex 1ac285c8d..4e6f93584 100644--- a/tests/api/x402-discovery-parity.test.js+++ b/tests/api/x402-discovery-parity.test.js@@ -27,6 +27,13 @@ const EXCLUSIONS = new Map(['returns null without CDP creds, so the live 402 (and thus the catalog) ' +'omits the route entirely in non-CDP environments.',],+ [+ '/api/x402/service',+ 'Dynamic dispatcher, not a single fixed-price route: it serves the paywall ' ++ 'for every agent-published listing at /api/x402/service/<slug>. Each ' ++ 'concrete listing is cataloged dynamically from agent_paid_services by ' ++ "handleX402Discovery's buildAgentServiceItems(), not as a static entry.",+ ],]);function paidRoutesFromFiles() {diff --git a/vercel.json b/vercel.jsonindex 763fde4b5..987f3e233 100644--- a/vercel.json+++ b/vercel.json@@ -2883,6 +2883,10 @@"src": "/paywall/","dest": "/paywall.html"},+ {+ "src": "/api/x402/service/([^/?]+)",+ "dest": "/api/x402/service.js?slug=$1"+ },{"src": "/api/x402/fact-check","dest": "/api/x402/fact-check.js"