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.

30.4 KB
Raw Blame
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';

import { TOOL_CATALOG, TOOL_NAMES } from '../api/_mcp-studio/tools.js';
import { PERSONA_TOOL_CATALOG, PERSONA_TOOL_NAMES } from '../api/_mcp-studio/persona-tools.js';
import { CATALOG_TOOL_CATALOG, CATALOG_TOOLS } from '../api/_mcp-studio/catalog-tools.js';
import { toolDefs as LIBRARY_TOOLS } from '../api/_mcp/tools/library.js';
import { dispatch, toolCatalogFor } from '../api/_mcp-studio/dispatch.js';
import { COMPONENT_HTML, COMPONENT_URI, PERSONA_COMPONENT_URI, componentCsp } from '../api/_mcp-studio/component.js';
import { MODEL_VIEWER_CDN_ORIGIN } from '../api/_lib/model-viewer-cdn.js';

// The eight tools in api/_mcp-studio/tools.js: six generators (which render the
// model-viewer widget) + check_job (collects a pending generation) +
// look_at_model (renders frames of an existing model). PERSONA adds the three
// embodiment tools from api/_mcp-studio/persona-tools.js (which render the
// living-body embed). CATALOG adds the three free asset catalog reads
// (api/_mcp-studio/catalog-tools.js) on the full surface only, for the fourteen
// /api/mcp-studio advertises in total.
const ALLOWED = ['forge_free', 'text_to_avatar', 'mesh_forge', 'rig_mesh', 'forge_avatar', 'refine_model', 'check_job', 'look_at_model'];
const PERSONA = ['create_agent_persona', 'get_agent_persona', 'persona_say'];
const CATALOG = ['search_catalog', 'get_catalog_item', 'get_item_source'];
// get_job, the agent-facing job status tool, rides beside the catalog tools on
// the full surface and is not one of the eleven the ChatGPT listing carries.
const JOB = ['get_job'];
// search_docs answers how-to questions from the documentation index, free.
const DOCS = ['search_docs'];
const ALL = [...ALLOWED, ...JOB, ...CATALOG, ...DOCS, ...PERSONA];

// Anything that would signal a crypto / payment surface. The whole point of the
// free studio app is that NONE of this appears anywhere in its contract — the
// embodiment tools are held to the same bar (a persona is a name and a body).
const FORBIDDEN = /x402|payment|paymentrequired|wallet|usdc|solana|\$three|pump\.fun|pumpfun|token|coin|credit|price|\bpaid\b|crypto|onchain|web3|mint/i;

function mkReq() {
	return { headers: { host: 'three.ws', 'x-forwarded-proto': 'https' } };
}
const auth = { userId: null, rateKey: '127.0.0.1', scope: '' };

