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: add model validation, inspection, and optimization functionalities

nirholasace069158cb7
diff --git a/api/_lib/fetch-model.js b/api/_lib/fetch-model.js
new file mode 100644
index 000000000..34c6ea3c9
--- /dev/null
+++ b/api/_lib/fetch-model.js
@@ -0,0 +1,185 @@
+// SSRF-hardened model fetcher.
+//
+// Arbitrary URL fetching from a server reachable by the internet is a classic
+// SSRF vector: an attacker can point "url" at internal metadata endpoints
+// (169.254.169.254 on AWS/GCP), private RFC1918 ranges, or loopback and we'd
+// happily proxy the response back to them. Defenses here:
+// 1. Scheme allowlist — only https by default (http permitted in dev).
+// 2. DNS resolution happens on OUR side, and the resolved address is
+// checked against an IP blocklist before the connection is opened.
+// 3. Follow redirects manually, re-validating the target host each hop.
+// 4. Size limit — we stop reading after N bytes.
+// 5. Timeout — total request + streaming is bounded.
+
+import { lookup } from 'node:dns/promises';
+import { env } from './env.js';
+
+const DEFAULT_MAX_BYTES = 50 * 1024 * 1024; // 50 MB
+const DEFAULT_TIMEOUT_MS = 20_000;
+const MAX_REDIRECTS = 3;
+
+const IS_DEV = env.NODE_ENV !== 'production';
+
+export class FetchModelError extends Error {
+ constructor(message, code = 'fetch_failed') {
+ super(message);
+ this.code = code;
+ }
+}
+
+function isPrivateIPv4(ip) {
+ const p = ip.split('.').map(Number);
+ if (p.length !== 4 || p.some((n) => Number.isNaN(n))) return true;
+ if (p[0] === 10) return true;
+ if (p[0] === 127) return true;
+ if (p[0] === 0) return true;
+ if (p[0] === 169 && p[1] === 254) return true; // link-local, cloud metadata
+ if (p[0] === 172 && p[1] >= 16 && p[1] <= 31) return true;
+ if (p[0] === 192 && p[1] === 168) return true;
+ if (p[0] === 192 && p[1] === 0 && p[2] === 0) return true; // IETF
+ if (p[0] === 192 && p[1] === 0 && p[2] === 2) return true; // docs
+ if (p[0] === 198 && (p[1] === 18 || p[1] === 19)) return true; // benchmark
+ if (p[0] === 198 && p[1] === 51 && p[2] === 100) return true; // docs
+ if (p[0] === 203 && p[1] === 0 && p[2] === 113) return true; // docs
+ if (p[0] >= 224) return true; // multicast + reserved
+ return false;
+}
+
+function isPrivateIPv6(ip) {
+ const lower = ip.toLowerCase();
+ if (lower === '::' || lower === '::1') return true;
+ if (lower.startsWith('fe80:') || lower.startsWith('fe80::')) return true; // link-local
+ if (lower.startsWith('fc') || lower.startsWith('fd')) return true; // ULA fc00::/7
+ if (lower.startsWith('::ffff:')) {
+ const mapped = lower.replace(/^::ffff:/, '');
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(mapped)) return isPrivateIPv4(mapped);
+ }
+ if (lower.startsWith('2001:db8:')) return true; // docs
+ return false;
+}
+
+async function assertPublicHost(host) {
+ if (!host) throw new FetchModelError('missing host', 'invalid_url');
+ let resolved;
+ try {
+ resolved = await lookup(host, { all: true });
+ } catch (e) {
+ throw new FetchModelError(`DNS lookup failed for ${host}`, 'dns_failed');
+ }
+ const addrs = Array.isArray(resolved) ? resolved : [resolved];
+ for (const { address, family } of addrs) {
+ if (family === 4 && isPrivateIPv4(address)) {
+ throw new FetchModelError(`host resolves to private address: ${address}`, 'private_address');
+ }
+ if (family === 6 && isPrivateIPv6(address)) {
+ throw new FetchModelError(`host resolves to private address: ${address}`, 'private_address');
+ }
+ }
+}
+
+function validateUrl(rawUrl) {
+ let url;
+ try {
+ url = new URL(rawUrl);
+ } catch {
+ throw new FetchModelError('invalid URL', 'invalid_url');
+ }
+ if (url.protocol !== 'https:' && !(IS_DEV && url.protocol === 'http:')) {
+ throw new FetchModelError(`scheme not allowed: ${url.protocol}`, 'scheme_not_allowed');
+ }
+ return url;
+}
+
+/**
+ * Fetch bytes from an untrusted URL with SSRF protection.
+ *
+ * @param {string} rawUrl
+ * @param {{ maxBytes?: number, timeoutMs?: number }} opts
+ * @returns {Promise<{ bytes: Uint8Array, url: string, contentType: string, filename: string }>}
+ */
+export async function fetchModel(rawUrl, opts = {}) {
+ const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+
+ let currentUrl = validateUrl(rawUrl);
+ let redirects = 0;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+
+ try {
+ while (true) {
+ await assertPublicHost(currentUrl.hostname);
+
+ const res = await fetch(currentUrl, {
+ method: 'GET',
+ redirect: 'manual',
+ signal: controller.signal,
+ headers: {
+ 'user-agent': '3d-agent-mcp/1.0 (+https://3d.irish)',
+ accept: 'model/gltf-binary, model/gltf+json, application/octet-stream, */*;q=0.5',
+ },
+ });
+
+ if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
+ if (++redirects > MAX_REDIRECTS) {
+ throw new FetchModelError('too many redirects', 'too_many_redirects');
+ }
+ const next = new URL(res.headers.get('location'), currentUrl);
+ currentUrl = validateUrl(next.toString());
+ continue;
+ }
+
+ if (!res.ok) {
+ throw new FetchModelError(`upstream returned ${res.status}`, 'upstream_error');
+ }
+
+ const lenHeader = res.headers.get('content-length');
+ if (lenHeader && Number(lenHeader) > maxBytes) {
+ throw new FetchModelError(
+ `file too large (${lenHeader} > ${maxBytes} bytes)`,
+ 'file_too_large',
+ );
+ }
+
+ const reader = res.body?.getReader();
+ if (!reader) throw new FetchModelError('no response body', 'no_body');
+
+ const chunks = [];
+ let received = 0;
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ received += value.byteLength;
+ if (received > maxBytes) {
+ try {
+ reader.cancel();
+ } catch {}
+ throw new FetchModelError(
+ `file exceeded ${maxBytes} bytes during download`,
+ 'file_too_large',
+ );
+ }
+ chunks.push(value);
+ }
+
+ const bytes = new Uint8Array(received);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+
+ const contentType = res.headers.get('content-type') || 'application/octet-stream';
+ const filename = currentUrl.pathname.split('/').pop() || 'model';
+
+ return {
+ bytes,
+ url: currentUrl.toString(),
+ contentType,
+ filename,
+ };
+ }
+ } finally {
+ clearTimeout(timer);
+ }
+}
diff --git a/api/_lib/model-inspect.js b/api/_lib/model-inspect.js
new file mode 100644
index 000000000..3299e6f52
--- /dev/null
+++ b/api/_lib/model-inspect.js
@@ -0,0 +1,236 @@
+// Model inspection + optimization suggestions using glTF-Transform.
+//
+// Runs in a Vercel Node function. Input is raw bytes (Uint8Array) of either
+// a binary GLB or a JSON glTF. Output is a structured summary suitable for
+// MCP tool responses.
+
+import { WebIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+
+const GLB_MAGIC = 0x46546c67; // "glTF"
+
+function isGLB(bytes) {
+ if (!bytes || bytes.byteLength < 4) return false;
+ const view = new DataView(
+ bytes.buffer,
+ bytes.byteOffset,
+ Math.min(4, bytes.byteLength),
+ );
+ return view.getUint32(0, true) === GLB_MAGIC;
+}
+
+async function readDocument(bytes) {
+ const io = new WebIO().registerExtensions(ALL_EXTENSIONS);
+ if (isGLB(bytes)) return io.readBinary(bytes);
+ // Fall back to JSON glTF (rare, usually requires external buffers we don't have).
+ const text = new TextDecoder().decode(bytes);
+ let json;
+ try {
+ json = JSON.parse(text);
+ } catch {
+ throw new Error('input is not a valid GLB or JSON glTF');
+ }
+ return io.readJSON({ json, resources: {} });
+}
+
+/**
+ * Inspect a model's structure. Pure stats — no optimization advice.
+ * @param {Uint8Array} bytes
+ * @param {{ fileSize?: number }} opts
+ */
+export async function inspectModel(bytes, opts = {}) {
+ const doc = await readDocument(bytes);
+ const root = doc.getRoot();
+ const asset = root.getAsset();
+
+ const meshes = root.listMeshes();
+ const materials = root.listMaterials();
+ const textures = root.listTextures();
+ const animations = root.listAnimations();
+ const nodes = root.listNodes();
+ const scenes = root.listScenes();
+ const skins = root.listSkins();
+
+ let totalVertices = 0;
+ let totalTriangles = 0;
+ let indexedPrimitives = 0;
+ let nonIndexedPrimitives = 0;
+ const primitiveModes = new Set();
+
+ for (const mesh of meshes) {
+ for (const prim of mesh.listPrimitives()) {
+ const pos = prim.getAttribute('POSITION');
+ const verts = pos ? pos.getCount() : 0;
+ totalVertices += verts;
+ const idx = prim.getIndices();
+ if (idx) {
+ indexedPrimitives++;
+ totalTriangles += Math.floor(idx.getCount() / 3);
+ } else {
+ nonIndexedPrimitives++;
+ totalTriangles += Math.floor(verts / 3);
+ }
+ primitiveModes.add(prim.getMode());
+ }
+ }
+
+ const textureDetails = textures.map((tex) => {
+ const img = tex.getImage();
+ const size = tex.getSize();
+ const [w, h] = size || [0, 0];
+ return {
+ name: tex.getName() || null,
+ mimeType: tex.getMimeType(),
+ width: w,
+ height: h,
+ byteSize: img ? img.byteLength : 0,
+ };
+ });
+
+ const materialSummary = materials.map((m) => ({
+ name: m.getName() || null,
+ alphaMode: m.getAlphaMode(),
+ doubleSided: m.getDoubleSided(),
+ hasBaseColorTexture: !!m.getBaseColorTexture(),
+ hasNormalTexture: !!m.getNormalTexture(),
+ hasMetallicRoughnessTexture: !!m.getMetallicRoughnessTexture(),
+ hasEmissiveTexture: !!m.getEmissiveTexture(),
+ hasOcclusionTexture: !!m.getOcclusionTexture(),
+ }));
+
+ return {
+ fileSize: opts.fileSize ?? bytes.byteLength,
+ container: isGLB(bytes) ? 'glb' : 'gltf',
+ generator: asset.generator || null,
+ version: asset.version || null,
+ copyright: asset.copyright || null,
+ extensionsUsed: root.listExtensionsUsed().map((x) => x.extensionName),
+ extensionsRequired: root.listExtensionsRequired().map((x) => x.extensionName),
+ counts: {
+ scenes: scenes.length,
+ nodes: nodes.length,
+ meshes: meshes.length,
+ materials: materials.length,
+ textures: textures.length,
+ animations: animations.length,
+ skins: skins.length,
+ totalVertices,
+ totalTriangles,
+ indexedPrimitives,
+ nonIndexedPrimitives,
+ },
+ primitiveModes: [...primitiveModes],
+ textures: textureDetails,
+ materials: materialSummary,
+ };
+}
+
+/**
+ * Offer optimization suggestions based on structural analysis.
+ * Each suggestion has a severity (info|warn|critical), id, message, and
+ * optional estimate of impact.
+ *
+ * @param {Awaited<ReturnType<typeof inspectModel>>} info
+ * @returns {Array<{ id: string, severity: 'info'|'warn'|'critical', message: string, estimate?: string }>}
+ */
+export function suggestOptimizations(info) {
+ const out = [];
+ const c = info.counts;
+
+ if (c.totalTriangles > 500_000) {
+ out.push({
+ id: 'tri_budget',
+ severity: 'warn',
+ message: `Model has ${c.totalTriangles.toLocaleString()} triangles — consider mesh decimation or LODs for web delivery.`,
+ });
+ }
+
+ if (!info.extensionsUsed.includes('KHR_draco_mesh_compression') && c.totalVertices > 50_000) {
+ out.push({
+ id: 'draco',
+ severity: 'info',
+ message: 'Apply Draco compression to geometry for ~60-80% smaller vertex buffers.',
+ estimate: `~${Math.round((c.totalVertices * 12) / 1024)} KB potential savings`,
+ });
+ }
+
+ if (!info.extensionsUsed.includes('EXT_meshopt_compression') && c.totalVertices > 50_000) {
+ out.push({
+ id: 'meshopt',
+ severity: 'info',
+ message: 'Meshopt compression can reduce vertex+index size with faster decode than Draco.',
+ });
+ }
+
+ const bigTextures = info.textures.filter(
+ (t) => Math.max(t.width, t.height) >= 4096,
+ );
+ if (bigTextures.length > 0) {
+ out.push({
+ id: 'texture_oversized',
+ severity: 'warn',
+ message: `${bigTextures.length} texture(s) at ≥4K. Resize to 2048px for web unless hero detail is required.`,
+ });
+ }
+
+ const pngTextures = info.textures.filter((t) => t.mimeType === 'image/png');
+ if (pngTextures.length > 0 && !info.extensionsUsed.includes('KHR_texture_basisu')) {
+ out.push({
+ id: 'texture_basisu',
+ severity: 'info',
+ message: 'Transcode PNG textures to KTX2 (Basis Universal) for GPU-direct upload and smaller download.',
+ });
+ }
+
+ if (c.nonIndexedPrimitives > 0) {
+ out.push({
+ id: 'non_indexed',
+ severity: 'info',
+ message: `${c.nonIndexedPrimitives} primitive(s) are non-indexed — re-indexing typically reduces vertex count by 2-3×.`,
+ });
+ }
+
+ const unusedMaterials = info.materials.length - Math.min(info.materials.length, c.meshes);
+ if (info.materials.length > c.meshes * 2 && c.meshes > 0) {
+ out.push({
+ id: 'too_many_materials',
+ severity: 'info',
+ message: `${info.materials.length} materials for ${c.meshes} meshes. Merging identical materials can reduce draw calls.`,
+ });
+ }
+
+ const totalTextureBytes = info.textures.reduce((a, t) => a + t.byteSize, 0);
+ if (totalTextureBytes > 20 * 1024 * 1024) {
+ out.push({
+ id: 'texture_weight',
+ severity: 'warn',
+ message: `Textures alone weigh ${(totalTextureBytes / 1024 / 1024).toFixed(1)} MB — combine with KTX2 compression and resize for web.`,
+ });
+ }
+
+ if (info.fileSize > 25 * 1024 * 1024) {
+ out.push({
+ id: 'file_size',
+ severity: 'warn',
+ message: `Overall file size ${(info.fileSize / 1024 / 1024).toFixed(1)} MB is heavy for web delivery; target <10 MB.`,
+ });
+ }
+
+ if (c.animations > 0 && c.skins === 0) {
+ out.push({
+ id: 'anim_without_skin',
+ severity: 'info',
+ message: `${c.animations} animation(s) without skins — confirm these are node-level and not orphan data.`,
+ });
+ }
+
+ if (out.length === 0) {
+ out.push({
+ id: 'ok',
+ severity: 'info',
+ message: 'Model looks well-optimized for web delivery — no suggestions flagged.',
+ });
+ }
+
+ return out;
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index e1ae72ee0..adf27663f 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -64,6 +64,9 @@ export const limits = {
oauthRegisterIp: (ip) => getLimiter('oauth:register:ip', { limit: 10, window: '1 h' }).limit(ip),
mcpUser: (userId) => getLimiter('mcp:user', { limit: 1200, window: '1 m' }).limit(userId),
mcpIp: (ip) => getLimiter('mcp:ip', { limit: 600, window: '1 m' }).limit(ip),
+ mcpValidate: (key) => getLimiter('mcp:validate', { limit: 10, window: '1 m' }).limit(key),
+ mcpInspect: (key) => getLimiter('mcp:inspect', { limit: 30, window: '1 m' }).limit(key),
+ mcpOptimize: (key) => getLimiter('mcp:optimize', { limit: 10, window: '1 m' }).limit(key),
oauthToken: (clientId) => getLimiter('oauth:token', { limit: 120, window: '1 m' }).limit(clientId),
upload: (userId) => getLimiter('upload', { limit: 60, window: '1 h' }).limit(userId),
};
diff --git a/api/mcp.js b/api/mcp.js
index 478f3dc16..5b32bed1e 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -17,6 +17,9 @@ import { cors, readJson, wrap } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { recordEvent, logger } from './_lib/usage.js';
import { listAvatars, getAvatar, getAvatarBySlug, searchPublicAvatars, resolveAvatarUrl, deleteAvatar } from './_lib/avatars.js';
+import { fetchModel, FetchModelError } from './_lib/fetch-model.js';
+import { inspectModel, suggestOptimizations } from './_lib/model-inspect.js';
+import { validateBytes } from 'gltf-validator';
const PROTOCOL_VERSION = '2025-06-18';
const SERVER_INFO = { name: '3d-agent-mcp', version: '1.0.0' };
@@ -234,6 +237,49 @@ const TOOL_CATALOG = [
additionalProperties: false,
},
},
+ {
+ name: 'validate_model',
+ title: 'Validate glTF/GLB model',
+ description:
+ 'Run the Khronos glTF-Validator against a remote GLB or glTF URL. Returns a structured report of errors, warnings, infos, and hints — the authoritative answer to "is this file spec-compliant?". SSRF-hardened: only public https URLs are fetched.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ url: { type: 'string', format: 'uri', description: 'Public https URL of a .glb or .gltf file.' },
+ max_issues: { type: 'integer', minimum: 1, maximum: 500, default: 100 },
+ },
+ required: ['url'],
+ additionalProperties: false,
+ },
+ },
+ {
+ name: 'inspect_model',
+ title: 'Inspect glTF/GLB model',
+ description:
+ 'Parse a remote GLB or glTF and return structural stats: scene/node/mesh counts, vertex and triangle totals, material and texture summaries, extensions used. Pure inspection — no optimization advice.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ url: { type: 'string', format: 'uri', description: 'Public https URL of a .glb or .gltf file.' },
+ },
+ required: ['url'],
+ additionalProperties: false,
+ },
+ },
+ {
+ name: 'optimize_model',
+ title: 'Suggest optimizations for a glTF/GLB model',
+ description:
+ 'Inspect the model and return actionable suggestions for reducing size and draw-call overhead: triangle budget, Draco/Meshopt compression, oversized textures, KTX2 transcoding, non-indexed primitives, redundant materials, and more.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ url: { type: 'string', format: 'uri', description: 'Public https URL of a .glb or .gltf file.' },
+ },
+ required: ['url'],
+ additionalProperties: false,
+ },
+ },
];
const TOOLS = {
@@ -331,8 +377,111 @@ const TOOLS = {
return { content: [{ type: 'text', text: `Deleted avatar ${args.id}.` }] };
},
},
+
+ validate_model: {
+ async handler(args, auth) {
+ const rl = await limits.mcpValidate(auth.userId);
+ if (!rl.success) throw rpcError(-32000, 'rate_limited', { retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });
+ const { bytes, url, filename } = await safeFetchModel(args.url);
+ const max = Math.min(Math.max(args.max_issues || 100, 1), 500);
+ const report = await validateBytes(bytes, { maxIssues: max, uri: filename });
+ const issues = report?.issues || {};
+ const summary = {
+ url,
+ filename,
+ fileSize: bytes.byteLength,
+ validatorVersion: report?.validatorVersion,
+ mimeType: report?.mimeType,
+ numErrors: issues.numErrors ?? 0,
+ numWarnings: issues.numWarnings ?? 0,
+ numInfos: issues.numInfos ?? 0,
+ numHints: issues.numHints ?? 0,
+ truncated: !!issues.truncated,
+ };
+ return {
+ content: [{ type: 'text', text: formatValidationSummary(summary, issues.messages || []) }],
+ structuredContent: { ...summary, messages: issues.messages || [], info: report?.info || null },
+ };
+ },
+ },
+
+ inspect_model: {
+ async handler(args, auth) {
+ const rl = await limits.mcpInspect(auth.userId);
+ if (!rl.success) throw rpcError(-32000, 'rate_limited', { retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });
+ const { bytes, url, filename } = await safeFetchModel(args.url);
+ const info = await inspectModel(bytes, { fileSize: bytes.byteLength });
+ return {
+ content: [{ type: 'text', text: formatInspection({ url, filename, ...info }) }],
+ structuredContent: { url, filename, ...info },
+ };
+ },
+ },
+
+ optimize_model: {
+ async handler(args, auth) {
+ const rl = await limits.mcpOptimize(auth.userId);
+ if (!rl.success) throw rpcError(-32000, 'rate_limited', { retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });
+ const { bytes, url, filename } = await safeFetchModel(args.url);
+ const info = await inspectModel(bytes, { fileSize: bytes.byteLength });
+ const suggestions = suggestOptimizations(info);
+ return {
+ content: [{ type: 'text', text: formatSuggestions(suggestions) }],
+ structuredContent: { url, filename, suggestions, info },
+ };
+ },
+ },
};
+async function safeFetchModel(url) {
+ try {
+ return await fetchModel(url);
+ } catch (e) {
+ if (e instanceof FetchModelError) throw new Error(`fetch failed: ${e.message} (${e.code})`);
+ throw e;
+ }
+}
+
+function formatValidationSummary(s, messages) {
+ const head = `glTF-Validator report for ${s.filename} (${(s.fileSize / 1024).toFixed(1)} KB)\n` +
+ `Errors: ${s.numErrors}, Warnings: ${s.numWarnings}, Infos: ${s.numInfos}, Hints: ${s.numHints}` +
+ (s.truncated ? ' (truncated)' : '');
+ if (!messages.length) return head;
+ const lines = messages.slice(0, 40).map((m) => {
+ const sev = ['ERR', 'WRN', 'INF', 'HNT'][m.severity] || '?';
+ const ptr = m.pointer ? ` @ ${m.pointer}` : '';
+ return ` [${sev}] ${m.code}: ${m.message}${ptr}`;
+ });
+ const more = messages.length > 40 ? `\n … ${messages.length - 40} more` : '';
+ return `${head}\n${lines.join('\n')}${more}`;
+}
+
+function formatInspection(info) {
+ const c = info.counts;
+ const tex = info.textures.length
+ ? info.textures.map((t) => ` • ${t.name || '(unnamed)'} — ${t.mimeType} ${t.width}×${t.height}, ${(t.byteSize / 1024).toFixed(1)} KB`).join('\n')
+ : ' (none)';
+ return [
+ `Model: ${info.filename} (${(info.fileSize / 1024 / 1024).toFixed(2)} MB, ${info.container})`,
+ `Generator: ${info.generator || 'unknown'} · glTF ${info.version || '?'}`,
+ `Scenes: ${c.scenes}, Nodes: ${c.nodes}, Meshes: ${c.meshes}, Materials: ${c.materials}, Textures: ${c.textures}`,
+ `Animations: ${c.animations}, Skins: ${c.skins}`,
+ `Vertices: ${c.totalVertices.toLocaleString()}, Triangles: ${c.totalTriangles.toLocaleString()}`,
+ `Indexed primitives: ${c.indexedPrimitives}, Non-indexed: ${c.nonIndexedPrimitives}`,
+ `Extensions used: ${info.extensionsUsed.join(', ') || '(none)'}`,
+ `Textures:\n${tex}`,
+ ].join('\n');
+}
+
+function formatSuggestions(suggestions) {
+ if (!suggestions.length) return 'No suggestions.';
+ return suggestions.map((s) => {
+ const tag = { info: 'INFO', warn: 'WARN', critical: 'CRIT' }[s.severity] || s.severity.toUpperCase();
+ const est = s.estimate ? ` — ${s.estimate}` : '';
+ return `[${tag}] ${s.id}: ${s.message}${est}`;
+ }).join('\n');
+}
+
// ── <model-viewer> artifact builder ─────────────────────────────────────────
function renderModelViewerHtml({ src, name, poster, background, height, width, autoRotate, ar, cameraOrbit }) {
const attrs = [
diff --git a/public/.well-known/agent-card.json b/public/.well-known/agent-card.json
index 41dd0b2d3..4b0072e8e 100644
--- a/public/.well-known/agent-card.json
+++ b/public/.well-known/agent-card.json
@@ -53,6 +53,39 @@
"description": "Delete an avatar owned by the authenticated user",
"tags": ["avatar", "delete"],
"examples": ["Delete my old avatar", "Remove avatar abc123"]
+ },
+ {
+ "id": "validate-model",
+ "name": "Validate glTF/GLB Model",
+ "description": "Run the Khronos glTF-Validator against a remote model URL and return a structured error/warning/info/hint report",
+ "tags": ["model", "validation", "gltf", "glb"],
+ "examples": [
+ "Validate https://example.com/model.glb",
+ "Is this GLB spec-compliant?",
+ "Check my model for errors"
+ ]
+ },
+ {
+ "id": "inspect-model",
+ "name": "Inspect glTF/GLB Model",
+ "description": "Parse a remote model and return structural stats: scene/node/mesh counts, vertex and triangle totals, material and texture summaries, extensions used",
+ "tags": ["model", "inspect", "stats", "gltf", "glb"],
+ "examples": [
+ "How many triangles are in this model?",
+ "Inspect https://example.com/scene.glb",
+ "Show texture stats for this GLB"
+ ]
+ },
+ {
+ "id": "optimize-model",
+ "name": "Suggest Optimizations",
+ "description": "Inspect a remote model and return actionable suggestions for reducing size and draw-call overhead (Draco/Meshopt, KTX2, texture resize, reindexing, material merging)",
+ "tags": ["model", "optimize", "suggestions", "performance"],
+ "examples": [
+ "How can I make this model smaller?",
+ "Optimize this GLB for web delivery",
+ "Suggest compression for https://example.com/avatar.glb"
+ ]
}
]
}