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(mcp): let AI clients search every three.ws asset and leave with working code
nirholas486163e68c9f
diff --git a/api/_lib/asset-catalog.js b/api/_lib/asset-catalog.jsnew file mode 100644index 000000000..348872634--- /dev/null+++ b/api/_lib/asset-catalog.js@@ -0,0 +1,330 @@+// One searchable read model over every ready-made asset library three.ws+// publishes: the CC0 object/prop library, the ready-made character library, and+// the motion-clip library. Each of those already has a browse page and a REST+// endpoint of its own, but nothing joined them, so an agent could not ask "what+// does three.ws already have that I can drop in?" without knowing which of three+// manifests to read and how each one names its fields.+//+// The manifests live on R2 and are read here directly (same keys the+// /api/objects/library, /api/avatars/library and /api/animations/library+// handlers use) rather than over HTTP against our own origin: a self-call would+// add a round trip, a TLS handshake, and a second failure mode for data we can+// read from storage in one hop.+//+// Every item is normalized to ONE shape so a caller filters, ranks, and renders+// all three kinds with the same code:+//+// { id, kind, name, title, categories[], tags[], license, url, thumb, bytes, ... }+//+// `id` is `<kind>:<name>` and is the stable handle every consumer quotes back.++import { getObjectBuffer } from './r2.js';++// Each source: the R2 manifest key, the array field inside it, and the kind the+// rows become. The generated animation catalog is a separate object that may not+// exist yet, exactly as api/animations/library.js treats it.+const SOURCES = [+ { kind: 'object', key: 'objects/library/manifest.json', field: 'objects' },+ { kind: 'character', key: 'avatars/library/manifest.json', field: 'avatars' },+ { kind: 'animation', key: 'animations/library/manifest.json', field: 'clips' },+ { kind: 'animation', key: 'animations/library/generated/manifest.json', field: 'clips' },+];++export const KINDS = ['object', 'character', 'animation'];++// Manifests change only when a publish job runs, so a short process-local TTL+// removes almost every storage read while keeping a fresh publish visible within+// minutes. Concurrent misses share one load (INFLIGHT) instead of each firing+// four R2 GETs.+const TTL_MS = 5 * 60 * 1000;+let CACHE = null;+let INFLIGHT = null;++function asArray(parsed, field) {+ if (Array.isArray(parsed)) return parsed;+ if (parsed && Array.isArray(parsed[field])) return parsed[field];+ return [];+}++async function readManifest({ key, field }) {+ try {+ const buf = await getObjectBuffer(key);+ const parsed = JSON.parse(buf.toString('utf8'));+ return { rows: asArray(parsed, field), generatedAt: parsed?.generated_at || null };+ } catch (err) {+ // A manifest that was never published is the expected steady state for the+ // generated catalog, so it degrades to empty. Anything else is logged and+ // also degrades: a catalog missing one kind is far more useful to the+ // caller than a hard failure that hides the other two.+ const code = err?.$metadata?.httpStatusCode;+ if (err?.name !== 'NoSuchKey' && code !== 404) {+ console.error('[asset-catalog]', key, err?.message || err);+ }+ return { rows: [], generatedAt: null };+ }+}++function cleanList(value) {+ if (!Array.isArray(value)) return [];+ const out = [];+ for (const entry of value) {+ const s = String(entry ?? '').trim();+ if (s && !out.includes(s)) out.push(s);+ }+ return out;+}++// The object manifest folds provenance into `categories` as "collection: x".+// That is browse metadata, not a category a caller would ever filter on, so it+// is lifted out to `collection` and dropped from the facet list.+function splitCategories(raw) {+ const categories = [];+ let collection = null;+ for (const entry of cleanList(raw)) {+ const m = /^collection:\s*(.+)$/i.exec(entry);+ if (m) {+ if (!collection) collection = m[1].trim();+ continue;+ }+ categories.push(entry);+ }+ return { categories, collection };+}++function normalize(row, kind) {+ const name = String(row?.name ?? '').trim();+ if (!name) return null;+ const title = String(row?.label || row?.name || '').trim() || name;+ const { categories, collection } = splitCategories(row?.categories);+ const base = {+ id: `${kind}:${name}`,+ kind,+ name,+ title,+ categories,+ tags: cleanList(row?.tags),+ license: String(row?.license || '').trim() || null,+ url: typeof row?.url === 'string' ? row.url : null,+ thumb: typeof row?.thumb === 'string' ? row.thumb : null,+ bytes: Number.isFinite(row?.bytes) ? row.bytes : null,+ };+ if (collection) base.collection = collection;++ if (kind === 'animation') {+ base.format = 'three-animation-clip-json';+ base.duration_seconds = Number.isFinite(row?.duration) ? row.duration : null;+ base.loop = row?.loop !== false;+ if (row?.icon) base.icon = row.icon;+ } else {+ base.format = 'glb';+ if (kind === 'character') {+ base.rigged = true;+ base.skins = Number.isFinite(row?.skins) ? row.skins : null;+ base.baked_animations = Number.isFinite(row?.animations) ? row.animations : null;+ base.source = row?.source || null;+ }+ }+ return base;+}++/**+ * Load and normalize every library, deduped by id (a curated clip wins over a+ * generated one of the same name, matching /api/animations/library) and sorted+ * by kind then title so paging is stable across calls.+ *+ * @returns {Promise<{ items: object[], generated_at: object, counts: object }>}+ */+async function loadCatalog() {+ const results = await Promise.all(SOURCES.map((s) => readManifest(s)));+ const byId = new Map();+ const generatedAt = {};+ for (let i = 0; i < SOURCES.length; i++) {+ const { kind } = SOURCES[i];+ const { rows, generatedAt: at } = results[i];+ if (at && !generatedAt[kind]) generatedAt[kind] = at;+ for (const row of rows) {+ const item = normalize(row, kind);+ if (item && !byId.has(item.id)) byId.set(item.id, item);+ }+ }+ const items = [...byId.values()].sort(+ (a, b) => a.kind.localeCompare(b.kind) || a.title.localeCompare(b.title),+ );+ const counts = {};+ for (const kind of KINDS) counts[kind] = items.filter((i) => i.kind === kind).length;+ return { items, generated_at: generatedAt, counts, total: items.length };+}++/** The cached catalog, refreshed at most once per TTL. Concurrent misses share one load. */+export async function getCatalog({ force = false } = {}) {+ const fresh = CACHE && !force && Date.now() - CACHE.at < TTL_MS;+ if (fresh) return CACHE.value;+ if (INFLIGHT) return INFLIGHT;+ INFLIGHT = loadCatalog()+ .then((value) => {+ CACHE = { at: Date.now(), value };+ return value;+ })+ .finally(() => {+ INFLIGHT = null;+ });+ return INFLIGHT;+}++/** Drop the memo. Used by tests to re-read a changed manifest without waiting out the TTL. */+export function resetCatalogCache() {+ CACHE = null;+ INFLIGHT = null;+}++function tokenize(query) {+ return String(query || '')+ .toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter((t) => t.length > 1);+}++// Weighted term match. A title hit ranks above a tag hit, which ranks above a+// category hit, and a whole-word match ranks above a substring one, so "wrench"+// puts "Adjustable Wrench" above a chair tagged "wrenched metal". Every term+// must land somewhere or the item is not a result at all (AND across terms),+// which keeps a two-word query from returning everything that matches either.+function scoreItem(item, terms, { requireAll = true } = {}) {+ if (!terms.length) return 1;+ const title = item.title.toLowerCase();+ const name = item.name.toLowerCase();+ const tags = item.tags.map((t) => t.toLowerCase());+ const cats = item.categories.map((c) => c.toLowerCase());+ let total = 0;+ let matched = 0;+ for (const term of terms) {+ let best = 0;+ if (title === term) best = 10;+ else if (title.split(/\s+/).includes(term)) best = 8;+ else if (title.includes(term)) best = 6;+ if (best < 5 && (name === term || name.split(/[-_]/).includes(term))) best = 5;+ if (best < 4 && tags.includes(term)) best = 4;+ if (best < 3 && tags.some((t) => t.includes(term))) best = 3;+ if (best < 2 && cats.some((c) => c.includes(term))) best = 2;+ if (best < 1 && name.includes(term)) best = 1;+ if (!best && requireAll) return 0;+ if (best) matched++;+ total += best;+ }+ // Under OR, an item matching more of the terms still outranks one matching+ // fewer, so "office lamp" puts a lamp tagged office above a bare lamp.+ return requireAll ? total : matched ? total + matched * 4 : 0;+}++/**+ * Search the joined catalog.+ *+ * @param {object} opts+ * @param {string} [opts.q] Free text over title, name, tags, categories.+ * @param {string} [opts.kind] One of KINDS.+ * @param {string} [opts.category] Exact (case-insensitive) category match.+ * @param {string} [opts.tag] Exact (case-insensitive) tag match.+ * @param {number} [opts.limit] Page size (default 12).+ * @param {number} [opts.offset] Page offset (default 0).+ * @returns {Promise<{ items, total, matched, relaxed, offset, next_offset, facets, generated_at }>}+ */+export async function searchCatalog({ q, kind, category, tag, limit = 12, offset = 0 } = {}) {+ const catalog = await getCatalog();+ const terms = tokenize(q);+ const wantKind = kind ? String(kind).toLowerCase() : null;+ const wantCategory = category ? String(category).toLowerCase() : null;+ const wantTag = tag ? String(tag).toLowerCase() : null;++ const candidates = catalog.items.filter((item) => {+ if (wantKind && item.kind !== wantKind) return false;+ if (wantCategory && !item.categories.some((c) => c.toLowerCase() === wantCategory)) return false;+ if (wantTag && !item.tags.some((t) => t.toLowerCase() === wantTag)) return false;+ return true;+ });++ const rank = (requireAll) => {+ const out = [];+ for (const item of candidates) {+ const score = scoreItem(item, terms, { requireAll });+ if (score) out.push({ item, score });+ }+ // Ties break on title so two calls with the same query return the same+ // order, which is what makes offset paging safe.+ out.sort((a, b) => b.score - a.score || a.item.title.localeCompare(b.item.title));+ return out;+ };++ // Every term must land (AND), because that is what makes a two-word query+ // precise. But a caller who types "office lamp" against a library that tags+ // neither word together deserves the lamps, not an empty page, so a query+ // that finds nothing under AND is retried under OR and the response says so.+ let scored = rank(true);+ let relaxed = false;+ if (!scored.length && terms.length > 1) {+ scored = rank(false);+ relaxed = scored.length > 0;+ }++ const start = Math.max(0, offset);+ const page = scored.slice(start, start + Math.max(1, limit)).map((s) => s.item);+ return {+ items: page,+ matched: scored.length,+ relaxed,+ total: catalog.total,+ offset: start,+ next_offset: start + page.length < scored.length ? start + page.length : null,+ facets: facetsFor(scored.map((s) => s.item)),+ generated_at: catalog.generated_at,+ };+}++/** Kind counts plus the most common categories and tags across a result set. */+function facetsFor(items) {+ const kinds = {};+ const categories = new Map();+ const tags = new Map();+ for (const item of items) {+ kinds[item.kind] = (kinds[item.kind] || 0) + 1;+ for (const c of item.categories) categories.set(c, (categories.get(c) || 0) + 1);+ for (const t of item.tags) tags.set(t, (tags.get(t) || 0) + 1);+ }+ const top = (map, n) =>+ [...map.entries()]+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))+ .slice(0, n)+ .map(([value, count]) => ({ value, count }));+ return { kinds, categories: top(categories, 12), tags: top(tags, 12) };+}++/** One item by `<kind>:<name>` id, or null. A bare name is accepted and resolved across kinds. */+export async function getCatalogItem(id) {+ const catalog = await getCatalog();+ const raw = String(id || '').trim();+ if (!raw) return null;+ const exact = catalog.items.find((i) => i.id === raw);+ if (exact) return exact;+ return catalog.items.find((i) => i.name === raw) || null;+}++/**+ * Up to `limit` other items of the same kind that share the most tags and+ * categories with `item`. Used to answer "what else goes with this?" without a+ * second search round trip.+ */+export async function relatedItems(item, limit = 6) {+ if (!item) return [];+ const catalog = await getCatalog();+ const tags = new Set(item.tags.map((t) => t.toLowerCase()));+ const cats = new Set(item.categories.map((c) => c.toLowerCase()));+ const scored = [];+ for (const other of catalog.items) {+ if (other.id === item.id || other.kind !== item.kind) continue;+ let score = 0;+ for (const t of other.tags) if (tags.has(t.toLowerCase())) score += 2;+ for (const c of other.categories) if (cats.has(c.toLowerCase())) score += 1;+ if (score) scored.push({ other, score });+ }+ scored.sort((a, b) => b.score - a.score || a.other.title.localeCompare(b.other.title));+ return scored.slice(0, limit).map((s) => s.other);+}diff --git a/api/_lib/asset-snippets.js b/api/_lib/asset-snippets.jsnew file mode 100644index 000000000..045a08d08--- /dev/null+++ b/api/_lib/asset-snippets.js@@ -0,0 +1,328 @@+// Paste-ready source for one three.ws library asset.+//+// A catalog is only half an answer: an agent that finds the right prop still has+// to know which tag renders it, which script to load, and how to pin it. This+// module turns a normalized catalog item (api/_lib/asset-catalog.js) into code+// that runs as-is on any site, in the same shapes three.ws itself ships:+//+// agent-3d the <agent-3d> web component (what our own embeds use)+// model-viewer the <model-viewer> tag the /objects and /character-library+// grids render each card with+// three plain three.js with GLTFLoader, for an existing scene+// react the web component wrapped as a React component+//+// The <agent-3d> snippet is pinned to the exact version this deployment serves+// and carries its Subresource Integrity hash, both read from the release+// manifest `npm run publish:lib` writes into dist/. A snippet that says "latest"+// is a snippet that can break under the reader with no action on their side, so+// we never emit one.++import { readFileSync } from 'node:fs';++const VERSIONS_PATH = new URL('../../dist/agent-3d/versions.json', import.meta.url);++// Read once per process: the manifest changes only when a new image is built,+// and every miss would otherwise cost a synchronous disk read per tool call.+let RELEASE = undefined;++/**+ * The published <agent-3d> release: { version, integrity } when the manifest is+ * readable, else null. Null degrades the snippet to the major-version channel+ * (still stable, just not byte-pinned) rather than emitting a wrong hash.+ */+export function agentElementRelease() {+ if (RELEASE !== undefined) return RELEASE;+ try {+ const manifest = JSON.parse(readFileSync(VERSIONS_PATH, 'utf8'));+ const version = String(manifest?.latest || '').trim();+ const integrity = manifest?.channels?.[version]?.integrity?.['agent-3d.js'] || null;+ RELEASE = version ? { version, integrity } : null;+ } catch {+ RELEASE = null;+ }+ return RELEASE;+}++/** Drop the memo so a test can exercise both the pinned and the fallback path. */+export function resetReleaseCache() {+ RELEASE = undefined;+}++// The <model-viewer> build and hash the /objects and /character-library pages+// load. Kept identical to pages/objects.html on purpose: a reader who copies+// this snippet gets exactly the renderer they saw on the site.+const MODEL_VIEWER_SRC =+ 'https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js';+const MODEL_VIEWER_SRI =+ 'sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw';++export const MODEL_FRAMEWORKS = ['agent-3d', 'model-viewer', 'three', 'react'];+export const CLIP_FRAMEWORKS = ['three', 'react', 'agent-3d'];++/** Which frameworks apply to an item, most appropriate first. */+export function frameworksFor(item) {+ if (item?.kind === 'animation') return CLIP_FRAMEWORKS;+ // A prop is not an embodied agent: the object grid renders it with+ // <model-viewer>, so that is what we recommend first for objects, and the+ // avatar component comes first for a rigged character.+ return item?.kind === 'object'+ ? ['model-viewer', 'three', 'agent-3d', 'react']+ : MODEL_FRAMEWORKS;+}++function attrEscape(value) {+ return String(value ?? '').replace(/[&<>"]/g, (c) => ({+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ })[c]);+}++function jsString(value) {+ return JSON.stringify(String(value ?? ''));+}++function agentScriptTag() {+ const release = agentElementRelease();+ if (release?.version && release.integrity) {+ return {+ tag:+ `<script\n type="module"\n src="https://three.ws/agent-3d/${release.version}/agent-3d.js"\n` ++ ` integrity="${release.integrity}"\n crossorigin="anonymous"\n></script>`,+ note: `Pinned to agent-3d ${release.version} with its published SRI hash. Release data: https://three.ws/agent-3d/versions.json`,+ };+ }+ return {+ tag:+ '<script type="module" src="https://three.ws/agent-3d/1/agent-3d.js" crossorigin="anonymous"></script>',+ note:+ 'Pinned to the agent-3d 1.x channel. For production, read https://three.ws/agent-3d/versions.json and pin the exact version plus its integrity hash.',+ };+}++function modelSnippets(item, origin) {+ const url = item.url;+ const alt = item.title;+ const script = agentScriptTag();+ const react = `import { useEffect } from "react";++const AGENT_3D_SRC = ${jsString(+ agentElementRelease()?.version+ ? `https://three.ws/agent-3d/${agentElementRelease().version}/agent-3d.js`+ : 'https://three.ws/agent-3d/1/agent-3d.js',+ )};++/** Renders the three.ws ${alt} model. The custom element is defined once per page. */+export function ${componentName(item)}() {+ useEffect(() => {+ if (document.querySelector('script[data-agent-3d]')) return;+ const s = document.createElement("script");+ s.type = "module";+ s.src = AGENT_3D_SRC;+ s.crossOrigin = "anonymous";+ s.dataset.agent3d = "1";+ document.head.appendChild(s);+ }, []);++ return (+ <agent-3d+ body=${jsString(url)}+ mode="section"+ style={{ width: "100%", height: 420, display: "block" }}+ />+ );+}`;++ return {+ 'agent-3d': {+ language: 'html',+ code: `${script.tag}\n\n<agent-3d\n body="${attrEscape(url)}"\n mode="section"\n style="width:100%;height:420px;display:block"\n></agent-3d>`,+ notes: [+ script.note,+ 'The bundle is served with access-control-allow-origin: *, so it loads from any domain.',+ ],+ },+ 'model-viewer': {+ language: 'html',+ code: `<script\n type="module"\n src="${MODEL_VIEWER_SRC}"\n integrity="${MODEL_VIEWER_SRI}"\n crossorigin="anonymous"\n></script>\n\n<model-viewer\n src="${attrEscape(url)}"\n alt="${attrEscape(alt)}"\n camera-controls\n auto-rotate\n ar\n shadow-intensity="1"\n style="width:100%;height:420px"\n></model-viewer>`,+ notes: [+ 'This is the exact renderer and build the three.ws browse grids use.',+ 'Drop the `ar` attribute if you do not want the mobile AR button.',+ ],+ },+ three: {+ language: 'javascript',+ code: `import * as THREE from "three";+import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";++const loader = new GLTFLoader();+const gltf = await loader.loadAsync(${jsString(url)});+scene.add(gltf.scene);${+ item.kind === 'character'+ ? `++// The character ships rigged. Drive it with any clip from the three.ws motion+// library (see the "animation" kind in search_catalog).+const mixer = new THREE.AnimationMixer(gltf.scene);+if (gltf.animations.length) mixer.clipAction(gltf.animations[0]).play();+// Call mixer.update(delta) from your render loop.`+ : ''+ }`,+ notes: [+ `The GLB is served cross-origin from the three.ws CDN; no proxy or re-hosting is needed.${+ item.bytes ? ` It is ${formatBytes(item.bytes)}.` : ''+ }`,+ ],+ },+ react: { language: 'jsx', code: react, notes: [script.note] },+ _links: modelLinks(item, origin),+ };+}++function clipSnippets(item, origin) {+ const url = item.url;+ return {+ three: {+ language: 'javascript',+ code: `import * as THREE from "three";++// three.ws motion clips are plain THREE.AnimationClip JSON.+const json = await fetch(${jsString(url)}).then((r) => r.json());+const clip = THREE.AnimationClip.parse(json);++// Track names use the canonical (Mixamo) bone names. Any avatar whose rig maps+// to that skeleton plays it directly; retarget first if yours does not.+const mixer = new THREE.AnimationMixer(avatar);+const action = mixer.clipAction(clip);+action.setLoop(${item.loop ? 'THREE.LoopRepeat, Infinity' : 'THREE.LoopOnce, 1'});+action.play();+// Call mixer.update(delta) from your render loop.`,+ notes: [+ item.duration_seconds+ ? `The clip runs ${item.duration_seconds.toFixed(2)}s and ${item.loop ? 'loops' : 'plays once'}.`+ : `The clip ${item.loop ? 'loops' : 'plays once'}.`,+ 'To bake this clip onto your own rig server-side instead, call the apply_animation MCP tool with your GLB url and this clip name.',+ ],+ },+ react: {+ language: 'jsx',+ code: `import { useEffect } from "react";+import * as THREE from "three";++const CLIP_URL = ${jsString(url)};++/** Plays the three.ws "${item.title}" clip on an existing avatar object. */+export function use${componentName(item)}(avatar) {+ useEffect(() => {+ if (!avatar) return;+ let mixer;+ let raf;+ let cancelled = false;+ const clock = new THREE.Clock();++ fetch(CLIP_URL)+ .then((r) => r.json())+ .then((json) => {+ if (cancelled) return;+ mixer = new THREE.AnimationMixer(avatar);+ const action = mixer.clipAction(THREE.AnimationClip.parse(json));+ action.setLoop(${item.loop ? 'THREE.LoopRepeat, Infinity' : 'THREE.LoopOnce, 1'});+ action.play();+ const tick = () => {+ mixer.update(clock.getDelta());+ raf = requestAnimationFrame(tick);+ };+ tick();+ });++ return () => {+ cancelled = true;+ if (raf) cancelAnimationFrame(raf);+ mixer?.stopAllAction();+ };+ }, [avatar]);+}`,+ notes: ['Pair this with the three snippet for the avatar itself.'],+ },+ 'agent-3d': {+ language: 'html',+ code: `${agentScriptTag().tag}\n\n<agent-3d\n body="https://three.ws/avatars/default.glb"\n clip="idle"\n mode="section"\n style="width:100%;height:420px;display:block"\n></agent-3d>`,+ notes: [+ 'The `clip` attribute resolves names from the built-in gesture manifest (https://three.ws/animations/manifest.json), which is a curated subset and does not include this library clip.',+ `To use "${item.title}" in an embed, bake it onto your avatar first with the apply_animation MCP tool, then point \`body\` at the returned GLB.`,+ ],+ },+ _links: clipLinks(item, origin),+ };+}++function componentName(item) {+ const pascal = String(item.title || item.name)+ .replace(/[^A-Za-z0-9]+/g, ' ')+ .trim()+ .split(/\s+/)+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))+ .join('');+ // A component identifier cannot start with a digit, and a purely numeric+ // title (the motion library has clips named for angles) would produce one.+ return /^[A-Za-z]/.test(pascal) ? pascal : `Asset${pascal}`;+}++function formatBytes(n) {+ const mb = n / 1024 / 1024;+ return mb >= 1 ? `${mb.toFixed(1)} MB` : `${Math.round(n / 1024)} KB`;+}++function modelLinks(item, origin) {+ const model = encodeURIComponent(item.url || '');+ if (!item.url) return { browse: `${origin}/${item.kind === 'object' ? 'objects' : 'character-library'}` };+ if (item.kind === 'object') {+ return {+ browse: `${origin}/objects`,+ preview: `${origin}/app#model=${model}&kind=object&title=${encodeURIComponent(item.title)}`,+ ar: `${origin}/ar/studio?src=${model}&title=${encodeURIComponent(item.title)}`,+ download: item.url,+ };+ }+ return {+ browse: `${origin}/character-library`,+ preview: `${origin}/app#model=${model}`,+ use: `${origin}/studio?model=${model}`,+ animate: `${origin}/pose?src=${model}&title=${encodeURIComponent(item.title)}`,+ download: item.url,+ };+}++function clipLinks(item, origin) {+ return {+ browse: `${origin}/animations`,+ preview: `${origin}/animations?clip=${encodeURIComponent(item.name)}`,+ download: item.url,+ };+}++/**+ * Every snippet for an item, plus the site links that go with it.+ *+ * @param {object} item A normalized catalog item.+ * @param {string} origin Absolute site origin for links.+ * @returns {{ frameworks: string[], snippets: object, links: object }}+ */+export function sourceFor(item, origin) {+ const built = item.kind === 'animation' ? clipSnippets(item, origin) : modelSnippets(item, origin);+ const { _links: links, ...snippets } = built;+ return { frameworks: frameworksFor(item), snippets, links };+}++/**+ * One framework's snippet, or null when the framework does not apply to the+ * item (asking for `model-viewer` on a motion clip, say).+ */+export function snippetFor(item, framework, origin) {+ const { snippets, links, frameworks } = sourceFor(item, origin);+ const chosen = framework || frameworks[0];+ const snippet = snippets[chosen];+ if (!snippet) return null;+ return { framework: chosen, ...snippet, links, available_frameworks: frameworks };+}diff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.jsindex c569cc896..b78843365 100644--- a/api/_mcp/catalog.js+++ b/api/_mcp/catalog.js@@ -20,8 +20,10 @@ import { toolDefs as garmentDefs } from './tools/garments.js';import { toolDefs as signDefs } from './tools/sign.js';import { toolDefs as feedbackDefs } from './tools/feedback.js';import { toolDefs as homeDefs } from './tools/home.js';+import { toolDefs as libraryDefs } from './tools/library.js';const baseDefs = [+ ...libraryDefs,...avatarDefs,...embedDefs,...modelDefs,@@ -50,7 +52,7 @@ const gettingStarted = {...buildGettingStartedTool({server: 'three.ws',tagline:- 'The main three.ws MCP server: render and manage 3D avatars and models, animations, American Sign Language, an agent registry, agent memory, live pump.fun market data, Oracle conviction signals, the trader leaderboard + copy-trading system, and safe control of a connected Home Assistant house.',+ 'The main three.ws MCP server: render and manage 3D avatars and models, animations, American Sign Language, a free searchable catalog of ready-made CC0 props, rigged characters and motion clips with paste-ready embed source, an agent registry, agent memory, live pump.fun market data, Oracle conviction signals, the trader leaderboard + copy-trading system, and safe control of a connected Home Assistant house.',tools: baseDefs,priceFor,access: [diff --git a/api/_mcp/dispatch.js b/api/_mcp/dispatch.jsindex f41097228..7feb076db 100644--- a/api/_mcp/dispatch.js+++ b/api/_mcp/dispatch.js@@ -8,9 +8,29 @@ import {} from '../_lib/pump-pricing.js';import { declareMcpDiscovery } from '../_lib/x402/bazaar-helpers.js';import { sanitizeToolError } from '../_lib/mcp-error-sanitize.js';+import { GETTING_STARTED_TOOL } from '../_lib/mcp-getting-started.js';import { TOOL_CATALOG, TOOLS } from './catalog.js';-export { isPublicTool } from '../_lib/mcp-getting-started.js';+// Tools any caller may invoke with no OAuth token and no x402 payment.+//+// Membership is an explicit allowlist, never "is unpriced": a scoped tool that+// happens to cost nothing (recall, list_my_avatars) still reads account data and+// must stay behind auth. Everything here is a read of an already-public,+// already-published artifact with no caller state in it, which is precisely why+// it is safe to hand to an anonymous client. Per-IP rate limits still apply.+const PUBLIC_TOOLS = new Set([+ GETTING_STARTED_TOOL,+ // The asset catalog: published CC0 / free-to-use library manifests plus the+ // code that renders them. Discovery has to work before a client signs in, or+ // nobody discovers anything.+ 'search_catalog',+ 'get_catalog_item',+ 'get_item_source',+]);++export function isPublicTool(name) {+ return PUBLIC_TOOLS.has(name);+}export const PROTOCOL_VERSION = '2025-06-18';const SERVER_INFO = { name: '3d-agent-mcp', version: '1.0.0' };diff --git a/api/_mcp/tools/library.js b/api/_mcp/tools/library.jsnew file mode 100644index 000000000..767815fad--- /dev/null+++ b/api/_mcp/tools/library.js@@ -0,0 +1,255 @@+// MCP tools for the three.ws asset catalog: the ready-made props, characters,+// and motion clips the platform already publishes.+//+// search_catalog (free): one search across all three libraries.+// get_catalog_item (free): one item in full, with its links and related items.+// get_item_source (free): paste-ready code that renders the item on any site.+//+// All three are free, unauthenticated public reads: they serve published CC0 and+// free-to-use manifests, touch no account data, and hold no user state. That is+// deliberate. An agent should be able to discover what three.ws already has and+// leave with working code before it ever signs in or pays for anything.+//+// The join and ranking live in api/_lib/asset-catalog.js; the code generation+// lives in api/_lib/asset-snippets.js. This file is the MCP surface over both.++import { KINDS, searchCatalog, getCatalogItem, relatedItems } from '../../_lib/asset-catalog.js';+import { sourceFor, snippetFor, frameworksFor } from '../../_lib/asset-snippets.js';+import { resolveOrigin } from '../origin.js';++const READ_ANNOTATIONS = {+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: true,+ openWorldHint: false,+};++function rpcError(code, message, data) {+ const e = new Error(message);+ e.code = code;+ e.data = data;+ return e;+}++function kindLabel(kind) {+ if (kind === 'object') return 'prop';+ if (kind === 'character') return 'rigged character';+ return 'motion clip';+}++function itemLine(item) {+ const bits = [`\`${item.id}\``, item.title];+ if (item.license) bits.push(item.license);+ if (item.kind === 'animation' && item.duration_seconds) {+ bits.push(`${item.duration_seconds.toFixed(1)}s${item.loop ? ' loop' : ''}`);+ }+ const tags = item.tags.slice(0, 4).join(', ');+ return `- ${bits.join(' | ')}${tags ? ` | ${tags}` : ''}`;+}++function renderResults(result, query) {+ if (!result.items.length) {+ return [+ `No catalog items match ${query ? `"${query}"` : 'that filter'}.`,+ `The catalog holds ${result.total} items. Try a broader term, or drop the kind/category filter.`,+ ].join('\n');+ }+ const lines = [+ result.relaxed+ ? `Nothing matches every word of "${query}". Showing the ${result.matched} items that match part of it, best first (${result.items.length} from offset ${result.offset}):`+ : `${result.matched} match${result.matched === 1 ? '' : 'es'}${query ? ` for "${query}"` : ''} (showing ${result.items.length} from offset ${result.offset}):`,+ '',+ ...result.items.map(itemLine),+ ];+ const kinds = Object.entries(result.facets.kinds)+ .map(([k, n]) => `${k} ${n}`)+ .join(', ');+ if (kinds) lines.push('', `Kinds: ${kinds}`);+ const cats = result.facets.categories.slice(0, 8).map((c) => `${c.value} (${c.count})`).join(', ');+ if (cats) lines.push(`Categories: ${cats}`);+ if (result.next_offset != null) lines.push(`More: call again with offset ${result.next_offset}.`);+ lines.push('', 'Next: get_item_source with an id above returns code you can paste.');+ return lines.join('\n');+}++function renderItem(item, related, links) {+ const lines = [+ `# ${item.title}`,+ '',+ `\`${item.id}\`: a ${kindLabel(item.kind)}${item.license ? `, ${item.license}` : ''}.`,+ ];+ if (item.categories.length) lines.push(`Categories: ${item.categories.join(', ')}`);+ if (item.tags.length) lines.push(`Tags: ${item.tags.join(', ')}`);+ if (item.kind === 'animation') {+ lines.push(+ `Clip: ${item.duration_seconds ? `${item.duration_seconds.toFixed(2)}s` : 'unknown length'}, ${item.loop ? 'loops' : 'one-shot'}, THREE.AnimationClip JSON.`,+ );+ } else {+ lines.push(+ `Asset: GLB${item.bytes ? `, ${(item.bytes / 1024 / 1024).toFixed(1)} MB` : ''}${item.rigged ? ', rigged and animation-ready' : ''}.`,+ );+ }+ lines.push('', 'Links:', ...Object.entries(links).map(([k, v]) => `- ${k}: ${v}`));+ if (related.length) {+ lines.push('', 'Related:', ...related.map((r) => `- \`${r.id}\` ${r.title}`));+ }+ lines.push('', `Frameworks for get_item_source: ${frameworksFor(item).join(', ')}.`);+ return lines.join('\n');+}++export const toolDefs = [+ {+ name: 'search_catalog',+ title: 'Search the three.ws asset catalog',+ annotations: READ_ANNOTATIONS,+ description:+ 'FREE, no account or payment. Search every ready-made asset three.ws publishes in one call: CC0 3D props and objects, rigged humanoid characters, and retargetable motion clips. ' ++ 'Returns ids, titles, tags, licenses, and CDN urls, plus category facets to narrow the next query. ' ++ 'Use this before generating anything: if the catalog already has the prop or character, dropping it in is instant and free where generating one is not. ' ++ 'Feed a returned id to get_item_source for code that renders it on any site.',+ inputSchema: {+ type: 'object',+ additionalProperties: false,+ properties: {+ q: {+ type: 'string',+ maxLength: 200,+ description:+ 'Free text over titles, names, tags, and categories, e.g. "wooden chair", "office", "wave". Every word must match somewhere, so start broad.',+ },+ kind: {+ type: 'string',+ enum: KINDS,+ description:+ 'Narrow to one library: object (CC0 props), character (rigged humanoids), animation (motion clips).',+ },+ category: { type: 'string', maxLength: 80, description: 'Exact category from a previous result\'s facets.' },+ tag: { type: 'string', maxLength: 80, description: 'Exact tag from a previous result\'s facets.' },+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 12 },+ offset: { type: 'integer', minimum: 0, default: 0, description: 'Page offset. Use next_offset from the previous response.' },+ },+ },+ async handler(args = {}) {+ const result = await searchCatalog({+ q: args.q,+ kind: args.kind,+ category: args.category,+ tag: args.tag,+ limit: args.limit || 12,+ offset: args.offset || 0,+ });+ return {+ content: [{ type: 'text', text: renderResults(result, args.q) }],+ structuredContent: { ok: true, ...result },+ };+ },+ },+ {+ name: 'get_catalog_item',+ title: 'Read one catalog item',+ annotations: READ_ANNOTATIONS,+ description:+ 'FREE, no account or payment. Read one three.ws catalog item in full by its id from search_catalog (for example "object:adjustable_wrench"): metadata, license, CDN urls, the site links that preview or edit it, related items of the same kind, and which source frameworks get_item_source can emit for it.',+ inputSchema: {+ type: 'object',+ additionalProperties: false,+ required: ['id'],+ properties: {+ id: {+ type: 'string',+ maxLength: 200,+ description: 'Catalog id as `<kind>:<name>` from search_catalog. A bare name is also accepted.',+ },+ },+ },+ async handler(args = {}, _auth, req) {+ const item = await getCatalogItem(args.id);+ if (!item) {+ throw rpcError(-32602, `no catalog item with id "${args.id}"`, {+ hint: 'Call search_catalog first; ids look like "object:adjustable_wrench".',+ });+ }+ const origin = resolveOrigin(req);+ const { links } = sourceFor(item, origin);+ const related = await relatedItems(item, 6);+ return {+ content: [{ type: 'text', text: renderItem(item, related, links) }],+ structuredContent: {+ ok: true,+ item,+ links,+ related,+ frameworks: frameworksFor(item),+ },+ };+ },+ },+ {+ name: 'get_item_source',+ title: 'Get paste-ready source for a catalog item',+ annotations: READ_ANNOTATIONS,+ description:+ 'FREE, no account or payment. Returns working code that renders one three.ws catalog item on any site: the <agent-3d> web component (pinned to the exact published version with its SRI hash), the <model-viewer> tag our own browse grids use, plain three.js with GLTFLoader, or a React component. ' ++ 'Motion clips return three.js code that parses the clip JSON and plays it. Omit `framework` to get the one that fits the item best; pass `all` to get every variant at once.',+ inputSchema: {+ type: 'object',+ additionalProperties: false,+ required: ['id'],+ properties: {+ id: { type: 'string', maxLength: 200, description: 'Catalog id from search_catalog.' },+ framework: {+ type: 'string',+ enum: ['agent-3d', 'model-viewer', 'three', 'react', 'all'],+ description:+ 'Which form to emit. Defaults to the recommended one for the item kind. "all" returns every applicable variant.',+ },+ },+ },+ async handler(args = {}, _auth, req) {+ const item = await getCatalogItem(args.id);+ if (!item) {+ throw rpcError(-32602, `no catalog item with id "${args.id}"`, {+ hint: 'Call search_catalog first; ids look like "object:adjustable_wrench".',+ });+ }+ const origin = resolveOrigin(req);++ if (args.framework === 'all') {+ const { snippets, links, frameworks } = sourceFor(item, origin);+ const text = frameworks+ .map((f) => `## ${f}\n\n\`\`\`${snippets[f].language}\n${snippets[f].code}\n\`\`\``)+ .join('\n\n');+ return {+ content: [{ type: 'text', text: `# ${item.title}\n\n${text}` }],+ structuredContent: { ok: true, item, frameworks, snippets, links },+ };+ }++ const snippet = snippetFor(item, args.framework, origin);+ if (!snippet) {+ throw rpcError(+ -32602,+ `framework "${args.framework}" does not apply to a ${kindLabel(item.kind)}`,+ { available_frameworks: frameworksFor(item) },+ );+ }+ const text = [+ `# ${item.title} (${snippet.framework})`,+ '',+ `\`\`\`${snippet.language}`,+ snippet.code,+ '```',+ '',+ ...snippet.notes.map((n) => `- ${n}`),+ '',+ `Preview: ${snippet.links.preview || snippet.links.browse}`,+ item.license ? `License: ${item.license}` : 'License: free to use on three.ws.',+ `Other frameworks: ${snippet.available_frameworks.filter((f) => f !== snippet.framework).join(', ')}.`,+ ].join('\n');+ return {+ content: [{ type: 'text', text }],+ structuredContent: { ok: true, item, ...snippet },+ };+ },+ },+];diff --git a/data/changelog.json b/data/changelog.jsonindex 137bf4539..b139f43e1 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-09-05",+ "title": "AI coding assistants can now search the three.ws asset library and get working code back",+ "summary": "Every ready-made asset the platform publishes is now one search away from any AI coding client connected to the three.ws MCP server: 511 CC0 props, 107 rigged characters and 2,874 motion clips, all in a single searchable catalog instead of three separate browse pages. Ask for a wooden chair or an industrial lamp and you get matching items ranked best first, with tags, license, and the CDN link. Ask for the source and you get code that runs as it is: the model-viewer tag our own gallery renders with, the agent-3d web component pinned to the exact published version and its integrity hash, plain three.js, or a React component. Motion clips come back as three.js code that loads and plays them. All three tools are free and need no account, no API key and no payment, because you should be able to find out what is already here before you sign up for anything. A search that matches only part of what you typed says so instead of returning nothing.",+ "tags": [+ "feature",+ "sdk"+ ],+ "link": "/docs/mcp"+ },{"date": "2026-09-04","title": "Generation jobs can now push their result to your server, and the health page finally watches the editing tools",diff --git a/docs/mcp.md b/docs/mcp.mdindex 3e9c8582a..2663604cd 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -234,7 +234,130 @@ Send `POST /api/mcp` with valid JSON-RPC 2.0 messages and a bearer token. The seAll tools return `{ content: [{ type, text }], structuredContent: {...} }`. On error, `isError: true` is set and `content[0].text` contains the message.-The tools below are the core avatar, validation, minting, and market-data set. The server registers more beyond this page (memory `remember`/`recall`/`forget`, `register_agent`, oracle and pump.fun intel reads, trader analytics, copy-trading); call `tools/list` for the complete live catalog with schemas.+`search_catalog`, `get_catalog_item`, and `get_item_source` are free and need no account, API key, or payment: start there. The tools below them are the core avatar, validation, minting, and market-data set. The server registers more beyond this page (memory `remember`/`recall`/`forget`, `register_agent`, oracle and pump.fun intel reads, trader analytics, copy-trading); call `tools/list` for the complete live catalog with schemas.++---++### `search_catalog`++Search every ready-made asset three.ws publishes in one call: 511 CC0 props, 107 rigged+characters, and 2,874 retargetable motion clips (live counts come back in `facets.kinds`).++**Free. No account, no API key, no x402 payment.** Discovery works before you connect.++```json+{+ "type": "object",+ "properties": {+ "q": { "type": "string", "maxLength": 200 },+ "kind": { "type": "string", "enum": ["object", "character", "animation"] },+ "category": { "type": "string", "maxLength": 80 },+ "tag": { "type": "string", "maxLength": 80 },+ "limit": { "type": "integer", "minimum": 1, "maximum": 50, "default": 12 },+ "offset": { "type": "integer", "minimum": 0, "default": 0 }+ },+ "additionalProperties": false+}+```++Every word of `q` must match somewhere (title, name, tag, or category), which keeps a+two-word query precise. If nothing matches all of the words, the search retries on any of+them and sets `relaxed: true` so you know the results are partial rather than exact.++Each result carries a stable `id` of the form `<kind>:<name>`, plus `title`, `tags`,+`categories`, `license`, `thumb`, and the CDN `url` of the GLB or clip JSON. The response+also carries `facets` (kind counts and the most common categories and tags in the result+set) to narrow the next call, and `next_offset` for paging.++```jsonc+// search_catalog { "q": "wooden chair", "kind": "object", "limit": 2 }+{+ "ok": true,+ "matched": 10,+ "relaxed": false,+ "items": [+ {+ "id": "object:painted_wooden_chair_01",+ "kind": "object",+ "title": "Painted Wooden Chair 01",+ "categories": ["furniture"],+ "tags": ["chair", "wood", "painted"],+ "license": "CC0",+ "format": "glb",+ "url": "https://.../objects/polyhaven/glb/painted_wooden_chair_01.glb",+ "thumb": "https://.../objects/polyhaven/thumbs/painted_wooden_chair_01.png",+ "bytes": 1483264+ }+ ],+ "facets": { "kinds": { "object": 10 }, "categories": [{ "value": "furniture", "count": 8 }] },+ "next_offset": 2+}+```++Check the catalog before generating anything. If the prop or character already exists,+dropping it in is instant and free, where a Forge generation is neither.++---++### `get_catalog_item`++One catalog item in full, by the `id` from `search_catalog` (a bare name also resolves).++**Free. No account or payment.**++```json+{+ "type": "object",+ "required": ["id"],+ "properties": {+ "id": { "type": "string", "maxLength": 200 }+ },+ "additionalProperties": false+}+```++Returns the item, the `links` that browse/preview/edit it on three.ws (an object opens in+the viewer and in AR Studio, a character in the viewer, Widget Studio, and the pose editor,+a clip in the animation gallery), up to six `related` items of the same kind, and the+`frameworks` that `get_item_source` can emit for it.++---++### `get_item_source`++Paste-ready code that renders one catalog item on any site.++**Free. No account or payment.**++```json+{+ "type": "object",+ "required": ["id"],+ "properties": {+ "id": { "type": "string", "maxLength": 200 },+ "framework": { "type": "string", "enum": ["agent-3d", "model-viewer", "three", "react", "all"] }+ },+ "additionalProperties": false+}+```++| Framework | What you get |+| --- | --- |+| `agent-3d` | The `<agent-3d>` web component, pinned to the exact version this deployment serves with its published SRI hash. Never `latest`. |+| `model-viewer` | The `<model-viewer>` tag, build, and integrity hash the three.ws browse grids themselves use. |+| `three` | Plain three.js: `GLTFLoader` for a model, `THREE.AnimationClip.parse` for a motion clip. |+| `react` | The same, wrapped as a React component (or a hook, for a clip). |+| `all` | Every variant that applies to the item, in one response. |++Omit `framework` and you get the one that fits the item: `model-viewer` for a prop (what the+object grid renders), `agent-3d` for a rigged character, `three` for a motion clip. A+framework that does not apply to the item (asking for `model-viewer` on a clip) is rejected+with the list that does.++Motion clips are `THREE.AnimationClip` JSON on canonical (Mixamo) bone names. To bake one+onto your own rig server-side instead of playing it in the browser, pass the returned clip+name to the `apply_animation` tool with your GLB url; it retargets and returns an animated+GLB.---diff --git a/tests/api/mcp-asset-catalog.test.js b/tests/api/mcp-asset-catalog.test.jsnew file mode 100644index 000000000..71309e494--- /dev/null+++ b/tests/api/mcp-asset-catalog.test.js@@ -0,0 +1,306 @@+// The asset-catalog MCP tools (api/_mcp/tools/library.js) and the two libraries+// under them: the manifest join (api/_lib/asset-catalog.js) and the snippet+// builder (api/_lib/asset-snippets.js).+//+// R2 is stubbed with manifests shaped exactly like the published ones (the+// field names and the "collection: x" category convention come from the live+// objects/avatars/animations manifests), so the suite exercises the real join,+// the real ranking, and the real code generation without a network call.++import { describe, it, expect, beforeEach, vi } from 'vitest';++const MANIFESTS = {+ 'objects/library/manifest.json': {+ generated_at: '2026-09-01T00:00:00.000Z',+ objects: [+ {+ name: 'adjustable_wrench',+ label: 'Adjustable Wrench',+ url: 'https://cdn.test/objects/adjustable_wrench.glb',+ thumb: 'https://cdn.test/objects/adjustable_wrench.png',+ bytes: 2639744,+ categories: ['collection: project_lighthouse', 'props', 'tools'],+ tags: ['vintage', 'garage', 'hand tool'],+ license: 'CC0',+ },+ {+ name: 'wooden_chair',+ label: 'Wooden Chair',+ url: 'https://cdn.test/objects/wooden_chair.glb',+ thumb: 'https://cdn.test/objects/wooden_chair.png',+ bytes: 1048576,+ categories: ['furniture'],+ tags: ['wood', 'seating'],+ license: 'CC0',+ },+ ],+ },+ 'avatars/library/manifest.json': {+ avatars: [+ {+ name: 'abe',+ label: 'Abe',+ url: 'https://cdn.test/avatars/abe.glb',+ thumb: 'https://cdn.test/avatars/abe.png',+ bytes: 35947032,+ skins: 1,+ animations: 1,+ source: 'mixamo',+ license: 'Mixamo',+ },+ ],+ },+ 'animations/library/manifest.json': {+ clips: [+ {+ name: 'mx-wave-abc123',+ label: 'Wave',+ url: 'https://cdn.test/animations/mx-wave-abc123.json',+ thumb: 'https://cdn.test/animations/mx-wave-abc123.webp',+ duration: 2.5,+ loop: false,+ icon: '👋',+ },+ ],+ },+ // The generated catalog may not exist yet; a missing key must degrade to+ // empty rather than failing the whole catalog.+ 'animations/library/generated/manifest.json': null,+};++const getObjectBuffer = vi.fn(async (key) => {+ const value = MANIFESTS[key];+ if (value == null) {+ const err = new Error('NoSuchKey');+ err.name = 'NoSuchKey';+ throw err;+ }+ return Buffer.from(JSON.stringify(value), 'utf8');+});++vi.mock('../../api/_lib/r2.js', () => ({ getObjectBuffer }));++const { searchCatalog, getCatalogItem, relatedItems, resetCatalogCache } = await import(+ '../../api/_lib/asset-catalog.js'+);+const { sourceFor, snippetFor, frameworksFor, agentElementRelease } = await import(+ '../../api/_lib/asset-snippets.js'+);+const { toolDefs } = await import('../../api/_mcp/tools/library.js');+const { isPublicTool } = await import('../../api/_mcp/dispatch.js');++const tool = (name) => toolDefs.find((t) => t.name === name);+const req = { headers: { host: 'three.ws' } };++beforeEach(() => {+ resetCatalogCache();+ getObjectBuffer.mockClear();+});++describe('catalog join', () => {+ it('reads all three libraries into one normalized list', async () => {+ const res = await searchCatalog({ limit: 50 });+ expect(res.total).toBe(4);+ expect(res.items.map((i) => i.id).sort()).toEqual([+ 'animation:mx-wave-abc123',+ 'character:abe',+ 'object:adjustable_wrench',+ 'object:wooden_chair',+ ]);+ });++ it('lifts "collection: x" out of the browsable categories', async () => {+ const item = await getCatalogItem('object:adjustable_wrench');+ expect(item.categories).toEqual(['props', 'tools']);+ expect(item.collection).toBe('project_lighthouse');+ });++ it('degrades to empty for a manifest that was never published', async () => {+ // The generated animation manifest throws NoSuchKey above; the catalog+ // still holds the curated clip.+ const res = await searchCatalog({ kind: 'animation', limit: 50 });+ expect(res.items).toHaveLength(1);+ });++ it('memoizes the manifests so repeat searches do not re-read storage', async () => {+ await searchCatalog({ q: 'chair' });+ const afterFirst = getObjectBuffer.mock.calls.length;+ await searchCatalog({ q: 'wrench' });+ expect(getObjectBuffer.mock.calls.length).toBe(afterFirst);+ });+});++describe('ranking', () => {+ it('ranks a title match above a tag match', async () => {+ const res = await searchCatalog({ q: 'wrench' });+ expect(res.items[0].id).toBe('object:adjustable_wrench');+ });++ it('requires every term to match, so a two-word query does not return everything', async () => {+ const res = await searchCatalog({ q: 'wooden chair' });+ expect(res.items.map((i) => i.id)).toEqual(['object:wooden_chair']);+ expect(res.relaxed).toBe(false);+ });++ it('relaxes to a partial match rather than dead-ending an unmatched phrase', async () => {+ const res = await searchCatalog({ q: 'wooden wrench' });+ expect(res.relaxed).toBe(true);+ // Both words land somewhere, and the item matching a title word outranks+ // the one matching only a tag.+ expect(res.items.map((i) => i.id)).toEqual([+ 'object:adjustable_wrench',+ 'object:wooden_chair',+ ]);+ });++ it('does not relax a single-word query that simply has no match', async () => {+ const res = await searchCatalog({ q: 'submarine' });+ expect(res.relaxed).toBe(false);+ expect(res.items).toHaveLength(0);+ });++ it('filters by kind, category, and tag', async () => {+ expect((await searchCatalog({ kind: 'character' })).items[0].id).toBe('character:abe');+ expect((await searchCatalog({ category: 'FURNITURE' })).items[0].id).toBe('object:wooden_chair');+ expect((await searchCatalog({ tag: 'Garage' })).items[0].id).toBe('object:adjustable_wrench');+ });++ it('pages with a stable order and reports next_offset', async () => {+ const first = await searchCatalog({ kind: 'object', limit: 1 });+ expect(first.next_offset).toBe(1);+ const second = await searchCatalog({ kind: 'object', limit: 1, offset: 1 });+ expect(second.items[0].id).not.toBe(first.items[0].id);+ expect(second.next_offset).toBeNull();+ });++ it('resolves a bare name as well as a `<kind>:<name>` id', async () => {+ expect((await getCatalogItem('abe')).id).toBe('character:abe');+ expect(await getCatalogItem('nope')).toBeNull();+ });++ it('relates items of the same kind that share tags', async () => {+ const wrench = await getCatalogItem('object:adjustable_wrench');+ const related = await relatedItems(wrench);+ expect(related.every((r) => r.kind === 'object')).toBe(true);+ expect(related.some((r) => r.id === 'object:adjustable_wrench')).toBe(false);+ });+});++describe('source snippets', () => {+ it('recommends model-viewer for a prop and the avatar component for a character', async () => {+ expect(frameworksFor(await getCatalogItem('object:wooden_chair'))[0]).toBe('model-viewer');+ expect(frameworksFor(await getCatalogItem('character:abe'))[0]).toBe('agent-3d');+ expect(frameworksFor(await getCatalogItem('animation:mx-wave-abc123'))[0]).toBe('three');+ });++ it('pins the agent-3d snippet to a version and never ships "latest"', async () => {+ const item = await getCatalogItem('character:abe');+ const snippet = snippetFor(item, 'agent-3d', 'https://three.ws');+ expect(snippet.code).not.toContain('/latest/');+ const release = agentElementRelease();+ if (release?.version && release.integrity) {+ expect(snippet.code).toContain(`/agent-3d/${release.version}/agent-3d.js`);+ expect(snippet.code).toContain(release.integrity);+ } else {+ expect(snippet.code).toContain('/agent-3d/1/agent-3d.js');+ }+ });++ it('emits the asset url into every model framework', async () => {+ const item = await getCatalogItem('object:wooden_chair');+ const { snippets } = sourceFor(item, 'https://three.ws');+ for (const framework of ['agent-3d', 'model-viewer', 'three', 'react']) {+ expect(snippets[framework].code).toContain(item.url);+ }+ });++ it('builds a clip snippet that parses THREE.AnimationClip JSON with the clip loop mode', async () => {+ const item = await getCatalogItem('animation:mx-wave-abc123');+ const snippet = snippetFor(item, 'three', 'https://three.ws');+ expect(snippet.code).toContain('THREE.AnimationClip.parse');+ expect(snippet.code).toContain('THREE.LoopOnce');+ expect(snippet.code).toContain(item.url);+ });++ it('produces a legal React identifier even for a title that starts with a digit', async () => {+ const item = { ...(await getCatalogItem('animation:mx-wave-abc123')), title: '135 Degree Turn' };+ const snippet = snippetFor(item, 'react', 'https://three.ws');+ expect(snippet.code).toMatch(/export function use[A-Za-z]/);+ });++ it('links each kind to the page that actually browses it', async () => {+ expect(sourceFor(await getCatalogItem('object:wooden_chair'), 'https://three.ws').links.browse)+ .toBe('https://three.ws/objects');+ expect(sourceFor(await getCatalogItem('character:abe'), 'https://three.ws').links.browse)+ .toBe('https://three.ws/character-library');+ expect(sourceFor(await getCatalogItem('animation:mx-wave-abc123'), 'https://three.ws').links.preview)+ .toBe('https://three.ws/animations?clip=mx-wave-abc123');+ });+});++describe('mcp tools', () => {+ it('search_catalog returns readable text and structured results', async () => {+ const out = await tool('search_catalog').handler({ q: 'chair' }, {}, req);+ expect(out.structuredContent.ok).toBe(true);+ expect(out.structuredContent.items[0].id).toBe('object:wooden_chair');+ expect(out.content[0].text).toContain('object:wooden_chair');+ });++ it('search_catalog tells an empty result what to do next', async () => {+ const out = await tool('search_catalog').handler({ q: 'submarine' }, {}, req);+ expect(out.structuredContent.items).toHaveLength(0);+ expect(out.content[0].text).toContain('No catalog items match');+ });++ it('search_catalog says so when it fell back to a partial match', async () => {+ const out = await tool('search_catalog').handler({ q: 'wooden wrench' }, {}, req);+ expect(out.structuredContent.relaxed).toBe(true);+ expect(out.content[0].text).toContain('Nothing matches every word');+ });++ it('get_catalog_item rejects an unknown id with a usable hint', async () => {+ await expect(tool('get_catalog_item').handler({ id: 'object:nope' }, {}, req)).rejects.toThrow(+ /no catalog item/,+ );+ });++ it('get_item_source defaults to the recommended framework', async () => {+ const out = await tool('get_item_source').handler({ id: 'object:wooden_chair' }, {}, req);+ expect(out.structuredContent.framework).toBe('model-viewer');+ expect(out.content[0].text).toContain('<model-viewer');+ });++ it('get_item_source with framework "all" returns every applicable variant', async () => {+ const out = await tool('get_item_source').handler(+ { id: 'character:abe', framework: 'all' },+ {},+ req,+ );+ expect(Object.keys(out.structuredContent.snippets).sort()).toEqual(+ ['agent-3d', 'model-viewer', 'react', 'three'].sort(),+ );+ });++ it('get_item_source refuses a framework that does not apply to a motion clip', async () => {+ await expect(+ tool('get_item_source').handler(+ { id: 'animation:mx-wave-abc123', framework: 'model-viewer' },+ {},+ req,+ ),+ ).rejects.toThrow(/does not apply/);+ });++ it('every catalog tool is callable with no account and no payment', () => {+ for (const def of toolDefs) {+ expect(def.scope).toBeUndefined();+ expect(isPublicTool(def.name)).toBe(true);+ }+ });++ it('does not make an account-scoped tool public', () => {+ expect(isPublicTool('list_my_avatars')).toBe(false);+ expect(isPublicTool('recall')).toBe(false);+ expect(isPublicTool('getting_started')).toBe(true);+ });+});