Skip to content

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.

8.5 KB
Raw Blame
// threews-agent MCP: named commerce tools, hosted mirror of
// packages/x402-mcp/src/tools.json. Order 521 built the stdio package's 17
// fixed-endpoint, fixed-price tools (weather_forecast, domain_rdap_check, ...);
// this file gives the hosted agent the SAME names, prices and schemas so a
// client sees one consistent catalog regardless of which three.ws MCP server
// it talks to. Only the payer differs: the stdio tools sign with a local
// Solana key, these pay from the signed-in user's own three.ws agent wallet
// (payExternalX402, the same rail pay_and_call already uses).
//
// Each service name N gets a pair:
//   N_quote  (read)      prices the fixed endpoint, never pays. Reuses the
//                         same probePrice/selectRail pay_quote uses.
//   N        (financial) pays it. Gated by the shared policy runtime
//                         (packages/mcp-policy): needs N_quote's preview id
//                         plus confirm_payment: true. N_quote's preview tool
//                         name is unique to this one service, so its id can
//                         never unlock a different (cheaper or costlier)
//                         service's payment.
//
// Tool policy rows live in packages/mcp-policy/src/table.js under
// 'threews-agent', one r()/f() pair per service, generated by the same
// registry this file reads.

import { createRequire } from 'node:module';

import { limits } from '../_lib/rate-limit.js';
import { env } from '../_lib/env.js';
import { hasScope } from '../_lib/auth.js';
import { getUserWalletStatus, payExternalX402, resolveSpendEnabled } from '../_lib/x402-user-payer.js';
import { probePrice, selectRail } from '../_lib/pay/probe.js';
import {
	enforce,
	payLink,
	agreementRequired,
	scopeRequired,
	chainLabel,
	quoteRefusal,
	payBlockers,
} from './tools.js';

const require = createRequire(import.meta.url);
const registry = require('../../packages/x402-mcp/src/tools.json');

function serviceUrl(entry, args) {
	const url = new URL(entry.path, env.APP_ORIGIN);
	if (entry.method === 'GET') {
		for (const [key, value] of Object.entries(args || {})) {
			if (value === undefined) continue;
			url.searchParams.set(key, Array.isArray(value) ? value.join(',') : String(value));
		}
	}
	return url.toString();
}

function quoteToolName(entry) {
	return `${entry.name}_quote`;
}

function buildQuoteTool(entry) {
	return {
		name: quoteToolName(entry),
		title: `Price ${entry.title} without paying`,
		annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
		description: `Price three.ws's ${entry.title} (${entry.method} ${entry.path}, listed at $${entry.priceUsd}) without paying: returns the confirmation table ${entry.name} would settle from your agent wallet. Call this before ${entry.name}; it needs the quote_id this returns.`,
		inputSchema: entry.inputSchema,
		async handler(args, auth) {
			await enforce(limits.mcpAgent, auth);
			const url = serviceUrl(entry, args);
			const probe = await probePrice(url, { method: entry.method, body: entry.method === 'POST' ? args : null });
			if (probe.kind === 'error') {
				return quoteRefusal(url, probe.code, `Could not price ${entry.title}: ${probe.message}.`);
			}
			const rail = probe.kind === 'priced' ? selectRail(probe.rails, 'solana') : null;
			if (probe.kind === 'priced' && !rail) {
				const offered = [...new Set(probe.rails.map((r) => r.network).filter(Boolean))];
				return quoteRefusal(
					url,
					'no_solana_rail',
					`${entry.title} does not accept payment on Solana (it offers ${offered.join(', ') || 'no readable network'}).`,
					{ networks: offered },
				);
			}
			if (rail && rail.amount_usd == null) {
				return quoteRefusal(url, 'unreadable_price', `${entry.title} sent a payment challenge whose amount could not be read.`);
			}
			const priceUsd = rail ? rail.amount_usd : 0;

			const canReadWallet =
				Boolean(auth.userId) && (hasScope(auth.scope, 'wallet:read') || hasScope(auth.scope, 'wallet:write'));
			const wallet = canReadWallet ? await getUserWalletStatus(auth.userId) : null;
			const capPerCall = wallet?.caps?.max_per_call_usdc ?? null;
			const perCallLimit = capPerCall;
			const spendEnabled = resolveSpendEnabled();
			const blockers = payBlockers({ auth, spendEnabled, wallet, priceUsd, perCallLimit });
			const hard = blockers.filter((b) => b.hard);

			const token = rail ? (rail.usdc ? 'USDC' : String(rail.asset ?? 'unknown token')) : null;
			const lines = [`Payment preview for ${entry.title} (nothing was paid):`];
			if (rail) {
				lines.push(
					`  Recipient: ${rail.pay_to ?? 'not stated by the service'}`,
					`  Amount: ${priceUsd} ${token}`,
					`  Token: ${token}${rail.asset ? ` (${rail.asset})` : ''}`,
					`  Chain: ${chainLabel(rail.network)}`,
				);
			} else {
				lines.push(`  This endpoint did not ask for payment, so ${entry.name} would call it and pay nothing.`);
			}
			if (wallet?.provisioned) lines.push(`  From: ${wallet.address} (${wallet.balances?.usdc ?? '?'} USDC)`);
			if (perCallLimit != null) lines.push(`  Per-call limit: $${perCallLimit}`);
			for (const b of blockers) lines.push(`  ${b.hard ? 'Blocked' : 'Note'}: ${b.message}`);
			if (!auth.userId || !spendEnabled) lines.push(`  Pay manually: ${payLink(url)}`);

			return {
				content: [{ type: 'text', text: lines.join('\n') }],
				structuredContent: {
					ok: hard.length === 0,
					service: entry.name,
					resource: url,
					method: entry.method,
					free: !rail,
					recipient: rail?.pay_to ?? null,
					amount_usd: priceUsd,
					amount_atomics: rail?.amount_atomics ?? '0',
					token,
					asset: rail?.asset ?? null,
					network: rail?.network ?? null,
					from: wallet?.provisioned ? wallet.address : null,
					balance_usdc: wallet?.balances?.usdc ?? null,
					per_call_limit_usd: perCallLimit,
					spend_enabled: spendEnabled,
					blockers: blockers.map(({ code, message }) => ({ code, message })),
					...(!auth.userId || !spendEnabled ? { pay_link: payLink(url) } : {}),
				},
				...(hard.length ? { isError: true } : {}),
			};
		},
	};
}

