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.

9.3 KB
Raw Blame
// Demo driver for the Spatial MCP reference renderer (/spatial-mcp).
//
// This lives in its own file inside /public on purpose. Two constraints meet
// here and only a sibling module satisfies both:
//
//   1. The route serves the page at BOTH /spatial-mcp and /spatial-mcp/. From an
//      inline script on the slash-less URL, './spatial-renderer.js' resolves
//      against the site root and 404s, leaving blank stages.
//   2. Vite refuses to transform an import of a JS file inside /public ("can
//      only be referenced via <script src>"), so an inline module with an
//      absolute /spatial-mcp/… specifier 500s in dev.
//
// A module referenced by <script type="module" src="/spatial-mcp/demo.js"> is
// copied as-is by the build, and its own relative import resolves against the
// module's URL, which always carries the directory. Correct in dev and prod, on
// either URL form.
import { renderSpatialArtifact } from './spatial-renderer.js';
import { validateSpatialArtifact, lintSpatialMeta } from './spatial-validator.js';

// Left stage: a real forge_free output, generated by the free text→3D lane.
// Served through the first-party CDN (/cdn/<r2-key>, api/cdn-object.js) rather
// than the bucket's public r2.dev domain: that domain is Cloudflare
// rate-limited, "not meant for production traffic", and answers CORS with an
// exact-origin allowlist, so a third party copying this artifact to prove
// portability would be blocked. /cdn serves the same object with
// `access-control-allow-origin: *` and a 30-day edge cache. Right stage: a
// genuinely third-party asset (Khronos glTF sample) so the foreign payload is
// foreign end to end, asset and shape both.
const FORGE_GLB = 'https://three.ws/cdn/forge/anon/eddcea57-a278-474a-a632-99ca99861755.glb';
const FOREIGN_GLB = 'https://cdn.jsdelivr.net/gh/KhronosGroup/glTF-Sample-Assets@main/Models/DamagedHelmet/glTF-Binary/DamagedHelmet.glb';

// 1) A native three.ws artifact. This IS forge_free's structuredContent.spatial
//    for the prompt below, field for field.
const native = {
	spatialMcpVersion: '0.1',
	kind: 'model',
	scene: { glbUrl: FORGE_GLB, format: 'glb', alt: 'a weathered brass diving helmet with a riveted porthole' },
	camera: { autoRotate: true },
	environment: { image: 'neutral', exposure: 1, shadowIntensity: 1 },
	affordances: { orbit: true, zoom: true, fullscreen: true, download: true },
	meta: { title: 'Brass diving helmet', prompt: 'a weathered brass diving helmet, cracked glass porthole, verdigris patina' },
};

// 2) A FOREIGN tool result in some other server's shape…
const foreignResult = { model_url: FOREIGN_GLB, thumbnail: null, name: 'A helmet from another server' };

// …transformed into a conformant artifact by a 6-line adapter (the portability proof).
function toSpatialArtifact(foreign) {
	return {
		spatialMcpVersion: '0.1',
		kind: 'model',
		scene: { glbUrl: foreign.model_url, format: 'glb', ...(foreign.thumbnail ? { poster: foreign.thumbnail } : {}) },
		camera: { autoRotate: true },
		affordances: { orbit: true, zoom: true },
		meta: { title: foreign.name },
	};
}

const transformed = toSpatialArtifact(foreignResult);

// ── Conformance, on screen ───────────────────────────────────────────────────
// The page used to assert conformance in prose. Now every payload it renders is
// run through the real validator in the browser and the verdict is shown next to
// the scene, so the claim is demonstrated instead of stated.

/** A status pill. Text carries the meaning; colour only reinforces it. */
function chip(kind, label) {
	const el = document.createElement('span');
	el.className = `chip chip-${kind}`;
	el.textContent = `${kind === 'ok' ? '✓' : kind === 'err' ? '✕' : '!'} ${label}`;
	return el;
}

/** One `{ path, message }` diagnostic as a row. */
function diagnostic(kind, path, message) {
	const row = document.createElement('div');
	row.className = `diag diag-${kind}`;
	const code = document.createElement('code');
	code.textContent = path;
	const text = document.createElement('span');
	text.textContent = message;
	row.append(code, text);
	return row;
}

const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;

/**
 * Render the validator's verdict for `artifact` into `mount`.
 * @param {HTMLElement|null} mount
 * @param {any} artifact
 * @returns {{ valid:boolean, errors:Array, warnings:Array, version:(string|null) }}
 */
