3D engine that AI agents drive
Add the mesh_inspect MCP tool
Nguyen Xuan Anfecd10031b4d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5b00abb4..a1a669aa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,7 @@## Unreleased- Add `67js/addons/mesh`, a polygon mesh core for agent modeling: compact `MeshData` with attributes on point, edge, face and corner domains, a half-edge `EditMesh` with typed-array disk and radial cycles, `validateTopology`, conversion from renderer geometry with welding, quads and axis face tags, hard-edge corner normals, n-gon triangulation, render extraction and `lintMesh`+- Add the `mesh_inspect` MCP tool: polygon counts, face sizes, parts, face tags, bounds and lint problems with suggested fixes for every recipe geometry## 0.10.0diff --git a/ROADMAP.md b/ROADMAP.mdindex 2956c4d3..8cbd5240 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -27,7 +27,7 @@ Version `0.8.0` adds source-node authoring on imported GLBs with retained rigs,Version `0.9.0` adds isolated multi-angle and pose review with unchanged source revision and preview state.-The stdio MCP server supplies eighteen schema-backed tools and persistent CPU/GPU image previews.+The stdio MCP server supplies nineteen schema-backed tools and persistent CPU/GPU image previews.Recipes retain lighting, volumetric fog, grading and directional shadow coverage with atomic edits and undo.Imported asset sessions retain supported textures, rigs, morphs and clips from a configured local GLB catalog.diff --git a/docs/guide.md b/docs/guide.mdindex 355a15c3..e2c979ef 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -464,7 +464,7 @@ Disconnect observers, cancel animation frames, release pointer state and call `d## Models and AI agentsVersion `0.5.0` includes [agent scene sessions](/agent-scene.md) and the `67js-mcp` command.-Its [MCP server](/mcp.md) provides eighteen tools for authoring, previewing and exporting scenes through a persistent browser runtime.+Its [MCP server](/mcp.md) provides nineteen tools for authoring, previewing and exporting scenes through a persistent browser runtime.Release `0.7.0` adds [agent motion](/agent-motion.md) for deterministic joint, material and camera keyframes.Read the MCP guide for npm installation, client configuration and CPU/GPU selection.The [agent look contract](/agent-look.md) adds retained lighting, volumetric fog, grading and directional shadows to recipe edits and checkpoints.diff --git a/docs/mcp.md b/docs/mcp.mdindex 3bb1a6a6..94f2ff37 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -102,6 +102,7 @@ Inspect or export the recipe before retrying. Context loss still permits recipe| `scene_create_asset` | `recipe` using `67js.asset` | Imported scene ID, revision, inspection and render status || `scene_inspect` | `sessionId`, optional `ids`, `limit`, `includeBounds` | Compact node records and revision || `scene_apply` | `sessionId`, `expectedRevision`, `operations` | Updated revision, inspection, and render status |+| `mesh_inspect` | `sessionId`, optional `geometries` (up to 16 IDs) | Per geometry: polygon counts, face sizes, parts, face tags, bounds and lint problems with fixes || `scene_look` | `sessionId`, optional `width`, `height`, `motionTime` | PNG image and metadata || `scene_review` | `sessionId`, `expectedRevision`, `shots`, optional `width`, `height` | Labeled PNG grid and metadata from an isolated snapshot || `scene_checkpoint` | `sessionId` | Checkpoint ID, session ID, and revision |diff --git a/docs/mesh.md b/docs/mesh.mdindex 98b7f736..491ba89d 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -102,6 +102,24 @@ rebuilding the topology.`ok` is false when any error is present. Self-intersections and wall thickness are not checked yet.+## MCP++`mesh_inspect` runs the same conversion and lint on the geometries of a procedural recipe scene and returns one+compact record per geometry:++```json+{ "geometry": "cube", "ok": true,+ "counts": { "vertices": 8, "edges": 12, "faces": 6, "corners": 24, "triangles": 12, "renderVertices": 24 },+ "faces": { "triangles": 0, "quads": 6, "ngons": 0 },+ "parts": { "count": 1, "closed": 1 },+ "tags": { "right": 1, "left": 1, "top": 1, "bottom": 1, "front": 1, "back": 1, "side": 4 },+ "bounds": { "min": [-0.5, -0.5, -0.5], "max": [0.5, 0.5, 0.5] },+ "problems": [] }+```++Reports are cached per generated geometry, so asking again without edits is free. Imported asset scenes are not+supported yet.+## Measured speed`node scripts/benchmark-mesh-core.mjs 1000` on a 1000 x 1000 quad grid (one million faces), Node 24, Ryzen 5 5600X,diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex 63be2493..2bd11386 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -278,6 +278,13 @@ window.__agentPreview = {inspect({ sessionId, ...options }) {return { sessionId, ...requireSession(sessionId).scene.inspect(options) };},+ inspectMeshes({ sessionId, ...options }) {+ const scene = requireSession(sessionId).scene;+ if (typeof scene.inspectMeshes !== 'function') {+ throw new TypeError('mesh_inspect supports procedural recipe scenes. Imported asset scenes are not inspected as polygon meshes yet.');+ }+ return { sessionId, ...scene.inspectMeshes(options) };+ },apply({ sessionId, operations, expectedRevision }) {const record = requireSession(sessionId);validatePreviewCamera(candidateCamera(record, operations));diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex 3e962902..d37a7d4b 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -362,6 +362,9 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memoinspect(input) {return enqueue(() => invoke('inspect', input));},+ inspectMeshes(input) {+ return enqueue(() => invoke('inspectMeshes', input));+ },apply(input) {return enqueue(async () => {await requirePreviewRenderer();diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 62247f57..5296c96d 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -244,6 +244,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioregister('scene_asset_catalog', 'List content-bound GLB IDs from the configured local asset directory. No arbitrary paths or downloads.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.assetCatalog()));register('scene_create_asset', 'Create the active scene from a catalog GLB and editable asset recipe. Preserves supported maps, skins, morphs and clips. Dispose the existing scene first.', z.strictObject({ recipe: assetRecipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.createAsset(argumentsValue)));register('scene_inspect', 'Read revision, counts and selected nodes. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs. Omit to inspect scene order.'), kind: z.enum(['meshes', 'hierarchy']).optional().describe('Imported assets only: hierarchy exposes stable source-node IDs and joints.'), offset: z.number().int().min(0).max(4096).optional().describe('Imported assets only: pagination offset.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));+ register('mesh_inspect', 'Check recipe geometries as polygon meshes: vertex, edge and face counts, triangles/quads/n-gons, connected and closed parts, face tags (top, bottom, side, left, right, front, back), bounds, and lint problems (non-manifold, inconsistent winding, inverted, degenerate, open, loose) with a suggested fix each. Procedural scenes only. Read-only and cached per geometry.', z.strictObject({ ...sessionFields, geometries: z.array(identifier).min(1).max(16).optional().describe('Geometry IDs to check. Omit to check the first 16 geometries.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspectMeshes(argumentsValue)));register('scene_apply', 'Atomically edit transforms, look, camera or materials. Procedural scenes support membership and set-motion authoring. Imported assets support set-root, set-asset-node, set-motion and absolute set-animation sampling. Successful batches increment revision once.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Node/material/camera/root/animation commands use flat fields. Motion, look patches and add commands contain nested records. Backend validates each scene mode before publication.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));register('scene_look', 'Render the active scene as a bounded PNG. Optional authored motionTime seeks without changing revision; null restores the authored base pose. Omit to retain the last preview pose.', z.strictObject({ ...sessionFields, motionTime: z.number().min(0).max(3600).nullable().optional(), width: z.number().int().min(64).max(1024).default(768).describe('PNG width in pixels.'), height: z.number().int().min(64).max(1024).default(512).describe('PNG height in pixels.') }), readOnly, async argumentsValue => {const { data, mimeType, metadata } = await runtime.look(argumentsValue);diff --git a/scripts/smoke-agent-assets.mjs b/scripts/smoke-agent-assets.mjsindex 243627b4..1aed3c6c 100644--- a/scripts/smoke-agent-assets.mjs+++ b/scripts/smoke-agent-assets.mjs@@ -35,7 +35,7 @@ async function look(sessionId, label) {}try {await client.connect(transport, { timeout: 180000 });- assert.equal((await client.listTools()).tools.length, 18);+ assert.equal((await client.listTools()).tools.length, 19);const catalog = (await call('scene_asset_catalog')).structuredContent;assert.equal(catalog.configured, true);assert.equal(catalog.assets.length, 2);diff --git a/scripts/smoke-agent-render-jobs.mjs b/scripts/smoke-agent-render-jobs.mjsindex 90c5002c..72946bb6 100644--- a/scripts/smoke-agent-render-jobs.mjs+++ b/scripts/smoke-agent-render-jobs.mjs@@ -57,7 +57,7 @@ async function close() {}try {await connect();- assert.equal((await client.listTools()).tools.length, 18);+ assert.equal((await client.listTools()).tools.length, 19);const catalog = (await call('scene_asset_catalog')).structuredContent;const created = (await call('scene_create_asset', { recipe: {format: '67js.asset', schemaVersion: 1, assetId: catalog.assets[0].assetId,diff --git a/scripts/smoke-agent-review.mjs b/scripts/smoke-agent-review.mjsindex 8cb65113..3b58de85 100644--- a/scripts/smoke-agent-review.mjs+++ b/scripts/smoke-agent-review.mjs@@ -48,7 +48,7 @@ function pixels(bytes, crop) {}try {await client.connect(transport);- assert.equal((await client.listTools()).tools.length, 18);+ assert.equal((await client.listTools()).tools.length, 19);const created = (await call('scene_create_asset', { recipe: fixture.recipe })).structuredContent;const sessionId = created.sessionId;const checkpoint = (await call('scene_checkpoint', { sessionId })).structuredContent;diff --git a/scripts/smoke-mcp-package.mjs b/scripts/smoke-mcp-package.mjsindex 5d027147..e82e4afe 100644--- a/scripts/smoke-mcp-package.mjs+++ b/scripts/smoke-mcp-package.mjs@@ -108,7 +108,7 @@ for (const era of ['modern', 'legacy']) {const connectMs = performance.now() - start;processId = transport.pid;assert.equal(client.getServerVersion().version, metadata.version);- assert.equal((await client.listTools()).tools.length, 18);+ assert.equal((await client.listTools()).tools.length, 19);const capabilities = (await call('scene_capabilities')).structuredContent;assert.equal(capabilities.phase, 'idle');assert.equal(capabilities.preview.maximumActiveScenes, 1);diff --git a/scripts/smoke-mcp.mjs b/scripts/smoke-mcp.mjsindex 22d19ad8..4f79b4c9 100644--- a/scripts/smoke-mcp.mjs+++ b/scripts/smoke-mcp.mjs@@ -53,7 +53,7 @@ try {await client.connect(transport);processId = transport.pid;const listing = await client.listTools();- assert.equal(listing.tools.length, 18);+ assert.equal(listing.tools.length, 19);const capabilities = (await call('scene_capabilities')).structuredContent;assert.equal(capabilities.phase, 'idle');const fixture = createAgentPreviewFixture();@@ -70,6 +70,9 @@ try {assert.equal(created.inspection.counts.geometries, 7);assert.equal(created.revision, 1);assert.match(created.render.graphics, backend === 'gpu' ? /NVIDIA/i : /SwiftShader/i);+ const meshes = (await call('mesh_inspect', { sessionId })).structuredContent;+ assert.equal(meshes.meshes.length, 7);+ assert.ok(meshes.meshes.every(mesh => mesh.counts.faces > 0 && Array.isArray(mesh.problems)));const before = await look(sessionId, 'before');const checkpoint = (await call('scene_checkpoint', { sessionId })).structuredContent;const edited = (await call('scene_apply', {diff --git a/src/agent-mesh.js b/src/agent-mesh.jsnew file mode 100644index 00000000..866119dd--- /dev/null+++ b/src/agent-mesh.js@@ -0,0 +1,45 @@+import { meshFromGeometry } from './mesh-convert.js';+import { lintMesh } from './mesh-lint.js';++// Compact, agent-facing mesh reports for scene geometry. Reports are cached per immutable geometry object, so+// repeated inspection of an unchanged scene costs nothing.++const reports = new WeakMap();++function faceSizeHistogram(mesh) {+ const histogram = { triangles: 0, quads: 0, ngons: 0 };+ for (let face = 0; face < mesh.faceCount; face++) {+ const size = mesh.faceOffsets[face + 1] - mesh.faceOffsets[face];+ if (size === 3) histogram.triangles++;+ else if (size === 4) histogram.quads++;+ else histogram.ngons++;+ }+ return histogram;+}++function roundedBounds(bounds) {+ const round = value => Math.round(value * 1e5) / 1e5;+ return { min: bounds.min.map(round), max: bounds.max.map(round) };+}++/**+ * Polygon view and lint of renderer geometry: counts, face sizes, connected parts, face tags, bounds and problems+ * with suggested fixes. The geometry is welded and joined into quads first, as meshFromGeometry does.+ */+export function meshReport(geometry) {+ let report = reports.get(geometry);+ if (report) return report;+ const mesh = meshFromGeometry(geometry);+ const lint = lintMesh(mesh);+ report = Object.freeze({+ ok: lint.ok,+ counts: { ...lint.counts, triangles: geometry.indices.length / 3, renderVertices: geometry.positions.length / 3 },+ faces: faceSizeHistogram(mesh),+ parts: lint.parts,+ tags: lint.tags,+ bounds: roundedBounds(lint.bounds),+ problems: lint.problems,+ });+ reports.set(geometry, report);+ return report;+}diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 83e71bbf..a0f19607 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -5,6 +5,7 @@ import { createSceneGraph } from './scene-graph.js';import { applyProjection } from './camera.js';import { normalizeAgentLook } from './agent-look.js';import { normalizeAgentMotion, compileAgentMotion } from './agent-motion.js';+import { meshReport } from './agent-mesh.js';export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';const DEFAULT_LIMITS = Object.freeze({@@ -12,6 +13,7 @@ const DEFAULT_LIMITS = Object.freeze({maxVertices: 250_000, maxGeometryBytes: 32 * 1024 * 1024,maxOperations: 256, maxCheckpoints: 8, maxRecipeBytes: 1024 * 1024,});+const MAX_MESH_REPORTS = 16;const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 });const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material'];const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided'];@@ -950,6 +952,24 @@ export function createAgentScene(input, inputLimits = {}) {nodes, truncated: selected.length > nodes.length,};},+ /** Polygon counts, parts, face tags and lint problems for recipe geometries (all, or the given IDs). */+ inspectMeshes(options = {}) {+ knownKeys(options, ['geometries'], 'mesh inspection');+ const requested = options.geometries ?? [...state.geometries.keys()];+ if (!Array.isArray(requested) || (options.geometries !== undefined && requested.length > MAX_MESH_REPORTS)) {+ throw new RangeError(`Inspect at most ${MAX_MESH_REPORTS} geometry IDs per call.`);+ }+ const selected = requested.slice(0, MAX_MESH_REPORTS);+ const meshes = selected.map(id => {+ identifier(id);+ const geometry = state.geometries.get(id);+ if (!geometry) {+ throw new RangeError(`Geometry ID was not found: ${id}. Known IDs: ${[...state.geometries.keys()].join(', ')}.`);+ }+ return { geometry: id, ...meshReport(geometry) };+ });+ return { revision, meshes, truncated: requested.length > selected.length };+ },checkpoint() {if (checkpoints.size >= limits.maxCheckpoints) {throw new RangeError('Checkpoint budget exhausted. Release a checkpoint.');diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.jsindex 64fd616d..e6fc3f16 100644--- a/tests/mcp-tools.test.js+++ b/tests/mcp-tools.test.js@@ -38,6 +38,11 @@ async function connect(context) {assert.equal(requested, sessionId);return { sessionId, ...scene.inspect(options) };},+ async inspectMeshes({ sessionId: requested, ...options }) {+ calls++;+ assert.equal(requested, sessionId);+ return { sessionId, ...scene.inspectMeshes(options) };+ },async apply({ expectedRevision, operations }) {calls++;scene.apply(operations, { expectedRevision });@@ -105,7 +110,7 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'const { client } = await connect(context);const { tools } = await client.listTools();assert.deepEqual(tools.map(tool => tool.name).sort(), [- 'scene_apply', 'scene_asset_catalog', 'scene_capabilities', 'scene_checkpoint', 'scene_create', 'scene_create_asset', 'scene_dispose',+ 'mesh_inspect', 'scene_apply', 'scene_asset_catalog', 'scene_capabilities', 'scene_checkpoint', 'scene_create', 'scene_create_asset', 'scene_dispose','scene_export_recipe', 'scene_inspect', 'scene_look', 'scene_review', 'scene_release_checkpoint', 'scene_restore','scene_render_cancel', 'scene_render_release', 'scene_render_result', 'scene_render_status', 'scene_render_submit',].sort());@@ -143,7 +148,7 @@ test('review SDK exposes one image and rejects unknown or unbounded shot fieldsawait client.callTool({ name: 'scene_create', arguments: { recipe: recipe() } });const { tools } = await client.listTools();const tool = tools.find(tool => tool.name === 'scene_review');- assert.equal(tools.length, 18);+ assert.equal(tools.length, 19);assert.equal(tool.annotations.readOnlyHint, true);assert.equal(tool.inputSchema.properties.shots.maxItems, 4);assert.equal(tool.inputSchema.properties.shots.items.additionalProperties, false);@@ -193,6 +198,36 @@ test('SDK rejects unknown fields, missing revisions, invalid vectors and oversizassert.equal(boundary.calls(), 0);});+test('mesh_inspect reports polygon counts, tags and lint for recipe geometries', async context => {+ const { client, sessionId } = await connect(context);+ await client.callTool({ name: 'scene_create', arguments: { recipe: {+ ...recipe(),+ geometries: [+ { id: 'cube', type: 'box', bevel: 0 },+ { id: 'cable', type: 'tube', path: [[0, 0, 0], [1, 1, 0], [2, 0, 0]], radius: 0.05 },+ ],+ } } });+ const result = await client.callTool({ name: 'mesh_inspect', arguments: { sessionId } });+ assert.equal(result.isError, undefined);+ const [cube, cable] = result.structuredContent.meshes;+ assert.equal(cube.geometry, 'cube');+ assert.equal(cube.ok, true);+ assert.deepEqual(cube.faces, { triangles: 0, quads: 6, ngons: 0 });+ assert.equal(cube.tags.top, 1);+ assert.deepEqual(cube.problems, []);+ assert.equal(cable.parts.closed, 0, 'an uncapped tube is open');+ assert.equal(cable.problems[0].kind, 'boundary-edge');+ assert.ok(JSON.stringify(result.structuredContent).length < 4096, 'default report stays compact');+ const one = await client.callTool({ name: 'mesh_inspect', arguments: { sessionId, geometries: ['cube'] } });+ assert.equal(one.structuredContent.meshes.length, 1);+ const missing = await client.callTool({ name: 'mesh_inspect', arguments: { sessionId, geometries: ['nope'] } });+ assert.equal(missing.isError, true);+ assert.match(missing.content[0].text, /Known IDs: cube, cable/);+ await rejected(client, 'mesh_inspect', { sessionId, geometries: [] });+ await rejected(client, 'mesh_inspect', { sessionId, geometries: Array.from({ length: 17 }, (_, index) => `g${index}`) });+ await rejected(client, 'mesh_inspect', { sessionId, path: '../file' });+});+test('real SDK round trip authors motion, seeks without revisions and rejects unknown track fields', async context => {const { client, sessionId } = await connect(context);const motion = { duration: 1, tracks: [{ kind: 'node', id: 'mesh', property: 'translation',