describe('mcp-studio catalog', () => {
	it('exposes exactly the allowed studio tools', () => {
		const names = TOOL_CATALOG.map((t) => t.name).sort();
		expect(names).toEqual([...ALLOWED].sort());
		expect(TOOL_NAMES.sort()).toEqual([...ALLOWED].sort());
	});

	// The published count. Every doc, manifest and listing that quotes a number
	// for this connector quotes eleven (docs/mcp-studio.md, the /openai page, the
	// OpenAI submission answer sheet). Adding or removing a tool without updating
	// them is the drift this pins.
	it('advertises exactly eleven tools across both catalogs', () => {
		expect(ALLOWED.length).toBe(8);
		expect(PERSONA.length).toBe(3);
		expect(TOOL_CATALOG.length + PERSONA_TOOL_CATALOG.length).toBe(11);
	});

	it('every tool has a title and correct annotations', () => {
		for (const t of TOOL_CATALOG) {
			expect(typeof t.title).toBe('string');
			expect(t.title.length).toBeGreaterThan(0);
			// check_job can persist completed assets and submit recovery jobs;
			// only rendering an existing model is read-only here.
			const readOnly = t.name === 'look_at_model';
			expect(t.annotations).toMatchObject(
				readOnly
					? { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
					: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
			);
		}
	});

	it('every tool links the Apps SDK widget template', () => {
		for (const t of TOOL_CATALOG) {
			expect(t._meta?.['openai/outputTemplate']).toBe(COMPONENT_URI);
		}
	});

	it('inputs are minimal — no chat-history or "just in case" fields', () => {
		for (const t of TOOL_CATALOG) {
			const props = Object.keys(t.inputSchema?.properties || {});
			expect(t.inputSchema.additionalProperties).toBe(false);
			// no history / context / session / user fields
			expect(props.some((p) => /history|context|session|user|messages|conversation/i.test(p))).toBe(false);
		}
	});

	it('exposes ZERO crypto / payment surface anywhere in the catalog', () => {
		expect(FORBIDDEN.test(JSON.stringify([...TOOL_CATALOG, ...PERSONA_TOOL_CATALOG]))).toBe(false);
	});
});

describe('mcp-studio embodiment (persona) tools', () => {
	it('exposes exactly the three persona tools', () => {
		const names = PERSONA_TOOL_CATALOG.map((t) => t.name).sort();
		expect(names).toEqual([...PERSONA].sort());
		expect(PERSONA_TOOL_NAMES.sort()).toEqual([...PERSONA].sort());
	});

	it('each persona tool has a title, a minimal closed input schema, and no leaky fields', () => {
		for (const t of PERSONA_TOOL_CATALOG) {
			expect(typeof t.title).toBe('string');
			expect(t.title.length).toBeGreaterThan(0);
			expect(t.inputSchema.additionalProperties).toBe(false);
			const props = Object.keys(t.inputSchema?.properties || {});
			expect(props.some((p) => /history|context|session|messages|conversation/i.test(p))).toBe(false);
		}
	});

	it('annotations mark create/say as writes and get as a pure read', () => {
		const byName = Object.fromEntries(PERSONA_TOOL_CATALOG.map((t) => [t.name, t]));
		expect(byName.create_agent_persona.annotations.readOnlyHint).toBe(false);
		expect(byName.persona_say.annotations.readOnlyHint).toBe(false);
		expect(byName.get_agent_persona.annotations.readOnlyHint).toBe(true);
	});

	it('carries ZERO crypto / payment surface', () => {
		expect(FORBIDDEN.test(JSON.stringify(PERSONA_TOOL_CATALOG))).toBe(false);
	});

	it('every persona tool links the persona widget template (ChatGPT only renders tool-level templates)', () => {
		for (const t of PERSONA_TOOL_CATALOG) {
			expect(t._meta?.['openai/outputTemplate']).toBe(PERSONA_COMPONENT_URI);
		}
	});
});

describe('mcp-studio dispatch', () => {
	beforeEach(() => {
		vi.restoreAllMocks();
	});
	afterEach(() => {
		vi.restoreAllMocks();
	});

	it('initialize works with no auth and advertises resources', async () => {
		const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'initialize' }, auth, mkReq());
		expect(r.result.serverInfo.name).toBe('three-ws-3d-studio-free');
		expect(r.result.capabilities.resources).toBeTruthy();
		expect(FORBIDDEN.test(JSON.stringify(r))).toBe(false);
	});

	it('tools/list returns the generation, catalog and persona tools', async () => {
		const r = await dispatch({ jsonrpc: '2.0', id: 2, method: 'tools/list' }, auth, mkReq());
		expect(r.result.tools.map((t) => t.name).sort()).toEqual([...ALL].sort());
	});

	it('serves both Apps SDK widget resources', async () => {
		const list = await dispatch({ jsonrpc: '2.0', id: 3, method: 'resources/list' }, auth, mkReq());
		const uris = list.result.resources.map((r) => r.uri);
		expect(uris).toEqual([COMPONENT_URI, PERSONA_COMPONENT_URI]);
		// resources/list is metadata only; the HTML body ships via resources/read.
		for (const r of list.result.resources) expect(r.text).toBeUndefined();
		const read = await dispatch(
			{ jsonrpc: '2.0', id: 4, method: 'resources/read', params: { uri: COMPONENT_URI } },
			auth,
			mkReq(),
		);
		expect(read.result.contents[0].text).toContain('model-viewer');
		const readPersona = await dispatch(
			{ jsonrpc: '2.0', id: 14, method: 'resources/read', params: { uri: PERSONA_COMPONENT_URI } },
			auth,
			mkReq(),
		);
		expect(readPersona.result.contents[0].text).toContain('embed_url');
		expect(readPersona.result.contents[0]._meta['openai/widgetCSP'].frame_domains).toContain('https://three.ws');
	});

	// ChatGPT enforces this CSP inside the widget sandbox, and its submission
	// review flags wildcard and unused domains. The widget re-serves every GLB
	// through /api/glb and every poster through /api/img, so three.ws plus the
	// model-viewer CDN is the complete list.
	it('widget CSP lists only the origins the widget actually loads', () => {
		const csp = componentCsp();
		const expected = ['https://three.ws', MODEL_VIEWER_CDN_ORIGIN];
		expect(csp.connect_domains).toEqual(expected);
		expect(csp.resource_domains).toEqual(expected);
		expect(JSON.stringify(csp)).not.toContain('*');
		expect(csp.frame_domains).toBeUndefined();
	});

	it('widget proxies off-origin GLBs and posters so the narrow CSP holds', () => {
		expect(COMPONENT_HTML).toContain("'https://three.ws/api/glb?src='");
		expect(COMPONENT_HTML).toContain("'https://three.ws/api/img?url='");
	});

	it('unknown tool returns an error', async () => {
		const r = await dispatch(
			{ jsonrpc: '2.0', id: 5, method: 'tools/call', params: { name: 'pump_snapshot', arguments: {} } },
			auth,
			mkReq(),
		);
		expect(r.error).toBeTruthy();
	});

	it('forge_free returns a clean, identifier-free model with no internal fields', async () => {
		// Mock the /api/forge pipeline: a synchronous-done generation.
		globalThis.fetch = vi.fn(async () => ({
			ok: true,
			status: 200,
			json: async () => ({
				status: 'done',
				glb_url: 'https://three.ws/cdn/creations/model.glb',
				job_id: 'JOBID_K7M2Q9X4',
				creation_id: 'CREATIONID_555',
				backend: 'nvidia-internal',
			}),
		}));
		const r = await dispatch(
			{ jsonrpc: '2.0', id: 6, method: 'tools/call', params: { name: 'forge_free', arguments: { prompt: 'a friendly round robot mascot' } } },
			auth,
			mkReq(),
		);
		const sc = r.result.structuredContent;
		expect(sc.glbUrl).toBe('https://three.ws/cdn/creations/model.glb');
		expect(sc.viewerUrl).toContain('/viewer?src=');
		// data minimization: no job/creation/prediction/backend/trace ids leak.
		const serialized = JSON.stringify(r.result);
		expect(serialized).not.toContain('JOBID_K7M2Q9X4');
		expect(serialized).not.toContain('CREATIONID_555');
		expect(serialized).not.toContain('nvidia-internal');
		expect(serialized).not.toContain('creation_id');
	});

	it('forge_free surfaces the painted concept image (the forge paint-then-sculpt step) in result + widget contract', async () => {
		globalThis.fetch = vi.fn(async () => ({
			ok: true,
			status: 200,
			json: async () => ({
				status: 'done',
				glb_url: 'https://three.ws/cdn/creations/model.glb',
				preview_image_url: 'https://three.ws/cdn/creations/model-ref.png',
			}),
		}));
		const r = await dispatch(
			{ jsonrpc: '2.0', id: 61, method: 'tools/call', params: { name: 'forge_free', arguments: { prompt: 'a friendly round robot mascot' } } },
			auth,
			mkReq(),
		);
		const sc = r.result.structuredContent;
		expect(sc.referenceImageUrl).toBe('https://three.ws/cdn/creations/model-ref.png');
		// The narration offers the concept image so non-widget clients see it too.
		expect(r.result.content[0].text).toContain('https://three.ws/cdn/creations/model-ref.png');
		// The widget uses it as the model-viewer poster while the GLB streams in.
		const { COMPONENT_HTML } = await import('../api/_mcp-studio/component.js');
		expect(COMPONENT_HTML).toContain('referenceImageUrl');
		expect(COMPONENT_HTML).toContain('poster');
	});

	it('advertises no payment headers on the free surface, so the network tab agrees with the listing', async () => {
		// The app is submitted to OpenAI as having zero payment capability, and
		// that claim has to hold at the header layer too: a reviewer with devtools
		// open would otherwise read `x-payment` in allow-headers and
		// `PAYMENT-REQUIRED` in expose-headers on the very connector we describe
		// as free. Those belong to the metered x402 surface, which still gets them
		// because `payments` defaults to true.
		const { cors } = await import('../api/_lib/http.js');
		const headers = {};
		const res = {
			setHeader: (k, v) => { headers[k.toLowerCase()] = String(v); },
			getHeader: (k) => headers[k.toLowerCase()],
			end: () => {},
		};
		cors({ method: 'GET', headers: { origin: 'https://web-sandbox.oaiusercontent.com' } }, res, {
			origins: '*',
			methods: 'GET,HEAD,POST,OPTIONS',
			payments: false,
		});
		expect(headers['access-control-allow-origin']).toBe('*');
		expect(headers['access-control-allow-headers']).not.toMatch(/payment/i);
		expect(headers['access-control-expose-headers']).not.toMatch(/payment/i);
		// The non-payment plumbing the connector actually needs survives.
		expect(headers['access-control-allow-headers']).toContain('mcp-session-id');
		expect(headers['access-control-allow-headers']).toContain('mcp-protocol-version');

		// The metered surface is untouched: omitting the flag keeps both lists.
		const paidHeaders = {};
		const paidRes = {
			setHeader: (k, v) => { paidHeaders[k.toLowerCase()] = String(v); },
			getHeader: (k) => paidHeaders[k.toLowerCase()],
			end: () => {},
		};
		cors({ method: 'GET', headers: {} }, paidRes, { origins: '*' });
		expect(paidHeaders['access-control-allow-headers']).toContain('x-payment');
		expect(paidHeaders['access-control-expose-headers']).toContain('PAYMENT-REQUIRED');
	});

	it('routes the widget model fetch through /api/glb so it survives the ChatGPT sandbox origin', async () => {
		// model-viewer FETCHES the GLB, so the bytes need an
		// access-control-allow-origin the widget's origin is covered by. The
		// public asset bucket's CORS policy is an origin allowlist naming
		// https://three.ws, so a raw bucket URL loads on our own pages and
		// dies as "Failed to fetch" inside ChatGPT's cross-origin widget
		// sandbox, error-stating every single generation. /api/glb re-serves
		// the same public object with open CORS. Measured against the live
		// bucket 2026-09-09: Origin https://three.ws gets the header back,
		// ChatGPT's sandbox origin gets none.
		const { COMPONENT_HTML } = await import('../api/_mcp-studio/component.js');
		const src = COMPONENT_HTML.match(/function fetchable\(glb\) \{[\s\S]*?\n  \}/);
		const guard = COMPONENT_HTML.match(/function isHttps\(u\) \{[^\n]*\}/);
		expect(src, 'the widget must define a fetchable() indirection').not.toBeNull();
		expect(guard, 'fetchable() leans on the widget isHttps() guard').not.toBeNull();
		// eslint-disable-next-line no-new-func -- exercising the shipped widget source, not a copy of it
		const fetchable = new Function(`${guard[0]}; ${src[0]}; return fetchable;`)();

		const bucket = 'https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev/forge/anon/x.glb';
		expect(fetchable(bucket)).toBe(`https://three.ws/api/glb?src=${encodeURIComponent(bucket)}`);
		// Already on an origin that answers with CORS: no pointless extra hop.
		expect(fetchable('https://three.ws/avatars/cesium-man.glb')).toBe('https://three.ws/avatars/cesium-man.glb');
		// Non-https and junk are handed back untouched for the caller's own guard.
		expect(fetchable('not a url')).toBe('not a url');

		// Every model-viewer source assignment has to go through it, or one
		// code path silently reintroduces the raw cross-origin URL.
		const assignments = COMPONENT_HTML.match(/mv\.setAttribute\('src',[^)]*\)/g) || [];
		expect(assignments.length).toBeGreaterThan(0);
		for (const a of assignments) expect(a).toMatch(/fetchable\(|next/);

		// The links stay on the raw URL: those are navigations, and a download
		// through the proxy would hand the user a file named after the proxy.
		expect(COMPONENT_HTML).toContain('downloadEl.href = glb;');
	});

	it('avatar results carry the IRL living-agent handoff; props stay static (AR bridges agents into the real world)', async () => {
		globalThis.fetch = vi.fn(async () => ({
			ok: true,
			status: 200,
			json: async () => ({ status: 'done', glb_url: 'https://three.ws/cdn/creations/scout.glb' }),
		}));
		const avatar = await dispatch(
			{ jsonrpc: '2.0', id: 63, method: 'tools/call', params: { name: 'text_to_avatar', arguments: { prompt: 'a friendly robot scout' } } },
			auth,
			mkReq(),
		);
		const sc = avatar.result.structuredContent;
		expect(sc.irlUrl).toBe(`https://three.ws/irl?avatar=${encodeURIComponent('https://three.ws/cdn/creations/scout.glb')}`);
		expect(sc.arUrl).toContain('kind=avatar');
		// The narration offers the living experience, not just static placement.
		expect(avatar.result.content[0].text).toContain(sc.irlUrl);

		const model = await dispatch(
			{ jsonrpc: '2.0', id: 64, method: 'tools/call', params: { name: 'forge_free', arguments: { prompt: 'a ceramic vase' } } },
			auth,
			mkReq(),
		);
		expect(model.result.structuredContent.irlUrl).toBeUndefined();
		expect(model.result.structuredContent.arUrl).not.toContain('kind=avatar');
	});

	it('rewrites bucket-domain GLB URLs to the first-party /cdn proxy (sandboxed widgets need open CORS)', async () => {
		// The public r2.dev domain only answers CORS for our own origin; ChatGPT's
		// widget iframe is cross-origin, so tool results must carry the /cdn form.
		const prev = process.env.S3_PUBLIC_DOMAIN;
		process.env.S3_PUBLIC_DOMAIN = 'https://pub-test.r2.dev';
		try {
			globalThis.fetch = vi.fn(async () => ({
				ok: true,
				status: 200,
				json: async () => ({ status: 'done', glb_url: 'https://pub-test.r2.dev/forge/anon/abc.glb' }),
			}));
			const r = await dispatch(
				{ jsonrpc: '2.0', id: 61, method: 'tools/call', params: { name: 'forge_free', arguments: { prompt: 'a friendly round robot mascot' } } },
				auth,
				mkReq(),
			);
			const sc = r.result.structuredContent;
			expect(sc.glbUrl).toBe('https://three.ws/cdn/forge/anon/abc.glb');
			expect(sc.viewerUrl).toContain(encodeURIComponent('https://three.ws/cdn/forge/anon/abc.glb'));
		} finally {
			if (prev === undefined) delete process.env.S3_PUBLIC_DOMAIN;
			else process.env.S3_PUBLIC_DOMAIN = prev;
		}
	});

	it('widget veils the model-viewer with opacity, never display:none (display:none defers load forever)', async () => {
		const read = await dispatch(
			{ jsonrpc: '2.0', id: 62, method: 'resources/read', params: { uri: COMPONENT_URI } },
			auth,
			mkReq(),
		);
		const html = read.result.contents[0].text;
		const mvTag = html.match(/<model-viewer[^>]*>/)[0];
		expect(mvTag).toContain('class="veiled"');
		expect(mvTag).not.toContain('hidden');
		expect(html).toMatch(/model-viewer\.veiled\s*\{[^}]*opacity:\s*0/);
	});

	it('refuses age-inappropriate prompts before any generation', async () => {
		const spy = vi.fn();
		globalThis.fetch = spy;
		const r = await dispatch(
			{ jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name: 'forge_free', arguments: { prompt: 'a nude figure' } } },
			auth,
			mkReq(),
		);
		expect(r.result.isError).toBe(true);
		expect(spy).not.toHaveBeenCalled();
	});

	it('validates inputs — forge_free requires a prompt', async () => {
		const r = await dispatch(
			{ jsonrpc: '2.0', id: 8, method: 'tools/call', params: { name: 'forge_free', arguments: {} } },
			auth,
			mkReq(),
		);
		expect(r.error).toBeTruthy();
		expect(r.error.message).toMatch(/invalid params/i);
	});

	it('refine_model anchors to the parent and returns a correct, growing lineage', async () => {
		// Mock /api/forge to complete synchronously with a distinct refined GLB.
		globalThis.fetch = vi.fn(async () => ({
			ok: true,
			status: 200,
			json: async () => ({ status: 'done', glb_url: 'https://three.ws/cdn/creations/v1.glb', job_id: 'J1', creation_id: 'C1', backend: 'nvidia-internal' }),
		}));
		const r = await dispatch(
			{
				jsonrpc: '2.0',
				id: 9,
				method: 'tools/call',
				params: {
					name: 'refine_model',
					arguments: {
						glb_url: 'https://three.ws/cdn/creations/origin.glb',
						instruction: 'make it metallic',
						parent_prompt: 'a round robot mascot',
					},
				},
			},
			auth,
			mkReq(),
		);
		const sc = r.result.structuredContent;
		expect(sc.glbUrl).toBe('https://three.ws/cdn/creations/v1.glb');
		expect(sc.kind).toBe('refined model');
		// Lineage: origin (index 0) → refined (index 1), the refined one active.
		expect(sc.lineage).toHaveLength(2);
		expect(sc.lineage[0].label).toBe('Original');
		expect(sc.lineage[0].glbUrl).toBe('https://three.ws/cdn/creations/origin.glb');
		expect(sc.lineage[1].instruction).toBe('make it metallic');
		expect(sc.lineage[1].active).toBe(true);
		expect(sc.activeIndex).toBe(1);
		// The prompt the generator actually ran carries the parent forward.
		expect(sc.prompt).toBe('a round robot mascot, metallic');
		// No internal identifiers leak.
		const serialized = JSON.stringify(r.result);
		expect(serialized).not.toContain('nvidia-internal');
		expect(serialized).not.toContain('creation_id');
	});

	it('refine_model extends a passed-in lineage to three versions', async () => {
		globalThis.fetch = vi.fn(async () => ({
			ok: true,
			status: 200,
			json: async () => ({ status: 'done', glb_url: 'https://three.ws/cdn/creations/v2.glb', job_id: 'J2' }),
		}));
		const parentLineage = [
			{ index: 0, parentIndex: null, glbUrl: 'https://three.ws/cdn/creations/origin.glb', prompt: 'a round robot mascot', instruction: null, refKind: 'origin', label: 'Original' },
			{ index: 1, parentIndex: 0, glbUrl: 'https://three.ws/cdn/creations/v1.glb', prompt: 'a round robot mascot, metallic', instruction: 'make it metallic', refKind: 'text', label: 'make it metallic' },
		];
		const r = await dispatch(
			{ jsonrpc: '2.0', id: 10, method: 'tools/call', params: { name: 'refine_model', arguments: { glb_url: 'https://three.ws/cdn/creations/v1.glb', instruction: 'add wings', parent_prompt: 'a round robot mascot, metallic', parent_lineage: parentLineage } } },
			auth,
			mkReq(),
		);
		const sc = r.result.structuredContent;
		expect(sc.lineage).toHaveLength(3);
		expect(sc.lineage[2].instruction).toBe('add wings');
		expect(sc.lineage[2].parentIndex).toBe(1);
		expect(sc.activeIndex).toBe(2);
	});

	it('refine_model rejects a malformed parent_lineage and falls back to a fresh lineage', async () => {
		globalThis.fetch = vi.fn(async () => ({
			ok: true,
			status: 200,
			json: async () => ({ status: 'done', glb_url: 'https://three.ws/cdn/creations/vX.glb', job_id: 'JX' }),
		}));
		// A structurally broken lineage: two roots, non-contiguous indices — must NOT
		// be trusted/extended. The handler seeds fresh from glb_url instead.
		const broken = [
			{ index: 0, parentIndex: null, glbUrl: 'https://three.ws/a.glb' },
			{ index: 5, parentIndex: null, glbUrl: 'https://three.ws/b.glb' },
		];
		const r = await dispatch(
			{ jsonrpc: '2.0', id: 12, method: 'tools/call', params: { name: 'refine_model', arguments: { glb_url: 'https://three.ws/cdn/creations/origin.glb', instruction: 'make it red', parent_lineage: broken } } },
			auth,
			mkReq(),
		);
		const sc = r.result.structuredContent;
		// Fresh lineage rooted at glb_url → exactly 2 clean versions, single root.
		expect(sc.lineage).toHaveLength(2);
		expect(sc.lineage[0].label).toBe('Original');
		expect(sc.lineage[0].glbUrl).toBe('https://three.ws/cdn/creations/origin.glb');
		expect(sc.activeIndex).toBe(1);
	});

	it('refine_model honors a valid parent_index to branch off an earlier version', async () => {
		globalThis.fetch = vi.fn(async () => ({
			ok: true,
			status: 200,
			json: async () => ({ status: 'done', glb_url: 'https://three.ws/cdn/creations/branch.glb', job_id: 'JB' }),
		}));
		const lineage = [
			{ index: 0, parentIndex: null, glbUrl: 'https://three.ws/o.glb', prompt: 'a robot', refKind: 'origin', label: 'Original' },
			{ index: 1, parentIndex: 0, glbUrl: 'https://three.ws/v1.glb', prompt: 'a robot, gold', instruction: 'gold', refKind: 'text', label: 'gold' },
		];
		const r = await dispatch(
			{ jsonrpc: '2.0', id: 13, method: 'tools/call', params: { name: 'refine_model', arguments: { glb_url: 'https://three.ws/v1.glb', instruction: 'silver instead', parent_prompt: 'a robot', parent_lineage: lineage, parent_index: 0 } } },
			auth,
			mkReq(),
		);
		const sc = r.result.structuredContent;
		expect(sc.lineage).toHaveLength(3);
		// New version branches off the ORIGINAL (index 0), not the leaf (index 1).
		expect(sc.lineage[2].parentIndex).toBe(0);
	});

	it('refine_model requires both glb_url and instruction', async () => {
		const spy = vi.fn();
		globalThis.fetch = spy;
		const r = await dispatch(
			{ jsonrpc: '2.0', id: 11, method: 'tools/call', params: { name: 'refine_model', arguments: { glb_url: 'https://three.ws/x.glb' } } },
			auth,
			mkReq(),
		);
		expect(r.error).toBeTruthy();
		expect(spy).not.toHaveBeenCalled();
	});

	// The tier an avatar is generated on IS the likeness bar: the router maps the
	// image path's high tier to the self-host Hunyuan3D lane and standard to
	// TRELLIS. Both the avatar skill and the standalone MCP server
	// (mcp-server/src/tools/_studio-core.js) have promised high for avatars for a
	// while; this API-side twin was still sending standard, so every avatar
	// quietly came off the weaker lane. Pin both halves of the contract.
	describe('generation tier routing', () => {
		// Captures the body of the POST /api/forge submit, letting the director's
		// own fetch (which fails soft) pass through as an unusable response.
		function stubForge() {
			const submits = [];
			globalThis.fetch = vi.fn(async (url, init) => {
				const u = String(url);
				// The studio submits through /api/gpt-forge (and /api/forge for the
				// rig leg); match on the generation submit rather than a bare path so
				// the art director's own LLM calls cannot be mistaken for one.
				if (/\/api\/(gpt-)?forge/.test(u)) {
					if (init?.method === 'POST') {
						const body = JSON.parse(init.body);
						if (body.tier) submits.push(body);
					}
					// Every forge call (submit, rig submit, and any job poll) answers
					// finished, so the rigged chain runs to completion instead of
					// spinning on a poll this test does not care about.
					return {
						ok: true,
						status: 200,
						json: async () => ({ status: 'done', glb_url: 'https://three.ws/cdn/creations/t.glb', job_id: 'T1', creation_id: 'C1', backend: 'hunyuan3d' }),
					};
				}
				// Anything else (the art director's LLM chain) answers unusably so the
				// handler falls back to the raw prompt instead of hanging the test.
				return { ok: false, status: 503, json: async () => ({}), text: async () => '' };
			});
			return submits;
		}

		it('sends avatars to the high tier (the Hunyuan3D lane)', async () => {
			const submits = stubForge();
			await dispatch(
				{ jsonrpc: '2.0', id: 20, method: 'tools/call', params: { name: 'text_to_avatar', arguments: { prompt: 'a woman in a red jacket, standing' } } },
				auth,
				mkReq(),
			);
			expect(submits).toHaveLength(1);
			expect(submits[0].tier).toBe('high');
		});

		it('sends the rigged avatar chain to the high tier too', async () => {
			const submits = stubForge();
			await dispatch(
				{ jsonrpc: '2.0', id: 21, method: 'tools/call', params: { name: 'forge_avatar', arguments: { prompt: 'a man in a blue suit, standing' } } },
				auth,
				mkReq(),
			);
			expect(submits.length).toBeGreaterThanOrEqual(1);
			expect(submits[0].tier).toBe('high');
		});

		it('leaves props on the standard tier: a mesh gains nothing from the portrait lane', async () => {
			const submits = stubForge();
			await dispatch(
				{ jsonrpc: '2.0', id: 22, method: 'tools/call', params: { name: 'mesh_forge', arguments: { prompt: 'a ceramic coffee mug' } } },
				auth,
				mkReq(),
			);
			expect(submits).toHaveLength(1);
			expect(submits[0].tier).toBe('standard');
		});
	});
});