function renderVerdict(mount, artifact) {
	const result = validateSpatialArtifact(artifact);
	if (!mount) return result;
	mount.textContent = '';

	mount.appendChild(
		result.valid ? chip('ok', 'conformant, 0 errors') : chip('err', plural(result.errors.length, 'error', 'errors')),
	);
	if (result.warnings.length) mount.appendChild(chip('warn', plural(result.warnings.length, 'warning', 'warnings')));

	const version = document.createElement('span');
	version.textContent = `spatialMcpVersion ${result.version || 'missing'}`;
	mount.appendChild(version);
	return result;
}

renderSpatialArtifact(document.getElementById('stage-native'), native);
renderVerdict(document.getElementById('conf-native'), native);

renderSpatialArtifact(document.getElementById('stage-foreign'), transformed);
renderVerdict(document.getElementById('conf-foreign'), transformed);
document.getElementById('artifact-json').textContent = JSON.stringify(transformed, null, 2);

// ── The checker ──────────────────────────────────────────────────────────────
// Paste a tool result, see the verdict as you type, render it on demand. This is
// the part an implementer actually uses: it names the field to fix while they are
// writing the adapter, instead of making them read the spec and guess.

// Deliberately wrong in seven distinct ways, one per rule class the spec
// defines, so the diagnostics teach the shape rather than just rejecting the
// payload. The meta block violates data minimization on purpose: internal ids
// and payment fields must never ride in an artifact, and the lint says so.
const BROKEN_EXAMPLE = {
	spatialMcpVersion: '0.2',
	kind: 'hologram',
	scene: { glbUrl: 'http://three.ws/avatars/xbot.glb', format: 'usdz' },
	camera: { autoRotate: 'yes' },
	ar: { supported: true },
	meta: { title: 'ok to keep', session_id: 'sess_01HZY3', price_usd: '0.25' },
	metaa: { title: 'a typo in a top-level key' },
};

const PRESETS = { conformant: native, broken: BROKEN_EXAMPLE };

const input = document.getElementById('payload-input');
const report = document.getElementById('check-report');
const checkStage = document.getElementById('stage-check');

/** Parse the textarea. Returns the artifact, or a JSON syntax diagnostic. */
function readPayload() {
	const text = input.value.trim();
	if (!text) return { empty: true };
	try {
		return { artifact: JSON.parse(text) };
	} catch (e) {
		return { syntaxError: e.message };
	}
}

function review() {
	const parsed = readPayload();
	report.textContent = '';

	if (parsed.empty) {
		report.appendChild(diagnostic('note', '(paste a payload)', 'or load one of the examples above'));
		return null;
	}
	if (parsed.syntaxError) {
		report.appendChild(diagnostic('err', 'JSON', parsed.syntaxError));
		return null;
	}

	const result = validateSpatialArtifact(parsed.artifact);
	const pills = document.createElement('div');
	pills.className = 'report-pills';
	pills.appendChild(
		result.valid ? chip('ok', 'conformant, 0 errors') : chip('err', plural(result.errors.length, 'error', 'errors')),
	);
	if (result.warnings.length) pills.appendChild(chip('warn', plural(result.warnings.length, 'warning', 'warnings')));
	report.appendChild(pills);

	for (const e of result.errors) report.appendChild(diagnostic('err', e.path, e.message));
	for (const w of result.warnings) report.appendChild(diagnostic('warn', w.path, w.message));
	// Data minimization is a spec requirement the shape checks can't express:
	// internal ids, wallets, and prices must never ride in the artifact. Surface
	// the lint here so an emitter learns it while writing the adapter, not in a
	// store review.
	for (const p of lintSpatialMeta(parsed.artifact)) report.appendChild(diagnostic('warn', p.path, p.message));
	return { result, artifact: parsed.artifact };
}

// Validate as you type, cheaply. The validator is pure and synchronous, so a
// short debounce is only there to keep keystrokes from re-rendering the report.
let debounce;
input.addEventListener('input', () => {
	clearTimeout(debounce);
	debounce = setTimeout(review, 200);
});

for (const button of document.querySelectorAll('[data-preset]')) {
	button.addEventListener('click', () => {
		input.value = JSON.stringify(PRESETS[button.dataset.preset], null, 2);
		review();
		// Renders on load for the conformant preset; for the broken one the
		// renderer's fallback is exactly what a host would show, which is the point.
		renderSpatialArtifact(checkStage, PRESETS[button.dataset.preset]);
	});
}

document.getElementById('check-render').addEventListener('click', () => {
	const reviewed = review();
	renderSpatialArtifact(checkStage, reviewed ? reviewed.artifact : null);
});

// Start populated so the section is useful before a single click, and so the
// empty state is never the first thing a visitor meets.
input.value = JSON.stringify(native, null, 2);
review();
renderSpatialArtifact(checkStage, native);