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 MCP server + three-token-mcp package, x402 user-payer
nirholas733dccf496bc
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 89ff1d554..356e2fcaf 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -81,6 +81,10 @@ export const limits = {// x402 Bazaar MCP. Discovery calls fan out to external facilitators, so cap// per principal to keep that egress bounded without throttling normal use.mcpBazaar: (key) => getLimiter('mcp:bazaar', { limit: 60, window: '1 m' }).limit(key),+ // threews-agent MCP. Read/discovery calls are cheap; pay_and_call moves real+ // money, so it gets a much tighter ceiling on top of the per-spend caps.+ mcpAgent: (key) => getLimiter('mcp:agent', { limit: 60, window: '1 m' }).limit(key),+ mcpAgentPay: (key) => getLimiter('mcp:agent:pay', { limit: 20, window: '1 m' }).limit(key),oauthToken: (clientId) =>getLimiter('oauth:token', { limit: 120, window: '1 m' }).limit(clientId),upload: (userId) => getLimiter('upload', { limit: 60, window: '1 h' }).limit(userId),diff --git a/api/_lib/x402-user-payer.js b/api/_lib/x402-user-payer.jsnew file mode 100644index 000000000..6bbafcc15--- /dev/null+++ b/api/_lib/x402-user-payer.js@@ -0,0 +1,225 @@+// Per-user x402 payer — lets an authenticated three.ws user's agent pay an+// arbitrary external x402 endpoint in USDC from THEIR OWN Solana agent wallet,+// bounded by spending caps. This is the money core behind the `pay_and_call`+// MCP tool ("add a wallet to Claude").+//+// It reuses the SDK's audited exact-scheme signing (@x402/svm) rather than+// hand-rolling transaction construction: we build an x402Client, register the+// Solana exact scheme with a signer derived from the user's recovered keypair,+// install the platform spending cap (enforceCap → commit / rollback), and let+// @x402/axios run the full 402 → sign → settle dance.+//+// SAFETY: spending is OFF unless THREEWS_AGENT_PAY_ENABLED=1. This is real money+// moving from a real user wallet; the flag exists so the capability ships dark+// and is only enabled after a funded-wallet integration test. When disabled,+// resolveSpendEnabled() returns false and callers degrade to a payment-details+// handoff instead of moving funds.++import { sql } from './db.js';+import { env } from './env.js';+import { recoverSolanaAgentKeypair } from './agent-wallet.js';+import { installSpendingCap } from './x402-spending-cap.js';++// Atomic-USDC caps. Defaults are intentionally tiny; operators raise them via+// env once they trust the flow. A per-call override from the tool can only+// LOWER the per-call cap, never raise it past the env ceiling.+const DEFAULT_MAX_PER_CALL = 100_000n; // $0.10+const DEFAULT_MAX_PER_HOUR = 1_000_000n; // $1.00+const DEFAULT_MAX_PER_DAY = 10_000_000n; // $10.00++function envAtomic(name, fallback) {+ const raw = env[name] ?? (typeof process !== 'undefined' ? process.env?.[name] : undefined);+ if (!raw) return fallback;+ try {+ const v = BigInt(raw);+ return v >= 0n ? v : fallback;+ } catch {+ return fallback;+ }+}++export function resolveSpendEnabled() {+ const raw =+ env.THREEWS_AGENT_PAY_ENABLED ??+ (typeof process !== 'undefined' ? process.env?.THREEWS_AGENT_PAY_ENABLED : undefined);+ return raw === '1' || raw === 'true';+}++// The user's primary agent wallet — first agent by creation, matching the+// existing x402-pay convention (getAgentsForUser orders by created_at ASC).+export async function resolveUserAgentWallet(userId) {+ if (!userId) return null;+ const [row] = await sql`+ SELECT id, name, meta FROM agent_identities+ WHERE user_id = ${userId} AND deleted_at IS NULL+ ORDER BY created_at ASC+ LIMIT 1+ `;+ if (!row) return null;+ const address = row.meta?.solana_address || null;+ return {+ agentId: row.id,+ name: row.name || null,+ address,+ hasSecret: !!row.meta?.encrypted_solana_secret,+ encryptedSecret: row.meta?.encrypted_solana_secret || null,+ };+}++// Build a paying axios instance bound to the user's Solana keypair, with the+// platform spending cap installed. Returns { api, client, uninstall, address }.+async function buildUserPayingClient({ wallet, userId, maxPerCallOverride }) {+ const [{ default: axios }, { x402Client, x402HTTPClient }, { wrapAxiosWithPayment }, { ExactSvmScheme }, { createKeyPairSignerFromBytes }] =+ await Promise.all([+ import('axios'),+ import('@x402/core/client'),+ import('@x402/axios'),+ import('@x402/svm/exact/client'),+ import('@solana/kit'),+ ]);++ const keypair = await recoverSolanaAgentKeypair(wallet.encryptedSecret, {+ agentId: wallet.agentId,+ userId,+ reason: 'pay_and_call',+ });+ const svmSigner = await createKeyPairSignerFromBytes(keypair.secretKey);++ const client = new x402Client();+ client.register('solana:*', new ExactSvmScheme(svmSigner));++ const envPerCall = envAtomic('X402_MAX_PER_CALL_ATOMIC', DEFAULT_MAX_PER_CALL);+ const perCall =+ maxPerCallOverride != null && maxPerCallOverride < envPerCall ? maxPerCallOverride : envPerCall;+ const uninstall = installSpendingCap(client, {+ address: wallet.address,+ maxPerCall: perCall.toString(),+ maxPerHour: envAtomic('X402_MAX_PER_HOUR_ATOMIC', DEFAULT_MAX_PER_HOUR).toString(),+ maxPerDay: envAtomic('X402_MAX_PER_DAY_ATOMIC', DEFAULT_MAX_PER_DAY).toString(),+ });++ const httpClient = new x402HTTPClient(client);+ const api = wrapAxiosWithPayment(+ axios.create({ timeout: 60_000, validateStatus: (s) => s >= 200 && s < 300 }),+ client,+ );+ return { api, client, httpClient, uninstall, address: wallet.address };+}++function extractReceipt(httpClient, response) {+ if (!response?.headers) return null;+ try {+ return httpClient.getPaymentSettleResponse((n) => response.headers[n] ?? response.headers[n.toLowerCase()]) || null;+ } catch {+ return null;+ }+}++const USDC_MAINNET_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++// Read-only wallet status for the user's primary agent: address, SOL + USDC+// balance, the active spending caps, and whether autonomous spend is enabled.+// Safe to expose — no keys touched, no funds moved.+export async function getUserWalletStatus(userId) {+ const wallet = await resolveUserAgentWallet(userId);+ const caps = {+ max_per_call_usdc: Number(envAtomic('X402_MAX_PER_CALL_ATOMIC', DEFAULT_MAX_PER_CALL)) / 1e6,+ max_per_hour_usdc: Number(envAtomic('X402_MAX_PER_HOUR_ATOMIC', DEFAULT_MAX_PER_HOUR)) / 1e6,+ max_per_day_usdc: Number(envAtomic('X402_MAX_PER_DAY_ATOMIC', DEFAULT_MAX_PER_DAY)) / 1e6,+ };+ const spend_enabled = resolveSpendEnabled();+ if (!wallet || !wallet.address) {+ return { provisioned: false, address: null, spend_enabled, caps };+ }++ let sol = null;+ let usdc = null;+ try {+ const { Connection, PublicKey } = await import('@solana/web3.js');+ const { getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID } =+ await import('@solana/spl-token');+ const rpc =+ env.SOLANA_RPC_URL ??+ (typeof process !== 'undefined' ? process.env?.SOLANA_RPC_URL : null) ??+ 'https://api.mainnet-beta.solana.com';+ const conn = new Connection(rpc, 'confirmed');+ const owner = new PublicKey(wallet.address);+ const lamports = await conn.getBalance(owner);+ sol = lamports / 1e9;+ try {+ const ata = getAssociatedTokenAddressSync(+ new PublicKey(USDC_MAINNET_MINT),+ owner,+ false,+ TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ const bal = await conn.getTokenAccountBalance(ata);+ usdc = bal?.value?.uiAmount ?? 0;+ } catch {+ usdc = 0; // no ATA yet → zero USDC+ }+ } catch {+ // RPC failure — report the wallet without live balances rather than throw.+ }++ return {+ provisioned: true,+ agent_id: wallet.agentId,+ agent_name: wallet.name,+ address: wallet.address,+ network: 'solana',+ balances: { sol, usdc },+ spend_enabled,+ caps,+ };+}++// Pay an external x402 endpoint from the user's wallet. Throws an Error with a+// `.code` for the boundary (the MCP handler) to translate into a clean result.+export async function payExternalX402({ userId, url, method = 'GET', body, maxUsd }) {+ if (!resolveSpendEnabled()) {+ throw Object.assign(new Error('autonomous spending is disabled on this server'), {+ code: 'spend_disabled',+ });+ }+ if (!userId) {+ throw Object.assign(new Error('sign in required to pay from your wallet'), {+ code: 'auth_required',+ });+ }+ const wallet = await resolveUserAgentWallet(userId);+ if (!wallet) {+ throw Object.assign(new Error('no agent wallet found for this account'), { code: 'no_wallet' });+ }+ if (!wallet.address || !wallet.hasSecret) {+ throw Object.assign(new Error('your agent has no Solana wallet provisioned'), {+ code: 'no_solana_wallet',+ });+ }++ const maxPerCallOverride =+ typeof maxUsd === 'number' && maxUsd > 0 ? BigInt(Math.round(maxUsd * 1_000_000)) : null;++ const { api, httpClient, uninstall, address } = await buildUserPayingClient({+ wallet,+ userId,+ maxPerCallOverride,+ });++ try {+ const response = await api.request({+ url,+ method,+ ...(body != null ? { data: body } : {}),+ });+ return {+ ok: true,+ payer: address,+ result: response.data,+ receipt: extractReceipt(httpClient, response),+ };+ } finally {+ if (typeof uninstall === 'function') uninstall();+ }+}diff --git a/api/_mcpagent/catalog.js b/api/_mcpagent/catalog.jsnew file mode 100644index 000000000..3ce4a22fa--- /dev/null+++ b/api/_mcpagent/catalog.js@@ -0,0 +1,15 @@+import Ajv from 'ajv';++import { toolDefs } from './tools.js';++// Schema objects for tools/list — strip internal fields (scope, handler).+export const TOOL_CATALOG = toolDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);++const ajv = new Ajv({ allErrors: true, useDefaults: true, coerceTypes: true, strict: false });++export const TOOLS = Object.fromEntries(+ toolDefs.map(({ name, scope, handler, inputSchema }) => [+ name,+ { scope, handler, validate: inputSchema ? ajv.compile(inputSchema) : null },+ ]),+);diff --git a/api/_mcpagent/dispatch.js b/api/_mcpagent/dispatch.jsnew file mode 100644index 000000000..a6fd0625b--- /dev/null+++ b/api/_mcpagent/dispatch.js@@ -0,0 +1,24 @@+// JSON-RPC dispatch for the threews-agent MCP server — thin binding of the+// shared payment-free dispatcher (api/_lib/mcp-dispatch.js) to this catalog.+// (The "payment-free" refers to MCP-tool pricing; pay_and_call moves the+// USER's funds to external services, which is orthogonal to tool billing.)+import { makeDispatcher, PROTOCOL_VERSION } from '../_lib/mcp-dispatch.js';+import { TOOL_CATALOG, TOOLS } from './catalog.js';++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.',+].join(' ');++export const dispatch = makeDispatcher({+ serverInfo: { name: 'threews-agent', version: '1.0.0' },+ instructions: INSTRUCTIONS,+ catalog: TOOL_CATALOG,+ tools: TOOLS,+ logName: 'mcp-agent',+});diff --git a/api/_mcpagent/tools.js b/api/_mcpagent/tools.jsnew file mode 100644index 000000000..c447b1a1d--- /dev/null+++ b/api/_mcpagent/tools.js@@ -0,0 +1,213 @@+// threews-agent MCP — "add a wallet to Claude."+//+// Three tools turn a Claude (or any MCP client) into an autonomous economic+// agent on the live x402 network:+// • wallet_status — what the agent's wallet holds and is allowed to spend+// • find_services — discover paid services it can call+// • pay_and_call — pay an x402 endpoint in USDC from the user's own wallet+// and return the result, bounded by spending caps+//+// pay_and_call moves real money. It requires an authenticated (OAuth) user so+// the agent spends THAT user's wallet, and it is hard-gated by+// THREEWS_AGENT_PAY_ENABLED on the server. When spend is disabled it degrades+// to returning the exact payment requirements + a pay link rather than failing.+import { limits } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';+import { Bazaar, filterByMaxPrice, filterByNetwork } from '../_lib/x402/bazaar-client.js';+import {+ getUserWalletStatus,+ payExternalX402,+ resolveSpendEnabled,+} from '../_lib/x402-user-payer.js';++function rpcError(code, message, data) {+ const e = new Error(message);+ e.code = code;+ e.data = data;+ return e;+}++async function enforce(limiter, auth) {+ const rl = await limiter(auth.userId || auth.rateKey || 'anon');+ if (!rl.success) {+ throw rpcError(-32000, 'rate_limited', {+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),+ });+ }+}++function payLink(resource) {+ const u = new URL(`${env.APP_ORIGIN}/pay`);+ u.searchParams.set('resource', resource);+ return u.toString();+}++export const toolDefs = [+ {+ name: 'wallet_status',+ title: "Check the agent's wallet",+ description:+ "Show the signed-in user's three.ws agent wallet: address, SOL and USDC balance, the per-call/hour/day spending caps, and whether autonomous spending is enabled. Read-only — never moves funds. Call this before pay_and_call to confirm there's balance and headroom.",+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },+ async handler(args, auth) {+ await enforce(limits.mcpAgent, auth);+ if (!auth.userId) {+ return {+ content: [+ { type: 'text', text: 'Sign in to three.ws to see your agent wallet.' },+ ],+ structuredContent: { provisioned: false, signed_in: false },+ isError: true,+ };+ }+ const status = await getUserWalletStatus(auth.userId);+ const lines = status.provisioned+ ? [+ `Agent wallet${status.agent_name ? ` (${status.agent_name})` : ''}: ${status.address}`,+ `Network: ${status.network}`,+ `Balance: ${status.balances.sol ?? '?'} SOL, ${status.balances.usdc ?? '?'} USDC`,+ `Spending caps: $${status.caps.max_per_call_usdc}/call, $${status.caps.max_per_hour_usdc}/hr, $${status.caps.max_per_day_usdc}/day`,+ `Autonomous spend: ${status.spend_enabled ? 'enabled' : 'disabled'}`,+ ]+ : ['No agent wallet is provisioned for this account yet. Create one on three.ws to enable payments.'];+ return {+ content: [{ type: 'text', text: lines.join('\n') }],+ structuredContent: { signed_in: true, ...status },+ };+ },+ },+ {+ name: 'find_services',+ title: 'Find paid services the agent can call',+ description:+ 'Search the live x402 facilitator network for paid services (HTTP APIs and MCP tools). Returns each match with its price and resource URL — feed a resource into pay_and_call to actually use it.',+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'What you need, e.g. "weather", "image upscale".' },+ type: { type: 'string', enum: ['http', 'mcp'], default: 'http' },+ network: { type: 'string', description: 'CAIP-2 network filter, e.g. "solana:*" or "eip155:8453".' },+ max_price_usdc: { type: 'number', minimum: 0 },+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 15 },+ },+ required: ['query'],+ additionalProperties: false,+ },+ async handler(args, auth) {+ await enforce(limits.mcpAgent, auth);+ const type = args.type || 'http';+ const { resources, errors } = await new Bazaar({}).search({ query: args.query, type });+ let out = resources;+ if (args.network) out = filterByNetwork(out, args.network);+ if (args.max_price_usdc != null)+ out = filterByMaxPrice(out, String(Math.round(args.max_price_usdc * 1_000_000)));+ const services = out.slice(0, args.limit || 15).map((it) => ({+ resource: it.resource,+ name: it.serviceName || undefined,+ description: it.description || undefined,+ price: it.minPriceLabel || undefined,+ networks: it.networks,+ tool_name: it.toolName || undefined,+ }));+ const text = services.length+ ? services+ .map((s, i) => `${i + 1}. ${s.name || s.resource}${s.price ? ` — ${s.price}` : ''}\n ${s.resource}`)+ .join('\n')+ : `No services matched "${args.query}".`;+ return {+ content: [{ type: 'text', text }],+ structuredContent: { query: args.query, count: services.length, services, errors },+ };+ },+ },+ {+ name: 'pay_and_call',+ title: 'Pay an x402 service and return its result',+ description:+ "Call a paid x402 endpoint and settle the USDC payment automatically from the signed-in user's three.ws agent wallet, bounded by spending caps. Returns the service's response. Requires sign-in. If the per-call price exceeds max_usd (or the caps), the call is refused before any money moves.",+ inputSchema: {+ type: 'object',+ properties: {+ resource_url: { type: 'string', format: 'uri', description: 'The x402 endpoint to call.' },+ method: { type: 'string', enum: ['GET', 'POST'], default: 'GET' },+ body: { type: 'object', description: 'JSON body for POST requests.' },+ max_usd: {+ type: 'number',+ minimum: 0,+ description: 'Hard ceiling for THIS call in USD. Can only lower the server caps, never raise them.',+ },+ },+ required: ['resource_url'],+ additionalProperties: false,+ },+ async handler(args, auth) {+ await enforce(limits.mcpAgentPay, auth);++ // Degrade gracefully when spend is off or the user can't pay: return the+ // exact payment details + a pay link instead of moving (or failing to move) funds.+ 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(args.resource_url)}`,+ },+ ],+ structuredContent: {+ paid: false,+ reason: auth.userId ? 'spend_disabled' : 'auth_required',+ resource: args.resource_url,+ pay_link: payLink(args.resource_url),+ },+ };+ }++ try {+ const res = await payExternalX402({+ userId: auth.userId,+ url: args.resource_url,+ method: args.method || 'GET',+ body: args.body,+ maxUsd: args.max_usd,+ });+ return {+ content: [+ {+ type: 'text',+ text: `Paid and called ${args.resource_url} from ${res.payer}. Result returned below.`,+ },+ ],+ structuredContent: {+ paid: true,+ payer: res.payer,+ resource: args.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.',+ };+ const msg = friendly[err.code] || `Payment failed: ${err.message}`;+ return {+ content: [{ type: 'text', text: msg }],+ structuredContent: {+ paid: false,+ reason: err.code || 'error',+ resource: args.resource_url,+ pay_link: payLink(args.resource_url),+ },+ isError: true,+ };+ }+ },+ },+];diff --git a/api/mcp-agent.js b/api/mcp-agent.jsnew file mode 100644index 000000000..2b6f8a540--- /dev/null+++ b/api/mcp-agent.js@@ -0,0 +1,47 @@+// three.ws Agent — MCP server (Streamable HTTP transport, MCP 2025-06-18).+// "Add a wallet to Claude": discover, pay for, and call x402 services in USDC+// from the signed-in user's own three.ws agent wallet, bounded by spend caps.+// POST /api/mcp-agent — tool calls GET — SSE DELETE — terminate.+// Registered with the MCP Registry as io.github.nirholas/threews-agent.+import { cors, readJson, wrap } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { PROTOCOL_VERSION, dispatch } from './_mcpagent/dispatch.js';+import { send401, sendJsonRpcError, authenticateRequest, handleSse, handleTerminate } from './_mcp/auth.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,HEAD,POST,DELETE,OPTIONS', origins: '*' })) return;++ if (req.method === 'GET' || req.method === 'HEAD') return handleSse(req, res);+ if (req.method === 'DELETE') return handleTerminate(req, res);+ if (req.method !== 'POST') return send401(res, 'method not supported');++ const result = await authenticateRequest(req, res);+ if (!result) return;+ const { auth } = result;++ const ipRl = await limits.mcpIp(clientIp(req));+ if (!ipRl.success)+ return sendJsonRpcError(res, null, -32000, 'rate_limited', {+ retry_after: Math.ceil((ipRl.reset - Date.now()) / 1000),+ });+ const userRl = await limits.mcpUser(auth.userId || auth.rateKey || clientIp(req));+ if (!userRl.success)+ return sendJsonRpcError(res, null, -32000, 'rate_limited', {+ retry_after: Math.ceil((userRl.reset - Date.now()) / 1000),+ });++ const body = await readJson(req, 1_000_000);+ const batch = Array.isArray(body) ? body : [body];+ if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');++ const responses = [];+ for (const msg of batch) {+ const r = await dispatch(msg, auth, req);+ if (r !== null) responses.push(r);+ }++ res.statusCode = 200;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);+ res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));+});diff --git a/packages/three-token-mcp/LICENSE b/packages/three-token-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/three-token-mcp/LICENSE@@ -0,0 +1,180 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship made available under+ the License, as indicated by a copyright notice that is included in+ or attached to the work (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other transformations+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean, as submitted to the Licensor for inclusion+ in the Work by the copyright owner or by an individual or Legal Entity+ authorized to submit on behalf of the copyright owner. For the purposes+ of this definition, "submitted" means any form of electronic, verbal,+ or written communication sent to the Licensor or its representatives,+ including but not limited to communication on electronic mailing lists,+ source code control systems, and issue tracking systems that are managed+ by, or on behalf of, the Licensor for the purpose of discussing and+ improving the Work, but excluding communication that is conspicuously+ marked or designated in writing by the copyright owner as "Not a+ Contribution."++ "Contributor" shall mean Licensor and any Legal Entity on behalf of+ whom a Contribution has been received by the Licensor and included+ within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by the combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a cross-claim+ or counterclaim in a lawsuit) alleging that the Work or any+ Contribution embodied within the Work constitutes direct or contributory+ patent infringement, then any patent licenses granted to You under+ this License for that Work shall terminate as of the date such+ litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or Derivative+ Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, You must include a readable copy of the+ attribution notices contained within such NOTICE file, in+ at least one of the following places: within a NOTICE text+ file distributed as part of the Derivative Works; within+ the Source form or documentation, if provided along with the+ Derivative Works; or, within a display generated by the+ Derivative Works, if and wherever such third-party notices+ normally appear. The contents of the NOTICE file are for+ informational purposes only and do not modify the License.+ You may add Your own attribution notices within Derivative+ Works that You distribute, alongside or in addition to the+ NOTICE text from the Work, provided that such additional+ attribution notices cannot be construed as modifying the License.++ You may add Your own license statement for Your modifications and+ may provide additional grant of rights to use, copy, modify, merge,+ publish, distribute, sublicense, and/or sell copies of the+ Derivative Works, and to permit persons to whom the Derivative Works+ are furnished to do so.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or reproducing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or exemplary damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or all other+ commercial damages or losses), even if such Contributor has been+ advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may offer only+ conditions consistent with this License.++ END OF TERMS AND CONDITIONS++ Copyright 2026 nirholas++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/three-token-mcp/package.json b/packages/three-token-mcp/package.jsonnew file mode 100644index 000000000..7e8b1e30d--- /dev/null+++ b/packages/three-token-mcp/package.json@@ -0,0 +1,61 @@+{+ "name": "@three-ws/three-token-mcp",+ "version": "1.0.0",+ "mcpName": "io.github.nirholas/three-token-mcp",+ "description": "The first MCP server whose actions burn a token. Let any AI agent price, hold, and burn $THREE on-chain — every burn splits to the incinerator + treasury via the live three.ws token rail, with Jupiter USD pricing. Deflation as an agent primitive.",+ "type": "module",+ "author": "nirholas <[email protected]>",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "https://github.com/nirholas/three.ws.git",+ "directory": "packages/three-token-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "model-context-protocol",+ "three.ws",+ "$three",+ "solana",+ "spl-token",+ "burn",+ "deflation",+ "x402",+ "jupiter",+ "ai-agent"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "three-token-mcp": "./src/index.js"+ },+ "main": "./src/index.js",+ "exports": {+ ".": "./src/index.js"+ },+ "engines": {+ "node": ">=20"+ },+ "scripts": {+ "start": "node src/index.js",+ "inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"+ },+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "@solana/spl-token": "^0.4.14",+ "@solana/web3.js": "^1.98.4",+ "bs58": "^6.0.0",+ "zod": "^3.23.8"+ }+}diff --git a/packages/three-token-mcp/src/config.js b/packages/three-token-mcp/src/config.jsnew file mode 100644index 000000000..c4933bca9--- /dev/null+++ b/packages/three-token-mcp/src/config.js@@ -0,0 +1,27 @@+// Centralized env access for the $THREE token MCP.+//+// This server is user-keyed: the on-chain burn is signed by a Solana keypair+// the operator supplies (SOLANA_SECRET_KEY) or that a tool call overrides with+// a per-call `secret`. We never bake in a key. Destination addresses (burn ++// treasury), token decimals, and live USD pricing all come from the PUBLIC+// three.ws token endpoints at runtime — nothing about the money split is+// hardcoded here, so it always tracks the canonical on-chain config.++export function env(key, fallback) {+ const v = process.env[key];+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;+}++// Base URL of the three.ws API that serves /api/token/config and /api/token/price.+export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws');++// Solana RPC. Bring your own (Helius / QuickNode / Triton) for production.+export const SOLANA_RPC_URL = env('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com');++// Optional default signer (base58 secret key). Tools that burn accept a+// per-call `secret` argument that overrides this.+export const SOLANA_DEFAULT_SECRET = env('SOLANA_SECRET_KEY') || env('FUNDER_SECRET') || '';++// The Solana Memo program — every burn tx carries a memo so the transfer is+// attributable on-chain to this MCP.+export const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';diff --git a/packages/three-token-mcp/src/lib/solana.js b/packages/three-token-mcp/src/lib/solana.jsnew file mode 100644index 000000000..adf267368--- /dev/null+++ b/packages/three-token-mcp/src/lib/solana.js@@ -0,0 +1,91 @@+// Solana primitives for the $THREE token MCP: connection, key handling, and+// balance reads. Self-contained so the published npm package has no internal+// cross-package imports.++import { Connection, Keypair, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js';+import bs58 from 'bs58';++import { SOLANA_RPC_URL, SOLANA_DEFAULT_SECRET } from '../config.js';++const bs58encode = bs58.default ? bs58.default.encode : bs58.encode;+const bs58decode = bs58.default ? bs58.default.decode : bs58.decode;++export { bs58encode, bs58decode, LAMPORTS_PER_SOL, PublicKey };++let _conn = null;+export function getConnection() {+ if (!_conn) _conn = new Connection(SOLANA_RPC_URL, 'confirmed');+ return _conn;+}++export function isValidPubkey(s) {+ try {+ // eslint-disable-next-line no-new+ new PublicKey(s);+ return true;+ } catch {+ return false;+ }+}++/**+ * Parse a base58 secret key (64-byte Solana keypair) into a Keypair. Accepts+ * either a base58 string or a JSON array of bytes.+ */+export function keypairFromSecret(secret) {+ const trimmed = (secret || '').trim();+ if (!trimmed) {+ throw Object.assign(new Error('No Solana secret key provided. Set SOLANA_SECRET_KEY or pass `secret`.'), {+ code: 'no_signer',+ });+ }+ let bytes;+ if (trimmed.startsWith('[')) {+ bytes = Uint8Array.from(JSON.parse(trimmed));+ } else {+ bytes = bs58decode(trimmed);+ }+ if (bytes.length !== 64) {+ throw Object.assign(new Error(`Invalid secret key length ${bytes.length} (expected 64 bytes).`), {+ code: 'bad_secret',+ });+ }+ return Keypair.fromSecretKey(bytes);+}++/** Resolve a signer from an explicit per-call secret or the configured default. */+export function loadSigner(secret) {+ return keypairFromSecret(secret || SOLANA_DEFAULT_SECRET);+}++export async function getSolBalance(pubkeyStr) {+ const conn = getConnection();+ const lamports = await conn.getBalance(new PublicKey(pubkeyStr), 'confirmed');+ return { lamports, sol: lamports / LAMPORTS_PER_SOL };+}++/**+ * Read an SPL token balance for a single mint owned by `pubkeyStr`. Returns the+ * raw atomic amount (string) and the UI amount, or zero if no token account+ * exists yet.+ */+export async function getSplBalance(pubkeyStr, mint) {+ const conn = getConnection();+ const res = await conn.getParsedTokenAccountsByOwner(new PublicKey(pubkeyStr), {+ mint: new PublicKey(mint),+ });+ let atomics = 0n;+ let decimals = 0;+ for (const { account } of res.value) {+ const info = account.data?.parsed?.info?.tokenAmount;+ if (!info) continue;+ atomics += BigInt(info.amount);+ decimals = info.decimals;+ }+ return {+ mint,+ atomics: atomics.toString(),+ decimals,+ uiAmount: decimals ? Number(atomics) / 10 ** decimals : Number(atomics),+ };+}diff --git a/server-agent.json b/server-agent.jsonnew file mode 100644index 000000000..15d746f5b--- /dev/null+++ b/server-agent.json@@ -0,0 +1,16 @@+{+ "$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.",+ "repository": {+ "url": "https://github.com/nirholas/three.ws",+ "source": "github"+ },+ "version": "1.0.0",+ "remotes": [+ {+ "type": "streamable-http",+ "url": "https://three.ws/api/mcp-agent"+ }+ ]+}