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: Solana-only x402 for mcp-server + new threews-avatar MCP server
overstepping44662d835405
diff --git a/package.json b/package.jsonindex 71c738ad3..8030a2c1d 100644--- a/package.json+++ b/package.json@@ -35,7 +35,8 @@"packages/avatar-cli","packages/viewer-presets","packages/pumpfun-mcp",- "packages/ibm-watsonx-mcp"+ "packages/ibm-watsonx-mcp",+ "packages/threews-avatar-mcp"],"main": "src/app.js","browserslist": [diff --git a/packages/threews-avatar-mcp/LICENSE b/packages/threews-avatar-mcp/LICENSEnew file mode 100644index 000000000..8e2251ab4--- /dev/null+++ b/packages/threews-avatar-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/threews-avatar-mcp/README.md b/packages/threews-avatar-mcp/README.mdnew file mode 100644index 000000000..ea7119458--- /dev/null+++ b/packages/threews-avatar-mcp/README.md@@ -0,0 +1,72 @@+# @three-ws/avatar-mcp++An [MCP](https://modelcontextprotocol.io) server that drops a **live three.ws 3D avatar** into any MCP client — Claude Desktop, Claude Code, Cursor, or any other host. Render a rotatable avatar inline, get a paste-anywhere embed iframe, or fetch avatar metadata.++It's a thin, **zero-config, read-only** bridge to the real three.ws endpoints. Public and unlisted avatars need **no API key**. No mock data — every tool reads live from three.ws.++> Registry name: `io.github.nirholas/threews-avatar`. Built by [three.ws](https://three.ws).++## Tools++| Tool | What it does |+| --- | --- |+| `render_avatar` | Renders an avatar inline: a preview image, an **interactive (rotatable) model-viewer artifact**, and a live embed URL. |+| `avatar_embed_code` | A ready-to-paste `<iframe>` that embeds the live avatar anywhere — as easy as a YouTube embed. |+| `get_avatar` | Avatar metadata: name, GLB model url, owner, visibility. |++Identify an avatar three ways: by **`id`** (UUID), by **`@handle`** (username), or by a raw **`model`** GLB url.++## Use with Claude Desktop / Claude Code / Cursor++```json+{+ "mcpServers": {+ "threews-avatar": {+ "command": "npx",+ "args": ["-y", "@three-ws/avatar-mcp"]+ }+ }+}+```++No environment variables required. To point at a different host, set `THREEWS_BASE_URL`.++## Run standalone++```bash+npx @three-ws/avatar-mcp+# inspect the tool surface:+npx -y @modelcontextprotocol/inspector npx @three-ws/avatar-mcp+```++## Example calls++```jsonc+// render_avatar — live, rotatable avatar in chat+{ "handle": "nirholas", "background": "dark", "auto_rotate": true }++// avatar_embed_code — paste into any website+{ "id": "c3d4e5f6-a7b8-9c0d-1e2f-3a4b5c6d7e8f", "height": 560 }++// get_avatar — metadata+{ "handle": "@nirholas" }+```++`render_avatar` returns three things so it looks great in every client:+1. a **preview image** (renders inline everywhere),+2. an **interactive `text/html` resource** (a `<model-viewer>` you can orbit — for clients that render HTML resources), and+3. the **embed URL + iframe** so you can drop the live avatar into any page.++## How it works++| Selector | Endpoint |+| --- | --- |+| `id` | `GET https://three.ws/api/avatars/:id` |+| `handle` | `GET https://three.ws/api/users/:handle/avatar` |+| preview image | `GET https://three.ws/api/avatar/render?avatar=:id` |+| live embed | `https://three.ws/avatar-embed.html?...` |+| viewer | `https://three.ws/viewer?src=:glb` |++## License++Apache-2.0diff --git a/packages/threews-avatar-mcp/package.json b/packages/threews-avatar-mcp/package.jsonnew file mode 100644index 000000000..830b38396--- /dev/null+++ b/packages/threews-avatar-mcp/package.json@@ -0,0 +1,56 @@+{+ "name": "@three-ws/avatar-mcp",+ "version": "0.1.0",+ "description": "MCP server for three.ws 3D avatars by three.ws — render a live, rotatable on-chain avatar inline, get a paste-anywhere embed iframe, or fetch avatar metadata. Free, no API key.",+ "type": "module",+ "author": "nirholas",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "mcpName": "io.github.nirholas/threews-avatar",+ "repository": {+ "type": "git",+ "url": "https://github.com/nirholas/three.ws.git",+ "directory": "packages/threews-avatar-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "model-context-protocol",+ "three.ws",+ "avatar",+ "3d-avatar",+ "glb",+ "gltf",+ "model-viewer",+ "embed",+ "ai-agent"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "avatar-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"+ }+}diff --git a/packages/threews-avatar-mcp/server.json b/packages/threews-avatar-mcp/server.jsonnew file mode 100644index 000000000..bd4b9d988--- /dev/null+++ b/packages/threews-avatar-mcp/server.json@@ -0,0 +1,29 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/threews-avatar",+ "description": "three.ws 3D avatars in your agent: render a live rotatable avatar inline, or get an embed iframe.",+ "repository": {+ "url": "https://github.com/nirholas/three.ws",+ "source": "github",+ "subfolder": "packages/threews-avatar-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/avatar-mcp",+ "version": "0.1.0",+ "transport": {+ "type": "stdio"+ },+ "environmentVariables": [+ {+ "name": "THREEWS_BASE_URL",+ "description": "three.ws host to read avatars from. Defaults to https://three.ws.",+ "isRequired": false,+ "format": "string"+ }+ ]+ }+ ]+}diff --git a/packages/threews-avatar-mcp/src/index.js b/packages/threews-avatar-mcp/src/index.jsnew file mode 100644index 000000000..b1df873cf--- /dev/null+++ b/packages/threews-avatar-mcp/src/index.js@@ -0,0 +1,76 @@+#!/usr/bin/env node+// @three-ws/avatar-mcp — stdio MCP server for three.ws 3D avatars.+//+// Drops a live, persistent three.ws 3D avatar into any MCP client (Claude+// Desktop/Code, Cursor, …): render it inline as an interactive, rotatable+// model, get a ready-to-paste embed iframe, or fetch avatar metadata.+//+// Architecture: a thin, zero-config bridge to real three.ws public endpoints+// (/api/avatars, /api/users/:handle/avatar, /api/avatar/render, /avatar-embed,+// /viewer). Public and unlisted avatars need no API key. No mock data — every+// tool reads live from three.ws. Override the host with THREEWS_BASE_URL.+//+// Run standalone: npx @three-ws/avatar-mcp+// Inspect: npx -y @modelcontextprotocol/inspector npx @three-ws/avatar-mcp++import { Server } from '@modelcontextprotocol/sdk/server/index.js';+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';+import {+ ListToolsRequestSchema,+ CallToolRequestSchema,+} from '@modelcontextprotocol/sdk/types.js';++import { buildTools } from './tools.js';+import { baseUrl, ThreewsError } from './threews.js';++const SERVER_NAME = 'three.ws-avatar-mcp';+const SERVER_VERSION = '0.1.0';++async function main() {+ const tools = buildTools();+ const byName = new Map(tools.map((t) => [t.definition.name, t]));++ const server = new Server(+ { name: SERVER_NAME, version: SERVER_VERSION },+ {+ capabilities: { tools: { listChanged: false } },+ instructions:+ 'three.ws 3D avatar tools. render_avatar shows a live, rotatable avatar inline ' ++ '(preview image + interactive model + embed URL); avatar_embed_code returns a ' ++ 'paste-anywhere iframe; get_avatar returns metadata. Identify avatars by id, ' ++ '@handle, or a raw GLB url. Free and read-only — no API key for public avatars.',+ },+ );++ server.setRequestHandler(ListToolsRequestSchema, async () => ({+ tools: tools.map((t) => t.definition),+ }));++ server.setRequestHandler(CallToolRequestSchema, async (request) => {+ const { name, arguments: args } = request.params;+ const tool = byName.get(name);+ if (!tool) {+ return { isError: true, content: [{ type: 'text', text: `Unknown tool: ${name}` }] };+ }+ try {+ return await tool.handler(args || {});+ } catch (err) {+ const text =+ err instanceof ThreewsError+ ? err.message+ : `Tool ${name} failed: ${err.message}`;+ return { isError: true, content: [{ type: 'text', text }] };+ }+ });++ const transport = new StdioServerTransport();+ await server.connect(transport);+ process.stderr.write(+ `[avatar-mcp] ${SERVER_NAME} v${SERVER_VERSION} ready — ${tools.length} tools via ${baseUrl()}\n`,+ );+}++main().catch((err) => {+ process.stderr.write(`[avatar-mcp] fatal: ${err?.stack || err}\n`);+ process.exit(1);+});diff --git a/packages/threews-avatar-mcp/src/threews.js b/packages/threews-avatar-mcp/src/threews.jsnew file mode 100644index 000000000..9f9a65962--- /dev/null+++ b/packages/threews-avatar-mcp/src/threews.js@@ -0,0 +1,190 @@+// three.ws public avatar API client.+//+// A dependency-free wrapper over the real three.ws endpoints that resolve an+// avatar (by id, @handle, or a raw GLB url), render it to a PNG, and produce+// the embed/viewer URLs used across the platform. Every method hits a live+// three.ws endpoint — there is no mock or sample path. Public and unlisted+// avatars need no credentials.+//+// Override the host with THREEWS_BASE_URL (e.g. a preview deployment).++const DEFAULT_BASE = 'https://three.ws';++export class ThreewsError extends Error {+ constructor(message, { status } = {}) {+ super(message);+ this.name = 'ThreewsError';+ this.status = status;+ }+}++export function baseUrl(env = process.env) {+ return (env.THREEWS_BASE_URL?.trim() || DEFAULT_BASE).replace(/\/$/, '');+}++function timeoutMs(env = process.env) {+ return Number(env.THREEWS_TIMEOUT_MS) || 30_000;+}++async function fetchWithTimeout(url, init = {}) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs());+ try {+ return await fetch(url, { ...init, signal: controller.signal });+ } catch (err) {+ if (err.name === 'AbortError') throw new ThreewsError(`Request to ${url} timed out.`);+ throw new ThreewsError(`Network error calling ${url}: ${err.message}`);+ } finally {+ clearTimeout(timer);+ }+}++// Normalize the various avatar shapes the API returns into one flat record.+function normalizeAvatar(avatar, user) {+ if (!avatar || typeof avatar !== 'object') return null;+ const model_url = avatar.model_url || avatar.base_model_url || avatar.url || null;+ return {+ id: avatar.id || null,+ name: avatar.name || avatar.display_name || user?.display_name || user?.username || 'Avatar',+ slug: avatar.slug || null,+ model_url,+ thumbnail: avatar.thumbnail_url || avatar.thumbnail || avatar.poster || null,+ visibility: avatar.visibility || null,+ owner: user ? { username: user.username, display_name: user.display_name } : undefined,+ };+}++async function readJson(res, url) {+ if (res.status === 404) throw new ThreewsError(`No avatar found at ${url}.`, { status: 404 });+ if (!res.ok) throw new ThreewsError(`three.ws ${url} → HTTP ${res.status}`, { status: res.status });+ try {+ return await res.json();+ } catch {+ throw new ThreewsError(`three.ws ${url} returned a non-JSON response.`);+ }+}++/**+ * Resolve an avatar from one of three selectors:+ * - { id } → GET /api/avatars/:id+ * - { handle } → GET /api/users/:handle/avatar+ * - { model } → a raw GLB url, used as-is (no API call)+ * Returns a normalized avatar record, or throws ThreewsError.+ */+export async function resolveAvatar({ id, handle, model }, env = process.env) {+ const base = baseUrl(env);++ if (model) {+ return { id: null, name: 'Avatar', slug: null, model_url: model, thumbnail: null, visibility: 'external' };+ }+ if (id) {+ const url = `${base}/api/avatars/${encodeURIComponent(id)}`;+ const data = await readJson(await fetchWithTimeout(url), url);+ const avatar = normalizeAvatar(data.avatar || data, data.user);+ if (!avatar?.model_url) throw new ThreewsError(`Avatar ${id} has no public model (it may be private).`);+ return avatar;+ }+ if (handle) {+ const h = handle.replace(/^@/, '');+ const url = `${base}/api/users/${encodeURIComponent(h)}/avatar`;+ const data = await readJson(await fetchWithTimeout(url), url);+ const avatar = normalizeAvatar(data.avatar || data, data.user);+ if (!avatar?.model_url) throw new ThreewsError(`@${h} has no public avatar model.`);+ return avatar;+ }+ throw new ThreewsError('Provide one of: id, handle, or model (GLB url).');+}++/**+ * Render an avatar to a PNG via /api/avatar/render and return it base64-encoded.+ * Only works for avatars that have an id (server-side render needs the record).+ */+export async function renderImage(+ { id, scene = 'portrait', size = 640, background = 'transparent', format = 'png' },+ env = process.env,+) {+ const base = baseUrl(env);+ const params = new URLSearchParams({+ avatar: id,+ scene,+ size: String(size),+ bg: background,+ format,+ });+ const url = `${base}/api/avatar/render?${params}`;+ const res = await fetchWithTimeout(url, { headers: { accept: `image/${format}` } });+ if (!res.ok) throw new ThreewsError(`Avatar render ${url} → HTTP ${res.status}`, { status: res.status });+ const buf = Buffer.from(await res.arrayBuffer());+ return { base64: buf.toString('base64'), mimeType: `image/${format}`, bytes: buf.length };+}++// Build the live, embeddable avatar URL (the page three.ws embeds like a video).+export function embedUrl({ id, handle, model, background = 'transparent', idle = true, overlay = false, animation }, env = process.env) {+ const base = baseUrl(env);+ const params = new URLSearchParams();+ if (id) params.set('id', id);+ else if (handle) params.set('handle', handle.replace(/^@/, ''));+ else if (model) params.set('model', model);+ params.set('bg', background);+ params.set('idle', idle ? 'on' : 'off');+ if (overlay) params.set('overlay', '1');+ if (animation) params.set('animation', animation);+ return `${base}/avatar-embed.html?${params}`;+}++// Build the standalone viewer URL (full-page interactive viewer).+export function viewerUrl({ model_url, camera = 'three-quarter', background = 'transparent', autoRotate = true }, env = process.env) {+ const base = baseUrl(env);+ const params = new URLSearchParams({+ src: model_url,+ camera,+ background,+ auto_rotate: autoRotate ? '1' : '0',+ });+ return `${base}/viewer?${params}`;+}++// A ready-to-paste iframe that embeds the live avatar anywhere — the+// "embed a 3D avatar as easily as a YouTube video" snippet.+export function iframeSnippet(embed, { width = '100%', height = 480 } = {}) {+ const h = typeof height === 'number' ? `${height}` : height;+ return (+ `<iframe src="${embed}" width="${width}" height="${h}" ` ++ `style="border:0;border-radius:16px;overflow:hidden" ` ++ `allow="camera; microphone; xr-spatial-tracking; fullscreen" allowfullscreen ` ++ `title="three.ws avatar"></iframe>`+ );+}++// Self-contained HTML that renders the GLB as an interactive <model-viewer>.+// Returned as an MCP text/html resource so capable clients show a live,+// rotatable 3D avatar inline.+export function modelViewerHtml({ model_url, name = 'Avatar', background = 'transparent', height = 480, cameraOrbit = '0deg 80deg 2m', autoRotate = true }) {+ const bg = background === 'transparent' ? 'transparent' : background;+ return `<!doctype html>+<html lang="en"><head><meta charset="utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1" />+<title>${escapeHtml(name)}</title>+<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>+<style>+ html,body { margin:0; height:100%; background:${bg}; }+ model-viewer { width:100%; height:${Number(height)}px; --progress-bar-color:#6a5cff; }+</style>+</head><body>+<model-viewer+ src="${escapeHtml(model_url)}"+ alt="${escapeHtml(name)}"+ camera-controls+ ${autoRotate ? 'auto-rotate' : ''}+ shadow-intensity="1"+ exposure="1"+ tone-mapping="aces"+ camera-orbit="${escapeHtml(cameraOrbit)}"+ ar ar-modes="webxr scene-viewer quick-look"+></model-viewer>+</body></html>`;+}++function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}diff --git a/packages/threews-avatar-mcp/src/tools.js b/packages/threews-avatar-mcp/src/tools.jsnew file mode 100644index 000000000..ada7427ce--- /dev/null+++ b/packages/threews-avatar-mcp/src/tools.js@@ -0,0 +1,188 @@+// Tool surface for the three.ws avatar MCP server.+//+// Three free, read-only tools over real three.ws endpoints:+// - render_avatar → live 3D avatar in chat (image + interactive HTML + embed)+// - avatar_embed_code → ready-to-paste iframe to embed the avatar anywhere+// - get_avatar → avatar metadata (name, model url, owner, visibility)+//+// Handlers trust their inputs (the JSON-Schema is the boundary) and let+// ThreewsError propagate — the server turns those into MCP tool errors with the+// real upstream cause.++import {+ resolveAvatar,+ renderImage,+ embedUrl,+ viewerUrl,+ iframeSnippet,+ modelViewerHtml,+} from './threews.js';++// One of these three selectors identifies an avatar across every tool.+const selectorProps = {+ id: { type: 'string', description: 'Avatar UUID (from a three.ws avatar URL or get_avatar).' },+ handle: { type: 'string', description: 'three.ws username/handle, e.g. "nirholas" or "@nirholas".' },+ model: { type: 'string', description: 'Direct GLB/GLTF model URL (skips lookup; used as-is).' },+};++function textBlock(text) {+ return { type: 'text', text };+}++export function buildTools() {+ return [+ {+ definition: {+ name: 'render_avatar',+ description:+ 'Render a three.ws 3D avatar inline: returns a preview image, an interactive ' ++ '(rotatable) model-viewer artifact, and a ready-to-embed live URL. Identify the ' ++ 'avatar by id, @handle, or a raw GLB url.',+ inputSchema: {+ type: 'object',+ properties: {+ ...selectorProps,+ background: {+ type: 'string',+ enum: ['transparent', 'dark', 'light'],+ default: 'transparent',+ description: 'Backdrop for the preview/embed.',+ },+ scene: {+ type: 'string',+ enum: ['portrait', 'headshot', 'upper-body', 'full-body'],+ default: 'portrait',+ description: 'Framing for the rendered preview image.',+ },+ auto_rotate: { type: 'boolean', default: true, description: 'Spin the model in the interactive view.' },+ height: { type: 'integer', minimum: 160, maximum: 1080, default: 480 },+ },+ anyOf: [{ required: ['id'] }, { required: ['handle'] }, { required: ['model'] }],+ },+ },+ handler: async (args) => {+ const avatar = await resolveAvatar(args);+ const background = args.background || 'transparent';+ const height = args.height || 480;+ const autoRotate = args.auto_rotate !== false;++ const embed = embedUrl(+ { id: avatar.id, handle: args.handle, model: args.model, background },+ );+ const viewer = viewerUrl({ model_url: avatar.model_url, background, autoRotate });+ const iframe = iframeSnippet(embed, { height });+ const html = modelViewerHtml({+ model_url: avatar.model_url,+ name: avatar.name,+ background,+ height,+ autoRotate,+ });++ const content = [];++ // Best-effort PNG preview (renders inline in every client). Only the+ // server-side renderer (needs an avatar id) can produce this; a raw+ // model url or a render failure simply omits the image.+ if (avatar.id) {+ try {+ const img = await renderImage({ id: avatar.id, scene: args.scene || 'portrait', background });+ content.push({ type: 'image', data: img.base64, mimeType: img.mimeType });+ } catch {+ /* preview is optional — fall through to the interactive + embed views */+ }+ }++ // Interactive, rotatable 3D for clients that render HTML resources.+ content.push({+ type: 'resource',+ resource: {+ uri: `avatar://${avatar.id || 'external'}`,+ mimeType: 'text/html',+ text: html,+ },+ });++ content.push(+ textBlock(+ `${avatar.name} — live 3D avatar from three.ws.\n\n` ++ `Interactive view: ${viewer}\n` ++ `Embed (live, like a YouTube video):\n${iframe}\n\n` ++ `Embed URL: ${embed}`,+ ),+ );++ return {+ content,+ structuredContent: {+ id: avatar.id,+ name: avatar.name,+ model_url: avatar.model_url,+ embed_url: embed,+ viewer_url: viewer,+ iframe,+ },+ };+ },+ },++ {+ definition: {+ name: 'avatar_embed_code',+ description:+ 'Get a ready-to-paste iframe that embeds a live, interactive three.ws 3D avatar ' ++ 'into any website or app — as easy as embedding a YouTube video.',+ inputSchema: {+ type: 'object',+ properties: {+ ...selectorProps,+ background: { type: 'string', enum: ['transparent', 'dark', 'light'], default: 'transparent' },+ width: { type: 'string', default: '100%', description: 'CSS width, e.g. "100%" or "480px".' },+ height: { type: 'integer', minimum: 160, maximum: 1080, default: 480 },+ idle: { type: 'boolean', default: true, description: 'Play the idle animation loop.' },+ overlay: { type: 'boolean', default: false, description: 'Chrome-free mode (good for OBS/overlays).' },+ },+ anyOf: [{ required: ['id'] }, { required: ['handle'] }, { required: ['model'] }],+ },+ },+ handler: async (args) => {+ // Validate the avatar exists (and surface a clear error if not) before+ // handing back embed code that would otherwise 404 for the user.+ const avatar = await resolveAvatar(args);+ const embed = embedUrl({+ id: avatar.id,+ handle: args.handle,+ model: args.model,+ background: args.background || 'transparent',+ idle: args.idle !== false,+ overlay: Boolean(args.overlay),+ });+ const iframe = iframeSnippet(embed, { width: args.width || '100%', height: args.height || 480 });+ return {+ content: [textBlock(`Embed code for ${avatar.name}:\n\n${iframe}\n\nEmbed URL: ${embed}`)],+ structuredContent: { embed_url: embed, iframe, name: avatar.name, id: avatar.id },+ };+ },+ },++ {+ definition: {+ name: 'get_avatar',+ description:+ 'Fetch metadata for a three.ws avatar (name, GLB model url, owner, visibility) by id or @handle.',+ inputSchema: {+ type: 'object',+ properties: { id: selectorProps.id, handle: selectorProps.handle },+ anyOf: [{ required: ['id'] }, { required: ['handle'] }],+ },+ },+ handler: async (args) => {+ const avatar = await resolveAvatar(args);+ return {+ content: [textBlock(JSON.stringify(avatar, null, 2))],+ structuredContent: avatar,+ };+ },+ },+ ];+}