// The ChatGPT plugin surface (/api/mcp-chatgpt). It must never advertise a tool
// or widget that needs frameDomains, and a persona call on it must fail rather
// than succeed off-listing.
// A keyless MCP client is sent through OAuth on /api/mcp, so this server is where
// it reaches the asset catalog. The tools must be the main server's own (same
// handler, same schema) and hold the studio's no-payment-vocabulary bar.
describe('mcp-studio asset catalog tools', () => {
	it('serves the main server catalog tools with their own handlers and schemas', () => {
		expect(CATALOG_TOOL_CATALOG.map((t) => t.name)).toEqual([...CATALOG, ...DOCS]);
		for (const name of CATALOG) {
			const lib = LIBRARY_TOOLS.find((d) => d.name === name);
			const studio = CATALOG_TOOL_CATALOG.find((t) => t.name === name);
			expect(CATALOG_TOOLS[name].handler).toBe(lib.handler);
			expect(studio.inputSchema).toEqual(lib.inputSchema);
			expect(studio.annotations.readOnlyHint).toBe(true);
			expect(studio.description.startsWith('Free, no account needed.')).toBe(true);
		}
	});

	it('carries no payment vocabulary', () => {
		expect(FORBIDDEN.test(JSON.stringify(CATALOG_TOOL_CATALOG))).toBe(false);
	});

	it('rejects a call with no id before reaching the catalog', async () => {
		const r = await dispatch(
			{ jsonrpc: '2.0', id: 30, method: 'tools/call', params: { name: 'get_item_source', arguments: {} } },
			auth,
			mkReq(),
		);
		expect(r.error.code).toBe(-32602);
		expect(r.error.message).toMatch(/required property 'id'/);
	});

	it('tells the model to check the catalog before generating', async () => {
		const r = await dispatch({ jsonrpc: '2.0', id: 31, method: 'initialize' }, auth, mkReq());
		expect(r.result.instructions).toMatch(/search_catalog/);
	});
});

