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: three-token-mcp tools + agent MCP docs/tests, payments updates
nirholasec5e2ac077e3
diff --git a/docs/mcp-agent.md b/docs/mcp-agent.mdnew file mode 100644index 000000000..308c650ad--- /dev/null+++ b/docs/mcp-agent.md@@ -0,0 +1,69 @@+# three.ws Agent — MCP server ("add a wallet to Claude")++The first MCP server where the assistant can **transact real value**: discover,+pay for, and call paid x402 services in USDC — settled on-chain from the+signed-in user's own three.ws agent wallet, bounded by spending caps.++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`)+- **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. |++## How payment works++`pay_and_call` reuses the audited SDK payment path — it does **not** hand-roll+transactions:++1. Resolve the signed-in user's primary agent wallet (`agent_identities`, Solana).+2. Recover the keypair (`recoverSolanaAgentKeypair`) and build an `x402Client`+ with `ExactSvmScheme`.+3. Install the platform spending cap (`enforceCap → commit / rollback`).+4. `wrapAxiosWithPayment` runs the 402 → sign → retry → settle dance.++Per-call/hour/day caps come from `X402_MAX_PER_CALL_ATOMIC`,+`X402_MAX_PER_HOUR_ATOMIC`, `X402_MAX_PER_DAY_ATOMIC` (atomic USDC, 6 decimals).+A `max_usd` argument can only **lower** the per-call cap, never raise it.++## Safety gate — this moves real money++Autonomous spending is **off** unless `THREEWS_AGENT_PAY_ENABLED=1`. While off,+`pay_and_call` returns the exact payment details and a `/pay` link instead of+moving funds. `wallet_status` and `find_services` work regardless.++**Before enabling spend in production:** run a funded-wallet integration test+against a live x402 endpoint (confirm a real USDC settlement + cap enforcement ++rollback on failure). Do not enable the flag for the public until that passes.++## Configuration++| Env | Purpose |+|-----|---------|+| `THREEWS_AGENT_PAY_ENABLED` | `1` to enable autonomous spend. Default off. |+| `X402_MAX_PER_CALL_ATOMIC` / `_HOUR_` / `_DAY_` | Spending caps (atomic USDC). |+| `SOLANA_RPC_URL` | RPC for balance reads + settlement. |++## Publishing to the MCP Registry++Manifest: [`server-agent.json`](../server-agent.json).++```bash+mcp-publisher login github+mcp-publisher publish --file server-agent.json+```++## Local development++```bash+npm run dev+npx @modelcontextprotocol/inspector http://localhost:5173/api/mcp-agent+```diff --git a/marketplace/plugins/three-ws-developer/.claude-plugin/plugin.json b/marketplace/plugins/three-ws-developer/.claude-plugin/plugin.jsonindex 6929455e5..b7123e89f 100644--- a/marketplace/plugins/three-ws-developer/.claude-plugin/plugin.json+++ b/marketplace/plugins/three-ws-developer/.claude-plugin/plugin.json@@ -15,7 +15,6 @@"@3d-agent/mcp-server"],"env": {- "MCP_EVM_PAYMENT_ADDRESS": "${MCP_EVM_PAYMENT_ADDRESS}","MCP_SVM_PAYMENT_ADDRESS": "${MCP_SVM_PAYMENT_ADDRESS}"}}diff --git a/mcp-server/server.json b/mcp-server/server.jsonindex 1b1e33065..fa941a2b2 100644--- a/mcp-server/server.json+++ b/mcp-server/server.json@@ -1,7 +1,7 @@{"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name": "io.github.nirholas/3d-agent-mcp",- "description": "Paid MCP tools for the 3d-agent stack by three.ws — pose generation, pump.fun snapshots, ERC-8004 agent reputation, and a Solana vanity grinder. Settled in USDC via x402.",+ "description": "Paid MCP tools for the 3d-agent stack by three.ws — pose generation, pump.fun snapshots, ERC-8004 agent reputation, and a Solana vanity grinder. Settled in USDC on Solana via x402.","repository": {"url": "https://github.com/nirholas/three.ws","source": "github",@@ -17,15 +17,9 @@"type": "stdio"},"environmentVariables": [- {- "name": "MCP_EVM_PAYMENT_ADDRESS",- "description": "Base address that receives USDC when a client pays for a tool call (falls back to X402_PAY_TO_BASE). Required to settle paid tools on Base.",- "format": "string",- "isRequired": false- },{"name": "MCP_SVM_PAYMENT_ADDRESS",- "description": "Solana address that receives USDC payments (falls back to X402_PAY_TO_SOLANA / X402_PAY_TO). Required to settle paid tools on Solana.",+ "description": "Solana address that receives USDC when a client pays for a tool call (falls back to X402_PAY_TO_SOLANA / X402_PAY_TO). Required to settle paid tools.","format": "string","isRequired": false},diff --git a/mcp-server/src/payments.js b/mcp-server/src/payments.jsindex 30f2e9044..6712634b9 100644--- a/mcp-server/src/payments.js+++ b/mcp-server/src/payments.js@@ -1,22 +1,21 @@-// Shared x402 payment wiring for paid MCP tools.+// Shared x402 payment wiring for paid MCP tools — Solana mainnet only.//// Every tool in mcp-server/src/tools/*.js wraps its handler in-// `paid(toolName, { schemeName, priceUsd, networks, inputSchema, ...}, fn)`.-// This file builds the single shared x402ResourceServer (one per process)-// that verifies + settles against the configured facilitators, and exposes-// `paid()` that produces the McpServer.tool() callback per the @x402/mcp-// transport spec (PaymentRequired in structuredContent + content[0].text,-// settlement response under _meta["x402/payment-response"]).+// `paid(cfg, fn)`. This file builds the single shared x402ResourceServer+// (one per process) that verifies + settles USDC payments on Solana via+// PayAI's Solana facilitator, and exposes `paid()` that produces the+// McpServer.tool() callback per the @x402/mcp transport spec+// (PaymentRequired in structuredContent + content[0].text, settlement+// response under _meta["x402/payment-response"]).//-// Networks supported here:-// - Base mainnet (eip155:8453) via CDP when CDP_API_KEY_ID/CDP_API_KEY_SECRET-// are set, else via PayAI's facilitator. Receiver: MCP_EVM_PAYMENT_ADDRESS-// (falls back to X402_PAY_TO_BASE).-// - Solana mainnet via PayAI's Solana facilitator. Receiver:-// MCP_SVM_PAYMENT_ADDRESS (falls back to X402_PAY_TO_SOLANA).+// Network: Solana mainnet (solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp).+// Receiver: MCP_SVM_PAYMENT_ADDRESS (falls back to X402_PAY_TO_SOLANA /+// X402_PAY_TO). Asset: USDC (EPjFW…), 6 decimals. Fee payer:+// X402_FEE_PAYER_SOLANA.//-// Both EVM `exact` + `upto` are registered so the vanity grinder can use-// upto-style metered billing while the other tools stay on exact.+// Only the `exact` scheme is supported: @x402/svm ships no `upto` scheme, so+// metered/`upto` billing is not available on Solana. Tools that previously+// metered (the vanity grinder) charge a flat exact price instead.//// `createPaymentWrapper` from @x402/mcp returns a function that wraps your// async tool handler into an MCP-compatible callback. It handles the entire@@ -25,23 +24,14 @@// verifies the payment, runs the handler, settles, and attaches the// SettleResponse to _meta["x402/payment-response"].-import { createCdpAuthHeaders } from '@coinbase/x402';import { HTTPFacilitatorClient, x402ResourceServer } from '@x402/core/server';-import { registerExactEvmScheme } from '@x402/evm/exact/server';-import { UptoEvmScheme as UptoEvmServerScheme } from '@x402/evm/upto/server';import { registerExactSvmScheme } from '@x402/svm/exact/server';-import {- createPaymentWrapper,- createToolResourceUrl,- extractPaymentFromMeta,-} from '@x402/mcp';+import { createPaymentWrapper, createToolResourceUrl } from '@x402/mcp';import { declareDiscoveryExtension } from '@x402/extensions/bazaar';-// CAIP-2 IDs we care about (mirrors api/_lib/x402-spec.js).-const NETWORK_BASE_MAINNET = 'eip155:8453';+// CAIP-2 id for Solana mainnet (mirrors api/_lib/x402-spec.js).const NETWORK_SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';-const DEFAULT_BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';const DEFAULT_SOLANA_USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';const env = (key, fallback) => {@@ -49,16 +39,6 @@ const env = (key, fallback) => {return v && v.trim() ? v.trim() : fallback;};-function requireEvmPayTo() {- const addr = env('MCP_EVM_PAYMENT_ADDRESS') || env('X402_PAY_TO_BASE');- if (!addr) {- throw new Error(- 'mcp-server: set MCP_EVM_PAYMENT_ADDRESS (or X402_PAY_TO_BASE) to receive Base USDC payments',- );- }- return addr;-}-function requireSvmPayTo() {const addr = env('MCP_SVM_PAYMENT_ADDRESS') || env('X402_PAY_TO_SOLANA') || env('X402_PAY_TO');if (!addr) {@@ -73,38 +53,6 @@ function svmFeePayer() {return env('X402_FEE_PAYER_SOLANA', '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4');}-// Build the CDP auth-headers async factory once and adapt it to the-// HTTPFacilitatorClient's per-path createAuthHeaders contract. The CDP SDK-// returns { verify, settle, supported, list } per call — we pick the slot-// matching the requested path.-function buildCdpFacilitator() {- const id = env('CDP_API_KEY_ID');- const secret = env('CDP_API_KEY_SECRET');- if (!id || !secret) return null;- const url = env('X402_CDP_FACILITATOR_URL', 'https://api.cdp.coinbase.com/platform/v2/x402');- const factory = createCdpAuthHeaders(id, secret);- return new HTTPFacilitatorClient({- url,- createAuthHeaders: async (path) => {- const all = await factory();- const map = { '/verify': 'verify', '/settle': 'settle', '/supported': 'supported' };- const op = map[path] || (path?.includes('verify') ? 'verify' : path?.includes('settle') ? 'settle' : 'supported');- return { headers: all?.[op] || {} };- },- });-}--function buildPayAiBaseFacilitator() {- const url = env('X402_FACILITATOR_URL_BASE') || env('X402_FACILITATOR_URL', 'https://facilitator.payai.network');- const token = env('X402_FACILITATOR_TOKEN_BASE') || env('X402_FACILITATOR_TOKEN');- return new HTTPFacilitatorClient({- url,- createAuthHeaders: token- ? async () => ({ headers: { Authorization: `Bearer ${token}` } })- : undefined,- });-}-function buildPayAiSolanaFacilitator() {const url = env('X402_FACILITATOR_URL_SOLANA') || env('X402_FACILITATOR_URL', 'https://facilitator.payai.network');const token = env('X402_FACILITATOR_TOKEN_SOLANA') || env('X402_FACILITATOR_TOKEN');@@ -119,27 +67,18 @@ function buildPayAiSolanaFacilitator() {let resourceServerPromise = null;let lastInitError = null;-// Build a single shared x402ResourceServer, register every scheme/network we-// advertise on a tool, and call .initialize() to fetch facilitator /supported-// (caches kinds + extensions for the per-network/per-scheme path).+// Build a single shared x402ResourceServer, register the Solana `exact`+// scheme, and call .initialize() to fetch the facilitator's /supported (caches+// kinds + extensions for the verify/settle path).//-// `initialize()` MUST run before any verify/settle — without it the server-// has no notion of which facilitator handles which network and will throw on-// the first paid call. We memoize the promise so concurrent tool calls don't-// race during startup.+// `initialize()` MUST run before any verify/settle — without it the server has+// no notion of which facilitator handles Solana and will throw on the first+// paid call. We memoize the promise so concurrent tool calls don't race during+// startup.export function getResourceServer() {if (resourceServerPromise) return resourceServerPromise;resourceServerPromise = (async () => {- const facilitators = [];- const cdp = buildCdpFacilitator();- if (cdp) facilitators.push(cdp);- facilitators.push(buildPayAiBaseFacilitator());- facilitators.push(buildPayAiSolanaFacilitator());-- const server = new x402ResourceServer(facilitators);- registerExactEvmScheme(server, {});- // upto on EVM is needed by the vanity grinder (metered billing).- server.register('eip155:*', new UptoEvmServerScheme());+ const server = new x402ResourceServer([buildPayAiSolanaFacilitator()]);registerExactSvmScheme(server, {});try {await server.initialize();@@ -159,46 +98,28 @@ export function getLastFacilitatorInitError() {return lastInitError;}-// Build the per-tool `accepts` list. Default networks are Base + Solana for-// `exact`-priced tools; `upto` tools only support EVM today because @x402/svm-// doesn't ship an upto scheme.+// Build the per-tool `accepts` list. Every paid tool settles in USDC on Solana+// mainnet via the `exact` scheme.async function buildAcceptsForTool({ resourceServer, scheme, priceUsd, networks, resourceUrl, extra }) {const opts = [];for (const net of networks) {- if (net === NETWORK_BASE_MAINNET) {- opts.push({- scheme,- network: NETWORK_BASE_MAINNET,- payTo: requireEvmPayTo(),- price: priceUsd,- maxTimeoutSeconds: 60,- extra: {- name: 'USD Coin',- version: '2',- decimals: 6,- asset: env('X402_ASSET_ADDRESS_BASE', DEFAULT_BASE_USDC),- ...(extra?.evm || {}),- },- });- } else if (net === NETWORK_SOLANA_MAINNET) {- if (scheme !== 'exact') continue; // upto on SVM not supported by @x402/[email protected].- opts.push({- scheme,- network: NETWORK_SOLANA_MAINNET,- payTo: requireSvmPayTo(),- price: priceUsd,- maxTimeoutSeconds: 60,- extra: {- name: 'USDC',- decimals: 6,- asset: env('X402_ASSET_MINT_SOLANA', DEFAULT_SOLANA_USDC),- feePayer: svmFeePayer(),- ...(extra?.svm || {}),- },- });- } else {- throw new Error(`mcp-server: unsupported network ${net}`);+ if (net !== NETWORK_SOLANA_MAINNET) {+ throw new Error(`mcp-server: unsupported network ${net} (Solana mainnet only)`);}+ opts.push({+ scheme,+ network: NETWORK_SOLANA_MAINNET,+ payTo: requireSvmPayTo(),+ price: priceUsd,+ maxTimeoutSeconds: 60,+ extra: {+ name: 'USDC',+ decimals: 6,+ asset: env('X402_ASSET_MINT_SOLANA', DEFAULT_SOLANA_USDC),+ feePayer: svmFeePayer(),+ ...(extra?.svm || {}),+ },+ });}if (opts.length === 0) {throw new Error(`mcp-server: no networks resolved for scheme=${scheme}`);@@ -207,20 +128,20 @@ async function buildAcceptsForTool({ resourceServer, scheme, priceUsd, networks,}/**- * Wrap a tool handler with x402 payment.+ * Wrap a tool handler with x402 payment (USDC on Solana, `exact` scheme).** @param {object} cfg* @param {string} cfg.toolName — e.g. "get_pose_seed"* @param {string} cfg.description — human-readable description- * @param {string} [cfg.scheme='exact'] — 'exact' or 'upto'- * @param {string|number} cfg.priceUsd — Price like "$0.001" (max for `upto`)- * @param {string[]} [cfg.networks] — default ['eip155:8453','solana:...']+ * @param {string} [cfg.scheme='exact'] — only 'exact' is supported on Solana+ * @param {string|number} cfg.priceUsd — Price like "$0.001"+ * @param {string[]} [cfg.networks] — default ['solana:5eykt4…']* @param {object} cfg.inputSchema — JSON Schema for the tool's args* @param {object} [cfg.example] — example invocation for bazaar* @param {object} [cfg.outputExample] — example output for bazaar- * @param {object} [cfg.extra] — extra fields per-network+ * @param {object} [cfg.extra] — extra fields (extra.svm)* @param {object} [cfg.hooks] — { onBeforeExecution, onAfterExecution, onAfterSettlement }- * @param {Function} handler — async (args, { settle? }) → { content }+ * @param {Function} handler — async (args, { settle? }) → result* @returns {Promise<Function>} MCP tool callback for McpServer.tool()*/export async function paid(cfg, handler) {@@ -229,7 +150,7 @@ export async function paid(cfg, handler) {description,scheme = 'exact',priceUsd,- networks = scheme === 'upto' ? [NETWORK_BASE_MAINNET] : [NETWORK_BASE_MAINNET, NETWORK_SOLANA_MAINNET],+ networks = [NETWORK_SOLANA_MAINNET],inputSchema,example,outputExample,@@ -241,6 +162,9 @@ export async function paid(cfg, handler) {if (!description) throw new Error('paid(): description is required');if (!priceUsd) throw new Error('paid(): priceUsd is required (e.g. "$0.001")');if (!inputSchema) throw new Error('paid(): inputSchema is required');+ if (scheme !== 'exact') {+ throw new Error(`paid(): only the 'exact' scheme is supported on Solana (got '${scheme}')`);+ }const resourceServer = await getResourceServer();const resourceUrl = createToolResourceUrl(toolName);@@ -278,136 +202,4 @@ export async function paid(cfg, handler) {});}-/**- * Wrap an `upto`-scheme tool whose handler decides the actual settlement- * amount based on resource consumption. The `priceUsd` becomes the- * authorized maximum; the handler returns `{ result, settleAmount }` where- * `settleAmount` is a percent string ("50%"), atomic units ("250000"), or a- * USD price ("$0.25"). The wrapper settles via x402ResourceServer's- * settlementOverrides — facilitator enforces settle <= max.- *- * Unlike `paid()` (which uses `createPaymentWrapper`), this wrapper- * implements the MCP transport flow manually so it can plumb- * `settlementOverrides.amount` through `settlePayment`. The 402 response- * shape (structuredContent + content[0].text + isError:true) matches the- * v2 MCP transport spec.- */-export async function paidUpto(cfg, handler) {- const {- toolName,- description,- priceUsd,- networks = [NETWORK_BASE_MAINNET],- inputSchema,- example,- outputExample,- extra,- } = cfg;-- if (!toolName) throw new Error('paidUpto(): toolName is required');- if (!priceUsd) throw new Error('paidUpto(): priceUsd is required (max)');- if (!inputSchema) throw new Error('paidUpto(): inputSchema is required');-- const resourceServer = await getResourceServer();- const resourceUrl = createToolResourceUrl(toolName);- const accepts = await buildAcceptsForTool({- resourceServer,- scheme: 'upto',- priceUsd,- networks,- resourceUrl,- extra,- });- const resourceInfo = { url: resourceUrl, description, mimeType: 'application/json' };- const bazaar = declareDiscoveryExtension({- toolName,- description,- transport: 'stdio',- inputSchema,- example,- output: outputExample ? { example: outputExample } : undefined,- });-- const paymentRequiredResult = async (errorMessage) => {- const paymentRequired = await resourceServer.createPaymentRequiredResponse(- accepts,- resourceInfo,- errorMessage,- bazaar,- );- return {- structuredContent: paymentRequired,- content: [{ type: 'text', text: JSON.stringify(paymentRequired) }],- isError: true,- };- };-- return async (args, extra) => {- const _meta = extra?._meta;- const paymentPayload = extractPaymentFromMeta({ name: toolName, arguments: args, _meta });- if (!paymentPayload) {- return paymentRequiredResult('Payment required to access this tool');- }- const matched = resourceServer.findMatchingRequirements(accepts, paymentPayload);- if (!matched) {- return paymentRequiredResult('No matching payment requirements for this payload');- }- const verify = await resourceServer.verifyPayment(paymentPayload, matched, bazaar);- if (!verify.isValid) {- return paymentRequiredResult(verify.invalidReason || 'Payment verification failed');- }- let handlerOutput;- try {- handlerOutput = await handler(args, { context: extra, requirement: matched });- } catch (err) {- return paymentRequiredResult(`Tool failed before settlement: ${err.message}`);- }- const { result, settleAmount } = handlerOutput;- if (!result) {- return paymentRequiredResult('Tool handler returned no result');- }- // Defense-in-depth: cap settleAmount at the matched requirement's max.- // The facilitator will reject an override that exceeds what the client- // signed, but a buggy/compromised handler returning an inflated- // settleAmount should fail fast server-side with a clear error rather- // than reaching the facilitator with a value that looks valid against- // other concurrent payments. Numeric settleAmount only — percent- // strings ("50%") and $-strings ("$0.25") pass through to the- // facilitator unchanged.- let overrides;- if (settleAmount) {- const amountStr = String(settleAmount);- if (/^\d+$/.test(amountStr)) {- let requested;- try { requested = BigInt(amountStr); }- catch {- return paymentRequiredResult(`Settlement failed: settleAmount ${amountStr} did not parse as atomic units`);- }- let maxAuthorized = 0n;- try { maxAuthorized = BigInt(matched.amount || '0'); }- catch { maxAuthorized = 0n; }- if (maxAuthorized > 0n && requested > maxAuthorized) {- return paymentRequiredResult(- `Settlement failed: handler returned settleAmount ${requested.toString()} exceeding authorized max ${maxAuthorized.toString()}`,- );- }- overrides = { amount: amountStr };- } else {- overrides = { amount: amountStr };- }- }- let settle;- try {- settle = await resourceServer.settlePayment(paymentPayload, matched, bazaar, undefined, overrides);- } catch (err) {- return paymentRequiredResult(`Settlement failed: ${err.message}`);- }- const text = typeof result === 'string' ? result : JSON.stringify(result);- return {- content: [{ type: 'text', text }],- _meta: { 'x402/payment-response': settle },- };- };-}--export { NETWORK_BASE_MAINNET, NETWORK_SOLANA_MAINNET };+export { NETWORK_SOLANA_MAINNET };diff --git a/mcp-server/src/tools/vanity-grinder.js b/mcp-server/src/tools/vanity-grinder.jsindex 6c23e0284..358d13a35 100644--- a/mcp-server/src/tools/vanity-grinder.js+++ b/mcp-server/src/tools/vanity-grinder.js@@ -2,15 +2,15 @@// base58 public key starts with a chosen prefix (and optionally ends with a// chosen suffix).//-// Pricing: `upto` scheme on Base, max $0.50. Actual settled amount scales-// with the number of attempts: we charge $0.01 base + ~$0.0000001 per-// attempt, capped at $0.50. The x402 facilitator enforces settle ≤ max.+// Pricing: flat `exact` price in USDC on Solana (default $0.05, override with+// MCP_VANITY_PRICE_USD). Metered/`upto` billing is not available on Solana —+// @x402/svm ships no `upto` scheme — so this tool charges a single flat fee+// regardless of attempt count.//// Output (over the same MCP channel — clients should treat as secret):// - address (base58)// - privateKey64 (base58, full 64-byte secret key as @solana/web3.js expects)// - iterations + durationMs-// - cost: { authorizedMaxUsd, settledUsd, settledAtomic }//// The grinder is the same async-yielding routine in api/_lib/pump-vanity.js// (BASE58_ALPHABET, 6-char max pattern, lowercase ignoreCase support). It@@ -18,23 +18,17 @@import { z } from 'zod';-import { paidUpto } from '../payments.js';+import { paid } from '../payments.js';import { grindMintKeypair, estimateAttempts, BASE58_ALPHABET } from '../../../api/_lib/pump-vanity.js';import bs58 from 'bs58';const TOOL_NAME = 'vanity_grinder';-const TOOL_DESCRIPTION =- 'Generate a Solana keypair whose base58 address starts with a chosen prefix (and optionally ends with a chosen suffix). Returns the full 64-byte secret key — handle as a secret. Billed via x402 `upto` (max $0.50 USDC on Base); actual cost scales with attempts so easy patterns are nearly free.';-const BASE_USD = 0.01;-const PER_ATTEMPT_USD = 1e-7;-const MAX_USD = 0.5;+// Flat price charged per successful grind, in USDC on Solana.+const PRICE_USD = process.env.MCP_VANITY_PRICE_USD?.trim() || '$0.05';-function priceForAttempts(attempts) {- const usd = Math.min(MAX_USD, BASE_USD + attempts * PER_ATTEMPT_USD);- const atomic = Math.round(usd * 1_000_000); // USDC has 6 decimals- return { usd: Number(usd.toFixed(6)), atomicUsdc: String(atomic) };-}+const TOOL_DESCRIPTION =+ `Generate a Solana keypair whose base58 address starts with a chosen prefix (and optionally ends with a chosen suffix). Returns the full 64-byte secret key — handle as a secret. Billed via x402 \`exact\` (flat ${PRICE_USD} USDC on Solana).`;const inputJsonSchema = {type: 'object',@@ -74,11 +68,11 @@ const inputZodShape = {};export async function buildVanityGrinderTool() {- const handler = await paidUpto(+ const handler = await paid({toolName: TOOL_NAME,description: TOOL_DESCRIPTION,- priceUsd: '$0.50',+ priceUsd: PRICE_USD,inputSchema: inputJsonSchema,example: { prefix: 'pump' },outputExample: {@@ -86,7 +80,7 @@ export async function buildVanityGrinderTool() {privateKey64: '5x...base58...',iterations: 12345,durationMs: 230,- cost: { authorizedMaxUsd: 0.5, settledUsd: 0.011, settledAtomic: '11234' },+ priceUsd: PRICE_USD,},},async ({ prefix, suffix, ignoreCase = false, maxIterations = 2_000_000 }) => {@@ -102,33 +96,24 @@ export async function buildVanityGrinderTool() {// (32-byte seed || 32-byte pubkey). Wallets like Phantom import this// directly as base58. The client is responsible for storing it.const privateKey64 = bs58.encode(Buffer.from(grind.keypair.secretKey));- const price = priceForAttempts(grind.iterations);return {- result: {- address,- privateKey64,- iterations: grind.iterations,- estimatedIterations: Math.round(expected),- durationMs: grind.durationMs,- prefix,- suffix: suffix || null,- ignoreCase,- cost: {- authorizedMaxUsd: MAX_USD,- settledUsd: price.usd,- settledAtomic: price.atomicUsdc,- pricingNote: '$0.01 base + $0.0000001 per attempt, capped at $0.50',- },- _secretWarning:- 'privateKey64 is a real private key. Treat the entire MCP response as a secret and store securely.',- },- settleAmount: price.atomicUsdc,+ address,+ privateKey64,+ iterations: grind.iterations,+ estimatedIterations: Math.round(expected),+ durationMs: grind.durationMs,+ prefix,+ suffix: suffix || null,+ ignoreCase,+ priceUsd: PRICE_USD,+ _secretWarning:+ 'privateKey64 is a real private key. Treat the entire MCP response as a secret and store securely.',};},);return {name: TOOL_NAME,- title: 'Solana vanity grinder (upto $0.50)',+ title: `Solana vanity grinder (${PRICE_USD})`,description: TOOL_DESCRIPTION,inputSchema: inputZodShape,handler,diff --git a/packages/three-token-mcp/README.md b/packages/three-token-mcp/README.mdnew file mode 100644index 000000000..46be850fc--- /dev/null+++ b/packages/three-token-mcp/README.md@@ -0,0 +1,104 @@+# @three-ws/three-token-mcp++**The first MCP server whose actions burn a token.** Give any AI agent three+$THREE primitives over the Model Context Protocol: read the live price, read a+wallet's balance, and **burn $THREE on-chain** — split between the incinerator+and the three.ws treasury, priced live via Jupiter.++Deflation as an agent primitive: every `three_burn` call is a real, verifiable+Solana transaction that permanently removes $THREE from supply and funds the+treasury.++```+io.github.nirholas/three-token-mcp → @three-ws/three-token-mcp+```++## Why this is different++Most paid MCP servers settle in USDC. This one moves the project's own token,+and the destinations are not hardcoded — they're read at runtime from the+**public** three.ws token surface (`/api/token/config`, `/api/token/price`), so+the mint, decimals, burn address, treasury, and split always track the canonical+on-chain config the rest of three.ws uses.++## Tools++| Tool | Type | What it does |+| :--- | :--- | :----------- |+| `three_price` | read-only | Live USD price of $THREE (Jupiter → Birdeye fallback). Pass `usd` to also get the token-amount quote. |+| `three_balance` | read-only | $THREE + SOL balance for any pubkey (defaults to the configured signer). |+| `three_burn` | **execution** | Burn a USD-denominated amount of $THREE in one Solana tx, split incinerator/treasury. Returns the signature + breakdown + Solscan link. |++`three_burn` burns $THREE the wallet **already holds**. To acquire $THREE first,+swap SOL→$THREE on any Solana DEX, then burn.++## Install++Add to your MCP client (Claude Desktop / Cursor / Claude Code):++```json+{+ "mcpServers": {+ "three-token": {+ "command": "npx",+ "args": ["-y", "@three-ws/three-token-mcp"],+ "env": {+ "SOLANA_SECRET_KEY": "<base58 secret of the wallet that holds $THREE>",+ "SOLANA_RPC_URL": "https://your-rpc-provider"+ }+ }+ }+}+```++`SOLANA_SECRET_KEY` is only required for `three_burn`. The read-only tools work+without it.++## Configuration++| Variable | Required | Purpose |+| :------- | :------- | :------ |+| `SOLANA_SECRET_KEY` | for burns | Base58 secret of the signing wallet. **Treat like cash.** |+| `SOLANA_RPC_URL` | no | Solana mainnet RPC (defaults to the public cluster). |+| `THREE_WS_BASE` | no | three.ws API base (defaults to `https://three.ws`). |++## Example++```+> three_price { "usd": 5 }+{ "price_usd": 0.0042, "quote": { "usd": 5, "token_amount": 1190.47, "atomics": "1190476190" } }++> three_burn { "usd": 5, "burnBps": 5000 }+{+ "ok": true,+ "signature": "5x...",+ "explorer": "https://solscan.io/tx/5x...",+ "usd": 5,+ "burned": 595.23,+ "legs": [+ { "role": "burn", "amount": 595.23 },+ { "role": "treasury", "amount": 595.23 }+ ]+}+```++`burnBps` controls the split: `5000` (default) = 50% burn / 50% treasury;+`10000` = burn everything.++## How a burn is built++`three_burn` mirrors the proven three.ws browser payment flow:++1. `GET /api/token/config` → mint, decimals, burn address, treasury.+2. `GET /api/token/price?usd=<n>` → live Jupiter price + the exact $THREE atomics.+3. Build **one** transaction: an idempotent ATA-create + SPL transfer per leg+ (burn + treasury), plus a memo tagging the burn on-chain.+4. Sign with your wallet, send, and confirm. The result reports the on-chain+ signature and per-leg amounts.++The server pre-checks your $THREE balance and fails fast with a clear error if+it can't cover the burn — no opaque on-chain failures.++## License++Apache-2.0 · [three.ws](https://three.ws)diff --git a/packages/three-token-mcp/server.json b/packages/three-token-mcp/server.jsonnew file mode 100644index 000000000..253044087--- /dev/null+++ b/packages/three-token-mcp/server.json@@ -0,0 +1,44 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/three-token-mcp",+ "description": "The first MCP server whose actions burn a token. Price, hold, and burn $THREE on Solana — every burn splits to the incinerator + treasury via the live three.ws token rail, with Jupiter USD pricing. Deflation as an agent primitive.",+ "repository": {+ "url": "https://github.com/nirholas/three.ws",+ "source": "github",+ "subfolder": "packages/three-token-mcp"+ },+ "version": "1.0.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/three-token-mcp",+ "version": "1.0.0",+ "transport": {+ "type": "stdio"+ },+ "environmentVariables": [+ {+ "name": "SOLANA_SECRET_KEY",+ "description": "Base58 Solana secret key that signs burns (the wallet that holds the $THREE). Not needed for the read-only tools (three_price, three_balance). Treat like cash.",+ "format": "string",+ "isRequired": false,+ "isSecret": true+ },+ {+ "name": "SOLANA_RPC_URL",+ "description": "Solana mainnet RPC endpoint. Defaults to the public cluster — bring your own (Helius / QuickNode / Triton) for production traffic.",+ "format": "string",+ "isRequired": false,+ "default": "https://api.mainnet-beta.solana.com"+ },+ {+ "name": "THREE_WS_BASE",+ "description": "Base URL of the three.ws token API (serves /api/token/config and /api/token/price). Override only when self-hosting.",+ "format": "string",+ "isRequired": false,+ "default": "https://three.ws"+ }+ ]+ }+ ]+}diff --git a/packages/three-token-mcp/src/index.js b/packages/three-token-mcp/src/index.jsnew file mode 100644index 000000000..f3e4ec411--- /dev/null+++ b/packages/three-token-mcp/src/index.js@@ -0,0 +1,81 @@+#!/usr/bin/env node+// @three-ws/three-token-mcp — MCP server entry point.+//+// The first MCP server whose actions burn a token. Gives any AI assistant+// three $THREE primitives over stdio:+// • three_price — live Jupiter USD price + USD→$THREE quote (read-only)+// • three_balance — a wallet's $THREE + SOL balance (read-only)+// • three_burn — burn $THREE on-chain, split incinerator/treasury+//+// Destinations, decimals, and pricing all come from the PUBLIC three.ws token+// endpoints at runtime — nothing about the money split is baked in.+//+// Run standalone:+// SOLANA_SECRET_KEY=<base58> node packages/three-token-mcp/src/index.js+//+// Or wire into Claude Desktop / Cursor — see README.md.++import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';++import { def as threePrice } from './tools/three-price.js';+import { def as threeBalance } from './tools/three-balance.js';+import { def as threeBurn } from './tools/three-burn.js';++const TOOLS = [threePrice, threeBalance, threeBurn];++async function main() {+ const server = new McpServer(+ { name: 'three-token-mcp', version: '1.0.0' },+ {+ capabilities: { tools: {} },+ instructions:+ '$THREE token MCP — price, hold, and BURN the three.ws token ($THREE) on Solana. ' ++ 'three_price returns the live USD price (Jupiter primary, Birdeye fallback) and, given `usd`, ' ++ 'how much $THREE that buys. three_balance reads any wallet\'s $THREE + SOL (defaults to the ' ++ 'configured signer). three_burn is an EXECUTION ACTION: it quotes a USD amount to $THREE and ' ++ 'sends one Solana transaction splitting it between the incinerator and the three.ws treasury ' ++ '(default 50/50, override with burnBps; 10000 = burn everything). Burning requires a signer ' ++ '(SOLANA_SECRET_KEY or a per-call `secret`) that already holds enough $THREE. Burn destinations ' ++ 'and the split come from the live public token config — never hardcoded.',+ },+ );++ for (const tool of TOOLS) {+ server.registerTool(+ tool.name,+ {+ title: tool.title,+ description: tool.description,+ inputSchema: tool.inputSchema,+ },+ async (args, extra) => {+ try {+ const result = await tool.handler(args, extra);+ const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);+ return { content: [{ type: 'text', text }] };+ } catch (err) {+ const payload = {+ ok: false,+ error: err?.code || 'unhandled',+ message: err?.message || String(err),+ ...(err?.signature ? { signature: err.signature } : {}),+ };+ return {+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],+ isError: true,+ };+ }+ },+ );+ }++ const transport = new StdioServerTransport();+ await server.connect(transport);+ console.error(`[three-token-mcp] connected over stdio with ${TOOLS.length} tools`);+}++main().catch((err) => {+ console.error('[three-token-mcp] fatal:', err);+ process.exit(1);+});diff --git a/packages/three-token-mcp/src/lib/token.js b/packages/three-token-mcp/src/lib/token.jsnew file mode 100644index 000000000..2d6828928--- /dev/null+++ b/packages/three-token-mcp/src/lib/token.js@@ -0,0 +1,181 @@+// The $THREE burn engine.+//+// Reads the PUBLIC three.ws token surface — /api/token/config (mint, decimals,+// burn + treasury addresses) and /api/token/price (live Jupiter USD pricing) —+// then builds, signs, sends, and confirms a single Solana transaction that+// splits a USD-denominated amount of $THREE between the incinerator and the+// treasury. Nothing about the destinations or the split is hardcoded here: it+// always tracks the canonical on-chain config the rest of three.ws uses.+//+// The transaction shape mirrors the proven browser flow in src/token-pay.js:+// one idempotent ATA-create + SPL transfer per leg, plus a memo carrying a tag+// so the burn is attributable on-chain.++import { Transaction, TransactionInstruction } from '@solana/web3.js';+import {+ createAssociatedTokenAccountIdempotentInstruction,+ createTransferInstruction,+ getAssociatedTokenAddressSync,+} from '@solana/spl-token';++import { THREE_WS_BASE, MEMO_PROGRAM_ID } from '../config.js';+import {+ PublicKey,+ getConnection,+ getSplBalance,+ loadSigner,+} from './solana.js';++async function getJson(path) {+ const url = `${THREE_WS_BASE}${path}`;+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ throw Object.assign(new Error(body.error_description || body.error || `GET ${path} ${res.status}`), {+ code: body.error || `http_${res.status}`,+ });+ }+ return body;+}++/** Public token config: { mint, symbol, decimals, treasury, burn_address, ... }. */+export function fetchTokenConfig() {+ return getJson('/api/token/config');+}++/**+ * Live $THREE price. Pass `usd` to also receive a token-amount quote+ * ({ usd, token_amount, atomics }).+ */+export function fetchTokenPrice(usd) {+ const q = usd != null ? `?usd=${encodeURIComponent(usd)}` : '';+ return getJson(`/api/token/price${q}`);+}++const fmt = (atomics, decimals) => Number(BigInt(atomics)) / 10 ** decimals;++/**+ * Split `totalAtomics` of $THREE into burn + treasury legs.+ * @param {bigint} totalAtomics+ * @param {number} burnBps — share to the incinerator in basis points (0–10000)+ * @param {object} config — output of fetchTokenConfig()+ * @returns {{ role: string, address: string, atomics: bigint }[]}+ */+export function computeSplit(totalAtomics, burnBps, config) {+ const total = BigInt(totalAtomics);+ const bps = Math.max(0, Math.min(10_000, Math.round(burnBps)));+ let burnAtomics = (total * BigInt(bps)) / 10_000n;+ let treasuryAtomics = total - burnAtomics;+ const legs = [];+ // Assign any rounding dust to the burn leg so we never under-burn.+ if (treasuryAtomics > 0n && config.treasury) {+ legs.push({ role: 'treasury', address: config.treasury, atomics: treasuryAtomics });+ } else {+ burnAtomics = total;+ }+ if (burnAtomics > 0n) {+ legs.unshift({ role: 'burn', address: config.burn_address, atomics: burnAtomics });+ }+ return legs;+}++/**+ * Buy is out of scope — this burns $THREE the wallet already holds. Quote a USD+ * amount to atomics via Jupiter, split it burn/treasury, sign, send, confirm.+ *+ * @param {object} p+ * @param {number} p.usd — USD value of $THREE to burn (> 0)+ * @param {number} [p.burnBps] — incinerator share in bps (default 5000 = 50%)+ * @param {string} [p.secret] — base58 signer override (else SOLANA_SECRET_KEY)+ * @param {string} [p.memo] — extra memo text appended to the on-chain tag+ * @returns {Promise<object>} receipt+ */+export async function burnThree({ usd, burnBps = 5000, secret, memo }) {+ if (!(Number(usd) > 0)) {+ throw Object.assign(new Error('usd must be a positive number'), { code: 'bad_amount' });+ }++ const signer = loadSigner(secret);+ const payer = signer.publicKey;++ const [config, price] = await Promise.all([fetchTokenConfig(), fetchTokenPrice(usd)]);+ if (!config.mint || !config.burn_address) {+ throw Object.assign(new Error('token config missing mint/burn_address'), { code: 'config_incomplete' });+ }+ if (!price.quote?.atomics) {+ throw Object.assign(new Error('price endpoint returned no quote for the requested usd'), { code: 'no_quote' });+ }++ const decimals = config.decimals;+ const total = BigInt(price.quote.atomics);+ const legs = computeSplit(total, burnBps, config);++ // Fail fast with a clear error if the wallet can't cover the burn, rather+ // than letting the transfer fail opaquely on-chain.+ const held = await getSplBalance(payer.toBase58(), config.mint);+ if (BigInt(held.atomics) < total) {+ throw Object.assign(+ new Error(+ `insufficient $THREE: need ${fmt(total, decimals)} ${config.symbol} (~$${usd}), wallet holds ${held.uiAmount}`,+ ),+ { code: 'insufficient_balance' },+ );+ }++ const conn = getConnection();+ const mintPk = new PublicKey(config.mint);+ const fromAta = getAssociatedTokenAddressSync(mintPk, payer);++ const tx = new Transaction();+ for (const leg of legs) {+ const ownerPk = new PublicKey(leg.address);+ // allowOwnerOffCurve: the burn incinerator address is off-curve.+ const destAta = getAssociatedTokenAddressSync(mintPk, ownerPk, true);+ tx.add(createAssociatedTokenAccountIdempotentInstruction(payer, destAta, ownerPk, mintPk));+ tx.add(createTransferInstruction(fromAta, destAta, payer, leg.atomics));+ }+ const tag = `three.ws mcp burn $${usd}${memo ? ` ${memo}` : ''}`.slice(0, 180);+ tx.add(+ new TransactionInstruction({+ keys: [],+ programId: new PublicKey(MEMO_PROGRAM_ID),+ data: Buffer.from(tag, 'utf8'),+ }),+ );++ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');+ tx.feePayer = payer;+ tx.recentBlockhash = blockhash;+ tx.sign(signer);++ const signature = await conn.sendRawTransaction(tx.serialize(), { maxRetries: 5 });+ const conf = await conn.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');+ if (conf.value?.err) {+ throw Object.assign(new Error(`transaction failed to confirm: ${JSON.stringify(conf.value.err)}`), {+ code: 'tx_failed',+ signature,+ });+ }++ return {+ ok: true,+ signature,+ explorer: `https://solscan.io/tx/${signature}`,+ mint: config.mint,+ symbol: config.symbol,+ decimals,+ usd: Number(usd),+ price_usd: price.price_usd,+ price_source: price.source,+ payer: payer.toBase58(),+ total: { atomics: total.toString(), amount: fmt(total, decimals) },+ legs: legs.map((l) => ({+ role: l.role,+ address: l.address,+ atomics: l.atomics.toString(),+ amount: fmt(l.atomics, decimals),+ })),+ burned: fmt(legs.find((l) => l.role === 'burn')?.atomics ?? 0n, decimals),+ burnedAt: new Date().toISOString(),+ };+}diff --git a/packages/three-token-mcp/src/tools/three-balance.js b/packages/three-token-mcp/src/tools/three-balance.jsnew file mode 100644index 000000000..b126bf589--- /dev/null+++ b/packages/three-token-mcp/src/tools/three-balance.js@@ -0,0 +1,51 @@+// `three_balance` — read the $THREE and SOL balance of a wallet. Defaults to+// the configured signer's address when no pubkey is supplied. Read-only.++import { z } from 'zod';++import { getSolBalance, getSplBalance, isValidPubkey, loadSigner } from '../lib/solana.js';+import { fetchTokenConfig } from '../lib/token.js';++export const def = {+ name: 'three_balance',+ title: "Read a wallet's $THREE + SOL balance",+ description:+ 'Return the $THREE and SOL balance for a Solana pubkey. If no pubkey is given, uses the configured signer (SOLANA_SECRET_KEY). Read-only — no payment.',+ inputSchema: {+ pubkey: z+ .string()+ .min(32)+ .max(64)+ .optional()+ .describe("Base58 pubkey to read. Defaults to the configured signer's address."),+ },+ async handler(args) {+ const { pubkey } = args || {};+ // loadSigner() throws a clear `no_signer` error if neither a pubkey nor a+ // configured secret is available.+ const owner = pubkey || loadSigner().publicKey.toBase58();+ if (!isValidPubkey(owner)) {+ return { ok: false, error: 'invalid_pubkey' };+ }+ const config = await fetchTokenConfig();+ const [sol, three] = await Promise.all([+ getSolBalance(owner),+ getSplBalance(owner, config.mint),+ ]);+ return {+ ok: true,+ pubkey: owner,+ symbol: config.symbol,+ three: {+ mint: config.mint,+ amount: three.uiAmount,+ atomics: three.atomics,+ decimals: three.decimals || config.decimals,+ },+ sol: sol.sol,+ lamports: sol.lamports,+ explorer: `https://solscan.io/account/${owner}`,+ fetchedAt: new Date().toISOString(),+ };+ },+};diff --git a/packages/three-token-mcp/src/tools/three-burn.js b/packages/three-token-mcp/src/tools/three-burn.jsnew file mode 100644index 000000000..f6a00c2a3--- /dev/null+++ b/packages/three-token-mcp/src/tools/three-burn.js@@ -0,0 +1,34 @@+// `three_burn` — the headline. Burn a USD-denominated amount of $THREE on-chain,+// split between the incinerator and the treasury per the live public config.+// EXECUTION ACTION: signs and broadcasts a Solana mainnet transaction.++import { z } from 'zod';++import { burnThree } from '../lib/token.js';++export const def = {+ name: 'three_burn',+ title: 'Burn $THREE on-chain (incinerator + treasury split)',+ description:+ 'Burn a USD-denominated amount of the $THREE your wallet holds. Quotes USD→$THREE via Jupiter, then sends ONE Solana transaction that splits it between the incinerator (burn) and the three.ws treasury, per the live public token config. EXECUTION ACTION — signs and broadcasts on Solana mainnet, irreversible. Requires a signer (SOLANA_SECRET_KEY env or the `secret` arg) holding enough $THREE. Returns the tx signature, the burned/treasury breakdown, and a Solscan link.',+ inputSchema: {+ usd: z.number().positive().describe('USD value of $THREE to burn (priced live via Jupiter).'),+ burnBps: z+ .number()+ .min(0)+ .max(10000)+ .optional()+ .describe(+ 'Share routed to the incinerator in basis points. Default 5000 (50% burn / 50% treasury). 10000 = burn everything.',+ ),+ memo: z.string().max(120).optional().describe('Optional note appended to the on-chain memo.'),+ secret: z+ .string()+ .optional()+ .describe('Base58 signer override. Defaults to SOLANA_SECRET_KEY. Treat like cash.'),+ },+ async handler(args) {+ const { usd, burnBps, memo, secret } = args || {};+ return burnThree({ usd, burnBps, memo, secret });+ },+};diff --git a/packages/three-token-mcp/src/tools/three-price.js b/packages/three-token-mcp/src/tools/three-price.jsnew file mode 100644index 000000000..692f2f96e--- /dev/null+++ b/packages/three-token-mcp/src/tools/three-price.js@@ -0,0 +1,28 @@+// `three_price` — live USD price of $THREE plus an optional USD→$THREE quote.+// Read-only: no signer, no payment.++import { z } from 'zod';++import { fetchTokenPrice } from '../lib/token.js';++export const def = {+ name: 'three_price',+ title: 'Live $THREE price (Jupiter) + USD→$THREE quote',+ description:+ 'Return the live USD price of $THREE (Jupiter primary, Birdeye fallback). Pass `usd` to also get how much $THREE that amount buys (token amount + atomic units). Read-only — no signer or payment required.',+ inputSchema: {+ usd: z.number().positive().optional().describe('Optional USD amount to quote into $THREE.'),+ },+ async handler(args) {+ const { usd } = args || {};+ const price = await fetchTokenPrice(usd);+ return {+ ok: true,+ mint: price.mint,+ price_usd: price.price_usd,+ source: price.source,+ as_of: price.as_of,+ ...(price.quote ? { quote: price.quote } : {}),+ };+ },+};diff --git a/tests/api/mcp-agent.test.js b/tests/api/mcp-agent.test.jsnew file mode 100644index 000000000..3d78814e7--- /dev/null+++ b/tests/api/mcp-agent.test.js@@ -0,0 +1,144 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';++process.env.PUBLIC_APP_ORIGIN ||= 'https://three.ws';++// ── Per-user payer (money core) — mocked; we test orchestration, not fund movement ──+const payerState = {+ spendEnabled: true,+ walletStatus: null,+ payResult: null,+ payError: null,+};+vi.mock('../../api/_lib/x402-user-payer.js', () => ({+ resolveSpendEnabled: () => payerState.spendEnabled,+ getUserWalletStatus: vi.fn(async () => payerState.walletStatus),+ payExternalX402: vi.fn(async () => {+ if (payerState.payError) throw payerState.payError;+ return payerState.payResult;+ }),+}));++// ── Bazaar (live discovery) ──────────────────────────────────────────────────+const bazState = { search: vi.fn(async () => ({ resources: [], errors: [] })) };+vi.mock('../../api/_lib/x402/bazaar-client.js', async (orig) => {+ const real = await orig();+ return { ...real, Bazaar: class { search(...a) { return bazState.search(...a); } } };+});++// ── Rate limits ──────────────────────────────────────────────────────────────+const rl = { agent: { success: true, reset: 0 }, pay: { success: true, reset: 0 } };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ mcpAgent: vi.fn(async () => rl.agent),+ mcpAgentPay: vi.fn(async () => rl.pay),+ },+ clientIp: vi.fn(() => '203.0.113.5'),+}));++vi.mock('../../api/_lib/usage.js', () => ({+ recordEvent: vi.fn(),+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),+}));++const payer = await import('../../api/_lib/x402-user-payer.js');+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', source: 'bearer' };+const call = (name, args, auth = USER) =>+ dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, auth);++beforeEach(() => {+ payerState.spendEnabled = true;+ payerState.walletStatus = null;+ payerState.payResult = null;+ payerState.payError = null;+ payer.payExternalX402.mockClear();+ payer.getUserWalletStatus.mockClear();+ bazState.search.mockClear();+ rl.agent = { success: true, reset: 0 };+ rl.pay = { success: true, reset: 0 };+});++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']);+ });++ it('wallet_status requires sign-in', async () => {+ const r = await call('wallet_status', {}, ANON);+ expect(r.result.isError).toBe(true);+ expect(r.result.structuredContent.signed_in).toBe(false);+ expect(payer.getUserWalletStatus).not.toHaveBeenCalled();+ });++ it('wallet_status reports balance + caps for a signed-in user', async () => {+ payerState.walletStatus = {+ provisioned: true,+ agent_id: 'a1',+ agent_name: 'Scout',+ address: 'SoLaddr',+ network: 'solana',+ balances: { sol: 0.2, usdc: 5 },+ spend_enabled: true,+ caps: { max_per_call_usdc: 0.1, max_per_hour_usdc: 1, max_per_day_usdc: 10 },+ };+ const r = await call('wallet_status', {});+ expect(payer.getUserWalletStatus).toHaveBeenCalledWith('user-1');+ expect(r.result.structuredContent).toMatchObject({ signed_in: true, address: 'SoLaddr', balances: { usdc: 5 } });+ expect(r.result.content[0].text).toContain('5 USDC');+ });++ it('find_services searches the live bazaar', async () => {+ bazState.search.mockResolvedValue({+ resources: [{ resource: 'https://svc.test', serviceName: 'Svc', minPriceLabel: '$0.01', networks: ['solana:*'], toolName: '' }],+ errors: [],+ });+ const r = await call('find_services', { query: 'weather' });+ expect(bazState.search).toHaveBeenCalledWith({ query: 'weather', type: 'http' });+ expect(r.result.structuredContent.services[0]).toMatchObject({ resource: 'https://svc.test', price: '$0.01' });+ });++ it('pay_and_call degrades to a pay link when spend is disabled', async () => {+ payerState.spendEnabled = false;+ const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' });+ expect(payer.payExternalX402).not.toHaveBeenCalled();+ expect(r.result.structuredContent).toMatchObject({ paid: false, reason: 'spend_disabled' });+ expect(r.result.structuredContent.pay_link).toContain('https://three.ws/pay?resource=');+ });++ it('pay_and_call degrades to auth handoff for anon callers', async () => {+ const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' }, ANON);+ expect(payer.payExternalX402).not.toHaveBeenCalled();+ expect(r.result.structuredContent.reason).toBe('auth_required');+ });++ it('pay_and_call pays and returns the result when enabled', async () => {+ payerState.payResult = { ok: true, payer: 'SoLaddr', result: { temp: 72 }, receipt: { tx: 'sig' } };+ const r = await call('pay_and_call', { resource_url: 'https://paid.test/weather', max_usd: 0.05 });+ expect(payer.payExternalX402).toHaveBeenCalledWith({+ userId: 'user-1',+ url: 'https://paid.test/weather',+ method: 'GET',+ body: undefined,+ maxUsd: 0.05,+ });+ expect(r.result.structuredContent).toMatchObject({ paid: true, payer: 'SoLaddr', result: { temp: 72 } });+ });++ it('pay_and_call surfaces payer errors with a friendly message + pay link', async () => {+ payerState.payError = Object.assign(new Error('boom'), { code: 'no_solana_wallet' });+ const r = await call('pay_and_call', { resource_url: 'https://paid.test/x' });+ expect(r.result.isError).toBe(true);+ expect(r.result.content[0].text).toContain('no Solana wallet');+ expect(r.result.structuredContent.reason).toBe('no_solana_wallet');+ });++ 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' });+ expect(r.error.code).toBe(-32000);+ expect(payer.payExternalX402).not.toHaveBeenCalled();+ });+});