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.

feat: enhance Solana RPC connection with additional fallback URLs and humanoid classifier integration

miniaturization18cfa2e45ef4
diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.js
index 0dee8036f..89e693021 100644
--- a/api/_lib/solana/connection.js
+++ b/api/_lib/solana/connection.js
@@ -10,10 +10,16 @@
// safe: Solana dedupes by signature.
//
// Priority (per network): the caller's explicit url (if any) → Helius → Alchemy
-// → Ankr (authenticated only) → PublicNode → the keyless public endpoint, always
+// → dRPC (authenticated) → Ankr (authenticated only) → operator-supplied
+// SOLANA_RPC_FALLBACK_URLS → PublicNode → the keyless public endpoint, always
// last. We never depend on the public endpoint alone — it is the most
// aggressively rate-limited (the source of the `getBalance 429` log noise) — and
// we never include a keyless Ankr URL, which Ankr now answers with a hard 403.
+//
+// To survive a single provider's quota running dry (e.g. a paid Helius plan
+// exhausting its monthly requests), register free-tier keys at several providers
+// and list their URLs in SOLANA_RPC_FALLBACK_URLS — every connection rotates
+// across the whole set, so the platform keeps serving even mid-outage.
import { Connection } from '@solana/web3.js';
@@ -111,21 +117,39 @@ function inferNetwork(url) {
return /devnet/i.test(String(url || '')) ? 'devnet' : 'mainnet';
}
+// Operator-supplied extra fallback URLs (comma-separated SOLANA_RPC_FALLBACK_URLS).
+// This is the zero-deploy lever for "spread load across as many free tiers as
+// possible": sign up for free-tier keys at several providers (Alchemy, dRPC,
+// QuickNode, Chainstack, Triton…), drop their URLs here, and EVERY Solana
+// connection rotates across them — so no single free quota becomes the bottleneck
+// and a provider running dry transparently fails over to the next.
+function extraFallbackUrls() {
+ return (process.env.SOLANA_RPC_FALLBACK_URLS || '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+}
+
/**
* Priority-ordered endpoint list for a network. An explicit `url` (the value a
- * call site already resolved) is pinned first; the keyed providers and public
- * endpoint follow as fallbacks.
+ * call site already resolved) is pinned first; keyed providers, then any
+ * operator-supplied SOLANA_RPC_FALLBACK_URLS, then the keyless public endpoints
+ * follow as fallbacks. The most-throttled public endpoint is always last.
*/
export function solanaRpcEndpoints(network = 'mainnet', url = null) {
const key = process.env.HELIUS_API_KEY;
const alch = process.env.ALCHEMY_API_KEY;
const ankr = process.env.ANKR_API_KEY;
+ // dRPC — free tier requires a key (keyless now returns "chain is not available
+ // on freetier"). Added in its authenticated form only when DRPC_API_KEY is set.
+ const drpc = process.env.DRPC_API_KEY;
if (network === 'devnet') {
return dedupe([
normalizeRpcUrl(url),
normalizeRpcUrl(process.env.SOLANA_RPC_URL_DEVNET),
key && `https://devnet.helius-rpc.com/?api-key=${key}`,
alch && `https://solana-devnet.g.alchemy.com/v2/${alch}`,
+ drpc && `https://lb.drpc.org/ogrpc?network=solana-devnet&dkey=${drpc}`,
PUBLIC_DEVNET,
]);
}
@@ -134,11 +158,16 @@ export function solanaRpcEndpoints(network = 'mainnet', url = null) {
normalizeRpcUrl(process.env.SOLANA_RPC_URL),
key && `https://mainnet.helius-rpc.com/?api-key=${key}`,
alch && `https://solana-mainnet.g.alchemy.com/v2/${alch}`,
+ drpc && `https://lb.drpc.org/ogrpc?network=solana&dkey=${drpc}`,
// Ankr sunset keyless access — every keyless rpc.ankr.com/<chain> now 403s
// ("authenticate with an API key"), so include it only in its authenticated
// form when ANKR_API_KEY is set. Mirrors idxRpcUrls() in api/cron/[name].js;
// a keyless entry here was a guaranteed 403 + cooldown log every cron tick.
ankr && `https://rpc.ankr.com/solana/${ankr}`,
+ // Operator's own free-tier fallbacks (mainnet only — devnet URLs would cross
+ // clusters and return wrong data). Tried before the public nodes so the
+ // configured providers absorb load first.
+ ...extraFallbackUrls(),
// PublicNode — a keyless, un-throttled fallback (the same node mcp-server
// uses) so failover lands on a working endpoint instead of depending on the
// aggressively rate-limited public mainnet-beta endpoint alone.
diff --git a/api/_lib/solana/rpc-fallback.js b/api/_lib/solana/rpc-fallback.js
index 468a545f6..0614b3aec 100644
--- a/api/_lib/solana/rpc-fallback.js
+++ b/api/_lib/solana/rpc-fallback.js
@@ -195,16 +195,13 @@ export function createRpcFallback(options) {
return new RpcFallback(options);
}
-// Convenience: build a fallback set from env. The endpoint list is the canonical
-// chain (explicit SOLANA_RPC_URL → Helius → Alchemy → Ankr-when-keyed →
-// PublicNode → public), with any extra SOLANA_RPC_FALLBACK_URLS appended. So even
-// with no SOLANA_RPC_URL set, the keyed providers plus the two keyless endpoints
-// give a real 3+ deep failover set.
+// Convenience: build a fallback set from env. solanaRpcEndpoints() is now the
+// single source of truth for the whole chain (explicit SOLANA_RPC_URL → Helius →
+// Alchemy → dRPC-when-keyed → Ankr-when-keyed → operator SOLANA_RPC_FALLBACK_URLS
+// → PublicNode → public), so even with no SOLANA_RPC_URL set the keyed providers
+// plus the keyless endpoints give a real deep failover set.
export function rpcFallbackFromEnv({ network = 'mainnet', commitment = 'confirmed' } = {}) {
- const extra = (process.env.SOLANA_RPC_FALLBACK_URLS || '')
- .split(',').map((s) => s.trim()).filter(Boolean);
- const urls = [...solanaRpcEndpoints(network), ...extra]
- .filter((u, i, a) => u && a.indexOf(u) === i);
+ const urls = solanaRpcEndpoints(network);
const [primary, ...fallbackUrls] = urls;
return new RpcFallback({ url: primary, fallbackUrls, commitment });
}
diff --git a/mcp-server/src/index.js b/mcp-server/src/index.js
index a122e7ab6..7d48889eb 100755
--- a/mcp-server/src/index.js
+++ b/mcp-server/src/index.js
@@ -35,6 +35,7 @@ import { buildTextToAvatarTool } from './tools/text-to-avatar.js';
import { buildMeshForgeTool } from './tools/mesh-forge.js';
import { buildForgeFreeTool } from './tools/forge-free.js';
import { buildRigMeshTool } from './tools/rig-mesh.js';
+import { buildForgeAvatarTool } from './tools/forge-avatar.js';
import { buildSentimentPulseTool } from './tools/sentiment-pulse.js';
import { buildEnsSnsResolveTool } from './tools/ens-sns-resolve.js';
import { buildAgentDelegateActionTool } from './tools/agent-delegate-action.js';
@@ -53,6 +54,8 @@ const SERVER_INSTRUCTIONS =
'Tools cover: free text→3D generation (forge_free), 3D avatar generation (text_to_avatar), ' +
'text/image-to-3D mesh generation via a Granite-directed model chain (mesh_forge), ' +
'auto-rigging a GLB into an animation-ready model (rig_mesh), ' +
+ 'one-call text→rigged-avatar generation that chains mesh generation and auto-rigging with a ' +
+ 'humanoid gate (forge_avatar), ' +
'ENS + SNS name resolution ' +
'(ens_sns_resolve), agent-to-agent delegation (agent_delegate_action), token sentiment pulse ' +
'(sentiment_pulse), pose generation (get_pose_seed), Solana token snapshots (pump_snapshot), ' +
@@ -76,6 +79,7 @@ const TOOL_BUILDERS = [
buildMeshForgeTool,
buildForgeFreeTool,
buildRigMeshTool,
+ buildForgeAvatarTool,
buildEnsSnsResolveTool,
buildAgentDelegateActionTool,
buildSentimentPulseTool,
diff --git a/mcp-server/src/tools/_humanoid.js b/mcp-server/src/tools/_humanoid.js
new file mode 100644
index 000000000..458af7ab0
--- /dev/null
+++ b/mcp-server/src/tools/_humanoid.js
@@ -0,0 +1,161 @@
+// Deterministic humanoid-prompt classifier — shared by the avatar tools.
+//
+// Auto-rigging is a paid GPU operation that only makes sense for a humanoid
+// character: the UniRig pipeline fits a humanoid skeleton, and the three.ws
+// canonical clip library (idle/walk) only retargets onto a humanoid rig. Rigging
+// "a worn leather armchair" burns a paid call and yields a useless skeleton, so
+// the avatar pipeline gates auto-rig on this check.
+//
+// It is a pure lexical heuristic on purpose: no network, no model call, zero
+// added latency, and fully deterministic (the same prompt always classifies the
+// same way — important for billing and tests). It reads the prompt the way the
+// downstream skeleton fitter does — does this describe a character with a body
+// plan a humanoid rig can drive? — and returns a confidence so callers can pick
+// a threshold. It never throws; an empty or junk prompt yields a low-confidence
+// non-humanoid verdict, which the caller treats as "don't auto-rig."
+
+// Strong positive signals: words that almost always denote a humanoid figure.
+// Matched as whole words (see WORD_RE) so "manifold" never trips "man".
+const HUMANOID_TERMS = [
+ 'avatar', 'character', 'humanoid', 'human', 'person', 'people', 'figure',
+ 'man', 'woman', 'men', 'women', 'boy', 'girl', 'child', 'kid', 'lady', 'guy', 'dude',
+ 'male', 'female', 'hero', 'heroine', 'villain', 'warrior', 'soldier', 'knight',
+ 'wizard', 'mage', 'witch', 'ninja', 'samurai', 'pirate', 'viking', 'gladiator',
+ 'astronaut', 'cyborg', 'android', 'robot', 'mecha', 'mech', 'golem', 'zombie',
+ 'skeleton', 'mummy', 'vampire', 'werewolf', 'demon', 'angel', 'goddess', 'god',
+ 'elf', 'orc', 'goblin', 'dwarf', 'troll', 'fairy', 'gnome', 'centaur',
+ 'alien', 'monster', 'creature', 'mascot', 'doll', 'mannequin', 'statue',
+ 'king', 'queen', 'prince', 'princess', 'soldier', 'guard', 'monk', 'priest',
+ 'dancer', 'fighter', 'athlete', 'player', 'gamer', 'superhero', 'spaceman',
+ 'goku', 'anime', 'waifu', 'vtuber', 'npc', 'biped', 'bipedal',
+];
+
+// Body-part / pose cues — a prompt that mentions these describes something with
+// a humanoid body plan even if it never names the figure directly
+// (e.g. "a suit of armour with crossed arms standing on two legs").
+const BODY_TERMS = [
+ 'arms', 'arm', 'legs', 'leg', 'torso', 'limbs', 'hands', 'hand', 'fingers',
+ 'shoulders', 'shoulder', 'hips', 'hip', 'spine', 'standing', 'walking',
+ 'posing', 'pose', 'running', 'sitting', 'two legs', 'upright', 'full body',
+ 'full-body', 'fullbody',
+];
+
+// Strong negatives: subjects that are emphatically NOT humanoid. Their presence
+// pulls confidence down hard, so "a cute teapot character" (toy with a face but
+// no body plan) doesn't get auto-rigged into a broken skeleton.
+const NON_HUMANOID_TERMS = [
+ 'armchair', 'chair', 'sofa', 'couch', 'table', 'desk', 'lamp', 'vase',
+ 'teapot', 'mug', 'cup', 'bottle', 'bowl', 'plate', 'cutlery',
+ 'car', 'truck', 'vehicle', 'tank', 'plane', 'aircraft', 'jet', 'ship',
+ 'boat', 'rocket', 'spaceship', 'spacecraft', 'drone', 'bicycle', 'motorcycle',
+ 'building', 'house', 'tower', 'castle', 'bridge', 'temple', 'cathedral',
+ 'tree', 'plant', 'flower', 'rock', 'stone', 'mountain', 'terrain', 'landscape',
+ 'sword', 'shield', 'gun', 'rifle', 'pistol', 'axe', 'hammer', 'helmet', 'crown',
+ 'ring', 'necklace', 'coin', 'gem', 'crystal', 'potion', 'barrel', 'crate', 'chest',
+ 'food', 'burger', 'pizza', 'cake', 'fruit', 'apple', 'sneaker', 'shoe', 'boot',
+ 'logo', 'icon', 'emblem', 'sign', 'gear', 'engine', 'machine', 'turbine',
+ 'fish', 'bird', 'insect', 'butterfly', 'flower', 'mushroom', 'leaf',
+];
+
+// Animals are quadrupeds/other — a humanoid rig won't drive them. Kept separate
+// because some are common ("dragon", "horse") and we want them firmly negative.
+const ANIMAL_TERMS = [
+ 'dog', 'cat', 'horse', 'cow', 'pig', 'sheep', 'goat', 'lion', 'tiger', 'bear',
+ 'wolf', 'fox', 'deer', 'rabbit', 'mouse', 'rat', 'elephant', 'giraffe', 'zebra',
+ 'dragon', 'dinosaur', 'dino', 'snake', 'lizard', 'turtle', 'frog', 'shark',
+ 'whale', 'dolphin', 'octopus', 'crab', 'spider', 'bee', 'ant', 'horse',
+ 'eagle', 'owl', 'penguin', 'duck', 'chicken', 'cow', 'bull', 'ram',
+];
+
+function buildWordSet(terms) {
+ // Multi-word terms ("two legs", "full body") are matched as substrings; the
+ // single-word majority go in a Set for O(1) whole-word lookup.
+ const single = new Set();
+ const phrases = [];
+ for (const t of terms) {
+ if (t.includes(' ') || t.includes('-')) phrases.push(t);
+ else single.add(t);
+ }
+ return { single, phrases };
+}
+
+const HUMANOID = buildWordSet(HUMANOID_TERMS);
+const BODY = buildWordSet(BODY_TERMS);
+const NON_HUMANOID = buildWordSet([...NON_HUMANOID_TERMS, ...ANIMAL_TERMS]);
+
+// Split on any run of non-letter characters so punctuation, digits, and emoji
+// never fuse into adjacent words. Lowercased for case-insensitive matching.
+function tokenize(text) {
+ return String(text || '')
+ .toLowerCase()
+ .split(/[^a-z]+/)
+ .filter(Boolean);
+}
+
+function countHits({ single, phrases }, tokens, lowerText) {
+ let hits = 0;
+ for (const tok of tokens) if (single.has(tok)) hits += 1;
+ for (const p of phrases) if (lowerText.includes(p)) hits += 1;
+ return hits;
+}
+
+/**
+ * Classify whether a text prompt describes a humanoid figure worth auto-rigging.
+ *
+ * @param {string} prompt
+ * @returns {{ humanoid: boolean, confidence: number, reason: string,
+ * signals: { humanoid: number, body: number, nonHumanoid: number } }}
+ * `confidence` is in [0,1]. `humanoid` is true when confidence ≥ 0.5.
+ */
+export function classifyHumanoidPrompt(prompt) {
+ const text = String(prompt || '').toLowerCase().trim();
+ const tokens = tokenize(text);
+
+ if (tokens.length === 0) {
+ return {
+ humanoid: false,
+ confidence: 0,
+ reason: 'empty prompt',
+ signals: { humanoid: 0, body: 0, nonHumanoid: 0 },
+ };
+ }
+
+ const humanoidHits = countHits(HUMANOID, tokens, text);
+ const bodyHits = countHits(BODY, tokens, text);
+ const nonHits = countHits(NON_HUMANOID, tokens, text);
+
+ const signals = { humanoid: humanoidHits, body: bodyHits, nonHumanoid: nonHits };
+
+ // Base score: humanoid nouns count full, body cues count half (supporting,
+ // not defining). A strong non-humanoid noun ("armchair", "dragon") subtracts
+ // more than a body cue adds, so "dragon with two arms" stays non-humanoid.
+ const positive = humanoidHits + bodyHits * 0.5;
+ const negative = nonHits;
+ const net = positive - negative * 1.25;
+
+ // Map the net score onto [0,1] with a soft ramp. net ≤ 0 → ≤0.25 (the prompt
+ // names a non-humanoid subject or nothing relevant); net 1 → ~0.6; net ≥ 2 →
+ // ≥0.8. A bare object prompt with zero signals lands at exactly 0.25 — below
+ // threshold, so the default for an ambiguous prompt is "don't rig."
+ let confidence;
+ if (net <= 0) {
+ confidence = Math.max(0, 0.25 + net * 0.12);
+ } else {
+ confidence = Math.min(1, 0.4 + net * 0.2);
+ }
+ confidence = Math.round(confidence * 100) / 100;
+
+ const humanoid = confidence >= 0.5;
+ let reason;
+ if (humanoid) {
+ reason = `humanoid signals (${humanoidHits} figure, ${bodyHits} body) outweigh ${nonHits} non-humanoid`;
+ } else if (nonHits > 0) {
+ reason = `non-humanoid subject detected (${nonHits} signal${nonHits === 1 ? '' : 's'})`;
+ } else {
+ reason = 'no clear humanoid signal';
+ }
+
+ return { humanoid, confidence, reason, signals };
+}
+
+export default classifyHumanoidPrompt;
diff --git a/mcp-server/src/tools/forge-avatar.js b/mcp-server/src/tools/forge-avatar.js
new file mode 100644
index 000000000..2576cda3a
--- /dev/null
+++ b/mcp-server/src/tools/forge-avatar.js
@@ -0,0 +1,319 @@
+// `forge_avatar` — paid MCP tool: text prompt → rigged, animation-ready avatar
+// in ONE call.
+//
+// Pricing: $0.40 USDC, settled `exact` on Solana. (A small bundle discount over
+// the $0.25 mesh_forge + $0.20 rig_mesh you'd pay running the two steps by hand.)
+//
+// This composes the two production three.ws pipelines — generate then rig — that
+// mesh_forge and rig_mesh expose individually, so an agent can go straight from a
+// description to a model that drops into the pose studio and plays the canonical
+// idle/walk clips. Like its siblings it is a thin, x402-gated client over the
+// prod /api/forge endpoint and holds NO generation credentials; the USDC payment
+// gates the call and all GPU work runs on three.ws prod.
+//
+// Stages:
+// 1. Generate — POST /api/forge with the prompt (text→3D). Produces a textured,
+// static GLB. Polled to a terminal state.
+// 2. Humanoid gate — the generated mesh is auto-rigged ONLY when the prompt
+// describes a humanoid figure (classifyHumanoidPrompt). UniRig fits a
+// humanoid skeleton and the canonical clip library only retargets onto a
+// humanoid rig, so a non-character prompt ("a leather armchair") skips
+// rigging instead of burning a paid rig call on a useless skeleton. Set
+// `force_rig:true` to override and rig regardless.
+// 3. Rig — POST /api/forge?action=rig with the durable mesh URL. Produces a
+// rigged GLB (skeleton + skin weights). Polled to a terminal state.
+//
+// Always returns the generated mesh; `rigged` reports whether stage 3 ran and,
+// when it did, the rigged GLB + pose-studio link. A rig failure never discards
+// the paid-for mesh — the mesh URL is always returned, with the rig error
+// attached, so the caller keeps the asset they paid to generate.
+//
+// Environment (all optional — sensible prod defaults):
+// MESH_FORGE_API_BASE — three.ws origin. Default https://three.ws
+// FORGE_AVATAR_TIMEOUT_MS — overall poll budget PER stage. Default 180000.
+// FORGE_AVATAR_POLL_MS — poll interval. Default 3000.
+
+import { z } from 'zod';
+
+import { paid, toolError } from '../payments.js';
+import { jsonSchemaFromZod } from './_shared.js';
+import { classifyHumanoidPrompt } from './_humanoid.js';
+
+const TOOL_NAME = 'forge_avatar';
+const TOOL_DESCRIPTION =
+ 'Generate a rigged, animation-ready 3D avatar from a text prompt in ONE call. Runs the three.ws ' +
+ 'pipeline end to end: text→3D mesh generation, then — when the prompt describes a humanoid figure — ' +
+ 'auto-rigging (humanoid skeleton + skin weights via UniRig). Returns the generated mesh URL, the ' +
+ 'rigged GLB URL, a three.ws pose-studio link that plays the canonical idle/walk clips, and per-stage ' +
+ 'timing. Non-humanoid prompts (a chair, a car) return the textured mesh and skip rigging automatically ' +
+ 'so you are never charged a wasted rig on a mesh no humanoid skeleton can drive; pass force_rig:true to ' +
+ 'rig anyway. For a static mesh only use mesh_forge; to rig an existing GLB use rig_mesh. Paid: $0.40 USDC.';
+
+function env(k, def) {
+ const v = process.env[k];
+ return v && String(v).trim() ? String(v).trim() : def;
+}
+
+function apiBase() {
+ return env('MESH_FORGE_API_BASE', 'https://three.ws').replace(/\/$/, '');
+}
+
+// Tag a thrown error with a stable `code` (and optional retryAfter) so the
+// handler can translate it into a toolError without string-sniffing messages.
+function fail(code, message, extra) {
+ const e = new Error(message);
+ e.code = code;
+ if (extra && extra.retryAfter != null) e.retryAfter = extra.retryAfter;
+ return e;
+}
+
+async function postForge(path, body) {
+ const res = await fetch(`${apiBase()}/api/forge${path}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(30_000),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 503) throw fail('not_configured', data?.message || 'this stage is not configured on the three.ws deployment');
+ if (res.status === 501) throw fail('not_configured', data?.message || 'this stage is not enabled on the three.ws deployment');
+ if (res.status === 429) throw fail('rate_limited', data?.message || 'the pipeline is busy; try again shortly', { retryAfter: data?.retry_after });
+ if (!res.ok || !data?.job_id) throw fail('provider_error', data?.message || `forge returned ${res.status}`);
+ return data;
+}
+
+// Poll a forge job to a terminal state. Returns the done payload (with glb_url),
+// or `{ ...last, _timedOut:true }` if the budget elapses before completion. A
+// transient network/timeout error during a single poll is retried, not fatal.
+async function pollForge(jobId, { timeoutMs, intervalMs }) {
+ const deadline = Date.now() + timeoutMs;
+ let last = null;
+ while (Date.now() < deadline) {
+ let res;
+ try {
+ res = await fetch(`${apiBase()}/api/forge?job=${encodeURIComponent(jobId)}`, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(Math.max(intervalMs * 3, 15_000)),
+ });
+ } catch (err) {
+ if (err?.name === 'AbortError' || err?.name === 'TimeoutError') {
+ await new Promise((r) => setTimeout(r, intervalMs));
+ continue;
+ }
+ throw fail('provider_error', `forge poll failed: ${err?.message || err}`);
+ }
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) throw fail('provider_error', data?.message || `forge poll returned ${res.status}`);
+ last = data;
+ if (data.status === 'done' && data.glb_url) return data;
+ if (data.status === 'failed') throw fail('stage_failed', data.error || 'stage failed');
+ await new Promise((r) => setTimeout(r, intervalMs));
+ }
+ return { ...(last || {}), _timedOut: true };
+}
+
+const inputZodShape = {
+ prompt: z
+ .string()
+ .min(3)
+ .max(1000)
+ .describe('Natural-language description of the character to model, e.g. "a friendly cartoon astronaut, glossy white suit". Lead with the figure and its key materials/colors.'),
+ aspect_ratio: z
+ .enum(['1:1', '4:3', '3:4', '16:9', '9:16'])
+ .describe('Reference image aspect ratio. Default 1:1 (best for an isolated figure).')
+ .optional(),
+ force_rig: z
+ .boolean()
+ .describe('Rig the mesh even when the prompt does not read as humanoid. Default false — non-humanoid prompts return the mesh and skip rigging.')
+ .optional(),
+ skip_rig: z
+ .boolean()
+ .describe('Generate the textured mesh only and never rig (equivalent to mesh_forge but on this tool). Default false.')
+ .optional(),
+};
+
+const inputJsonSchema = jsonSchemaFromZod(inputZodShape);
+const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);
+
+export async function buildForgeAvatarTool() {
+ const handler = await paid(
+ {
+ toolName: TOOL_NAME,
+ description: TOOL_DESCRIPTION,
+ scheme: 'exact',
+ priceUsd: '$0.40',
+ inputSchema: inputJsonSchema,
+ example: { prompt: 'a friendly cartoon astronaut, glossy white suit, rounded helmet' },
+ outputExample: {
+ ok: true,
+ prompt: 'a friendly cartoon astronaut, glossy white suit, rounded helmet',
+ meshGlbUrl: 'https://three.ws/cdn/creations/abc123/mesh.glb',
+ meshViewerUrl: 'https://three.ws/viewer?src=https%3A%2F%2Fthree.ws%2F...',
+ rigged: true,
+ riggedGlbUrl: 'https://three.ws/cdn/creations/def456/rigged.glb',
+ poseStudioUrl: 'https://three.ws/pose?src=https%3A%2F%2Fthree.ws%2F...',
+ humanoid: { humanoid: true, confidence: 0.8, reason: 'humanoid signals (1 figure, 0 body) outweigh 0 non-humanoid' },
+ generateJobId: 'k7m2q9x4',
+ rigJobId: 'r9k2m7x4',
+ creationId: 'def456',
+ timings: { generateMs: 96000, rigMs: 48000, totalMs: 144000 },
+ },
+ },
+ async ({ prompt, aspect_ratio, force_rig, skip_rig }) => {
+ const trimmedPrompt = typeof prompt === 'string' ? prompt.trim() : '';
+ if (trimmedPrompt.length < 3) {
+ return toolError('invalid_input', 'Provide a prompt of at least 3 characters describing the avatar.');
+ }
+ const aspect = VALID_ASPECT.has(aspect_ratio) ? aspect_ratio : '1:1';
+ const timeoutMs = Number(env('FORGE_AVATAR_TIMEOUT_MS', '180000'));
+ const intervalMs = Number(env('FORGE_AVATAR_POLL_MS', '3000'));
+ const startedAt = Date.now();
+
+ // Stage 1 — generate the textured mesh from the prompt (text→3D).
+ let genJob;
+ try {
+ genJob = await postForge('', { prompt: trimmedPrompt, aspect_ratio: aspect });
+ } catch (err) {
+ return toolError(err.code || 'provider_error', err.message, {
+ ...(err.retryAfter != null ? { retryAfter: err.retryAfter } : {}),
+ });
+ }
+ const genStart = Date.now();
+ let gen;
+ try {
+ gen = await pollForge(genJob.job_id, { timeoutMs, intervalMs });
+ } catch (err) {
+ return toolError(err.code === 'stage_failed' ? 'generation_failed' : err.code || 'provider_error', err.message, {
+ generateJobId: genJob.job_id,
+ creationId: genJob.creation_id ?? null,
+ durationMs: Date.now() - startedAt,
+ });
+ }
+ if (gen._timedOut) {
+ return toolError('timeout', `mesh generation did not finish within ${timeoutMs}ms`, {
+ generateJobId: genJob.job_id,
+ creationId: genJob.creation_id ?? null,
+ status: gen.status || 'running',
+ resumeUrl: `${apiBase()}/api/forge?job=${genJob.job_id}`,
+ durationMs: Date.now() - startedAt,
+ });
+ }
+
+ const meshGlbUrl = gen.glb_url;
+ const meshViewerUrl = `${apiBase()}/viewer?src=${encodeURIComponent(meshGlbUrl)}`;
+ const generateMs = Date.now() - genStart;
+
+ // Stage 2 — humanoid gate. Decide whether rigging is worth a paid call.
+ const humanoid = classifyHumanoidPrompt(trimmedPrompt);
+ const shouldRig = !skip_rig && (force_rig === true || humanoid.humanoid);
+
+ const meshResult = {
+ ok: true,
+ prompt: trimmedPrompt,
+ meshGlbUrl,
+ meshViewerUrl,
+ humanoid,
+ backend: gen.backend ?? genJob.backend ?? null,
+ generateJobId: genJob.job_id,
+ creationId: gen.creation_id ?? genJob.creation_id ?? null,
+ durable: Boolean(gen.durable),
+ };
+
+ if (!shouldRig) {
+ return {
+ ...meshResult,
+ rigged: false,
+ rigSkippedReason: skip_rig
+ ? 'skip_rig requested'
+ : `prompt is not humanoid (${humanoid.reason}); pass force_rig:true to rig anyway`,
+ riggedGlbUrl: null,
+ poseStudioUrl: null,
+ rigJobId: null,
+ timings: { generateMs, rigMs: 0, totalMs: Date.now() - startedAt },
+ fetchedAt: new Date().toISOString(),
+ };
+ }
+
+ // Stage 3 — auto-rig the durable mesh. A rig failure must NOT discard the
+ // mesh the caller already paid to generate: on any rig error we return
+ // the mesh with `rigged:false` and the error attached, not a hard fail.
+ const rigStart = Date.now();
+ let rigJob;
+ try {
+ rigJob = await postForge('?action=rig', { glb_url: meshGlbUrl });
+ } catch (err) {
+ return {
+ ...meshResult,
+ rigged: false,
+ rigError: { code: err.code || 'provider_error', message: err.message, ...(err.retryAfter != null ? { retryAfter: err.retryAfter } : {}) },
+ riggedGlbUrl: null,
+ poseStudioUrl: null,
+ rigJobId: null,
+ timings: { generateMs, rigMs: Date.now() - rigStart, totalMs: Date.now() - startedAt },
+ fetchedAt: new Date().toISOString(),
+ };
+ }
+
+ let rig;
+ try {
+ rig = await pollForge(rigJob.job_id, { timeoutMs, intervalMs });
+ } catch (err) {
+ return {
+ ...meshResult,
+ rigged: false,
+ rigError: { code: err.code === 'stage_failed' ? 'rig_failed' : err.code || 'provider_error', message: err.message },
+ rigJobId: rigJob.job_id,
+ riggedGlbUrl: null,
+ poseStudioUrl: null,
+ timings: { generateMs, rigMs: Date.now() - rigStart, totalMs: Date.now() - startedAt },
+ fetchedAt: new Date().toISOString(),
+ };
+ }
+
+ if (rig._timedOut) {
+ return {
+ ...meshResult,
+ rigged: false,
+ rigError: { code: 'timeout', message: `rigging did not finish within ${timeoutMs}ms`, status: rig.status || 'running', resumeUrl: `${apiBase()}/api/forge?job=${rigJob.job_id}` },
+ rigJobId: rigJob.job_id,
+ riggedGlbUrl: null,
+ poseStudioUrl: null,
+ timings: { generateMs, rigMs: Date.now() - rigStart, totalMs: Date.now() - startedAt },
+ fetchedAt: new Date().toISOString(),
+ };
+ }
+
+ const riggedGlbUrl = rig.glb_url;
+ const poseStudioUrl = `${apiBase()}/pose?src=${encodeURIComponent(riggedGlbUrl)}`;
+ const rigMs = Date.now() - rigStart;
+
+ return {
+ ...meshResult,
+ rigged: true,
+ riggedGlbUrl,
+ poseStudioUrl,
+ rigJobId: rigJob.job_id,
+ creationId: rig.creation_id ?? meshResult.creationId,
+ durable: Boolean(rig.durable),
+ timings: { generateMs, rigMs, totalMs: Date.now() - startedAt },
+ fetchedAt: new Date().toISOString(),
+ };
+ },
+ );
+
+ return {
+ name: TOOL_NAME,
+ title: 'Text → rigged avatar ($0.40)',
+ description: TOOL_DESCRIPTION,
+ inputSchema: inputZodShape,
+ // Generates a fresh mesh and (when humanoid) a rigged GLB via external
+ // generation/rig APIs; destroys nothing, mints new assets each call.
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: true,
+ },
+ handler,
+ };
+}
diff --git a/tests/api/solana-rpc-endpoints.test.js b/tests/api/solana-rpc-endpoints.test.js
index cedd85067..b06a20838 100644
--- a/tests/api/solana-rpc-endpoints.test.js
+++ b/tests/api/solana-rpc-endpoints.test.js
@@ -11,7 +11,14 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { solanaRpcEndpoints, shouldRotate } from '../../api/_lib/solana/connection.js';
-const KEYS = ['HELIUS_API_KEY', 'ALCHEMY_API_KEY', 'ANKR_API_KEY', 'SOLANA_RPC_URL'];
+const KEYS = [
+ 'HELIUS_API_KEY',
+ 'ALCHEMY_API_KEY',
+ 'ANKR_API_KEY',
+ 'DRPC_API_KEY',
+ 'SOLANA_RPC_URL',
+ 'SOLANA_RPC_FALLBACK_URLS',
+];
describe('solanaRpcEndpoints', () => {
let saved;
@@ -64,6 +71,26 @@ describe('solanaRpcEndpoints', () => {
expect(eps).toContain('https://api.devnet.solana.com');
expect(eps).not.toContain('https://api.mainnet-beta.solana.com');
});
+
+ it('adds dRPC only in its authenticated form when DRPC_API_KEY is set', () => {
+ process.env.DRPC_API_KEY = 'dk_test_456';
+ const eps = solanaRpcEndpoints('mainnet');
+ expect(eps).toContain('https://lb.drpc.org/ogrpc?network=solana&dkey=dk_test_456');
+ });
+
+ it('includes operator SOLANA_RPC_FALLBACK_URLS before the public endpoints', () => {
+ process.env.SOLANA_RPC_FALLBACK_URLS =
+ 'https://free-a.example/sol , https://free-b.example/sol';
+ const eps = solanaRpcEndpoints('mainnet');
+ expect(eps).toContain('https://free-a.example/sol');
+ expect(eps).toContain('https://free-b.example/sol');
+ // Operator fallbacks rank ahead of the most-throttled public endpoint.
+ expect(eps.indexOf('https://free-a.example/sol')).toBeLessThan(
+ eps.indexOf('https://api.mainnet-beta.solana.com'),
+ );
+ // And the public mainnet-beta endpoint is still last.
+ expect(eps[eps.length - 1]).toBe('https://api.mainnet-beta.solana.com');
+ });
});
// Regression guard for the production club-cover outage: a misconfigured primary
diff --git a/tests/forge-humanoid.test.js b/tests/forge-humanoid.test.js
new file mode 100644
index 000000000..0262b3e2c
--- /dev/null
+++ b/tests/forge-humanoid.test.js
@@ -0,0 +1,134 @@
+/**
+ * Humanoid-prompt classifier — unit tests.
+ *
+ * This is the gate that decides whether a generated mesh gets a *paid* auto-rig
+ * call in the forge_avatar pipeline. A false positive bills a user for a useless
+ * skeleton on a non-character mesh; a false negative ships an un-riggable avatar.
+ * Both are real-money / real-product failures, so the classifier is covered
+ * thoroughly: clear humanoids rig, clear objects/animals don't, ambiguous
+ * prompts default to not-rigging (below threshold), and the function never
+ * throws on junk input.
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import { classifyHumanoidPrompt } from '../mcp-server/src/tools/_humanoid.js';
+
+describe('classifyHumanoidPrompt — humanoid figures rig', () => {
+ const HUMANOID = [
+ 'a friendly cartoon astronaut, glossy white suit',
+ 'a medieval knight in plate armour',
+ 'an anime girl with pink hair',
+ 'a muscular warrior holding a sword', // object word present, figure dominates
+ 'cyberpunk character, neon jacket',
+ 'a robot mascot, rounded white plastic',
+ 'an elf ranger standing in a forest',
+ 'full body male avatar, casual streetwear',
+ 'a zombie shambling forward',
+ 'a wizard with a long beard',
+ ];
+ for (const prompt of HUMANOID) {
+ it(`rigs: "${prompt}"`, () => {
+ const r = classifyHumanoidPrompt(prompt);
+ expect(r.humanoid).toBe(true);
+ expect(r.confidence).toBeGreaterThanOrEqual(0.5);
+ });
+ }
+});
+
+describe('classifyHumanoidPrompt — non-humanoid subjects skip rigging', () => {
+ const NON_HUMANOID = [
+ 'a worn leather armchair, brass studs',
+ 'a sleek sports car, candy red paint',
+ 'a medieval sword with a jewelled hilt',
+ 'a cozy wooden cabin in the snow',
+ 'a red apple on a table',
+ 'a golden coin with an emblem',
+ 'a potted plant with green leaves',
+ 'a glossy ceramic teapot',
+ 'a fighter jet on a runway',
+ 'a treasure chest full of gold',
+ ];
+ for (const prompt of NON_HUMANOID) {
+ it(`skips: "${prompt}"`, () => {
+ const r = classifyHumanoidPrompt(prompt);
+ expect(r.humanoid).toBe(false);
+ expect(r.confidence).toBeLessThan(0.5);
+ });
+ }
+});
+
+describe('classifyHumanoidPrompt — animals are non-humanoid', () => {
+ for (const prompt of [
+ 'a fierce dragon breathing fire',
+ 'a galloping horse',
+ 'a cute cartoon dog',
+ 'a great white shark',
+ ]) {
+ it(`skips animal: "${prompt}"`, () => {
+ expect(classifyHumanoidPrompt(prompt).humanoid).toBe(false);
+ });
+ }
+
+ it('a non-humanoid noun overpowers stray body words', () => {
+ // "arms" is a body cue but "dragon" is a strong non-humanoid subject —
+ // the net must stay non-humanoid so we never rig a dragon.
+ const r = classifyHumanoidPrompt('a dragon with two arms and legs');
+ expect(r.humanoid).toBe(false);
+ });
+});
+
+describe('classifyHumanoidPrompt — whole-word matching', () => {
+ it('does not match "man" inside "manifold"', () => {
+ const r = classifyHumanoidPrompt('a chrome manifold engine part');
+ expect(r.signals.humanoid).toBe(0);
+ expect(r.humanoid).toBe(false);
+ });
+
+ it('does not match "arm" inside "armchair"', () => {
+ const r = classifyHumanoidPrompt('a velvet armchair');
+ // armchair is a non-humanoid term; "arm" must not also register as a body hit
+ expect(r.signals.body).toBe(0);
+ expect(r.humanoid).toBe(false);
+ });
+});
+
+describe('classifyHumanoidPrompt — robustness and contract', () => {
+ it('returns a low-confidence verdict for empty input, never throws', () => {
+ for (const junk of ['', ' ', null, undefined, '!!!', '12345']) {
+ const r = classifyHumanoidPrompt(junk);
+ expect(r.humanoid).toBe(false);
+ expect(r.confidence).toBeGreaterThanOrEqual(0);
+ expect(r.confidence).toBeLessThanOrEqual(1);
+ expect(typeof r.reason).toBe('string');
+ }
+ });
+
+ it('confidence is always within [0,1]', () => {
+ const prompts = [
+ 'a hero warrior knight soldier man',
+ 'armchair car table sword coin building',
+ 'a person',
+ 'random noise words about nothing in particular',
+ ];
+ for (const p of prompts) {
+ const r = classifyHumanoidPrompt(p);
+ expect(r.confidence).toBeGreaterThanOrEqual(0);
+ expect(r.confidence).toBeLessThanOrEqual(1);
+ }
+ });
+
+ it('is deterministic — same prompt, same verdict (billing-stable)', () => {
+ const p = 'a cyborg ninja with glowing eyes';
+ const a = classifyHumanoidPrompt(p);
+ const b = classifyHumanoidPrompt(p);
+ expect(a).toEqual(b);
+ });
+
+ it('exposes signal counts for observability', () => {
+ const r = classifyHumanoidPrompt('a warrior woman with strong arms');
+ expect(r.signals.humanoid).toBeGreaterThan(0);
+ expect(r.signals.body).toBeGreaterThan(0);
+ expect(r.signals.nonHumanoid).toBe(0);
+ });
+});