Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add persistent MCP scene previews and revision-safe tools

Nguyen Xuan An669ca41f02c6
diff --git a/.gitignore b/.gitignore
index 90f2f100..fe3df058 100644
--- a/.gitignore
+++ b/.gitignore
@@ -36,3 +36,4 @@ public/volumetric.md
public/film-physics.md
public/surface-attachment.md
public/agent-scene.md
+public/mcp.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f335b89a..d2475bd9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Add source-checkout MCP tools with strict scene schemas, persistent CPU/GPU previews and bounded PNG responses.
+- Keep renderer sessions alive across edits and close owned browser resources when the MCP connection ends.
- Add optional agent scene sessions with stable IDs, shared geometry, revision checks, atomic edits and bounded checkpoints.
- Prioritize agent authoring, visual feedback and MCP integration in the implementation roadmap.
diff --git a/README.md b/README.md
index 41cd5b71..46efed5a 100644
--- a/README.md
+++ b/README.md
@@ -127,7 +127,11 @@ The repository includes two reusable Codex skills.
The current source includes [agent scene sessions](docs/agent-scene.md), newer than npm `0.4.1`.
Agents can author JSON recipes, inspect object bounds, submit atomic edits and restore bounded checkpoints.
The optional addon retains renderer-facing parts and geometry across supported edits.
-An MCP server and persistent render jobs remain implementation work.
+
+The source [MCP server](docs/mcp.md) connects these sessions to a persistent browser renderer.
+Agents receive PNG previews and structured scene metadata through ten stdio tools.
+Run `node scripts/mcp-server.mjs --backend gpu --memory 192` from a checkout with project dependencies and a local Chrome installation.
+Dynamic node creation, asset ingestion and persistent video jobs remain implementation work.
## Checks and performance
diff --git a/ROADMAP.md b/ROADMAP.md
index 7b7c41bf..b1a25006 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -23,9 +23,10 @@ This document separates shipping capabilities from work in progress. Performance
## Next
The current source, after npm `0.4.1`, includes fixed-topology agent scenes with stable IDs, atomic revisioned edits and checkpoints.
+Its stdio MCP server supplies ten schema-backed tools and persistent CPU/GPU image previews.
1. Extend agent sessions with dynamic node and resource creation while preserving bounded allocation, replay and undo.
-2. An MCP adapter with capability discovery, compact scene inspection and visual feedback from multiple angles and animation frames.
+2. Extend MCP visual feedback with bounded multi-angle and absolute animation-time previews, plus persistent authored lighting and effect controls.
3. Persistent render jobs with progress, cancellation, explicit CPU/GPU budgets and deterministic image and video export.
4. Geometry, rig and asset diagnostics that help agents correct intersections, invalid transforms and unsupported materials.
5. Agent workflows for imported assets, sculpting, surface fitting, lighting and animation, verified against rendered reference scenes.
diff --git a/docs/guide.md b/docs/guide.md
index f5a790c3..985e22f1 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -401,10 +401,14 @@ Disconnect observers, cancel animation frames, release pointer state and call `d
## Models and AI agents
The current source includes [agent scene sessions](/agent-scene.md), newer than npm `0.4.1`.
+Its [MCP server](/mcp.md) provides ten tools for creating, inspecting, editing and previewing scenes through a persistent browser renderer.
+Read the matching checkout's MCP guide for launch configuration, CPU/GPU selection and source-only availability.
+
The addon accepts JSON recipes with stable object IDs, shared geometry and material resources, hierarchy and a camera.
Edits use an expected revision and commit as one batch. Checkpoints restore the supported scene state.
The session keeps existing renderer-facing parts and matrices for transform, material and camera edits.
-This CPU authoring API does not yet provide an MCP server or background render jobs.
+
+The CPU addon owns recipe state. The separate Node MCP server connects it to browser rendering. Background render jobs remain unsupported.
Give the agent this guide and the matching repository skill. Start with a scene brief: focal subject, visual references, camera, output size, required interaction, GPU/CPU backend and memory budget. Read the matching scene recipe and run the smallest trial first.
diff --git a/docs/mcp.md b/docs/mcp.md
new file mode 100644
index 00000000..6f0f0e8e
--- /dev/null
+++ b/docs/mcp.md
@@ -0,0 +1,146 @@
+# MCP scene authoring
+
+The stdio server is available in the source checkout after npm release `0.4.1`.
+The published `0.4.1` package does not include this server.
+It uses the maintained MCP TypeScript SDK v2 server and a local browser runtime.
+The [official SDK documentation](https://ts.sdk.modelcontextprotocol.io/v2/) describes its transport and protocol APIs.
+
+The server exposes ten tools for bounded JSON scene authoring.
+It renders one active scene and returns PNG images through MCP image content.
+Tool results also contain JSON text and structured metadata.
+The image bytes appear only in the image content block.
+
+## Requirements and launch
+
+The server requires Node.js 20 or later, installed project dependencies, and a local Chrome or Chromium executable.
+The browser starts when `scene_create` runs.
+The runtime serves its generated scene page on the loopback interface.
+The MCP connection uses stdin and stdout, without an HTTP MCP listener.
+
+1. Run the server from the source checkout:
+
+ ```powershell
+ node scripts/mcp-server.mjs --backend gpu --memory 192
+ ```
+
+2. Configure your MCP client with absolute paths:
+
+ ```json
+ {
+ "mcpServers": {
+ "67js-scene": {
+ "command": "C:/Program Files/nodejs/node.exe",
+ "args": [
+ "C:/projects/67js/scripts/mcp-server.mjs",
+ "--backend", "gpu",
+ "--memory", "192",
+ "--browser", "C:/Program Files/Google/Chrome/Application/chrome.exe"
+ ]
+ }
+ }
+ }
+ ```
+
+The browser path is optional when the runtime can locate a supported browser.
+`--backend` accepts `gpu` or `cpu` and defaults to `gpu`.
+`--memory` accepts an integer from 32 to 256 MiB and defaults to 192.
+These launch options remain outside tool arguments.
+The process runs below normal priority to reduce interference with other work.
+
+Stdout contains only MCP protocol messages, while errors go to stderr.
+Closing stdin or sending `SIGINT` or `SIGTERM` closes the runtime and releases its browser resources.
+
+## Workflow
+
+1. Call `scene_capabilities` to read supported features and runtime limits.
+2. Call `scene_create` with a [scene recipe](agent-scene.md#recipe-contract).
+3. Call `scene_inspect` to read node IDs, bounds, counts, and the current revision.
+4. Call `scene_checkpoint` before an experiment.
+5. Call `scene_apply` with a small batch and the current `expectedRevision`.
+6. Call `scene_look` to assess the rendered image.
+7. Call `scene_restore` with the current revision if the experiment fails.
+8. Call `scene_release_checkpoint` when you no longer need the saved state.
+9. Call `scene_export_recipe` to retain the canonical recipe.
+10. Call `scene_dispose` to release the scene before creating another one.
+
+`scene_create`, `scene_apply`, and `scene_restore` return the session ID, current revision, inspection, and render status.
+`scene_checkpoint` returns a checkpoint UUID scoped to its session UUID.
+A restore increments revision and keeps the checkpoint available.
+A stale revision or invalid command produces an error without publishing partial edits.
+SDK validation rejects unknown tool fields before dispatch.
+Backend errors return `isError: true` with a readable message.
+
+Successful apply and restore responses include `committed: true`, the new revision, and `renderSucceeded`.
+If rendering fails after the edit commits, the response retains that revision and includes `renderSucceeded: false` and `renderError`.
+Its render metadata describes the last successful render, rather than a new frame.
+Inspect or export the recipe before retrying. Context loss still permits recipe inspection, export, and disposal.
+
+## Tools
+
+| Tool | Arguments | Result |
+| --- | --- | --- |
+| `scene_capabilities` | None | Features, limits, and backend information |
+| `scene_create` | `recipe` | Session 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 |
+| `scene_look` | `sessionId`, optional `width`, `height` | PNG image and metadata |
+| `scene_checkpoint` | `sessionId` | Checkpoint ID, session ID, and revision |
+| `scene_restore` | `sessionId`, `checkpointId`, `expectedRevision` | Updated revision, inspection, and render status |
+| `scene_release_checkpoint` | `sessionId`, `checkpointId` | Release confirmation |
+| `scene_export_recipe` | `sessionId` | Canonical recipe and revision |
+| `scene_dispose` | `sessionId` | Disposal confirmation |
+
+The recipe uses `format: '67js.scene'` and `schemaVersion: 1`.
+Supported geometry types are `box`, `cylinder`, `sphere`, `torus`, `lathe`, `extrude`, and `tube`.
+Geometry fields remain flat inside each geometry record.
+Operations use `set-node`, `set-material`, or `set-camera`, with fields directly on each command.
+The [scene contract](agent-scene.md) defines the geometry fields, transforms, materials, and atomic validation rules.
+
+## Limits
+
+| Budget | Limit |
+| --- | --- |
+| Active render scenes | 1 |
+| Nodes | 4096 |
+| Geometries and materials | 256 each |
+| Operations per batch | 256 |
+| Checkpoints per session | 8 |
+| Geometry input points | 4096 per input, including all extrusion contours |
+| Extrusion holes | 128 |
+| Unique geometry vertices | 250000 |
+| Unique geometry buffers | 32 MiB |
+| Recipe or command JSON | 1 MiB |
+| Incoming stdio buffer | 2 MiB |
+| Preview dimensions | 64 to 1024 pixels per dimension |
+| Default preview dimensions | 768 by 512 pixels |
+| PNG payload | 1 MiB |
+
+The backend enforces combined budgets and numeric consistency beyond the advertised tool schemas.
+
+Render targets can shrink to fit the configured memory budget.
+Image metadata reports actual dimensions alongside requested dimensions and estimated render bytes.
+
+An oversized PNG response returns an error. Request a smaller preview rather than treating the failure as an empty image.
+Browser evaluations have a 30-second deadline. A timeout closes the preview browser and makes the runtime unavailable.
+Camera matrices must remain finite at every supported preview aspect ratio, from 1:16 to 16:1.
+
+Group and mesh membership, geometry definitions, and material tags remain fixed after creation.
+Adding nodes or changing geometry requires a new scene.
+
+The tools expose no arbitrary JavaScript execution, URLs, file access, asset ingestion, or render jobs.
+The transport supplies a visual feedback loop, but visual quality still depends on the authored scene and image assessment.
+MCP support does not establish Blender feature parity.
+
+## Boundary tests
+
+1. Run `node --test tests/mcp-tools.test.js`.
+
+The tests use a real SDK client and linked in-memory transports.
+They verify schemas, argument rejection, atomic revision errors, checkpoint behavior, and PNG content with structured metadata.
+The adapter uses the real CPU recipe backend and a fixed PNG fixture.
+These tests do not prove browser launch, GPU rendering, or final visual quality.
+
+Run `node scripts/smoke-mcp.mjs gpu modern` for a native browser test through real stdio tools.
+Run `node scripts/smoke-mcp.mjs cpu legacy` for the software backend and legacy protocol negotiation.
+Each checks landscape and portrait PNGs, stale revision rejection, exact PNG restoration, session disposal, and process cleanup.
+The scripts save images and metadata under `artifacts/`. They use one isolated browser and close it when finished.
diff --git a/package-lock.json b/package-lock.json
index 1ddae78c..f5e8cbb9 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -11,6 +11,8 @@
"devDependencies": {
"@codepawlhq/orglet-ui": "0.2.1",
"@dimforge/rapier3d-compat": "0.21.0",
+ "@modelcontextprotocol/client": "2.3.1",
+ "@modelcontextprotocol/server": "2.3.1",
"gl-matrix": "3.4.4",
"highlight.js": "11.12.0",
"playwright": "1.64.0",
@@ -19,7 +21,8 @@
"three": "0.186.1",
"three-mesh-bvh": "0.9.16",
"vite": "8.3.4",
- "wrangler": "4.149.0"
+ "wrangler": "4.149.0",
+ "zod": "4.6.5"
},
"peerDependencies": {
"@dimforge/rapier3d-compat": "0.21.0"
@@ -1233,6 +1236,52 @@
"@jridgewell/sourcemap-codec": "^1.4.10"
}
},
+ "node_modules/@modelcontextprotocol/client": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.3.1.tgz",
+ "integrity": "sha512-mIGZXpHsjnZ6lD+gD/WCMpR5k8yVQQ8nNFH1N0Srf7AvnwTUMYD6pvTY8ng2+He5FfV7YMZLmrjL7cLa/cc3dQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@modelcontextprotocol/core": "2.3.1",
+ "cross-spawn": "^7.0.5",
+ "eventsource": "^3.0.2",
+ "eventsource-parser": "^3.0.8",
+ "jose": "^6.1.3",
+ "pkce-challenge": "^5.0.0",
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/core": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.3.1.tgz",
+ "integrity": "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/server": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.3.1.tgz",
+ "integrity": "sha512-e59MfWuSssj6DoQ96JCTqdW1AXT5/XtnTl0WWd6MU1Ka434fFUGGosCLJbGNySDhHGvxQWoRWK137FXYFkYNWw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@modelcontextprotocol/core": "2.3.1",
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/@oxc-project/types": {
"version": "0.153.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.153.0.tgz",
@@ -1946,6 +1995,21 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/cross-spawn": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -2015,6 +2079,29 @@
"@esbuild/win32-x64": "0.28.2"
}
},
+ "node_modules/eventsource": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "eventsource-parser": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/eventsource-parser": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
+ "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -2075,6 +2162,23 @@
"node": ">=12.0.0"
}
},
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/jose": {
+ "version": "6.2.12",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz",
+ "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
"node_modules/kleur": {
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
@@ -2395,6 +2499,16 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
+ "node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/path-to-regexp": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz",
@@ -2429,6 +2543,16 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/pkce-challenge": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
"node_modules/playwright": {
"version": "1.64.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.0.tgz",
@@ -2686,6 +2810,29 @@
}
}
},
+ "node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/source-map-js": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
@@ -2904,6 +3051,22 @@
}
}
},
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
"node_modules/workerd": {
"version": "1.20261006.1",
"resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261006.1.tgz",
@@ -3007,6 +3170,16 @@
"@poppinss/exception": "^1.2.2",
"error-stack-parser-es": "^1.0.5"
}
+ },
+ "node_modules/zod": {
+ "version": "4.6.5",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",
+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
}
}
}
diff --git a/package.json b/package.json
index 97179c4e..54e73af7 100644
--- a/package.json
+++ b/package.json
@@ -42,7 +42,8 @@
"docs/primitives.md",
"docs/shrinkwrap.md",
"docs/surface-attachment.md",
- "docs/agent-scene.md"
+ "docs/agent-scene.md",
+ "docs/mcp.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
@@ -80,6 +81,8 @@
"score": "node scripts/score.mjs",
"export:model": "node scripts/export-model.mjs",
"smoke:package": "node scripts/smoke-package.mjs",
+ "mcp": "node scripts/mcp-server.mjs",
+ "smoke:mcp": "node scripts/smoke-mcp.mjs",
"smoke:enhancements": "node scripts/smoke-enhancements.mjs",
"smoke:site": "node scripts/smoke-site.mjs",
"publish:ci": "node scripts/publish-ci.mjs"
@@ -95,6 +98,8 @@
"devDependencies": {
"@codepawlhq/orglet-ui": "0.2.1",
"@dimforge/rapier3d-compat": "0.21.0",
+ "@modelcontextprotocol/client": "2.3.1",
+ "@modelcontextprotocol/server": "2.3.1",
"gl-matrix": "3.4.4",
"highlight.js": "11.12.0",
"playwright": "1.64.0",
@@ -103,6 +108,7 @@
"three": "0.186.1",
"three-mesh-bvh": "0.9.16",
"vite": "8.3.4",
- "wrangler": "4.149.0"
+ "wrangler": "4.149.0",
+ "zod": "4.6.5"
}
}
diff --git a/public/llms.txt b/public/llms.txt
index 68a5f4ab..c3ddc098 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -13,6 +13,14 @@ Use `session.inspect()` for compact object facts and `session.exportRecipe()` fo
Keep renderer-facing geometry immutable. Call `renderer.updateParts(session.parts)` after a successful edit or restore.
This addon does not expose an MCP server or a render job queue.
+The source checkout provides a separate stdio MCP server in `scripts/mcp-server.mjs`, after npm `0.4.1`.
+Read `/mcp.md` before configuring it. Start with `scene_capabilities`, create a recipe and inspect its stable IDs.
+
+Checkpoint, apply small revisioned batches, then use `scene_look` to assess the actual PNG.
+Restore failed experiments and release unused checkpoints. Export the recipe and dispose the scene when finished.
+The runtime keeps one browser scene alive, serializes calls, caps PNG responses and releases resources on stdin EOF.
+It exposes no arbitrary code, file access, asset providers, dynamic node creation or video jobs.
+
- [Release metadata](https://67js.codepawl.com/release.json): package name, version, publication status, install command, module URL and commit.
- [Complete plain-text guide](https://67js.codepawl.com/guide.md): renderer, parts, materials, cameras, animation, lifecycle, export and troubleshooting.
- [GLB contract](https://67js.codepawl.com/gltf.md): supported assets and conversion limits. Read before selecting or importing a model.
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
new file mode 100644
index 00000000..e8ad07b1
--- /dev/null
+++ b/scripts/agent-preview-browser.js
@@ -0,0 +1,182 @@
+import { createAgentScene } from '../src/agent-scene.js';
+import { Renderer67 } from '../src/renderer.js';
+import { applyProjection } from '../src/camera.js';
+import { mat4 } from 'gl-matrix';
+
+let active = null;
+let canvas = document.querySelector('canvas');
+const effects = { bloom: { strength: 0.12, threshold: 1, radius: 1 }, grain: 0, vignette: 0 };
+
+function requireSession(sessionId) {
+ if (!active || active.sessionId !== sessionId) {
+ throw new Error('Unknown or disposed scene session.');
+ }
+ return active;
+}
+
+function validatePreviewCamera(camera) {
+ const view = mat4.lookAt(mat4.create(), camera.eye, camera.target, camera.up);
+ for (const aspect of [1 / 16, 16]) {
+ const projection = applyProjection(mat4.create(), camera, aspect);
+ const viewProjection = mat4.multiply(mat4.create(), projection, view);
+ if (![projection, viewProjection].every(matrix => matrix.every(Number.isFinite))) {
+ throw new RangeError('Camera matrices must remain finite for all supported preview aspect ratios.');
+ }
+ }
+}
+
+function candidateCamera(record, operations) {
+ const camera = record.scene.camera;
+ for (const operation of operations) {
+ if (operation.type === 'set-camera') {
+ for (const field of ['eye', 'target', 'up', 'fov', 'near', 'far']) {
+ if (Object.hasOwn(operation, field)) {
+ camera[field] = operation[field];
+ }
+ }
+ }
+ }
+ return createAgentScene({ format: '67js.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [], camera }).camera;
+}
+
+function renderInfo(renderer) {
+ const context = renderer.context;
+ const debug = context.getExtension('WEBGL_debug_renderer_info');
+ return {
+ graphics: context.getParameter(debug ? debug.UNMASKED_RENDERER_WEBGL : context.RENDERER),
+ estimatedBytes: renderer.memoryPlan.estimatedBytes,
+ width: canvas.width,
+ height: canvas.height,
+ samples: renderer.capabilities.samples,
+ hdr: renderer.capabilities.hdr,
+ };
+}
+
+function draw(record) {
+ if (record.renderer.context.isContextLost()) {
+ throw new Error('The render context was lost. Export the recipe and dispose this session.');
+ }
+ record.renderer.resize();
+ record.renderer.updateParts(record.scene.parts);
+ record.renderer.render({ ...record.scene.camera, effects });
+ const error = record.renderer.context.getError();
+ if (error !== 0) {
+ throw new Error(`WebGL render failed with error ${error}.`);
+ }
+}
+
+function status(record) {
+ const render = renderInfo(record.renderer);
+ record.lastRender = render;
+ return {
+ sessionId: record.sessionId,
+ revision: record.scene.revision,
+ inspection: record.scene.inspect(),
+ render,
+ };
+}
+
+function mutationStatus(record) {
+ try {
+ draw(record);
+ return { ...status(record), committed: true, renderSucceeded: true };
+ } catch (error) {
+ return {
+ sessionId: record.sessionId,
+ revision: record.scene.revision,
+ inspection: record.scene.inspect(),
+ render: record.lastRender ?? null,
+ committed: true,
+ renderSucceeded: false,
+ renderError: error.message,
+ };
+ }
+}
+
+window.__agentPreview = {
+ create({ recipe, sessionId, memoryBudgetMiB, backend }) {
+ if (active) {
+ throw new Error('Dispose the current scene before creating another.');
+ }
+ const scene = createAgentScene(recipe);
+ validatePreviewCamera(scene.camera);
+ let renderer;
+ try {
+ renderer = new Renderer67(canvas, scene.parts, {
+ ground: false,
+ hdr: true,
+ pixelRatio: 1,
+ samples: backend === 'cpu' ? 1 : 4,
+ memoryBudgetMiB,
+ });
+ const record = { scene, renderer, sessionId, checkpoints: new Map() };
+ draw(record);
+ const result = status(record);
+ if (backend === 'gpu' && /swiftshader|llvmpipe|software/i.test(result.render.graphics)) {
+ throw new Error('Hardware GPU rendering was requested, but the browser selected a software renderer.');
+ }
+ active = record;
+ return result;
+ } catch (error) {
+ renderer?.dispose();
+ // A throwing constructor may already own GPU objects without returning an instance.
+ canvas.getContext('webgl2')?.getExtension('WEBGL_lose_context')?.loseContext();
+ const replacement = document.createElement('canvas');
+ canvas.replaceWith(replacement);
+ canvas = replacement;
+ throw error;
+ }
+ },
+ inspect({ sessionId, ...options }) {
+ return { sessionId, ...requireSession(sessionId).scene.inspect(options) };
+ },
+ apply({ sessionId, operations, expectedRevision }) {
+ const record = requireSession(sessionId);
+ validatePreviewCamera(candidateCamera(record, operations));
+ record.scene.apply(operations, { expectedRevision });
+ return mutationStatus(record);
+ },
+ look({ sessionId }) {
+ const record = requireSession(sessionId);
+ draw(record);
+ return {
+ data: canvas.toDataURL('image/png').split(',')[1],
+ mimeType: 'image/png',
+ metadata: { sessionId, revision: record.scene.revision, ...renderInfo(record.renderer) },
+ };
+ },
+ checkpoint({ sessionId, checkpointId }) {
+ const record = requireSession(sessionId);
+ const handle = record.scene.checkpoint();
+ record.checkpoints.set(checkpointId, handle);
+ return { sessionId, checkpointId, revision: record.scene.revision };
+ },
+ restore({ sessionId, checkpointId, expectedRevision }) {
+ const record = requireSession(sessionId);
+ if (!record.checkpoints.has(checkpointId)) {
+ throw new Error('Unknown or released checkpoint.');
+ }
+ record.scene.restore(record.checkpoints.get(checkpointId), { expectedRevision });
+ return mutationStatus(record);
+ },
+ releaseCheckpoint({ sessionId, checkpointId }) {
+ const record = requireSession(sessionId);
+ if (!record.checkpoints.has(checkpointId)) {
+ throw new Error('Unknown or released checkpoint.');
+ }
+ record.scene.releaseCheckpoint(record.checkpoints.get(checkpointId));
+ record.checkpoints.delete(checkpointId);
+ return { sessionId, checkpointId, released: true };
+ },
+ exportRecipe({ sessionId }) {
+ const record = requireSession(sessionId);
+ return { sessionId, revision: record.scene.revision, recipe: record.scene.exportRecipe() };
+ },
+ dispose({ sessionId }) {
+ const record = requireSession(sessionId);
+ record.renderer.dispose();
+ record.checkpoints.clear();
+ active = null;
+ return { sessionId, disposed: true };
+ },
+};
diff --git a/scripts/agent-preview-fixture.mjs b/scripts/agent-preview-fixture.mjs
new file mode 100644
index 00000000..7809466f
--- /dev/null
+++ b/scripts/agent-preview-fixture.mjs
@@ -0,0 +1,40 @@
+export function createAgentPreviewFixture() {
+ const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [
+ { id: 'pedestal', type: 'lathe', profile: [[0,0],[0.8,0],[0.9,0.07],[0.9,0.16],[0.74,0.22],[0.48,0.28],[0.42,0.34],[0,0.34]], segments: 64 },
+ { id: 'bulb', type: 'sphere', segments: 48, rings: 32 },
+ { id: 'ring', type: 'torus', tubeRadius: 0.025, segments: 80, sides: 12 },
+ { id: 'post', type: 'cylinder', segments: 40, bevel: 0.02, bevelSegments: 4 },
+ { id: 'rail', type: 'tube', path: [[-0.65,-0.35,0],[-0.68,0.3,0],[-0.5,1.05,0],[0,1.38,0],[0.5,1.05,0],[0.68,0.3,0],[0.65,-0.35,0]], radius: 0.026, segments: 80, radialSegments: 12 },
+ { id: 'fin', type: 'extrude', contour: [[0,0],[0.28,0],[0.38,0.2],[0.18,0.4],[0,0.32]], depth: 0.035, bevel: 0.008, bevelSegments: 2 },
+ { id: 'panel', type: 'box', bevel: 0.06, subdivisions: 4 },
+ ],
+ materials: [
+ { id: 'porcelain', color: [0.7,0.8,0.77], metallic: 0.15, roughness: 0.27 },
+ { id: 'brass', color: [0.58,0.3,0.06], metallic: 0.85, roughness: 0.25 },
+ { id: 'teal', color: [0.015,0.12,0.14], metallic: 0.72, roughness: 0.3 },
+ { id: 'light', color: [0.23,0.8,0.65], metallic: 0.1, roughness: 0.21, emission: 2, emissiveColor: [0.23,0.8,0.65] },
+ ],
+ nodes: [
+ { id: 'lamp', label: 'Aster lamp', translation: [0,0.82,0] },
+ { id: 'foot', parent: 'lamp', geometry: 'pedestal', material: 'porcelain', translation: [0,-0.8,0] },
+ { id: 'stem', parent: 'lamp', geometry: 'post', material: 'teal', translation: [0,-0.15,0], scale: [0.12,0.72,0.12] },
+ { id: 'glow', parent: 'lamp', geometry: 'bulb', material: 'light', translation: [0,0.55,0], scale: [0.3,0.48,0.3] },
+ { id: 'switch', parent: 'lamp', geometry: 'panel', material: 'teal', translation: [0,-0.65,0.82], scale: [0.16,0.06,0.04] },
+ ],
+ camera: { eye: [3.7,2.82,4.6], target: [0,1.06,0], fov: 36, near: 0.1, far: 40 },
+ };
+ for (let index = 0; index < 4; index++) {
+ const angle = index * Math.PI / 4;
+ recipe.nodes.push({ id: `rail-${index}`, parent: 'lamp', geometry: 'rail', material: 'brass', rotation: [0,Math.sin(angle/2),0,Math.cos(angle/2)] });
+ }
+ for (let index = 0; index < 3; index++) {
+ recipe.nodes.push({ id: `ring-${index}`, parent: 'lamp', geometry: 'ring', material: index === 1 ? 'teal' : 'brass', translation: [0,-0.38 + index * 0.34,0], scale: [0.65,0.65,0.65], rotation: [Math.SQRT1_2,0,0,Math.SQRT1_2] });
+ }
+ for (let index = 0; index < 8; index++) {
+ const angle = index * Math.PI / 4;
+ recipe.nodes.push({ id: `fin-${index}`, parent: 'lamp', geometry: 'fin', material: 'brass', translation: [Math.sin(angle)*0.43,-0.46,Math.cos(angle)*0.43], rotation: [0,Math.sin(angle/2),0,Math.cos(angle/2)], scale: [0.4,0.4,0.4] });
+ }
+ return recipe;
+}
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
new file mode 100644
index 00000000..062421f7
--- /dev/null
+++ b/scripts/agent-runtime.mjs
@@ -0,0 +1,249 @@
+import { createServer } from 'node:http';
+import { randomUUID } from 'node:crypto';
+import { existsSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { build } from 'vite';
+import { chromium } from 'playwright';
+import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';
+
+const EMPTY_RECIPE = { format: '67js.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [] };
+const SCENE_LIMITS = createAgentScene(EMPTY_RECIPE).limits;
+const MAXIMUM_IMAGE_BYTES = 1024 * 1024;
+const MAXIMUM_QUEUED_CALLS = 16;
+const EVALUATION_TIMEOUT_MS = 30000;
+const html = '<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#182126}canvas{display:block;width:100vw;height:100vh}</style></head><body><canvas></canvas><script type="module" src="/preview.js"></script></body></html>';
+
+/** Local, serialized browser preview. No browser is launched until scene creation. */
+export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memory = 192 } = {}) {
+ if (!['gpu', 'cpu'].includes(backend)) {
+ throw new RangeError('backend must be gpu or cpu.');
+ }
+ if (!Number.isInteger(memory) || memory < 32 || memory > 256) {
+ throw new RangeError('memory must be an integer from 32 to 256 MiB.');
+ }
+ if (browserPath !== undefined && (typeof browserPath !== 'string' || !existsSync(browserPath))) {
+ throw new Error('The configured browser executable does not exist.');
+ }
+ let phase = 'idle';
+ let browserInstance;
+ let httpServer;
+ let page;
+ let activeSessionId = null;
+ let queuedCalls = 0;
+ let queue = Promise.resolve();
+ let closing;
+
+ function enqueue(task) {
+ if (closing || phase === 'closing' || phase === 'closed' || phase === 'failed') {
+ return Promise.reject(new Error(`The agent runtime is ${phase}.`));
+ }
+ if (queuedCalls >= MAXIMUM_QUEUED_CALLS) {
+ return Promise.reject(new Error('The preview call queue is full. Retry after pending calls finish.'));
+ }
+ queuedCalls++;
+ const result = queue.then(() => {
+ if (closing || phase === 'closed' || phase === 'failed') {
+ throw new Error(`The agent runtime is ${closing ? 'closing' : phase}.`);
+ }
+ return task();
+ });
+ queue = result.catch(() => {}).finally(() => {
+ queuedCalls--;
+ });
+ return result;
+ }
+
+ async function shutdownResources() {
+ try {
+ await browserInstance?.close();
+ } finally {
+ browserInstance = undefined;
+ page = undefined;
+ if (httpServer?.listening) {
+ httpServer.closeAllConnections();
+ await new Promise((resolve, reject) => httpServer.close(error => error ? reject(error) : resolve()));
+ }
+ httpServer = undefined;
+ }
+ }
+
+ async function boot() {
+ if (page) {
+ return;
+ }
+ phase = 'starting';
+ try {
+ const root = fileURLToPath(new URL('..', import.meta.url));
+ const bundle = await build({
+ root,
+ configFile: false,
+ logLevel: 'silent',
+ build: {
+ write: false,
+ minify: false,
+ lib: { entry: fileURLToPath(new URL('./agent-preview-browser.js', import.meta.url)), formats: ['es'] },
+ },
+ });
+ const outputs = (Array.isArray(bundle) ? bundle : [bundle]).flatMap(result => result.output);
+ if (outputs.length !== 1 || outputs[0].type !== 'chunk' || !outputs[0].isEntry) {
+ throw new Error('The private preview must produce one self-contained module.');
+ }
+ const code = outputs[0].code;
+ httpServer = createServer((request, response) => {
+ response.setHeader('Cache-Control', 'no-store');
+ response.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src data:; connect-src 'none'");
+ if (request.method !== 'GET' || !['/', '/preview.js'].includes(request.url)) {
+ response.writeHead(404);
+ response.end();
+ return;
+ }
+ response.setHeader('Content-Type', request.url === '/' ? 'text/html; charset=utf-8' : 'application/javascript; charset=utf-8');
+ response.end(request.url === '/' ? html : code);
+ });
+ await new Promise((resolve, reject) => {
+ httpServer.once('error', reject);
+ httpServer.listen(0, '127.0.0.1', resolve);
+ });
+ const origin = `http://127.0.0.1:${httpServer.address().port}`;
+ const nativeChrome = 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+ const executablePath = browserPath ?? (existsSync(nativeChrome) ? nativeChrome : undefined);
+ const args = ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'];
+ if (backend === 'cpu') {
+ args.push('--use-angle=swiftshader', '--enable-unsafe-swiftshader');
+ }
+ browserInstance = await chromium.launch({ headless: true, executablePath, args });
+ page = await browserInstance.newPage({ viewport: { width: 768, height: 512 }, deviceScaleFactor: 1 });
+ await page.route('**/*', route => {
+ const url = new URL(route.request().url());
+ return url.origin === origin ? route.continue() : route.abort();
+ });
+ page.setDefaultTimeout(15000);
+ await page.goto(origin);
+ await page.waitForFunction(() => Boolean(window.__agentPreview));
+ phase = 'ready';
+ } catch (error) {
+ phase = 'failed';
+ await shutdownResources();
+ throw error;
+ }
+ }
+
+ function requireSession(sessionId) {
+ if (!activeSessionId || sessionId !== activeSessionId) {
+ throw new Error('Unknown or disposed scene session.');
+ }
+ }
+
+ async function invoke(method, input) {
+ requireSession(input.sessionId);
+ if (!browserInstance?.isConnected() || page.isClosed()) {
+ phase = 'failed';
+ throw new Error('The preview browser disconnected. The scene cannot be recovered from this runtime.');
+ }
+ return evaluate(method, input);
+ }
+
+ async function evaluate(method, input) {
+ let timer;
+ let timedOut = false;
+ try {
+ return await Promise.race([
+ page.evaluate(({ method, input }) => window.__agentPreview[method](input), { method, input }),
+ new Promise((resolve, reject) => {
+ timer = setTimeout(() => {
+ timedOut = true;
+ phase = 'failed';
+ reject(new Error('The preview operation exceeded 30 seconds. This runtime must be closed.'));
+ }, EVALUATION_TIMEOUT_MS);
+ }),
+ ]);
+ } catch (error) {
+ if (timedOut) {
+ activeSessionId = null;
+ await shutdownResources();
+ }
+ throw error;
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
+ return Object.freeze({
+ async capabilities() {
+ return {
+ scene: AGENT_SCENE_CAPABILITIES,
+ sceneLimits: SCENE_LIMITS,
+ preview: { backend, memoryBudgetMiB: memory, maximumWidth: 1024, maximumHeight: 1024, maximumImageBytes: MAXIMUM_IMAGE_BYTES, maximumActiveScenes: 1, maximumQueuedCalls: MAXIMUM_QUEUED_CALLS, evaluationTimeoutMs: EVALUATION_TIMEOUT_MS },
+ phase: closing && phase !== 'closed' ? 'closing' : phase,
+ availableIn: 'source after npm 0.4.1',
+ unsupported: ['dynamic node creation', 'asset providers', 'arbitrary code execution', 'animation authoring', 'video jobs'],
+ };
+ },
+ create({ recipe }) {
+ return enqueue(async () => {
+ if (activeSessionId) {
+ throw new Error('Dispose the current scene before creating another.');
+ }
+ await boot();
+ const sessionId = randomUUID();
+ const result = await evaluate('create', { recipe, sessionId, memoryBudgetMiB: memory, backend });
+ activeSessionId = sessionId;
+ return result;
+ });
+ },
+ inspect(input) {
+ return enqueue(() => invoke('inspect', input));
+ },
+ apply(input) {
+ return enqueue(() => invoke('apply', input));
+ },
+ look(input) {
+ return enqueue(async () => {
+ requireSession(input.sessionId);
+ const width = input.width ?? 768;
+ const height = input.height ?? 512;
+ if (![width, height].every(value => Number.isInteger(value) && value >= 64 && value <= 1024)) {
+ throw new RangeError('Preview dimensions must be integers from 64 to 1024.');
+ }
+ await page.setViewportSize({ width, height });
+ const result = await invoke('look', { sessionId: input.sessionId });
+ if (Buffer.byteLength(result.data, 'base64') > MAXIMUM_IMAGE_BYTES) {
+ throw new Error('The PNG exceeds the 1 MiB image response budget. Request a smaller preview.');
+ }
+ result.metadata.requestedWidth = width;
+ result.metadata.requestedHeight = height;
+ result.metadata.backend = backend;
+ return result;
+ });
+ },
+ checkpoint(input) {
+ return enqueue(() => invoke('checkpoint', { ...input, checkpointId: randomUUID() }));
+ },
+ restore(input) {
+ return enqueue(() => invoke('restore', input));
+ },
+ releaseCheckpoint(input) {
+ return enqueue(() => invoke('releaseCheckpoint', input));
+ },
+ exportRecipe(input) {
+ return enqueue(() => invoke('exportRecipe', input));
+ },
+ dispose(input) {
+ return enqueue(async () => {
+ const result = await invoke('dispose', input);
+ activeSessionId = null;
+ return result;
+ });
+ },
+ close() {
+ if (!closing) {
+ phase = 'closing';
+ closing = queue.then(shutdownResources).finally(() => {
+ activeSessionId = null;
+ phase = 'closed';
+ });
+ }
+ return closing;
+ },
+ });
+}
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
new file mode 100644
index 00000000..c9e2c58c
--- /dev/null
+++ b/scripts/mcp-server.mjs
@@ -0,0 +1,142 @@
+import { McpServer } from '@modelcontextprotocol/server';
+import { serveStdio, StdioServerTransport } from '@modelcontextprotocol/server/stdio';
+import * as z from 'zod/v4';
+import { setPriority, constants } from 'node:os';
+import { resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const finite = z.number().min(-3.4028234663852886e38).max(3.4028234663852886e38);
+const positive = finite.positive();
+const nonnegative = finite.nonnegative();
+const unit = z.number().min(0).max(1);
+const identifier = z.string().min(1).max(128).regex(/\S/).describe('Stable resource or node ID, with at least one non-space character.');
+const vector3 = z.tuple([finite, finite, finite]);
+const color = z.tuple([unit, unit, unit]);
+const quaternion = z.tuple([finite, finite, finite, finite]);
+const point2 = z.tuple([finite, finite]);
+const detail = (minimum, maximum) => z.number().int().min(minimum).max(maximum).optional();
+const segments = detail(3, 2048);
+const ring = z.array(point2).min(3).max(4096);
+const nodeFields = {
+ label: z.string().max(256).optional().describe('Human-readable label. Identity remains the node ID.'),
+ parent: identifier.nullable().optional().describe('Parent node ID, or null for a root. Local transforms stay unchanged.'),
+ translation: vector3.optional().describe('Local XYZ translation.'),
+ rotation: quaternion.optional().describe('Nonzero local XYZW quaternion. The backend normalizes it.'),
+ scale: z.tuple([positive, positive, positive]).optional().describe('Positive local XYZ scale.'),
+};
+const materialFields = {
+ color: color.optional().describe('Linear RGB base color, each component between zero and one.'),
+ metallic: unit.optional(),
+ roughness: unit.optional(),
+ emission: nonnegative.optional().describe('Emission multiplier. Backend checks Float32 radiance products.'),
+ emissiveColor: z.tuple([nonnegative, nonnegative, nonnegative]).optional().describe('Independent linear RGB emission color.'),
+};
+const cameraFields = {
+ eye: vector3.optional().describe('Camera position in world coordinates.'),
+ target: vector3.optional().describe('World point toward which the camera looks.'),
+ up: vector3.optional().describe('Nonzero camera up direction, not collinear with the view direction.'),
+ fov: finite.gt(0).lt(180).optional().describe('Vertical perspective field of view in degrees.'),
+ near: positive.optional().describe('Near clipping distance. Must be less than far.'),
+ far: positive.optional().describe('Far clipping distance. Must exceed near.'),
+};
+const geometry = z.discriminatedUnion('type', [
+ z.strictObject({ id: identifier, type: z.literal('box'), bevel: finite.optional(), subdivisions: detail(1, 128) }),
+ z.strictObject({ id: identifier, type: z.literal('cylinder'), segments, bevel: finite.optional(), bevelSegments: detail(1, 128) }),
+ z.strictObject({ id: identifier, type: z.literal('sphere'), segments, rings: detail(2, 2048) }),
+ z.strictObject({ id: identifier, type: z.literal('torus'), tubeRadius: finite.optional(), segments, sides: detail(3, 128), arc: finite.optional(), start: finite.optional() }),
+ z.strictObject({ id: identifier, type: z.literal('lathe'), profile: z.array(point2).min(2).max(4096), segments, startAngle: finite.optional(), sweep: finite.optional() }),
+ z.strictObject({ id: identifier, type: z.literal('extrude'), contour: ring, holes: z.array(ring).max(128).optional(), depth: finite.optional(), steps: detail(1, 256), bevel: finite.optional(), bevelThickness: finite.optional(), bevelSegments: detail(1, 32) }),
+ z.strictObject({ id: identifier, type: z.literal('tube'), path: z.array(vector3).min(2).max(4096), radius: finite.optional(), segments, radialSegments: detail(3, 128), closed: z.boolean().optional() }),
+]);
+const recipe = z.strictObject({
+ format: z.literal('67js.scene'),
+ schemaVersion: z.literal(1),
+ geometries: z.array(geometry).max(256),
+ materials: z.array(z.strictObject({ id: identifier, tag: z.enum(['surface', 'unlit']).optional(), ...materialFields })).max(256),
+ nodes: z.array(z.strictObject({ id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields })).max(4096),
+ camera: z.strictObject(cameraFields).optional(),
+}).describe('Bounded scene recipe. Backend validates references, mesh resource pairs, hierarchy, geometry budgets and camera consistency.');
+const operation = z.discriminatedUnion('type', [
+ z.strictObject({ type: z.literal('set-node'), id: identifier, ...nodeFields }),
+ z.strictObject({ type: z.literal('set-material'), id: identifier, ...materialFields }),
+ z.strictObject({ type: z.literal('set-camera'), ...cameraFields }),
+]);
+const sessionFields = { sessionId: z.uuid().describe('Session UUID returned by scene_create.') };
+const checkpointFields = { ...sessionFields, checkpointId: z.uuid().describe('Checkpoint UUID returned by scene_checkpoint for this session.') };
+const expectedRevision = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).describe('Current revision returned by create, inspect, apply or restore. Stale edits fail atomically.');
+const readOnly = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
+const edit = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false };
+
+function jsonResult(value) {
+ return { content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value };
+}
+
+export function createAgentMcpServer(runtime, { version = '0.4.1' } = {}) {
+ const server = new McpServer({ name: '67js-scene', version }, {
+ instructions: 'Start with scene_capabilities, then scene_create and scene_inspect. Before editing, save a scene_checkpoint. Apply small batches with the current expectedRevision and check committed, revision and renderSucceeded. A committed edit can have a separate renderError; do not retry it with an old revision. Use scene_look to judge the rendered image. Restore failed experiments or release unused checkpoints. Export the final recipe and dispose the scene when finished. Resources and node membership are fixed. No arbitrary JavaScript, URLs, files or jobs are exposed.',
+ });
+ let closePromise;
+ server.server.onclose = () => {
+ closePromise ??= Promise.resolve().then(() => runtime.close());
+ closePromise.then(
+ () => console.error('67js preview resources closed.'),
+ error => console.error(`67js runtime cleanup failed: ${error.message}`),
+ );
+ };
+ function register(name, description, inputSchema, annotations, run) {
+ server.registerTool(name, { description, inputSchema, annotations }, async argumentsValue => {
+ try {
+ return await run(argumentsValue);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ return { isError: true, content: [{ type: 'text', text: `${name} failed: ${message}` }] };
+ }
+ });
+ }
+ register('scene_capabilities', 'Read supported recipe features and runtime budgets before authoring. Does not launch a browser.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.capabilities()));
+ register('scene_create', 'Create the single active render scene from a JSON recipe. Dispose an existing scene first.', z.strictObject({ recipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.create(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.'), 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('scene_apply', 'Atomically apply one small command batch. Successful batches increment revision once. Geometry and node membership remain fixed.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Commands with flat fields. All commands validate before publication.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));
+ register('scene_look', 'Render the active scene as a bounded PNG image for visual assessment.', z.strictObject({ ...sessionFields, 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);
+ return { content: [{ type: 'image', data, mimeType }, { type: 'text', text: JSON.stringify(metadata) }], structuredContent: metadata };
+ });
+ register('scene_checkpoint', 'Save a private recipe snapshot. Up to eight checkpoints can be retained per session.', z.strictObject(sessionFields), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.checkpoint(argumentsValue)));
+ register('scene_restore', 'Restore a checkpoint atomically using the current revision. The checkpoint remains available and revision increments.', z.strictObject({ ...checkpointFields, expectedRevision }), edit, async argumentsValue => jsonResult(await runtime.restore(argumentsValue)));
+ register('scene_release_checkpoint', 'Release one checkpoint slot. Released or foreign checkpoints fail.', z.strictObject(checkpointFields), edit, async argumentsValue => jsonResult(await runtime.releaseCheckpoint(argumentsValue)));
+ register('scene_export_recipe', 'Read a detached canonical JSON recipe for reproduction.', z.strictObject(sessionFields), readOnly, async argumentsValue => jsonResult(await runtime.exportRecipe(argumentsValue)));
+ register('scene_dispose', 'Dispose the active scene and its checkpoints, releasing renderer resources.', z.strictObject(sessionFields), edit, async argumentsValue => jsonResult(await runtime.dispose(argumentsValue)));
+ return server;
+}
+
+async function main() {
+ const options = { backend: 'gpu', memory: 192 };
+ const argumentsValue = process.argv.slice(2);
+ for (let index = 0; index < argumentsValue.length; index += 2) {
+ const name = argumentsValue[index];
+ const value = argumentsValue[index + 1];
+ if (!['--backend', '--browser', '--memory'].includes(name) || value === undefined) {
+ throw new Error('Use --backend cpu|gpu, --browser <local executable path>, and --memory <32..256 MiB>.');
+ }
+ options[name.slice(2)] = name === '--memory' ? Number(value) : value;
+ }
+ if (!['cpu', 'gpu'].includes(options.backend) || !Number.isInteger(options.memory) || options.memory < 32 || options.memory > 256) {
+ throw new Error('Backend must be cpu or gpu, and memory must be an integer from 32 to 256 MiB.');
+ }
+ setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+ const { createAgentRuntime } = await import('./agent-runtime.mjs');
+ const handle = serveStdio(async () => createAgentMcpServer(await createAgentRuntime(options)), {
+ transport: new StdioServerTransport(process.stdin, process.stdout, { maxBufferSize: 2 * 1024 * 1024 }),
+ onerror: error => console.error(`67js MCP error: ${error.message}`),
+ });
+ for (const signal of ['SIGINT', 'SIGTERM']) {
+ process.once(signal, () => handle.close().catch(error => console.error(`67js shutdown failed: ${error.message}`)));
+ }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ main().catch(error => {
+ console.error(error.message);
+ process.exitCode = 1;
+ });
+}
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index ab270cf1..d670906c 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -40,7 +40,7 @@ const sourceDocuments = [
'gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md',
'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
- 'surface-attachment.md', 'agent-scene.md',
+ 'surface-attachment.md', 'agent-scene.md', 'mcp.md',
];
for (const name of sourceDocuments) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
diff --git a/scripts/smoke-agent-scene.mjs b/scripts/smoke-agent-scene.mjs
index f689d757..e922dda3 100644
--- a/scripts/smoke-agent-scene.mjs
+++ b/scripts/smoke-agent-scene.mjs
@@ -2,49 +2,14 @@ import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { constants, setPriority } from 'node:os';
import { chromium } from 'playwright';
+import { createAgentPreviewFixture } from './agent-preview-fixture.mjs';
setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
const width = Number(process.argv[2] ?? 960);
const height = Number(process.argv[3] ?? 540);
const origin = process.argv[4] ?? 'http://127.0.0.1:5173';
await mkdir('artifacts', { recursive: true });
-const recipe = {
- format: '67js.scene', schemaVersion: 1,
- geometries: [
- { id: 'pedestal', type: 'lathe', profile: [[0,0],[0.8,0],[0.9,0.07],[0.9,0.16],[0.74,0.22],[0.48,0.28],[0.42,0.34],[0,0.34]], segments: 64 },
- { id: 'bulb', type: 'sphere', segments: 48, rings: 32 },
- { id: 'ring', type: 'torus', tubeRadius: 0.025, segments: 80, sides: 12 },
- { id: 'post', type: 'cylinder', segments: 40, bevel: 0.02, bevelSegments: 4 },
- { id: 'rail', type: 'tube', path: [[-0.65,-0.35,0],[-0.68,0.3,0],[-0.5,1.05,0],[0,1.38,0],[0.5,1.05,0],[0.68,0.3,0],[0.65,-0.35,0]], radius: 0.026, segments: 80, radialSegments: 12 },
- { id: 'fin', type: 'extrude', contour: [[0,0],[0.28,0],[0.38,0.2],[0.18,0.4],[0,0.32]], depth: 0.035, bevel: 0.008, bevelSegments: 2 },
- { id: 'panel', type: 'box', bevel: 0.06, subdivisions: 4 },
- ],
- materials: [
- { id: 'porcelain', color: [0.7,0.8,0.77], metallic: 0.15, roughness: 0.27 },
- { id: 'brass', color: [0.58,0.3,0.06], metallic: 0.85, roughness: 0.25 },
- { id: 'teal', color: [0.015,0.12,0.14], metallic: 0.72, roughness: 0.3 },
- { id: 'light', color: [0.23,0.8,0.65], metallic: 0.1, roughness: 0.21, emission: 2, emissiveColor: [0.23,0.8,0.65] },
- ],
- nodes: [
- { id: 'lamp', label: 'Aster lamp', translation: [0,0.82,0] },
- { id: 'foot', parent: 'lamp', geometry: 'pedestal', material: 'porcelain', translation: [0,-0.8,0] },
- { id: 'stem', parent: 'lamp', geometry: 'post', material: 'teal', translation: [0,-0.15,0], scale: [0.12,0.72,0.12] },
- { id: 'glow', parent: 'lamp', geometry: 'bulb', material: 'light', translation: [0,0.55,0], scale: [0.3,0.48,0.3] },
- { id: 'switch', parent: 'lamp', geometry: 'panel', material: 'teal', translation: [0,-0.65,0.82], scale: [0.16,0.06,0.04] },
- ],
- camera: { eye: [3.7,2.82,4.6], target: [0,1.06,0], fov: 36, near: 0.1, far: 40 },
-};
-for (let index = 0; index < 4; index++) {
- const angle = index * Math.PI / 4;
- recipe.nodes.push({ id: `rail-${index}`, parent: 'lamp', geometry: 'rail', material: 'brass', rotation: [0,Math.sin(angle/2),0,Math.cos(angle/2)] });
-}
-for (let index = 0; index < 3; index++) {
- recipe.nodes.push({ id: `ring-${index}`, parent: 'lamp', geometry: 'ring', material: index === 1 ? 'teal' : 'brass', translation: [0,-0.38 + index * 0.34,0], scale: [0.65,0.65,0.65], rotation: [Math.SQRT1_2,0,0,Math.SQRT1_2] });
-}
-for (let index = 0; index < 8; index++) {
- const angle = index * Math.PI / 4;
- recipe.nodes.push({ id: `fin-${index}`, parent: 'lamp', geometry: 'fin', material: 'brass', translation: [Math.sin(angle)*0.43,-0.46,Math.cos(angle)*0.43], rotation: [0,Math.sin(angle/2),0,Math.cos(angle/2)], scale: [0.4,0.4,0.4] });
-}
+const recipe = createAgentPreviewFixture();
const harness = `<!doctype html><html><head><style>html,body{margin:0;height:100%;background:#152126}canvas{width:100vw;height:100vh;display:block}</style></head><body><canvas id="scene"></canvas><script type="module">
import {createAgentScene} from '/src/agent-scene.js';
import {Renderer67} from '/src/renderer.js';
diff --git a/scripts/smoke-mcp.mjs b/scripts/smoke-mcp.mjs
new file mode 100644
index 00000000..06f4cd27
--- /dev/null
+++ b/scripts/smoke-mcp.mjs
@@ -0,0 +1,120 @@
+import assert from 'node:assert/strict';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { constants, setPriority } from 'node:os';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+import { createAgentPreviewFixture } from './agent-preview-fixture.mjs';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const backend = process.argv[2] ?? 'gpu';
+const era = process.argv[3] ?? 'modern';
+assert.ok(['gpu', 'cpu'].includes(backend));
+assert.ok(['modern', 'legacy'].includes(era));
+await mkdir('artifacts', { recursive: true });
+const transport = new StdioClientTransport({
+ command: process.execPath,
+ args: [resolve('scripts/mcp-server.mjs'), '--backend', backend, '--memory', '192'],
+ stderr: 'pipe',
+ cwd: process.cwd(),
+});
+let errors = '';
+transport.stderr.on('data', chunk => { errors += chunk.toString(); });
+const client = new Client({ name: '67js-render-proof', version: '1' }, {
+ versionNegotiation: { mode: era === 'modern' ? { pin: '2026-07-28' } : 'legacy' },
+});
+let processId;
+let report;
+
+async function call(name, argumentsValue = {}) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 60000 });
+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);
+ return result;
+}
+
+async function look(sessionId, label, width = 960, height = 540) {
+ const result = await call('scene_look', { sessionId, width, height });
+ const image = result.content.find(item => item.type === 'image');
+ assert.equal(image.mimeType, 'image/png');
+ const bytes = Buffer.from(image.data, 'base64');
+ assert.deepEqual(bytes.subarray(0, 8), Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
+ assert.ok(bytes.byteLength > 10000);
+ assert.ok(bytes.byteLength <= 1024 * 1024);
+ assert.equal(bytes.readUInt32BE(16), result.structuredContent.width);
+ assert.equal(bytes.readUInt32BE(20), result.structuredContent.height);
+ assert.equal(result.structuredContent.requestedWidth, width);
+ assert.equal(result.structuredContent.requestedHeight, height);
+ assert.ok(result.structuredContent.estimatedBytes <= 192 * 1024 * 1024);
+ await writeFile(`artifacts/mcp-${backend}-${era}-${label}.png`, bytes);
+ return { bytes, metadata: result.structuredContent };
+}
+
+try {
+ await client.connect(transport);
+ processId = transport.pid;
+ const listing = await client.listTools();
+ assert.equal(listing.tools.length, 10);
+ const capabilities = (await call('scene_capabilities')).structuredContent;
+ assert.equal(capabilities.phase, 'idle');
+ const created = (await call('scene_create', { recipe: createAgentPreviewFixture() })).structuredContent;
+ const { sessionId } = created;
+ assert.equal(created.inspection.counts.parts, 19);
+ assert.equal(created.inspection.counts.geometries, 7);
+ assert.equal(created.revision, 0);
+ assert.match(created.render.graphics, backend === 'gpu' ? /NVIDIA/i : /SwiftShader/i);
+ const before = await look(sessionId, 'before');
+ const checkpoint = (await call('scene_checkpoint', { sessionId })).structuredContent;
+ const edited = (await call('scene_apply', {
+ sessionId, expectedRevision: 0,
+ operations: [
+ { type: 'set-node', id: 'lamp', translation: [0.18, 0.82, 0] },
+ { type: 'set-node', id: 'glow', scale: [0.34, 0.3, 0.34], translation: [0, 0.75, 0] },
+ { type: 'set-material', id: 'light', color: [0.9, 0.28, 0.04], emissiveColor: [0.9, 0.28, 0.04] },
+ ],
+ })).structuredContent;
+ assert.equal(edited.revision, 1);
+ assert.equal(edited.committed, true);
+ assert.equal(edited.renderSucceeded, true);
+ const after = await look(sessionId, 'after');
+ assert.notDeepEqual(after.bytes, before.bytes);
+ const stale = await client.callTool({ name: 'scene_apply', arguments: {
+ sessionId, expectedRevision: 0, operations: [{ type: 'set-node', id: 'lamp', translation: [20, 0, 0] }],
+ } });
+ assert.equal(stale.isError, true);
+ const inspection = (await call('scene_inspect', { sessionId, ids: ['lamp', 'glow'], includeBounds: true })).structuredContent;
+ assert.equal(inspection.revision, 1);
+ assert.equal(inspection.nodes.length, 2);
+ assert.ok(inspection.nodes[1].bounds);
+ const restoredStatus = (await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: 1 })).structuredContent;
+ assert.equal(restoredStatus.committed, true);
+ assert.equal(restoredStatus.renderSucceeded, true);
+ const restored = await look(sessionId, 'restored');
+ assert.deepEqual(restored.bytes, before.bytes);
+ await call('scene_release_checkpoint', { sessionId, checkpointId: checkpoint.checkpointId });
+ const exported = (await call('scene_export_recipe', { sessionId })).structuredContent;
+ assert.equal(exported.revision, 2);
+ assert.deepEqual(exported.recipe.nodes.find(node => node.id === 'lamp').translation, [0, 0.82, 0]);
+ await writeFile(`artifacts/mcp-${backend}-${era}-recipe.json`, JSON.stringify(exported.recipe, null, 2));
+ const portrait = await look(sessionId, 'portrait', 540, 960);
+ await call('scene_apply', { sessionId, expectedRevision: 2, operations: [
+ { type: 'set-camera', eye: [0, 5.5, 0], target: [0, 1.06, 0], up: [0, 0, -1] },
+ ] });
+ await look(sessionId, 'top', 540, 960);
+ const disposed = (await call('scene_dispose', { sessionId })).structuredContent;
+ assert.equal(disposed.disposed, true);
+ const missing = await client.callTool({ name: 'scene_inspect', arguments: { sessionId } });
+ assert.equal(missing.isError, true);
+ // The browser remains available after disposal, but a new scene receives a new identity.
+ const replacement = (await call('scene_create', { recipe: createAgentPreviewFixture() })).structuredContent;
+ assert.notEqual(replacement.sessionId, sessionId);
+ await call('scene_dispose', { sessionId: replacement.sessionId });
+ report = { backend, era, tools: listing.tools.length, parts: created.inspection.counts.parts, geometryBytes: created.inspection.geometryBytes,
+ graphics: created.render.graphics, before: before.metadata, portrait: portrait.metadata, restorePngExact: true, staleRevisionRejected: true };
+} finally {
+ await client.close();
+}
+assert.match(errors, /67js preview resources closed\./);
+assert.doesNotMatch(errors, /cleanup failed|shutdown failed/);
+assert.throws(() => process.kill(processId, 0), /ESRCH/);
+await writeFile(`artifacts/mcp-${backend}-${era}.json`, JSON.stringify(report, null, 2));
+console.log(JSON.stringify(report));
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 02fcb347..6a698f3d 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -30,6 +30,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Static vertex wrapping uses optional `src/shrinkwrap.js` and the checkout's `docs/shrinkwrap.md`.
- A rigid accessory on a morphing or skinned surface uses optional `src/surface-attachment.js` and `docs/surface-attachment.md`.
- Agent scene recipes use optional `src/agent-scene.js` and `docs/agent-scene.md`; verify source versus published availability before importing.
+- Agent tool calls use the source-only stdio server in `scripts/mcp-server.mjs`; read `docs/mcp.md` for launch, tool schemas and persistent PNG feedback.
- An image or video export uses `render-67js-media`.
Read [scene-contract.md](references/scene-contract.md) before creating parts or changing materials.
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index e7032f1a..b5cda096 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -142,6 +142,13 @@ Keep JSON commands and snapshots exposed to agents; retained matrices and immuta
Do not inspect all vertex bounds in a frame loop. Memory estimates cover unique geometry arrays, not total RAM or VRAM.
The scene addon does not implement MCP transport, dynamic node creation, asset search, or render jobs.
+For a configured MCP client, use the separate source-only server documented in `docs/mcp.md`.
+Call `scene_capabilities`, create one JSON scene, inspect IDs, checkpoint, apply a small batch, and assess `scene_look` PNG content.
+Use the revision returned by each committed apply or restore. A response with `committed: true` and `renderSucceeded: false` still advances revision.
+Inspect or export the canonical recipe after a render failure; do not retry the edit with its old revision.
+The server retains one renderer, bounds image dimensions and payloads, and closes its browser on stdio EOF.
+Export the recipe before disposal. Dynamic nodes, asset ingestion, animation authoring and video jobs remain unsupported by these tools.
+
`cameraView('front' | 'right' | 'top')` returns an orthographic camera with the correct up vector.
`fitOrthographicHeight(bounds, view, aspect)` frames both model width and height.
The `unlit` tag and a front orthographic camera produce flat XY geometry.
diff --git a/tests/agent-preview.test.js b/tests/agent-preview.test.js
new file mode 100644
index 00000000..b88bc3bf
--- /dev/null
+++ b/tests/agent-preview.test.js
@@ -0,0 +1,89 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { Script, createContext } from 'node:vm';
+import { mat4 } from 'gl-matrix';
+import { createAgentScene } from '../src/agent-scene.js';
+import { applyProjection } from '../src/camera.js';
+
+const source = (await readFile(new URL('../scripts/agent-preview-browser.js', import.meta.url), 'utf8')).replace(/^import .+;\r?$/gm, '');
+
+function previewHarness() {
+ let renderError = 0;
+ let lost = false;
+ const canvas = { width: 768, height: 512 };
+ class FaultInjectedRenderer {
+ memoryPlan = { estimatedBytes: 1024 };
+ capabilities = { hdr: true, samples: 4 };
+ context = {
+ isContextLost: () => lost,
+ getError: () => renderError,
+ getExtension: () => null,
+ getParameter: () => 'Test renderer',
+ };
+ resize() {}
+ updateParts() {}
+ render() {}
+ dispose() {}
+ }
+ const context = createContext({
+ window: {},
+ document: { querySelector: () => canvas },
+ // The real browser bundles these functions in one realm. Bridge only the VM realm here.
+ createAgentScene: input => createAgentScene(JSON.parse(JSON.stringify(input))),
+ applyProjection, mat4,
+ Renderer67: FaultInjectedRenderer,
+ });
+ // Evaluate only trusted repository adapter code; inject the driver boundary for failure cases.
+ new Script(source).runInContext(context);
+ return {
+ preview: context.window.__agentPreview,
+ injectError: value => { renderError = value; },
+ loseContext: () => { lost = true; },
+ };
+}
+
+function recipe() {
+ return { format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'cube', type: 'box', bevel: 0 }],
+ materials: [{ id: 'paint', color: [0.4, 0.5, 0.6] }],
+ nodes: [{ id: 'cube', geometry: 'cube', material: 'paint' }] };
+}
+
+test('preview rejects a camera that overflows at a permitted aspect before committing edits', () => {
+ const { preview } = previewHarness();
+ const input = recipe();
+ input.camera = { fov: 1e-36 };
+ assert.throws(() => preview.create({ recipe: input, sessionId: 'scene', backend: 'gpu', memoryBudgetMiB: 192 }), /aspect ratios/);
+ preview.create({ recipe: recipe(), sessionId: 'scene', backend: 'gpu', memoryBudgetMiB: 192 });
+ assert.throws(() => preview.apply({ sessionId: 'scene', expectedRevision: 0, operations: [
+ { type: 'set-node', id: 'cube', translation: [1, 2, 3] },
+ { type: 'set-camera', fov: 1e-36 },
+ ] }), /aspect ratios/);
+ assert.equal(preview.exportRecipe({ sessionId: 'scene' }).revision, 0);
+ assert.deepEqual(preview.exportRecipe({ sessionId: 'scene' }).recipe.nodes[0].translation, [0, 0, 0]);
+});
+
+test('driver errors disclose committed revision and context loss preserves recipe recovery', () => {
+ const harness = previewHarness();
+ const { preview } = harness;
+ preview.create({ recipe: recipe(), sessionId: 'scene', backend: 'gpu', memoryBudgetMiB: 192 });
+ preview.checkpoint({ sessionId: 'scene', checkpointId: 'checkpoint' });
+ harness.injectError(1285);
+ const result = preview.apply({ sessionId: 'scene', expectedRevision: 0, operations: [
+ { type: 'set-node', id: 'cube', translation: [1, 2, 3] },
+ ] });
+ assert.equal(result.committed, true);
+ assert.equal(result.renderSucceeded, false);
+ assert.equal(result.revision, 1);
+ assert.match(result.renderError, /1285/);
+ assert.deepEqual(preview.exportRecipe({ sessionId: 'scene' }).recipe.nodes[0].translation, [1, 2, 3]);
+ const restored = preview.restore({ sessionId: 'scene', checkpointId: 'checkpoint', expectedRevision: 1 });
+ assert.equal(restored.committed, true);
+ assert.equal(restored.renderSucceeded, false);
+ assert.equal(restored.revision, 2);
+ harness.loseContext();
+ assert.equal(preview.exportRecipe({ sessionId: 'scene' }).revision, 2);
+ assert.equal(preview.inspect({ sessionId: 'scene' }).revision, 2);
+ assert.equal(preview.dispose({ sessionId: 'scene' }).disposed, true);
+});
diff --git a/tests/agent-runtime.test.js b/tests/agent-runtime.test.js
new file mode 100644
index 00000000..02d2b25b
--- /dev/null
+++ b/tests/agent-runtime.test.js
@@ -0,0 +1,35 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createAgentRuntime } from '../scripts/agent-runtime.mjs';
+
+test('runtime reports real scene capabilities without launching a browser and closes idempotently', async () => {
+ const runtime = createAgentRuntime({ backend: 'cpu', memory: 64 });
+ const capabilities = await runtime.capabilities();
+ assert.equal(capabilities.phase, 'idle');
+ assert.equal(capabilities.scene.schemaVersion, 1);
+ assert.equal(capabilities.preview.maximumActiveScenes, 1);
+ assert.equal(capabilities.preview.memoryBudgetMiB, 64);
+ assert.equal(capabilities.preview.backend, 'cpu');
+ assert.equal(capabilities.sceneLimits.maxGeometryBytes, 32 * 1024 * 1024);
+ await runtime.close();
+ await runtime.close();
+ assert.equal((await runtime.capabilities()).phase, 'closed');
+ await assert.rejects(runtime.create({ recipe: {} }), /closed/);
+});
+
+test('invalid preview configuration rejects before any browser or renderer allocation', () => {
+ assert.throws(() => createAgentRuntime({ backend: 'fake' }), /backend/);
+ for (const memory of [0, 31, 257, 64.5, NaN]) {
+ assert.throws(() => createAgentRuntime({ memory }), /memory/);
+ }
+ assert.throws(() => createAgentRuntime({ browser: 'does-not-exist-browser.exe' }), /browser/);
+});
+
+test('requests cannot address an absent session or enter a closing runtime', async () => {
+ const runtime = createAgentRuntime();
+ await assert.rejects(runtime.inspect({ sessionId: 'missing' }), /Unknown/);
+ await assert.rejects(runtime.look({ sessionId: 'missing' }), /Unknown/);
+ const closing = runtime.close();
+ await assert.rejects(runtime.checkpoint({ sessionId: 'missing' }), /closing|closed/);
+ await closing;
+});
diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.js
new file mode 100644
index 00000000..f362a0d5
--- /dev/null
+++ b/tests/mcp-tools.test.js
@@ -0,0 +1,197 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { randomUUID } from 'node:crypto';
+import { PassThrough } from 'node:stream';
+import { Client } from '@modelcontextprotocol/client';
+import { InMemoryTransport } from '@modelcontextprotocol/server';
+import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
+import { createAgentMcpServer } from '../scripts/mcp-server.mjs';
+import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';
+
+const png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=';
+
+function recipe() {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'cube', type: 'box', bevel: 0 }],
+ materials: [{ id: 'blue', color: [0.1, 0.3, 0.8] }],
+ nodes: [{ id: 'mesh', geometry: 'cube', material: 'blue' }],
+ };
+}
+
+async function connect(context) {
+ let scene;
+ let closed = false;
+ let calls = 0;
+ const sessionId = randomUUID();
+ const checkpoints = new Map();
+ const status = () => ({ sessionId, revision: scene.revision, inspection: scene.inspect(), render: { backend: 'fake' } });
+ const runtime = {
+ async capabilities() { return AGENT_SCENE_CAPABILITIES; },
+ async create({ recipe: input }) {
+ calls++;
+ scene = createAgentScene(input);
+ return status();
+ },
+ async inspect({ sessionId: requested, ...options }) {
+ calls++;
+ assert.equal(requested, sessionId);
+ return { sessionId, ...scene.inspect(options) };
+ },
+ async apply({ expectedRevision, operations }) {
+ calls++;
+ scene.apply(operations, { expectedRevision });
+ return status();
+ },
+ async look({ width, height }) {
+ calls++;
+ return { data: png, mimeType: 'image/png', metadata: { sessionId, revision: scene.revision, width, height, backend: 'fake' } };
+ },
+ async checkpoint() {
+ const checkpointId = randomUUID();
+ checkpoints.set(checkpointId, scene.checkpoint());
+ return { checkpointId, sessionId, revision: scene.revision };
+ },
+ async restore({ checkpointId, expectedRevision }) {
+ scene.restore(checkpoints.get(checkpointId), { expectedRevision });
+ return status();
+ },
+ async releaseCheckpoint({ checkpointId }) {
+ scene.releaseCheckpoint(checkpoints.get(checkpointId));
+ checkpoints.delete(checkpointId);
+ return { released: true, sessionId, checkpointId };
+ },
+ async exportRecipe() { return { sessionId, revision: scene.revision, recipe: scene.exportRecipe() }; },
+ async dispose() {
+ scene = undefined;
+ return { disposed: true, sessionId };
+ },
+ async close() { closed = true; },
+ };
+ const server = createAgentMcpServer(runtime);
+ const client = new Client({ name: '67js-boundary-test', version: '1' });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ context.after(async () => {
+ await client.close();
+ await server.close();
+ });
+ return { client, server, sessionId, calls: () => calls, closed: () => closed };
+}
+
+async function rejected(client, name, argumentsValue) {
+ let result;
+ try {
+ result = await client.callTool({ name, arguments: argumentsValue });
+ } catch (error) {
+ assert.match(error.message, /invalid|validation|schema|expected|unrecognized/i);
+ return;
+ }
+ assert.equal(result.isError, true, `${name} must reject invalid arguments`);
+}
+
+test('SDK advertises the complete strict JSON contract and truthful annotations', async context => {
+ const { client } = await connect(context);
+ const { tools } = await client.listTools();
+ assert.deepEqual(tools.map(tool => tool.name).sort(), [
+ 'scene_apply', 'scene_capabilities', 'scene_checkpoint', 'scene_create', 'scene_dispose',
+ 'scene_export_recipe', 'scene_inspect', 'scene_look', 'scene_release_checkpoint', 'scene_restore',
+ ]);
+ for (const tool of tools) {
+ assert.equal(tool.inputSchema.type, 'object');
+ assert.equal(tool.inputSchema.additionalProperties, false);
+ assert.equal(tool.annotations.openWorldHint, false);
+ assert.ok(tool.description.length > 20);
+ }
+ const apply = tools.find(tool => tool.name === 'scene_apply');
+ assert.ok(apply.inputSchema.required.includes('expectedRevision'));
+ assert.equal(apply.inputSchema.properties.operations.maxItems, 256);
+ assert.equal(apply.annotations.idempotentHint, false);
+ const create = tools.find(tool => tool.name === 'scene_create');
+ const recipeSchema = create.inputSchema.properties.recipe;
+ assert.equal(recipeSchema.additionalProperties, false);
+ assert.equal(recipeSchema.properties.nodes.maxItems, 4096);
+ assert.equal(recipeSchema.properties.materials.maxItems, 256);
+ assert.equal(recipeSchema.properties.geometries.maxItems, 256);
+ const variants = recipeSchema.properties.geometries.items.oneOf ?? recipeSchema.properties.geometries.items.anyOf;
+ assert.deepEqual(variants.map(variant => variant.properties.type.const), ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube']);
+ assert.ok(variants.every(variant => variant.additionalProperties === false));
+ const look = tools.find(tool => tool.name === 'scene_look');
+ assert.equal(look.annotations.readOnlyHint, true);
+ assert.equal(look.inputSchema.properties.width.maximum, 1024);
+});
+
+test('SDK rejects unknown fields, missing revisions, invalid vectors and oversized inputs before runtime dispatch', async context => {
+ const boundary = await connect(context);
+ const { client, sessionId } = boundary;
+ await rejected(client, 'scene_capabilities', { javascript: 'process.exit()' });
+ await rejected(client, 'scene_inspect', { sessionId: 'not-a-uuid' });
+ await rejected(client, 'scene_look', { sessionId, width: 1025 });
+ await rejected(client, 'scene_look', { sessionId, file: 'out.png' });
+ await rejected(client, 'scene_restore', { sessionId, checkpointId: randomUUID() });
+ await rejected(client, 'scene_apply', { sessionId, operations: [{ type: 'set-camera' }] });
+ await rejected(client, 'scene_apply', { sessionId, expectedRevision: 0, operations: [] });
+ await rejected(client, 'scene_apply', { sessionId, expectedRevision: 0, operations: Array.from({ length: 257 }, () => ({ type: 'set-camera' })) });
+ await rejected(client, 'scene_apply', { sessionId, expectedRevision: 0, operations: [{ type: 'set-node', id: 'mesh', translation: [1, 2] }] });
+ await rejected(client, 'scene_create', { recipe: { ...recipe(), url: 'https://example.com/model' } });
+ await rejected(client, 'scene_create', { recipe: { ...recipe(), geometries: [{ id: 'box', type: 'box', parameters: {} }] } });
+ await rejected(client, 'scene_create', { recipe: { ...recipe(), geometries: [{ id: 'sphere', type: 'sphere', segments: 2049 }] } });
+ await rejected(client, 'scene_create', { recipe: { ...recipe(), nodes: Array.from({ length: 4097 }, () => ({ id: 'node' })) } });
+ assert.equal(boundary.calls(), 0);
+});
+
+test('real SDK calls preserve atomic revisions, checkpoints, recipe snapshots and PNG content', async context => {
+ const boundary = await connect(context);
+ const { client, sessionId } = boundary;
+ const call = (name, argumentsValue = {}) => client.callTool({ name, arguments: argumentsValue });
+ const capabilities = await call('scene_capabilities');
+ assert.equal(capabilities.structuredContent.format, '67js.scene');
+ const created = await call('scene_create', { recipe: recipe() });
+ assert.equal(created.structuredContent.sessionId, sessionId);
+ const revision = created.structuredContent.revision;
+ const checkpoint = (await call('scene_checkpoint', { sessionId })).structuredContent;
+ const edited = await call('scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-node', id: 'mesh', translation: [1, 2, 3] }] });
+ assert.equal(edited.structuredContent.revision, revision + 1);
+ const stale = await call('scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-node', id: 'mesh', translation: [9, 9, 9] }] });
+ assert.equal(stale.isError, true);
+ assert.match(stale.content[0].text, /expectedRevision/);
+ const inspected = await call('scene_inspect', { sessionId, includeBounds: true });
+ assert.equal(inspected.structuredContent.revision, revision + 1);
+ assert.ok(inspected.structuredContent.nodes[0].bounds);
+ const image = await call('scene_look', { sessionId });
+ assert.deepEqual(image.content[0], { type: 'image', data: png, mimeType: 'image/png' });
+ assert.equal(Buffer.from(image.content[0].data, 'base64').subarray(0, 8).toString('hex'), '89504e470d0a1a0a');
+ assert.deepEqual(JSON.parse(image.content[1].text), image.structuredContent);
+ assert.equal(image.structuredContent.width, 768);
+ assert.equal(image.structuredContent.height, 512);
+ assert.equal(Object.hasOwn(image.structuredContent, 'data'), false);
+ const restored = await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: revision + 1 });
+ assert.equal(restored.structuredContent.revision, revision + 2);
+ const exported = await call('scene_export_recipe', { sessionId });
+ assert.deepEqual(exported.structuredContent.recipe.nodes[0].translation, [0, 0, 0]);
+ assert.deepEqual(JSON.parse(exported.content[0].text), exported.structuredContent);
+ assert.equal((await call('scene_release_checkpoint', { sessionId, checkpointId: checkpoint.checkpointId })).structuredContent.released, true);
+ const released = await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: revision + 2 });
+ assert.equal(released.isError, true);
+ assert.match(released.content[0].text, /released checkpoint/);
+ assert.equal((await call('scene_dispose', { sessionId })).structuredContent.disposed, true);
+ await boundary.server.close();
+ await new Promise(resolve => setImmediate(resolve));
+ assert.equal(boundary.closed(), true);
+});
+
+test('SDK stdio EOF closes the runtime without launching a scene', async () => {
+ const input = new PassThrough();
+ const output = new PassThrough();
+ let resolveClosed;
+ const closed = new Promise(resolve => { resolveClosed = resolve; });
+ const server = createAgentMcpServer({ async close() { resolveClosed(); } });
+ await server.connect(new StdioServerTransport(input, output));
+ input.end();
+ await closed;
+ assert.equal(output.readableLength, 0);
+ await server.close();
+ input.destroy();
+ output.destroy();
+});