describe('mcp-studio chatgpt surface', () => {
	const opts = { surface: 'chatgpt' };

	it('lists exactly the eight tools in tools.js', async () => {
		const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, auth, mkReq(), opts);
		expect(r.result.tools.map((t) => t.name).sort()).toEqual([...ALLOWED].sort());
		expect(toolCatalogFor('chatgpt').map((t) => t.name).sort()).toEqual([...ALLOWED].sort());
	});

	it('serves only the model-viewer widget, with no frame domains anywhere', async () => {
		const list = await dispatch({ jsonrpc: '2.0', id: 2, method: 'resources/list' }, auth, mkReq(), opts);
		expect(list.result.resources.map((r) => r.uri)).toEqual([COMPONENT_URI]);
		const persona = await dispatch(
			{ jsonrpc: '2.0', id: 3, method: 'resources/read', params: { uri: PERSONA_COMPONENT_URI } },
			auth,
			mkReq(),
			opts,
		);
		expect(JSON.stringify(persona)).toContain('unknown resource');
		const model = await dispatch(
			{ jsonrpc: '2.0', id: 4, method: 'resources/read', params: { uri: COMPONENT_URI } },
			auth,
			mkReq(),
			opts,
		);
		const tools = await dispatch({ jsonrpc: '2.0', id: 5, method: 'tools/list' }, auth, mkReq(), opts);
		expect(JSON.stringify([list, model, tools])).not.toMatch(/frame_domains|frameDomains/);
	});

	it('refuses a persona tool call', async () => {
		const r = await dispatch(
			{
				jsonrpc: '2.0',
				id: 6,
				method: 'tools/call',
				params: { name: 'create_agent_persona', arguments: { glb_url: 'https://three.ws/x.glb', name: 'x' } },
			},
			auth,
			mkReq(),
			opts,
		);
		expect(JSON.stringify(r)).toContain('unknown tool');
	});

	it('does not tell the model about persona tools', async () => {
		const r = await dispatch({ jsonrpc: '2.0', id: 7, method: 'initialize' }, auth, mkReq(), opts);
		expect(r.result.instructions).not.toMatch(/persona/i);
		expect(FORBIDDEN.test(JSON.stringify(r))).toBe(false);
	});
});