function buildPayTool(entry) {
	return {
		name: entry.name,
		title: entry.title,
		annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
		description: `[$${entry.priceUsd} USDC per call] ${entry.description} Settles automatically from your three.ws agent wallet. Call ${quoteToolName(entry)} first and show the user its result.`,
		inputSchema: entry.inputSchema,
		async handler(args, auth) {
			await enforce(limits.mcpAgentPay, auth);
			const url = serviceUrl(entry, args);

			if (!resolveSpendEnabled() || !auth.userId) {
				return {
					content: [
						{
							type: 'text',
							text:
								(auth.userId ? 'Autonomous spending is not enabled on this server yet. ' : 'Sign in to pay from your wallet. ') +
								`You can complete this payment manually: ${payLink(url)}`,
						},
					],
					structuredContent: {
						paid: false,
						reason: auth.userId ? 'spend_disabled' : 'auth_required',
						resource: url,
						pay_link: payLink(url),
					},
				};
			}

			if (!hasScope(auth.scope, 'wallet:write')) return scopeRequired('wallet:write');

			const unsigned = await agreementRequired(auth.userId, url);
			if (unsigned) return unsigned;

			try {
				const res = await payExternalX402({
					userId: auth.userId,
					url,
					method: entry.method,
					body: entry.method === 'POST' ? args : undefined,
					maxUsd: entry.priceUsd,
				});
				return {
					content: [{ type: 'text', text: `Paid ${entry.title} from ${res.payer}. Result returned below.` }],
					structuredContent: {
						paid: true,
						payer: res.payer,
						resource: url,
						result: res.result,
						receipt: res.receipt,
					},
				};
			} catch (err) {
				const friendly = {
					spend_disabled: 'Autonomous spending is disabled on this server.',
					auth_required: 'Sign in to pay from your wallet.',
					no_wallet: 'No agent wallet found for your account. Create one on three.ws.',
					no_solana_wallet: 'Your agent has no Solana wallet provisioned.',
					invalid_url: 'That resource URL is not a permitted public https endpoint.',
					blocked_url: 'That resource URL resolves to a non-public address and was blocked.',
				};
				const msg = friendly[err.code] || `Payment failed: ${err.message}`;
				return {
					content: [{ type: 'text', text: msg }],
					structuredContent: { paid: false, reason: err.code || 'error', resource: url, pay_link: payLink(url) },
					isError: true,
				};
			}
		},
	};
}

export const namedServiceToolDefs = registry.tools.flatMap((entry) => [buildQuoteTool(entry), buildPayTool(entry)]);