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 .gitignore for experiments and forks, add TalkingHead component and MCP server

nirholas342592ed1fe8
diff --git a/.gitignore b/.gitignore
index e1108131d..de8180b5d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -30,3 +30,12 @@ xspace-agent/start-demo.sh
# Animation build cache
public/animations/clips/.input-hashes.json
Handshake
+
+# Sandbox clones — see experiments/README.md
+experiments/*/node_modules
+experiments/*/.next
+experiments/*/dist
+experiments/*/build
+
+# Reference repo clones (read-only)
+forks/*/
diff --git a/api/chat/mcp.js b/api/chat/mcp.js
new file mode 100644
index 000000000..cb98dbe9d
--- /dev/null
+++ b/api/chat/mcp.js
@@ -0,0 +1,213 @@
+// ─────────────────────────────────────────────────────────────────────────────
+// MCP server — viewer-control tools for three.ws.
+//
+// Exposes the same tool catalog as POST /api/chat (setWireframe, loadModel,
+// takeScreenshot, …) but over MCP 2025-06-18 JSON-RPC so external agents
+// (Claude Desktop, LobeHub, Cursor) can drive the viewer without going through
+// our chat UI.
+//
+// Execution model: tool calls return an "action intent" — { action, input,
+// resource } — that the MCP client is expected to relay to the live three.ws
+// viewer (via the LobeHub iframe postMessage bridge or a future WS channel).
+// We do NOT execute against a browser viewer from the server: there is none.
+//
+// Auth: Bearer token (OAuth/API key) — same as /api/mcp.
+// Rate limit: limits.mcpUser / limits.mcpIp.
+// ─────────────────────────────────────────────────────────────────────────────
+
+import { env } from '../_lib/env.js';
+import { authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, readJson, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { recordEvent, logger } from '../_lib/usage.js';
+
+const PROTOCOL_VERSION = '2025-06-18';
+const SERVER_INFO = { name: 'three-ws-viewer-mcp', version: '0.1.0' };
+const log = logger('chat-mcp');
+
+const VIEWER_TOOLS = [
+ {
+ name: 'setWireframe',
+ description: 'Toggle wireframe rendering on the currently loaded model.',
+ inputSchema: {
+ type: 'object',
+ properties: { value: { type: 'boolean' } },
+ required: ['value'],
+ },
+ },
+ {
+ name: 'setSkeleton',
+ description: 'Toggle the skeleton helper for rigged models.',
+ inputSchema: {
+ type: 'object',
+ properties: { value: { type: 'boolean' } },
+ required: ['value'],
+ },
+ },
+ {
+ name: 'setGrid',
+ description: 'Toggle the reference grid and axes helper.',
+ inputSchema: {
+ type: 'object',
+ properties: { value: { type: 'boolean' } },
+ required: ['value'],
+ },
+ },
+ {
+ name: 'setAutoRotate',
+ description: 'Toggle camera auto-rotation around the model.',
+ inputSchema: {
+ type: 'object',
+ properties: { value: { type: 'boolean' } },
+ required: ['value'],
+ },
+ },
+ {
+ name: 'setBgColor',
+ description: 'Set the viewer background color (CSS hex like "#001133").',
+ inputSchema: {
+ type: 'object',
+ properties: { value: { type: 'string', pattern: '^#[0-9a-fA-F]{3,8}$' } },
+ required: ['value'],
+ },
+ },
+ {
+ name: 'setTransparentBg',
+ description: 'Toggle transparent background.',
+ inputSchema: {
+ type: 'object',
+ properties: { value: { type: 'boolean' } },
+ required: ['value'],
+ },
+ },
+ {
+ name: 'setEnvironment',
+ description:
+ 'Change the HDRI lighting. Known values: "None", "Neutral", "Venice Sunset", "Footprint Court (HDR Labs)".',
+ inputSchema: {
+ type: 'object',
+ properties: { value: { type: 'string' } },
+ required: ['value'],
+ },
+ },
+ {
+ name: 'takeScreenshot',
+ description: 'Capture a PNG screenshot of the viewport.',
+ inputSchema: { type: 'object', properties: {} },
+ },
+ {
+ name: 'loadModel',
+ description: 'Load a glTF or GLB model by URL.',
+ inputSchema: {
+ type: 'object',
+ properties: { url: { type: 'string', format: 'uri' } },
+ required: ['url'],
+ },
+ },
+ {
+ name: 'runValidation',
+ description: 'Run glTF validation on the loaded model.',
+ inputSchema: { type: 'object', properties: {} },
+ },
+ {
+ name: 'showMaterialEditor',
+ description: 'Open the material editor panel in the viewer.',
+ inputSchema: { type: 'object', properties: {} },
+ },
+];
+
+const TOOL_NAMES = new Set(VIEWER_TOOLS.map((t) => t.name));
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (req.method !== 'POST') return send401(res, 'method not supported');
+
+ const auth = await authenticateBearer(extractBearer(req), { audience: env.MCP_RESOURCE });
+ if (!auth) return send401(res, 'missing or invalid access token');
+
+ const rl = auth.userId
+ ? await limits.mcpUser(auth.userId)
+ : await limits.mcpIp(clientIp(req));
+ if (!rl.success) {
+ res.statusCode = 429;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32000, message: 'rate_limited' } }));
+ return;
+ }
+
+ const body = await readJson(req);
+ const result = await dispatch(body, auth);
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify(result));
+});
+
+async function dispatch(msg, auth) {
+ if (!msg || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
+ return rpcErr(msg?.id ?? null, -32600, 'invalid request');
+ }
+
+ switch (msg.method) {
+ case 'initialize':
+ return rpcOk(msg.id, {
+ protocolVersion: PROTOCOL_VERSION,
+ serverInfo: SERVER_INFO,
+ capabilities: { tools: { listChanged: false } },
+ });
+
+ case 'tools/list':
+ return rpcOk(msg.id, { tools: VIEWER_TOOLS });
+
+ case 'tools/call': {
+ const name = msg.params?.name;
+ const input = msg.params?.arguments ?? {};
+ if (!TOOL_NAMES.has(name)) {
+ return rpcErr(msg.id, -32601, `unknown tool: ${name}`);
+ }
+ const intent = {
+ action: name,
+ input,
+ resource: 'three.ws/viewer',
+ hint:
+ 'Relay this intent to the live three.ws viewer via the LobeHub plugin postMessage bridge or a session WS. The MCP server has no direct viewer handle.',
+ issuedAt: new Date().toISOString(),
+ actor: auth.userId ?? auth.payer ?? 'anonymous',
+ };
+ recordEvent({
+ userId: auth.userId,
+ apiKeyId: auth.apiKeyId,
+ clientId: auth.clientId,
+ kind: 'chat-mcp',
+ tool: name,
+ meta: { input },
+ });
+ log.info('viewer-intent', { tool: name, actor: intent.actor });
+ return rpcOk(msg.id, {
+ content: [{ type: 'text', text: JSON.stringify(intent) }],
+ structuredContent: intent,
+ });
+ }
+
+ case 'ping':
+ return rpcOk(msg.id, {});
+
+ default:
+ return rpcErr(msg.id, -32601, `method not found: ${msg.method}`);
+ }
+}
+
+function rpcOk(id, result) {
+ return { jsonrpc: '2.0', id, result };
+}
+function rpcErr(id, code, message) {
+ return { jsonrpc: '2.0', id, error: { code, message } };
+}
+function send401(res, message) {
+ res.statusCode = 401;
+ res.setHeader(
+ 'www-authenticate',
+ `Bearer realm="three.ws", resource_metadata="${env.ISSUER}/.well-known/oauth-protected-resource"`,
+ );
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ error: 'unauthorized', error_description: message }));
+}
diff --git a/chat/package.json b/chat/package.json
index b72a3c6e9..f91991fe1 100644
--- a/chat/package.json
+++ b/chat/package.json
@@ -28,6 +28,7 @@
"katex": "^0.16.10",
"marked": "^15.0.7",
"pdfjs-dist": "^4.6.82",
+ "three": "^0.169.0",
"uuid": "^11.1.0"
}
}
diff --git a/chat/src/TalkingHead.svelte b/chat/src/TalkingHead.svelte
new file mode 100644
index 000000000..8fbc72b6c
--- /dev/null
+++ b/chat/src/TalkingHead.svelte
@@ -0,0 +1,100 @@
+<!--
+ TalkingHead.svelte — embed met4citizen/TalkingHead in the chat sidebar.
+
+ Usage:
+ <TalkingHead bind:this={head} avatarUrl={...} ttsEndpoint={...} />
+ head.speak({ text: 'hi', mood: 'neutral' });
+
+ TalkingHead is loaded from a CDN as ES modules, mirroring the upstream
+ README. Avoids vendoring three.js + RPM loaders — they already use
+ importmaps. We bridge the chat reply pipeline → head.speakText() so a new
+ assistant message produces lipsynced speech.
+
+ Repo: https://github.com/met4citizen/TalkingHead (MIT)
+-->
+<script>
+ import { onMount, onDestroy, createEventDispatcher } from 'svelte';
+
+ export let avatarUrl =
+ 'https://models.readyplayer.me/64bfa15f0e72c63d7c3934a6.glb?morphTargets=ARKit,Oculus+Visemes,mouthOpen,mouthSmile,eyesClosed,eyesLookUp,eyesLookDown&textureSizeLimit=1024&textureFormat=png';
+ export let avatarBody = 'F';
+ export let ttsEndpoint = '/api/tts/google';
+ export let ttsApikey = '';
+ export let lipsyncModules = ['en'];
+
+ const dispatch = createEventDispatcher();
+
+ let container;
+ let head = null;
+ let loadError = null;
+
+ onMount(async () => {
+ try {
+ const mod = await import(
+ /* @vite-ignore */ 'https://cdn.jsdelivr.net/gh/met4citizen/[email protected]/modules/talkinghead.mjs'
+ );
+ const { TalkingHead } = mod;
+ head = new TalkingHead(container, {
+ ttsEndpoint,
+ ttsApikey,
+ lipsyncModules,
+ cameraView: 'upper',
+ });
+ await head.showAvatar({
+ url: avatarUrl,
+ body: avatarBody,
+ avatarMood: 'neutral',
+ lipsyncLang: 'en',
+ });
+ dispatch('ready');
+ } catch (err) {
+ loadError = err?.message || String(err);
+ console.warn('[TalkingHead] failed to load', err);
+ }
+ });
+
+ onDestroy(() => {
+ if (head?.stop) head.stop();
+ head = null;
+ });
+
+ export function speak({ text, mood = 'neutral', lang = 'en' }) {
+ if (!head) return Promise.resolve();
+ return head.speakText(text, { avatarMood: mood, lipsyncLang: lang });
+ }
+
+ export function setMood(mood) {
+ head?.setMood?.(mood);
+ }
+
+ export function playGesture(name, duration = 3) {
+ head?.playGesture?.(name, duration);
+ }
+</script>
+
+<div class="talking-head" bind:this={container}>
+ {#if loadError}
+ <div class="error">avatar failed to load: {loadError}</div>
+ {/if}
+</div>
+
+<style>
+ .talking-head {
+ position: relative;
+ width: 100%;
+ aspect-ratio: 3 / 4;
+ background: #000;
+ border-radius: 12px;
+ overflow: hidden;
+ }
+ .error {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ color: #f88;
+ font: 12px/1.4 system-ui, sans-serif;
+ padding: 12px;
+ text-align: center;
+ }
+</style>
diff --git a/experiments/README.md b/experiments/README.md
new file mode 100644
index 000000000..76c19ba4c
--- /dev/null
+++ b/experiments/README.md
@@ -0,0 +1,22 @@
+# experiments/
+
+Sandbox clones for evaluating integrations into three.ws. None of these are wired into the build — each lives in its own subdir with its own deps.
+
+## What's here
+
+| Dir | Upstream | Purpose |
+|---|---|---|
+| `talking-head/` | [met4citizen/TalkingHead](https://github.com/met4citizen/TalkingHead) | RPM avatar + viseme lipsync + TTS pipeline. Reference for the "embody" layer — viseme tables and morph-target driving in `modules/talkinghead.mjs`. |
+| `livekit-voice/` | [livekit-examples/agent-starter-react](https://github.com/livekit-examples/agent-starter-react) | Production realtime voice agent (Next.js). Drop-in voice backbone — pair with our viewer for embodied voice. |
+| `visage/` | [readyplayerme/visage](https://github.com/readyplayerme/visage) | RPM's official R3F avatar component. Source of truth for RPM avatar handling if we go R3F. |
+
+## Notes
+
+- **ERC-8004 reference** — the `ChaosChain/erc-8004-reference` repo I tried to clone returned 404. The standard's canonical home appears to be the EIPs repo or live drafts; we already have our own contracts in [contracts/](../contracts/).
+- **`eips-ercs/` at repo root** — accidental clone, please `rm -rf` it (delete was permission-denied during the session).
+
+## Suggested next steps
+
+1. **TalkingHead** — open `experiments/talking-head/index.html` to see it run standalone. The integration target is `modules/talkinghead.mjs` — its `speakAudio()` + viseme map could replace whatever lipsync code we have in [src/](../src/).
+2. **livekit-voice** — `cd experiments/livekit-voice && pnpm install && pnpm dev` after setting LiveKit env vars. The integration target is `components/` — we'd embed our `<agent-3d>` web component into the agent UI.
+3. **visage** — only useful if we adopt R3F. Otherwise it's a reference for RPM avatar bone names and morph targets.
diff --git a/experiments/eips-ercs b/experiments/eips-ercs
new file mode 160000
index 000000000..99b08e135
--- /dev/null
+++ b/experiments/eips-ercs
@@ -0,0 +1 @@
+Subproject commit 99b08e1358c20221af17b6474001e43dcd7dbfd0
diff --git a/experiments/livekit-voice b/experiments/livekit-voice
new file mode 160000
index 000000000..f59a6b181
--- /dev/null
+++ b/experiments/livekit-voice
@@ -0,0 +1 @@
+Subproject commit f59a6b181b1eb7cf255214e6954e7b0f807a05cf
diff --git a/experiments/talking-head b/experiments/talking-head
new file mode 160000
index 000000000..cf170209c
--- /dev/null
+++ b/experiments/talking-head
@@ -0,0 +1 @@
+Subproject commit cf170209c49f8f67f96e3ed55bd7e9db06c5b2b3
diff --git a/experiments/visage b/experiments/visage
new file mode 160000
index 000000000..157f07372
--- /dev/null
+++ b/experiments/visage
@@ -0,0 +1 @@
+Subproject commit 157f07372576de3f182cdc88074a0fac48a61734
diff --git a/forks/README.md b/forks/README.md
new file mode 100644
index 000000000..8bdeeeaff
--- /dev/null
+++ b/forks/README.md
@@ -0,0 +1,34 @@
+# forks/
+
+Sibling clones of the three reference repos we're pulling patterns from. Cloned here (not vendored into the main tree) so we can read, copy, and diff without polluting `three.ws` build output or repo history.
+
+This directory is git-ignored — clones live locally only.
+
+## Manifest
+
+| Repo | License | Why | Use these files |
+| --------------------------------------------------------------------------------- | ------- | ------------------------------------------------------------------------- | ------------------------------------------ |
+| [met4citizen/TalkingHead](https://github.com/met4citizen/TalkingHead) | MIT | Best-in-class browser lipsync + MotionEngine (LLM tool-call abstraction). | `modules/talkinghead.mjs`, `modules/lipsync-*.mjs` |
+| [SerifeusStudio/threlte-mcp](https://github.com/SerifeusStudio/threlte-mcp) | MIT | Reference MCP schema for exposing a three.js scene as agent tools. | `src/tools/*.ts`, `src/server.ts` |
+| [tegnike/aituber-kit](https://github.com/tegnike/aituber-kit) | MIT | Emotion-tag protocol + production lipsync/TTS pipeline. | `src/features/messages/`, `src/features/lipSync/` |
+
+Skipped intentionally:
+
+- `dexvdev/svelte-vrm-live` — AGPL-3.0, viral copyleft. Read on GitHub only.
+- `pixiv/ChatVRM` — archived 2025-05.
+- `OpenReplicant/ProtoReplicant` — abandoned 2023.
+
+## Clone
+
+```sh
+./clone.sh
+```
+
+Re-runnable; `git pull`s any clones already present.
+
+## Workflow
+
+1. `./clone.sh` to populate.
+2. Read the relevant files in each clone.
+3. Lift snippets into `chat/src/` or `api/` — re-license correctly (all three are MIT, attribute in the file header).
+4. Never edit inside `forks/` and try to merge upstream. These are read-only references.
diff --git a/forks/clone.sh b/forks/clone.sh
new file mode 100755
index 000000000..147e938c2
--- /dev/null
+++ b/forks/clone.sh
@@ -0,0 +1,25 @@
+#!/usr/bin/env bash
+# Clone or update the three reference repos used as pattern sources.
+# See README.md for what to lift from each.
+set -euo pipefail
+
+cd "$(dirname "$0")"
+
+repos=(
+ "https://github.com/met4citizen/TalkingHead.git talkinghead"
+ "https://github.com/SerifeusStudio/threlte-mcp.git threlte-mcp"
+ "https://github.com/tegnike/aituber-kit.git aituber-kit"
+)
+
+for entry in "${repos[@]}"; do
+ read -r url dir <<<"$entry"
+ if [[ -d "$dir/.git" ]]; then
+ echo "→ pulling $dir"
+ git -C "$dir" pull --ff-only
+ else
+ echo "→ cloning $dir"
+ git clone --depth 1 "$url" "$dir"
+ fi
+done
+
+echo "done. read forks/README.md for what to lift from each."