3D engine that AI agents drive
MCP: cut tool schemas from 196,826 to about 66,000 bytes, serve field detail by topic (issue #648)
Nguyen Xuan Anad81a1dbc2a3
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 1baa8d86..0835faed 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -37,7 +37,7 @@ Screenshots and other output go to `artifacts/`, which Git ignores.Every pull request runs `npm audit`, `npm run size`, `npm run tool-cost`, `npm test` (with coverage, six shards; Node runs each file in its own process), `prepare:release`, `smoke:package` and `smoke:mcp-package` in the `Test` workflow. `smoke:mcp-package` draws through the MCP server on SwiftShader in Chrome. `npm run size` compares every bundle with `origin/main`. If a bundle grows past its allowance (64 bytes gzip for core and the scenes, 2% for the npm archive), add `changes/<issue>.size.md` with the line `- entry:core: <why it is worth the bytes>` and say why in the pull request. Never edit `bench/size/budgets.json` or `baseline.json` in a pull request. `bench/size/README.md` has the details.-`npm run tool-cost` does the same for what the MCP tools cost an agent. If a tool schema grows by more than 64 bytes, a typical result by more than 128 bytes, or the schema total by more than 128 bytes, first move rare detail into `scene_capabilities` or a shared schema. If the growth is worth it, add a line to `changes/<issue>.size.md`, such as `- tool:scene_create: <why it is worth the bytes>`, `- tool-total: <why>` or `- result:scene_capabilities: <why>`. Never edit `bench/tool-cost-budgets.json` in a pull request. `bench/tool-cost/README.md` has the details.+`npm run tool-cost` does the same for what the MCP tools cost an agent. If a tool schema grows by more than 64 bytes, a typical result by more than 128 bytes, or the schema total by more than 128 bytes, first move rare detail into `scene_capabilities` or a shared schema. If the growth is worth it, add a line to `changes/<issue>.size.md`, such as `- tool:scene_create: <why it is worth the bytes>`, `- tool-total: <why>` or `- result:scene_capabilities: <why>`. Never edit `bench/tool-cost-budgets.json` in a pull request. `bench/tool-cost-ceilings.json` holds fixed absolute ceilings (the schema total, each tool and the default `scene_capabilities` answer) that fail the check whatever the growth. Put field detail in a `scene_capabilities` topic and keep only the common fields in the tool schema. `bench/tool-cost/README.md` has the details.Branch protection on `main` requires the `test` check to pass before a merge. Merge a pull request only when `GitGuardian Security Checks` also passes.diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.jsonindex b944df27..aac13f4e 100644--- a/bench/tool-cost-budgets.json+++ b/bench/tool-cost-budgets.json@@ -1,15 +1,13 @@{- "schemaTotalBytes": 194070,+ "schemaTotalBytes": 67100,"schemaToolBytes": {- "scene_create": 69360,- "scene_apply": 44460,- "mesh_edit": 34430,- "scene_create_asset": 14370,- "mesh_stack": 11030+ "scene_apply": 20370,+ "scene_create": 12380,+ "scene_create_asset": 8770},"schemaOtherToolBytes": 4000,"resultBytes": {- "scene_capabilities": 24660,+ "scene_capabilities": 1380,"scene_create": 1200,"scene_inspect": 1150,"mesh_inspect": 940,diff --git a/bench/tool-cost-ceilings.json b/bench/tool-cost-ceilings.jsonnew file mode 100644index 00000000..c460a34e--- /dev/null+++ b/bench/tool-cost-ceilings.json@@ -0,0 +1,12 @@+{+ "schemaTotalBytes": 100000,+ "schemaToolBytes": {+ "scene_create": 15000,+ "scene_apply": 24000,+ "scene_create_asset": 10500+ },+ "schemaOtherToolBytes": 6000,+ "resultBytes": {+ "scene_capabilities": 4000+ }+}diff --git a/bench/tool-cost/README.md b/bench/tool-cost/README.mdindex 19ffb928..5b8b3ea9 100644--- a/bench/tool-cost/README.md+++ b/bench/tool-cost/README.md@@ -37,6 +37,12 @@ The allowance is about one short schema field. A change that adds a field to oneThe check reads only the notes that your branch adds, so a note from another pull request never accepts your growth. Your note is a new file, so it conflicts with nobody. A size note can hold bundle lines and tool cost lines together.+## Absolute ceilings++`bench/tool-cost-ceilings.json` holds hand-set ceilings for the schema total (100,000 bytes), each large tool, every other tool and the default `scene_capabilities` answer (4,000 bytes). `npm run tool-cost` enforces them on every run, beside the growth check, so the total cannot creep back up in allowed steps. A `size.md` line does not lift them: raising one means editing the file in the pull request, with the reason in the pull request.++Tools list their common fields and a one-line list of the rest. The strict schema still validates every call; scene_capabilities serves the full field outline of each recipe part by topic (`motion`, `environment`, `materialFields`, `meshEdit`, `meshEdit.<op>` and others).+## Release ceilings`bench/tool-cost-budgets.json` holds the absolute ceilings. They are reported on a pull request and enforced with `npm run tool-cost -- --absolute`. A release refreshes them with `npm run tool-cost:release`, which sets each ceiling 2% over the measured value. Read the diff, because a reset hides growth since the last reset.diff --git a/changes/648.md b/changes/648.mdnew file mode 100644index 00000000..a652f4da--- /dev/null+++ b/changes/648.md@@ -0,0 +1 @@+- MCP tool schemas shrink from 196,826 to about 66,000 bytes (#648). The tools list common fields and one line naming the rest, the strict schema still checks every call, and scene_capabilities answers with a short index and serves each recipe part by topic (motion, environment, materialFields, meshEdit, meshEdit.<op> and more). CI now has absolute ceilings for the schema total and each tool.diff --git a/changes/648.size.md b/changes/648.size.mdnew file mode 100644index 00000000..1fffd4f0--- /dev/null+++ b/changes/648.size.md@@ -0,0 +1 @@+- tool:scene_capabilities: the new topic field is what lets every other tool shed its long field lists; the tool grows by about 200 bytes and the other tools shrink by over 130,000.diff --git a/changes/661.md b/changes/661.mdnew file mode 100644index 00000000..fc36c9b3--- /dev/null+++ b/changes/661.md@@ -0,0 +1 @@+- set-environment accepts the opt-in volume fog fields (scatterOctaves, multiScatter, multiExtinction, multiAnisotropy, keyTransmittance, surfaceTransmittance and the rest) on a scene that did not set them at creation, and the MCP schema lists them (#661).diff --git a/docs/learn/optimize-for-agents.md b/docs/learn/optimize-for-agents.mdindex bcf5dc13..6c512001 100644--- a/docs/learn/optimize-for-agents.md+++ b/docs/learn/optimize-for-agents.md@@ -6,16 +6,16 @@ This page shows how to make an agent finish a 67js task with fewer tool calls, fAn agent pays for three things: the tool list, the results of its calls, and the pictures that it reads.-**The tool list.** The harness sends every tool's name, description and input schema to the model. The 22 tools total 189,144 bytes, about 54,000 tokens. Three tools make up most of it:+**The tool list.** The harness sends every tool's name, description and input schema to the model. The 23 tools total 65,777 bytes, about 18,800 tokens (measured 2026-11-09 on the main branch after the schema diet; it was 196,826 bytes before). A tool lists its common fields and one line naming the rest, and every call is still checked against the full schema. `scene_capabilities` with a `topic` gives the field list of one recipe part. Three tools make up most of it:| Tool | Schema size | Estimated tokens || --- | --- | --- |-| `scene_create` | 67,995 B | 19,428 |-| `scene_apply` | 43,581 B | 12,452 |-| `mesh_edit` | 33,752 B | 9,644 |-| `scene_create_asset` | 14,087 B | 4,025 |-| `mesh_stack` | 10,806 B | 3,088 |-| The other 17 tools | 18,923 B | 5,405 |+| `scene_apply` | 19,964 B | 5,704 |+| `scene_create` | 12,135 B | 3,468 |+| `scene_create_asset` | 8,597 B | 2,457 |+| `mesh_edit` | 2,558 B | 731 |+| `mesh_stack` | 1,920 B | 549 |+| The other 18 tools | 20,603 B | 5,885 |Claude Code loads tool schemas on demand through tool search by default, so it pays this cost only for the tools that a task uses. Other harnesses can send the whole list on every turn. If your harness does that, cut the list to the tools that your task needs:@@ -26,19 +26,19 @@ args = ["-y", "--package", "@codepawlhq/67js", "67js-mcp", "--backend", "gpu"]disabled_tools = ["mesh_edit", "mesh_stack", "mesh_inspect", "scene_create_asset", "scene_asset_catalog"]```-This is Codex syntax. Gemini CLI uses `"excludeTools": [...]` in the server entry. Dropping these five tools saves about 17,200 estimated tokens of schema, and the agent can no longer edit meshes or import GLB files. Keep them when the task needs them.+This is Codex syntax. Gemini CLI uses `"excludeTools": [...]` in the server entry. Dropping these five tools saves about 4,200 estimated tokens of schema, and the agent can no longer edit meshes or import GLB files. Keep them when the task needs them.**The results.** Most results are small. These sizes are from the same measurement:| Result | Size | Estimated tokens || --- | --- | --- |-| `scene_capabilities` | 24,167 B | 6,905 |+| `scene_capabilities` (no topic) | 1,347 B | 385 || `scene_export_recipe` | 2,664 B | 762 || `mesh_edit` | 2,009 B | 574 || `scene_create` | 1,176 B | 336 || `scene_inspect` | 1,123 B | 321 |-`scene_capabilities` is the one large result. The agent needs it once per session. Tell the agent in the first prompt that it must not call it again. A scene with more nodes gives a longer node list in `scene_create` and `scene_apply`. `scene_inspect` takes `ids` and `limit` to read only some nodes.+Without a topic `scene_capabilities` is a short index; a topic such as `motion` or `environment` answers with the fields of that recipe part, from a few hundred bytes to about 11,000 for `motion`. Ask for a topic only when the task needs it. A scene with more nodes gives a longer node list in `scene_create` and `scene_apply`. `scene_inspect` takes `ids` and `limit` to read only some nodes.**The pictures.** A picture is the largest single result. See the next section.diff --git a/docs/mcp.md b/docs/mcp.mdindex 27c34f59..b5ef6cfe 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -93,7 +93,7 @@ Known gaps, checked by `npm run check:tool-schemas`:## Workflow-1. Call `scene_capabilities` to read supported features and runtime limits.+1. Call `scene_capabilities` for the topic index, then again with `topic` for the detail you need (limits, field lists).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.@@ -121,7 +121,7 @@ Inspect or export the recipe before retrying. Context loss still permits recipe| Tool | Arguments | Result || --- | --- | --- |-| `scene_capabilities` | None | Features, limits, and backend information |+| `scene_capabilities` | `topic` (optional) | A short index of topics; with a topic, its limits and fields (`motion`, `environment`, `materialFields`, `meshEdit`, `meshEdit.<op>`, `physics`, `jobs` and more) || `scene_create` | `recipe` | Session ID, revision, inspection, and render status || `scene_asset_catalog` | None | Configured catalog and content-bound GLB, image, `.hdr` (kind `environment`) and `.cube` (kind `look`) IDs; an ID goes in `environment.hdri` or `environment.look`, see [agent-look](agent-look.md#catalog-hdris-and-looks) || `scene_create_asset` | `recipe` using `67js.asset` | Imported scene ID, revision, inspection and render status |diff --git a/scripts/capabilities-topics.mjs b/scripts/capabilities-topics.mjsnew file mode 100644index 00000000..a52adea2--- /dev/null+++ b/scripts/capabilities-topics.mjs@@ -0,0 +1,89 @@+// scene_capabilities answers with a short index and serves the detail by topic, so the tool schemas stay small.+// A topic is a key of the scene capabilities, a runtime section (jobs, assets, ...) or the outline of a full input schema+// (motion, environment, meshEdit, ...). A union such as meshEdit takes a branch: meshEdit.bevel.+import * as z from 'zod/v4';+import { outlineSchema, unionBranches } from './schema-outline.mjs';++const RUNTIME_SECTIONS = ['sceneLimits', 'preview', 'review', 'assets', 'jobs', 'unsupported'];+const SUMMARY_LENGTH = 110;+// Scalars (booleans and numbers) of the scene capabilities share one topic instead of one each.+const FLAGS_TOPIC = 'flags';++function isScalar(value) {+ return typeof value === 'boolean' || typeof value === 'number';+}++function firstSentence(text = '') {+ const sentence = text.split(/\.\s/)[0].replace(/\.$/, '');+ return sentence.length > SUMMARY_LENGTH ? `${sentence.slice(0, SUMMARY_LENGTH - 1)}…` : sentence;+}++function sceneTopics(scene) {+ const topics = new Map();+ const flags = {};+ for (const [name, value] of Object.entries(scene)) {+ if (isScalar(value)) flags[name] = value;+ else topics.set(name, value);+ }+ topics.set(FLAGS_TOPIC, flags);+ return topics;+}++function inputJsonSchema(schema) {+ return z.toJSONSchema(schema, { io: 'input', unrepresentable: 'any' });+}++function branchSummary(branch) {+ const fields = Object.keys(branch.properties ?? {}).filter(name => !(branch.properties[name].const !== undefined));+ return { fields, ...(branch.description ? { note: firstSentence(branch.description) } : {}) };+}++function unionIndex(topic, branches) {+ const entries = {};+ for (const [name, branch] of branches) entries[name] = branchSummary(branch);+ return { branches: entries, use: `topic ${topic}.<name> for the fields of one branch; modifier ops not listed here are in meshModifiers` };+}++function outlineAnswer(topic, branchName, schema) {+ const jsonSchema = inputJsonSchema(schema);+ const branches = unionBranches(jsonSchema);+ if (!branchName) return branches ? unionIndex(topic, branches) : outlineSchema(jsonSchema);+ if (!branches?.has(branchName)) {+ const known = branches ? [...branches.keys()].join(', ') : 'none: this topic has no branches';+ throw new Error(`Topic ${topic} has no branch ${branchName}. Branches: ${known}.`);+ }+ return outlineSchema({ ...branches.get(branchName), ...(jsonSchema.$defs ? { $defs: jsonSchema.$defs } : {}) });+}++/** The topics a caller can ask for, by name. */+export function capabilityTopicNames(capabilities, outlineSources) {+ const names = {+ scene: [...sceneTopics(capabilities.scene).keys()],+ runtime: RUNTIME_SECTIONS,+ schemas: [...outlineSources.keys()],+ };+ return names;+}++/** The index with no topic, or the detail of one topic. */+export function answerCapabilities(capabilities, topic, outlineSources) {+ const names = capabilityTopicNames(capabilities, outlineSources);+ if (topic === undefined) {+ return {+ format: capabilities.scene.format, schemaVersion: capabilities.scene.schemaVersion,+ phase: capabilities.phase, availableIn: capabilities.availableIn,+ how: 'Call scene_capabilities again with topic set to one name below. Tools list common fields; schemas names the full field list of a recipe part (meshEdit and meshStack also take <name>.<op>, geometries takes geometries.<type>).',+ topics: names,+ };+ }+ const [name, branchName] = topic.split('.');+ const notes = sceneTopics(capabilities.scene).get(name);+ const runtime = RUNTIME_SECTIONS.includes(name) ? capabilities[name] : undefined;+ const source = outlineSources.get(name);+ const found = [notes, runtime, source].some(value => value !== undefined);+ if (!found) {+ throw new Error(`Unknown topic ${topic}. Topics: ${[...names.scene, ...names.runtime, ...names.schemas].join(', ')}.`);+ }+ if (source) return { topic, ...(notes === undefined ? {} : { notes }), fields: outlineAnswer(name, branchName, source) };+ return { topic, value: notes ?? runtime };+}diff --git a/scripts/check-tool-cost.mjs b/scripts/check-tool-cost.mjsindex 552f2bcf..3f3247cf 100644--- a/scripts/check-tool-cost.mjs+++ b/scripts/check-tool-cost.mjs@@ -1,14 +1,16 @@// Checks what the MCP tools cost an agent: npm run tool-cost// A pull request fails when a tool schema, the schema total or a typical result grows past its allowance against the base branch// (--base, default origin/main) unless its own changes/*.size.md accepts it. --absolute also enforces the release ceilings in-// bench/tool-cost-budgets.json. --set-budgets refreshes the ceilings at release.+// bench/tool-cost-budgets.json. --set-budgets refreshes the ceilings at release. The absolute ceilings in+// bench/tool-cost-ceilings.json are enforced on every run, beside the growth check.import { readFile, writeFile } from 'node:fs/promises';import { fileURLToPath } from 'node:url';import { measureToolCost } from './measure-tool-cost.mjs';import { DEFAULT_BASE_REF, baseRefExists, measureBase, readAcceptedBundles } from './size-base.mjs';-import { budgetsFrom, ceilingProblems, compareCostsToBase, costsFrom, formatCostRows } from './tool-cost-growth.mjs';+import { budgetsFrom, ceilingProblems, compareCostsToBase, costsFrom, formatCostRows, hardCeilingProblems } from './tool-cost-growth.mjs';const BUDGETS_PATH = 'bench/tool-cost-budgets.json';+const CEILINGS_PATH = 'bench/tool-cost-ceilings.json';// The measuring script imports the source beside itself, so the base branch runs its own copy of it.const TOOL_COST_METHOD = {script: fileURLToPath(new URL('./measure-tool-cost.mjs', import.meta.url)),@@ -43,6 +45,9 @@ if (refreshing) {process.exit(0);}+const ceilings = JSON.parse(await readFile(CEILINGS_PATH, 'utf8'));+problems.push(...hardCeilingProblems(measured, ceilings));+if (checkGrowth) {const accepted = readAcceptedBundles(baseRef);const growth = compareCostsToBase(measured, costsFrom(await baseMeasurement), accepted);diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex aaea8696..6b99252b 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -1,3 +1,4 @@+import { answerCapabilities } from './capabilities-topics.mjs';import { BRANCH_NAME_PATTERN } from '../src/agent-branches.js';import { McpServer } from '@modelcontextprotocol/server';import { serveStdio, StdioServerTransport } from '@modelcontextprotocol/server/stdio';@@ -23,6 +24,14 @@ const vector3 = z.tuple([finite, finite, finite]).meta({ id: 'Vector3' });const color = z.tuple([unit, unit, unit]).meta({ id: 'Color' });const quaternion = z.tuple([finite, finite, finite, finite]).meta({ id: 'Quaternion' });const point2 = z.tuple([finite, finite]);+// A tool lists a short object (its common fields and one line naming the rest) while the full strict schema still validates+// every call, because a pipe publishes its input side. scene_capabilities serves the full schema as an outline by topic.+const outlineSources = new Map();+function listed(topic, fullSchema, description, coreShape = {}) {+ if (!outlineSources.has(topic)) outlineSources.set(topic, fullSchema);+ return z.looseObject(coreShape).describe(description).pipe(fullSchema);+}+const coreOf = (strictShape, names) => Object.fromEntries(names.map(name => [name, strictShape[name]]));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);@@ -38,7 +47,7 @@ const nodeFields = {relations: relationList.optional(),asset: placedAsset.optional(),vegetation: placedVegetation.optional(),- skin: skinSpec.optional(),+ skin: listed('skin', skinSpec, 'Bind this mesh node to an armature with automatic weights: { armature, maxInfluences, maxDistance }.', coreOf(skinSpec.shape, ['armature'])).optional(),decal: z.boolean().optional(),depthLayer: z.number().int().min(0).max(4).optional(),visible: z.boolean().optional().describe('false hides the node and children; keyable in motion. Flags: scene_capabilities renderFlags.'),@@ -65,7 +74,7 @@ const instanceSpec = z.strictObject({alignToNormal: z.boolean().optional().describe('Surface only: tilt up to the surface normal.'),scale: z.tuple([z.number().min(0.001).max(1000), z.number().min(0.001).max(1000)]).optional().describe('Random uniform scale range [min, max].'),}).describe('Exactly one of grid, scatter or surface. Expands at scene_create into a group node plus one child node per point (<id>.0, <id>.1, ...) that share geometry and material and draw as one instanced batch. At most 2048 candidate points.');-const nodeRecord = z.strictObject({ armature: identifier.optional().describe('Set on nodes an armature generates, and ignored on input. Edit bones through armatures.'), id: identifier, geometry: identifier.optional(), material: identifier.optional(), instances: instanceSpec.optional().describe('Repeat geometry and material at points; needs both ids. Only in the recipe given to scene_create, not in add-node.'), ...nodeFields });+const nodeRecord = z.strictObject({ armature: identifier.optional().describe('Set on nodes an armature generates, and ignored on input. Edit bones through armatures.'), id: identifier, geometry: identifier.optional(), material: identifier.optional(), instances: listed('instances', instanceSpec, 'Repeat geometry and material at points; needs both ids. Only in scene_create, not in add-node. One of grid {counts, spacing}, scatter {count, min, max} or surface {geometry, count}; also seed, where, yaw, alignToNormal, scale.').optional(), ...nodeFields });const materialGraph = z.record(z.string(), z.unknown()).describe('Node graph as plain JSON, never code. Outputs, nodes, inputs and limits are in scene_capabilities materialGraph.');const materialPattern = z.strictObject({type: z.enum([...MATERIAL_PATTERN_TYPES, 'graph']).describe('Surface look: a preset, or graph for your own node graph (give graph). Directional presets (wood, planks, metal) run along axis.'),@@ -79,39 +88,39 @@ const materialPattern = z.strictObject({axis: z.enum(['x', 'y', 'z']).optional().describe('Object axis the grain runs along. Defaults to y.'),resolution: z.union([z.literal(256), z.literal(512), z.literal(1024)]).optional().describe('Texture size. Defaults to 512; each pattern takes about 4 MiB at 512.'),}).describe('Procedural texture; box mapping needs no UVs. color tints it, roughness and metallic scale it.');-function layerNumber(field, description) {+function layerNumber(field) {const [minimum, maximum] = MATERIAL_LAYER_SCALAR_RANGES[field];- return z.number()+ const ranged = z.number().min(minimum, `${field} must be at least ${minimum}. Raise it to ${minimum} or more.`)- .max(maximum, `${field} must be at most ${maximum}. Lower it to ${maximum} or less.`)- .describe(description).optional();+ .max(maximum, `${field} must be at most ${maximum}. Lower it to ${maximum} or less.`);+ return z.number().pipe(ranged).optional();}-function layerColor(field, description) {+function layerColor(field) {const [minimum, maximum] = MATERIAL_LAYER_COLOR_RANGES[field];const component = z.number().min(minimum, `${field} components must be at least ${minimum}.`).max(maximum, `${field} components must be at most ${maximum}. Use linear values.`);- return z.tuple([component, component, component]).describe(description).optional();+ return z.array(z.number()).length(3).pipe(z.tuple([component, component, component])).optional();}-// One short line each; ranges and details are in scene_capabilities materialLayers.+// Ranges and one line per field are in scene_capabilities materialLayers; the server still checks each range.const materialLayerFields = {- clearcoat: layerNumber('clearcoat', 'Clear coat strength.'),- clearcoatRoughness: layerNumber('clearcoatRoughness', 'Coat roughness.'),- transmission: layerNumber('transmission', 'Light passing through (glass).'),- thickness: layerNumber('thickness', 'Metres light crosses.'),- ior: layerNumber('ior', 'Index of refraction.'),- attenuationColor: layerColor('attenuationColor', 'Linear RGB kept after attenuationDistance.'),+ clearcoat: layerNumber('clearcoat'),+ clearcoatRoughness: layerNumber('clearcoatRoughness'),+ transmission: layerNumber('transmission'),+ thickness: layerNumber('thickness'),+ ior: layerNumber('ior'),+ attenuationColor: layerColor('attenuationColor'),attenuationDistance: z.number().positive('attenuationDistance must be above 0. Leave it out for no absorption.').max(3.4e38).describe('Metres to reach attenuationColor.').optional(),- sheenColor: layerColor('sheenColor', 'Linear RGB cloth glow.'),- sheenRoughness: layerNumber('sheenRoughness', 'Sheen width.'),- specular: layerNumber('specular', 'Reflection strength.'),- specularColor: layerColor('specularColor', 'Reflection tint.'),- anisotropy: layerNumber('anisotropy', 'Highlight stretch along a grain.'),- anisotropyRotation: layerNumber('anisotropyRotation', 'Grain turn, radians.'),- iridescence: layerNumber('iridescence', 'Thin-film colour shift.'),- iridescenceIor: layerNumber('iridescenceIor', 'Film index of refraction.'),- iridescenceThickness: layerNumber('iridescenceThickness', 'Film thickness, nanometres.'),- toon: layerNumber('toon', 'Light steps (toon); 0 off.'),+ sheenColor: layerColor('sheenColor'),+ sheenRoughness: layerNumber('sheenRoughness'),+ specular: layerNumber('specular'),+ specularColor: layerColor('specularColor'),+ anisotropy: layerNumber('anisotropy'),+ anisotropyRotation: layerNumber('anisotropyRotation'),+ iridescence: layerNumber('iridescence'),+ iridescenceIor: layerNumber('iridescenceIor'),+ iridescenceThickness: layerNumber('iridescenceThickness'),+ toon: layerNumber('toon'),};@@ -131,9 +140,9 @@ const subsurface = z.strictObject({const materialFields = {...waterFields,...materialLayerFields,- subsurface: subsurface.optional(),+ subsurface: listed('subsurface', subsurface, 'Subsurface scattering (skin, wax, leaves): weight, radius [r,g,b], scale, color [r,g,b]; ranges in scene_capabilities materialSubsurface.').optional(),snippet: z.record(z.string(), z.unknown()).nullable().optional().describe('GLSL fragment hook; scene_capabilities materialSnippet.'),- pattern: materialPattern.optional(),+ pattern: listed('pattern', materialPattern, 'Procedural texture; box mapping needs no UVs. type is a preset or graph (give graph); also mapping, colors, size, count, bump, seed, axis, resolution; see scene_capabilities pattern.', coreOf(materialPattern.shape, ['type'])).optional(),map: z.strictObject({ sequence: z.strictObject({frames: z.array(z.string().regex(/^[a-f0-9]{64}$/)).min(2).max(64),fps: z.number().positive().max(60),@@ -148,7 +157,10 @@ const materialFields = {alphaMode: z.enum(['opaque', 'blend']).optional().describe('blend draws after opaque geometry, sorted back to front.'),doubleSided: z.boolean().optional().describe('Draw and light both faces (thin sheets, leaves, cloth).'),};-const materialTag = z.enum(['surface', 'unlit', 'liquid', 'foam', 'foliage', 'grass', 'water']).optional().describe('liquid refracts what lies behind it and absorbs by thickness: color is the light one metre lets through. foam is soft blended whitewater. foliage and grass sway in environment.wind. water is a flat mirror sheet; scene_capabilities water has its fields.');+const materialTag = z.enum(['surface', 'unlit', 'liquid', 'foam', 'foliage', 'grass', 'water']).optional().describe('Surface kind; liquid, foam, foliage, grass and water change how it renders: see scene_capabilities materialTags and water.');+const materialCore = coreOf(materialFields, ['color', 'metallic', 'roughness', 'emission', 'opacity']);+const materialMore = 'More fields: tag, alphaMode, doubleSided, emissiveColor, map, pattern, subsurface, snippet, waterPreset, absorption, turbidity and the layers clearcoat, clearcoatRoughness, transmission, thickness, ior, attenuationColor, attenuationDistance, sheenColor, sheenRoughness, specular, specularColor, anisotropy, anisotropyRotation, iridescence, iridescenceIor, iridescenceThickness, toon; see scene_capabilities materialFields.';+const materialListed = (strictSchema, description, extraCore) => listed('materialFields', strictSchema, `${description} ${materialMore}`, { ...extraCore, ...materialCore });const liquidOptics = z.strictObject({thickness: z.number().min(0).max(100).optional().describe('Metres of liquid where it faces the camera.'),ior: z.number().min(1).max(3).optional(),@@ -158,18 +170,18 @@ const liquidOptics = z.strictObject({foamSoftness: unit.optional(),});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.'),+ eye: vector3.optional(),+ target: vector3.optional(),+ up: vector3.optional(),fov: finite.gt(0).lt(180).optional().describe('Vertical perspective field of view in degrees. Not with focalLength.'),- near: positive.optional().describe('Near clipping distance. Must be less than far.'),- far: positive.optional().describe('Far clipping distance. Must exceed near.'),- projection: z.enum(['perspective', 'orthographic']).optional().describe('Defaults to perspective.'),- orthoScale: positive.optional().describe('Orthographic view height in metres (default 4); needs projection orthographic.'),+ near: positive.optional(),+ far: positive.optional(),+ projection: z.enum(['perspective', 'orthographic']).optional(),+ orthoScale: positive.optional(),focalLength: positive.max(10000).optional().describe('Lens in mm, instead of fov.'),- sensorWidth: positive.max(1000).optional().describe('Sensor width in mm with focalLength; default 36.'),- shift: z.tuple([z.number().min(-1).max(1), z.number().min(-1).max(1)]).optional().describe('Lens shift [x, y] as a fraction of the frame; positive moves the frame right and up.'),- fStop: z.number().min(0.7).max(64).optional().describe('Depth of field focused on target; 1.4 is full blur. Not with effects.depthOfField.blur above 0.'),+ sensorWidth: positive.max(1000).optional(),+ shift: z.tuple([z.number().min(-1).max(1), z.number().min(-1).max(1)]).optional(),+ fStop: z.number().min(0.7).max(64).optional(),};const bounded = (minimum, maximum) => z.number().min(minimum).max(maximum);const boundedVector = (minimum, maximum) => z.tuple([bounded(minimum, maximum), bounded(minimum, maximum), bounded(minimum, maximum)]);@@ -192,6 +204,13 @@ const volumeFog = z.strictObject({contrast: bounded(0, 4).optional(),profileSoftness: bounded(0, 0.95).optional(),keyScattering: bounded(0, 10).optional(),+ heightFalloff: finite.optional(),+ scatterOctaves: finite.optional(),+ multiScatter: finite.optional(),+ multiExtinction: finite.optional(),+ multiAnisotropy: finite.optional(),+ keyTransmittance: finite.optional(),+ surfaceTransmittance: finite.optional(),});const affects = z.array(z.string()).optional();const lines = z.record(z.string(), z.unknown()).describe('Outlines, toon light and polylines as plain JSON; fields and limits in scene_capabilities lineArt. null clears.');@@ -257,12 +276,8 @@ const environment = z.strictObject({look: z.union([z.enum([...LOOK_NAMES, ...BUNDLED_CUBE_LOOK_NAMES]), z.string().regex(CATALOG_FILE_ID)]).nullable().optional().describe('Look preset or .cube; scene_capabilities catalogLooks. null clears.'),wind: z.strictObject({ strength: bounded(0, 4).optional(), direction: bounded(-360, 360).optional().describe('Degrees: 0 toward +x, 90 toward +z.') }).optional().describe('Sway of foliage and grass materials; strength defaults to 0.3.'),});-// The full environment schema is published once, in scene_create. A JSON Schema $ref can not point from one tool's-// inputSchema into another's, so scene_apply and scene_create_asset publish a plain object that names it and still-// check every field against the same schema here, with the same error paths.-const environmentReference = z.record(z.string(), z.unknown())- .describe('Same fields as recipe.environment in scene_create.')- .pipe(environment);+// Every tool lists the same short environment; the full schema is served by scene_capabilities topic environment.+const environmentListed = listed('environment', environment, 'Lighting and sky. More fields: hdri, look, viewTransform, keyColor, keyIntensity, fillIntensity, ambientIntensity, daylight, keyAffects, shadowCascades, pointLights, spotLights, areaLights, skyTop, skyBottom, fogColor, fogDensity, volumeFog (density, scatterOctaves, multiScatter, keyTransmittance, surfaceTransmittance and more: scene_capabilities environment), liquid, lines, wind, objectReflections, floorSkyTrace, sunBounce, specularAntiAliasing, resolveCoplanar; see scene_capabilities environment.', coreOf(environment.shape, ['setup', 'world', 'ground', 'lightDirection', 'environmentIntensity']));const effects = z.strictObject({exposure: bounded(0.01, 16).optional(),saturation: bounded(0, 2).optional(),@@ -280,6 +295,7 @@ const effects = z.strictObject({depthOfField: z.strictObject({ blur: unit.optional(), focusDistance: bounded(0.01, 100000).optional() }).optional().describe('Lens blur: blur 0 to 1, focusDistance metres.'),motionBlur: z.strictObject({ shutter: bounded(0, 0.5).optional() }).optional().describe('Camera motion smear, shutter in seconds.'),});+const effectsListed = listed('effects', effects, 'Post effects: exposure, saturation, contrast, temperature, vignette, grain, ambientOcclusion, ambientOcclusionRadius, bloom {strength, threshold, radius}, depthOfField {blur, focusDistance}, motionBlur {shutter}; see scene_capabilities effects.', coreOf(effects.shape, ['exposure']));const shadow = z.strictObject({target: boundedVector(-1e6, 1e6).optional(),extent: bounded(0.01, 1e5).optional(),@@ -418,8 +434,12 @@ const stackNodes = [// A whole-mesh modifier is a free record { op, ...fields }: its ops and fields live in scene_capabilities meshModifiers, so// the schema does not grow with each modifier, and the backend validates every field.const modifierRecord = z.record(z.string(), z.unknown()).describe(`Whole-mesh modifier { op, ...fields }, op one of: ${Object.keys(MODIFIER_OPERATIONS).join(', ')}.`);-const meshStack = z.array(z.union([z.discriminatedUnion('op', stackNodes), modifierRecord])).max(16);-const meshEdits = z.array(z.union([z.discriminatedUnion('op', [...meshEdit.options, ...stackNodes]), modifierRecord])).max(64);+const stackNodeUnion = z.union([z.discriminatedUnion('op', stackNodes), modifierRecord]);+const meshEditUnion = z.union([z.discriminatedUnion('op', [...meshEdit.options, ...stackNodes]), modifierRecord]);+const stackOperationNames = [...stackNodes.map(node => node.shape.op.value), ...Object.keys(MODIFIER_OPERATIONS)];+const editOperationNames = [...meshEdit.options.map(option => option.shape.op.value), ...stackOperationNames];+const meshStack = z.array(listed('meshStack', stackNodeUnion, 'Stack node { op, ...fields }; fields per op: scene_capabilities meshStack.', { op: z.enum(stackOperationNames) })).max(16);+const meshEdits = z.array(listed('meshEdit', meshEditUnion, 'Edit { op, ...fields }, applied in order; fields per op: scene_capabilities meshEdit, or meshEdit.<op> for one op.', { op: z.enum(editOperationNames) })).max(64);// The full edit and stack schemas live in mesh_edit and mesh_stack. Repeating them in every recipe cost about 45 KB// per tool; the backend still validates each item and names the valid ops when one is wrong.const recipeMeshEdits = z.array(z.record(z.string(), z.unknown())).max(64);@@ -605,20 +625,26 @@ const armature = z.strictObject({}).describe('A skeleton. Each bone becomes a recipe node named after it (parented like the bones, rotating about its head), so motion tracks, motion.ik and set-node address bones by name. Mesh nodes bind with skin. scene_inspect rig lists unweighted vertices, bones with no vertices and joint axis problems.');const armaturesReference = z.array(z.record(z.string(), z.unknown())).max(16).describe('The same array as recipe.armatures in scene_create: id, parent, preset, fit, bones. Read that tool for the fields.');const timelineReference = z.record(z.string(), z.unknown()).describe('Shots in order, up to 60 s; fields in scene_capabilities filmTimeline.');+const geometryTypes = geometry.options.map(option => option.shape.type.value);+const geometryListed = listed('geometries', geometry, 'Geometry { id, type, ...fields of that type }; mesh also takes base, edits, stack, smoothAngle. Fields per type: scene_capabilities geometries.', { id: identifier, type: z.enum(geometryTypes) });+const motionListed = listed('motion', motion, 'One absolute-time clip: duration in s, loop, tracks [{kind, id, property, interpolation, keyframes [{time, value, easing}]}], ik, constraints, drivers; see scene_capabilities motion.', coreOf(motion.shape, ['duration', 'loop']));+const physicsListed = listed('physics', physics, 'Rigid bodies recorded offline with Rapier: duration, gravity, bodies [{node, type, shape, mass, ...}], joints; see scene_capabilities physics.', coreOf(physics.shape, ['duration']));+const clothListed = listed('cloth', cloth, 'Baked cloth sheets: duration, gravity, wind, sheets [{node, pin, pinTo, stiffness, ...}], colliders; see scene_capabilities cloth.', coreOf(cloth.shape, ['duration']));+const armatureListed = listed('armatures', armature, 'A skeleton { id, parent, preset humanoid|quadruped, fit, bones [{name, parent, head, tail}], prefix, translation, rotation }; see scene_capabilities armatures.', { id: identifier });const recipe = z.strictObject({format: z.literal('67js.scene'),schemaVersion: z.literal(1),- geometries: z.array(geometry).max(256).optional(),- materials: z.array(z.strictObject({ id: identifier, tag: materialTag, ...materialFields })).max(256).optional().describe('Omit for none.'),+ geometries: z.array(geometryListed).max(256).optional(),+ materials: z.array(materialListed(z.strictObject({ id: identifier, tag: materialTag, ...materialFields }), 'Material.', { id: identifier })).max(256).optional().describe('Omit for none.'),nodes: z.array(nodeRecord).max(4096),- armatures: z.array(armature).max(16).optional(),+ armatures: z.array(armatureListed).max(16).optional(),camera: z.strictObject(cameraFields).optional(),- environment: environment.optional(),- effects: effects.optional(),+ environment: environmentListed.optional(),+ effects: effectsListed.optional(),shadow: shadow.optional(),- motion: motion.nullable().optional(),- physics: physics.nullable().optional(),- cloth: cloth.nullable().optional(),+ motion: motionListed.nullable().optional(),+ physics: physicsListed.nullable().optional(),+ cloth: clothListed.nullable().optional(),timeline: timelineReference.nullable().optional(),particles: z.record(z.string(), z.unknown()).nullable().optional().describe('Particle emitters and hair, seeked by motionTime. Fields: scene_capabilities particles.'),bake: z.record(z.string(), z.unknown()).nullable().optional().describe('Bounced light baked at build time. Fields: scene_capabilities bake.'),@@ -629,15 +655,15 @@ const assetRecipe = z.strictObject({schemaVersion: z.literal(1),assetId: z.string().regex(/^[a-f0-9]{64}$/).describe('SHA-256 asset ID from scene_asset_catalog.'),camera: z.strictObject(cameraFields).optional(),- environment: environmentReference.optional(),- effects: effects.optional(),+ environment: environmentListed.optional(),+ effects: effectsListed.optional(),shadow: shadow.optional(),root: z.strictObject({translation: vector3.optional(), rotation: quaternion.optional(),scale: z.tuple([positive, positive, positive]).optional(),}).optional(),animation: z.strictObject({ clip: z.number().int().min(0), time: nonnegative }).nullable().optional().describe('Absolute clip/time sample. null selects the original decoded pose.'),- materialOverrides: z.array(z.strictObject({ id: identifier, ...materialFields })).max(4096).optional(),+ materialOverrides: z.array(materialListed(z.strictObject({ id: identifier, ...materialFields }), 'Override of a source material.', { id: identifier })).max(4096).optional(),nodeOverrides: z.array(z.strictObject({ id: identifier, translation: vector3.optional(), rotation: quaternion.optional(), scale: z.tuple([positive, positive, positive]).optional() })).max(4096).optional(),motion: recipeMotionReference.nullable().optional(),});@@ -653,7 +679,7 @@ const nodeOperations = (nodeFieldShape, nodeSchema) => [z.strictObject({ type: z.literal('add-node'), node: nodeSchema }),];const otherOperations = [- z.strictObject({ type: z.literal('set-material'), id: identifier, ...materialFields }, { error: flatFieldsHint('set-material', 'material') }),+ materialListed(z.strictObject({ type: z.literal('set-material'), id: identifier, ...materialFields }, { error: flatFieldsHint('set-material', 'material') }), 'Change a material.', { type: z.literal('set-material'), id: identifier }),z.strictObject({ type: z.literal('set-camera'), ...cameraFields }),z.strictObject({ type: z.literal('set-motion'), motion: recipeMotionReference.nullable() }),z.strictObject({ type: z.literal('set-armatures'), armatures: armaturesReference.nullable() }),@@ -663,16 +689,16 @@ const otherOperations = [z.strictObject({ type: z.literal('set-particles'), particles: z.record(z.string(), z.unknown()).nullable() }),z.strictObject({ type: z.literal('set-bake'), bake: z.record(z.string(), z.unknown()).nullable() }),z.strictObject({ type: z.literal('set-post-passes'), postPasses: z.array(z.record(z.string(), z.unknown())).nullable() }),- z.strictObject({ type: z.literal('set-environment'), environment: environmentReference }),- z.strictObject({ type: z.literal('set-effects'), effects }),+ z.strictObject({ type: z.literal('set-environment'), environment: environmentListed }),+ z.strictObject({ type: z.literal('set-effects'), effects: effectsListed }),z.strictObject({ type: z.literal('set-shadow'), shadow }),z.strictObject({ type: z.literal('set-root'), translation: vector3.optional(), rotation: quaternion.optional(), scale: z.tuple([positive, positive, positive]).optional() }),z.strictObject({ type: z.literal('set-asset-node'), id: identifier, translation: vector3.optional(), rotation: quaternion.optional(), scale: z.tuple([positive, positive, positive]).optional() }),z.strictObject({ type: z.literal('set-animation'), clip: z.number().int().min(0).nullable().optional(), time: nonnegative.optional() }),z.strictObject({ type: z.literal('remove-node'), id: identifier, recursive: z.boolean().optional().describe('Remove descendants too. Defaults to false; dangling children reject the batch.') }),- z.strictObject({ type: z.literal('add-geometry'), geometry }),+ z.strictObject({ type: z.literal('add-geometry'), geometry: geometryListed }),z.strictObject({ type: z.literal('remove-geometry'), id: identifier }),- z.strictObject({ type: z.literal('add-material'), material: z.strictObject({ id: identifier, tag: materialTag, ...materialFields }) }),+ z.strictObject({ type: z.literal('add-material'), material: materialListed(z.strictObject({ id: identifier, tag: materialTag, ...materialFields }), 'New material.', { id: identifier, tag: materialTag }) }),z.strictObject({ type: z.literal('remove-material'), id: identifier }),];const operation = z.discriminatedUnion('type', [...nodeOperations(nodeFields, nodeRecord), ...otherOperations]);@@ -780,7 +806,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio}});}- register('scene_capabilities', 'Read supported recipe features and runtime budgets before authoring. Does not launch a browser.', z.strictObject({}), readOnly, async () => jsonResult(relations ? await runtime.capabilities() : withoutRelationsAdvice(await runtime.capabilities())));+ register('scene_capabilities', 'Index of supported recipe features and runtime budgets; pass topic for the detail of one. Read it before authoring. Does not launch a browser.', z.strictObject({ topic: z.string().min(1).max(64).optional().describe('A name from the index, or name.branch such as meshEdit.bevel. Leave out for the index.') }), readOnly, async ({ topic }) => jsonResult(answerCapabilities(relations ? await runtime.capabilities() : withoutRelationsAdvice(await runtime.capabilities()), topic, outlineSources)));register('scene_create', 'Create the single active render scene from a JSON recipe. Dispose an existing scene first.', z.strictObject({ recipe: relations ? recipe : recipeWithoutRelations }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.create(argumentsValue)));register('scene_asset_catalog', 'List content-bound GLB and PNG, JPEG or WebP image 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)));diff --git a/scripts/measure-tool-cost.mjs b/scripts/measure-tool-cost.mjsindex 0334ac7e..b80f8a8e 100644--- a/scripts/measure-tool-cost.mjs+++ b/scripts/measure-tool-cost.mjs@@ -54,16 +54,29 @@ export function sampleRecipe() {};}-export async function listTools() {- const server = createAgentMcpServer({ async close() {} });+async function withClient(runtime, use) {+ const server = createAgentMcpServer(runtime);const client = new Client({ name: 'tool-cost', version: '1' });const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();await server.connect(serverTransport);await client.connect(clientTransport);- const { tools } = await client.listTools();- await client.close();- await server.close();- return tools;+ try {+ return await use(client);+ } finally {+ await client.close();+ await server.close();+ }+}++export async function listTools() {+ return withClient({ async close() {} }, async client => (await client.listTools()).tools);+}++/** What an agent receives from scene_capabilities with no topic: the index on this branch, the whole list on an older one. */+async function defaultCapabilitiesResult() {+ const scene = { ...AGENT_SCENE_CAPABILITIES, postPasses: USER_PASS_CAPABILITIES, meshBlend: MESH_BLEND_CAPABILITIES, materialSnippet: MATERIAL_SNIPPET_CAPABILITIES, vegetation: VEGETATION_CAPABILITY_NOTE, crowd: CROWD_CAPABILITY_NOTE, textureSequence: TEXTURE_SEQUENCE_CAPABILITIES };+ const runtime = { async close() {}, async capabilities() { return { scene, phase: 'idle', availableIn: '0.0.0' }; } };+ return withClient(runtime, async client => (await client.callTool({ name: 'scene_capabilities', arguments: {} })).structuredContent);}async function typicalResults(recipe) {@@ -74,7 +87,7 @@ async function typicalResults(recipe) {const meshReport = scene.inspectMeshes({ geometries: ['seat'] });const { inspection, ...statusWithoutInspection } = status;return {- scene_capabilities: { ...AGENT_SCENE_CAPABILITIES, postPasses: USER_PASS_CAPABILITIES, meshBlend: MESH_BLEND_CAPABILITIES, materialSnippet: MATERIAL_SNIPPET_CAPABILITIES, vegetation: VEGETATION_CAPABILITY_NOTE, crowd: CROWD_CAPABILITY_NOTE, textureSequence: TEXTURE_SEQUENCE_CAPABILITIES },+ scene_capabilities: await defaultCapabilitiesResult(),scene_create: status,scene_inspect: { sessionId: SAMPLE_SESSION, ...scene.inspect() },mesh_inspect: { sessionId: SAMPLE_SESSION, ...meshReport },diff --git a/scripts/schema-outline.mjs b/scripts/schema-outline.mjsnew file mode 100644index 00000000..dcd07af3--- /dev/null+++ b/scripts/schema-outline.mjs@@ -0,0 +1,104 @@+// Turns a JSON Schema into a compact outline an agent can read: field names, types, ranges, enums and one-line notes+// without the JSON Schema bookkeeping. scene_capabilities serves these outlines by topic, so the tool schemas themselves+// stay short while the full field detail is one call away.++const DESCRIPTION_KEY = '_';++// The Float32 limit on a plain number is not a useful bound to read.+const FLOAT32_LIMIT = 3e38;+const boundOf = value => (Math.abs(value) >= FLOAT32_LIMIT ? undefined : value);++function rangeText(node) {+ const lowest = boundOf(node.minimum);+ const highest = boundOf(node.maximum);+ const minimum = lowest ?? (node.exclusiveMinimum === undefined ? undefined : `>${node.exclusiveMinimum}`);+ const maximum = highest ?? (node.exclusiveMaximum === undefined ? undefined : `<${node.exclusiveMaximum}`);+ if (minimum === undefined && maximum === undefined) return '';+ return `[${minimum ?? ''}..${maximum ?? ''}]`;+}++function lengthText(node) {+ if (node.minItems === undefined && node.maxItems === undefined) return '';+ return `{${node.minItems ?? ''}..${node.maxItems ?? ''}}`;+}++function withNote(text, node) {+ return node.description ? `${text} // ${node.description}` : text;+}++function referenceName(reference) {+ return reference.replace('#/$defs/', '');+}++function literalOf(node) {+ if (node.const !== undefined) return JSON.stringify(node.const);+ if (node.enum) return node.enum.map(value => JSON.stringify(value)).join('|');+ return undefined;+}++function outlineUnion(branches, node, definitions) {+ const literals = branches.map(literalOf);+ if (literals.every(Boolean)) return withNote(literals.join('|'), node);+ const outlined = branches.map(branch => outline(branch, definitions));+ if (outlined.every(entry => typeof entry === 'string')) return withNote(outlined.join(' | '), node);+ return { oneOf: outlined, ...(node.description ? { [DESCRIPTION_KEY]: node.description } : {}) };+}++function outlineObject(node, definitions) {+ const required = new Set(node.required ?? []);+ const result = {};+ if (node.description) result[DESCRIPTION_KEY] = node.description;+ for (const [name, child] of Object.entries(node.properties ?? {})) {+ result[required.has(name) ? name : `${name}?`] = outline(child, definitions);+ }+ if (node.additionalProperties && typeof node.additionalProperties === 'object' && Object.keys(node.additionalProperties).length) {+ result['*'] = outline(node.additionalProperties, definitions);+ }+ return result;+}++function outline(node, definitions) {+ if (node.$ref) return withNote(referenceName(node.$ref), node);+ const literal = literalOf(node);+ if (literal) return withNote(literal, node);+ const branches = node.oneOf ?? node.anyOf;+ if (branches) return outlineUnion(branches, node, definitions);+ if (node.prefixItems) return withNote(`[${node.prefixItems.map(item => outline(item, definitions)).join(', ')}]`, node);+ if (node.type === 'array') {+ const item = node.items ? outline(node.items, definitions) : 'any';+ if (typeof item === 'string') return withNote(`${item}[]${lengthText(node)}`, node);+ return { array: item, ...(lengthText(node) ? { length: lengthText(node) } : {}), ...(node.description ? { [DESCRIPTION_KEY]: node.description } : {}) };+ }+ if (node.type === 'object' || node.properties) return outlineObject(node, definitions);+ if (node.type === 'number' || node.type === 'integer') return withNote(`${node.type === 'integer' ? 'int' : 'number'}${rangeText(node)}`, node);+ if (Array.isArray(node.type)) return withNote(node.type.join('|'), node);+ return withNote(node.type ?? 'any', node);+}++/** Compact outline of a JSON Schema; shared definitions are listed once under $defs. */+export function outlineSchema(jsonSchema) {+ const definitions = jsonSchema.$defs ?? {};+ const result = outline(jsonSchema, definitions);+ const used = JSON.stringify(result);+ const shared = Object.fromEntries(Object.entries(definitions)+ .filter(([name]) => new RegExp(String.raw`\b${name}\b`).test(used))+ .map(([name, definition]) => [name, outline(definition, definitions)]));+ if (typeof result === 'string' || !Object.keys(shared).length) return result;+ return { ...result, $defs: shared };+}++/** The branches of a union keyed by the value of their first literal field, such as op or type. */+export function unionBranches(jsonSchema) {+ const flatten = node => {+ const members = node.oneOf ?? node.anyOf;+ return members ? members.flatMap(flatten) : [node];+ };+ if (!(jsonSchema.oneOf ?? jsonSchema.anyOf)) return undefined;+ const keyed = new Map();+ for (const branch of flatten(jsonSchema)) {+ const properties = Object.values(branch.properties ?? {});+ const discriminator = properties.map(literalOf).find(Boolean);+ if (discriminator) keyed.set(JSON.parse(discriminator.split('|')[0]), branch);+ }+ return keyed.size ? keyed : undefined;+}diff --git a/scripts/smoke-agent-cloth.mjs b/scripts/smoke-agent-cloth.mjsindex d775113f..34a49a3c 100644--- a/scripts/smoke-agent-cloth.mjs+++ b/scripts/smoke-agent-cloth.mjs@@ -50,8 +50,8 @@ const recipe = {try {await client.connect(transport);- const capabilities = (await call('scene_capabilities')).structuredContent;- assert.deepEqual(capabilities.scene.cloth.limits.maxSheets, 8);+ const capabilities = (await call('scene_capabilities', { topic: 'cloth' })).structuredContent;+ assert.deepEqual(capabilities.notes.limits.maxSheets, 8);const created = (await call('scene_create', { recipe }, 180000)).structuredContent;const sessionId = created.sessionId;const report = (await call('scene_inspect', { sessionId })).structuredContent.cloth;diff --git a/scripts/smoke-agent-material-snippet.mjs b/scripts/smoke-agent-material-snippet.mjsindex 65f40fc2..3d0ebf0c 100644--- a/scripts/smoke-agent-material-snippet.mjs+++ b/scripts/smoke-agent-material-snippet.mjs@@ -85,8 +85,8 @@ const broken = { fragment: 'void materialHook(inout vec3 color, inout float alphtry {await client.connect(transport);assert.equal((await client.listTools()).tools.length, 22);- const capabilities = (await call('scene_capabilities')).structuredContent;- assert.equal(capabilities.scene.materialSnippet.limits.maxUniforms, 16);+ const capabilities = (await call('scene_capabilities', { topic: 'materialSnippet' })).structuredContent;+ assert.equal(capabilities.value.limits.maxUniforms, 16);const created = (await call('scene_create', { recipe })).structuredContent;const sessionId = created.sessionId;diff --git a/scripts/smoke-agent-particles.mjs b/scripts/smoke-agent-particles.mjsindex 912d024c..bb46066a 100644--- a/scripts/smoke-agent-particles.mjs+++ b/scripts/smoke-agent-particles.mjs@@ -62,8 +62,8 @@ const recipe = {try {await client.connect(transport);- const capabilities = (await call('scene_capabilities')).structuredContent;- assert.equal(capabilities.scene.particles.limits.maxParticles, 4000);+ const capabilities = (await call('scene_capabilities', { topic: 'particles' })).structuredContent;+ assert.equal(capabilities.value.limits.maxParticles, 4000);const created = (await call('scene_create', { recipe }, 180000)).structuredContent;const sessionId = created.sessionId;const report = (await call('scene_inspect', { sessionId })).structuredContent.particles;diff --git a/scripts/smoke-agent-physics.mjs b/scripts/smoke-agent-physics.mjsindex 52eb5e10..e5a1386e 100644--- a/scripts/smoke-agent-physics.mjs+++ b/scripts/smoke-agent-physics.mjs@@ -53,8 +53,8 @@ const recipe = {try {await client.connect(transport);- const capabilities = (await call('scene_capabilities')).structuredContent;- assert.deepEqual(capabilities.scene.physics.shapes, ['box', 'ball', 'capsule', 'convex', 'trimesh']);+ const capabilities = (await call('scene_capabilities', { topic: 'physics' })).structuredContent;+ assert.deepEqual(capabilities.notes.shapes, ['box', 'ball', 'capsule', 'convex', 'trimesh']);const created = (await call('scene_create', { recipe }, 180000)).structuredContent;const sessionId = created.sessionId;const report = (await call('scene_inspect', { sessionId })).structuredContent.physics;diff --git a/scripts/smoke-agent-post-pass.mjs b/scripts/smoke-agent-post-pass.mjsindex 495730fd..cd9288db 100644--- a/scripts/smoke-agent-post-pass.mjs+++ b/scripts/smoke-agent-post-pass.mjs@@ -94,9 +94,9 @@ async function waitForJob(jobId) {try {await client.connect(transport);assert.equal((await client.listTools()).tools.length, 22);- const capabilities = (await call('scene_capabilities')).structuredContent;- assert.equal(capabilities.scene.postPasses.limits.maxPasses, 4);- assert.ok(capabilities.scene.operations.includes('set-post-passes'));+ const capabilities = (await call('scene_capabilities', { topic: 'postPasses' })).structuredContent;+ assert.equal(capabilities.value.limits.maxPasses, 4);+ assert.ok((await call('scene_capabilities', { topic: 'operations' })).structuredContent.value.includes('set-post-passes'));const created = (await call('scene_create', { recipe: createAgentPreviewFixture() })).structuredContent;const sessionId = created.sessionId;diff --git a/scripts/smoke-agent-render-jobs.mjs b/scripts/smoke-agent-render-jobs.mjsindex 149dbf52..2ca3738d 100644--- a/scripts/smoke-agent-render-jobs.mjs+++ b/scripts/smoke-agent-render-jobs.mjs@@ -118,10 +118,11 @@ try {await connect();const recovered = (await call('scene_capabilities')).structuredContent;assert.equal(recovered.phase, 'idle');- assert.equal(recovered.jobs.records.find(record => record.jobId === interrupted.jobId).state, 'cancelled');+ const recoveredJobs = (await call('scene_capabilities', { topic: 'jobs' })).structuredContent.value;+ assert.equal(recoveredJobs.records.find(record => record.jobId === interrupted.jobId).state, 'cancelled');assert.deepEqual((await call('scene_render_result', { jobId: videoJob.jobId })).structuredContent, result);for (const jobId of [videoJob.jobId, longJob.jobId, interrupted.jobId, ...imageJobs]) await call('scene_render_release', { jobId });- assert.equal((await call('scene_capabilities')).structuredContent.jobs.records.length, 0);+ assert.equal((await call('scene_capabilities', { topic: 'jobs' })).structuredContent.value.records.length, 0);await mkdir('artifacts', { recursive: true });await writeFile('artifacts/mcp-render-jobs-proof.json', JSON.stringify({ cli, video, result,animatedFramesDiffer: true, activeCancel: true, eofCleanup: true, restartResults: true,diff --git a/scripts/smoke-material-layers.mjs b/scripts/smoke-material-layers.mjsindex 9f57b2cf..84930b1c 100644--- a/scripts/smoke-material-layers.mjs+++ b/scripts/smoke-material-layers.mjs@@ -122,8 +122,8 @@ const BALL_REGION = { left: 125, right: 195, top: 85, bottom: 155 };try {await client.connect(transport);- const capabilities = (await call('scene_capabilities')).structuredContent;- const layerNames = Object.keys(capabilities.scene?.materialLayers ?? {});+ const capabilities = (await call('scene_capabilities', { topic: 'materialLayers' })).structuredContent;+ const layerNames = Object.keys(capabilities.value ?? {});for (const field of ['clearcoat', 'transmission', 'thickness', 'ior', 'anisotropy', 'iridescence']) {assert.ok(layerNames.includes(field), `scene_capabilities materialLayers lists ${field}`);}diff --git a/scripts/smoke-mcp-linking.mjs b/scripts/smoke-mcp-linking.mjsindex f40fc5d8..ba75af78 100644--- a/scripts/smoke-mcp-linking.mjs+++ b/scripts/smoke-mcp-linking.mjs@@ -60,8 +60,8 @@ async function look(sessionId, motionTime) {let report;try {await client.connect(transport);- const capabilities = (await call('scene_capabilities')).structuredContent;- assert.ok(capabilities.scene.lightLinking.fields.length > 0);+ const capabilities = (await call('scene_capabilities', { topic: 'lightLinking' })).structuredContent;+ assert.ok(capabilities.value.fields.length > 0);const created = (await call('scene_create', { recipe: streetRecipe() })).structuredContent;const { sessionId } = created;assert.ok(created.render.graphics, 'the scene rendered');diff --git a/scripts/smoke-mcp-package.mjs b/scripts/smoke-mcp-package.mjsindex 7f1db034..9620cb7a 100644--- a/scripts/smoke-mcp-package.mjs+++ b/scripts/smoke-mcp-package.mjs@@ -120,7 +120,7 @@ for (const era of ['modern', 'legacy']) {assert.equal((await client.listTools()).tools.length, 23);const capabilities = (await call('scene_capabilities')).structuredContent;assert.equal(capabilities.phase, 'idle');- assert.equal(capabilities.preview.maximumActiveScenes, 1);+ assert.equal((await call('scene_capabilities', { topic: 'preview' })).structuredContent.value.maximumActiveScenes, 1);assert.equal(capabilities.availableIn, metadata.version);if (protocolOnly) {results.push({ era, tools: 18, connectMs, browserStarted: false });diff --git a/scripts/tool-cost-growth.mjs b/scripts/tool-cost-growth.mjsindex 9e55558a..7adc9da6 100644--- a/scripts/tool-cost-growth.mjs+++ b/scripts/tool-cost-growth.mjs@@ -73,6 +73,26 @@ export function budgetsFrom(measured, previous) {return budgets;}+/**+ * The absolute ceilings in bench/tool-cost-ceilings.json. Unlike the release budgets they are set by hand and checked on every run,+ * so the total cannot drift back up one allowed step at a time. A ceiling is only raised with a reason in the pull request.+ */+export function hardCeilingProblems(measured, ceilings) {+ const problems = [];+ const check = (name, bytes, ceiling) => {+ if (bytes > ceiling) problems.push(`${name} is ${bytes} bytes, over its absolute ceiling of ${ceiling} by ${bytes - ceiling}. ${MOVE_ADVICE} Raise the ceiling in bench/tool-cost-ceilings.json only with a reason in the pull request.`);+ };+ check(TOTAL_NAME, measured[TOTAL_NAME], ceilings.schemaTotalBytes);+ for (const [name, bytes] of Object.entries(measured)) {+ if (name.startsWith('tool:')) check(name, bytes, ceilings.schemaToolBytes[name.slice('tool:'.length)] ?? ceilings.schemaOtherToolBytes);+ if (name.startsWith('result:')) {+ const ceiling = ceilings.resultBytes[name.slice('result:'.length)];+ if (ceiling !== undefined) check(name, bytes, ceiling);+ }+ }+ return problems;+}+/** The release ceilings in bench/tool-cost-budgets.json that the measured costs are past, as problems. */export function ceilingProblems(measured, budgets) {const problems = [];diff --git a/src/agent-look.js b/src/agent-look.jsindex 85d0b01e..3b3c63ba 100644--- a/src/agent-look.js+++ b/src/agent-look.js@@ -23,6 +23,7 @@ const SPOT_LIGHT_FIELDS = ['position', 'direction', 'angle', 'penumbra', 'color'const AREA_LIGHT_FIELDS = ['position', 'direction', 'up', 'width', 'height', 'color', 'intensity', 'affects'];const VOLUME_VECTOR_FIELDS = ['minimum', 'maximum', 'color', 'ambient', 'drift'];const VOLUME_NUMBER_FIELDS = ['density', 'steps', 'anisotropy', 'noiseAmount', 'noiseScale', 'maxDistance', 'shadowAmbient', 'heightFalloff', 'detailOctaves', 'detailAmount', 'warp', 'contrast', 'profileSoftness', 'keyScattering', 'scatterOctaves', 'multiScatter', 'multiExtinction', 'multiAnisotropy', 'keyTransmittance', 'surfaceTransmittance'];+export const VOLUME_FOG_FIELDS = Object.freeze([...VOLUME_VECTOR_FIELDS, ...VOLUME_NUMBER_FIELDS]);const BLOOM_FIELDS = ['strength', 'threshold', 'radius'];const DEPTH_OF_FIELD_FIELDS = ['blur', 'focusDistance'];const MOTION_BLUR_FIELDS = ['shutter'];@@ -217,7 +218,7 @@ function areaLightFrom(light) {}function volumeFogFrom(input = {}) {- knownKeys(input, [...VOLUME_VECTOR_FIELDS, ...VOLUME_NUMBER_FIELDS], 'volumeFog');+ knownKeys(input, VOLUME_FOG_FIELDS, 'volumeFog');for (const field of VOLUME_VECTOR_FIELDS) {if (Object.hasOwn(input, field)) {vectorInRange(input[field], -1e5, 1e5, `volumeFog.${field}`);diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 703c4931..21fbb6c0 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -2,7 +2,7 @@ import { mat4, mat3 } from 'gl-matrix';import { box, cylinder, grid, sphere, torus } from './geometry.js';import { createSceneGraph } from './scene-graph.js';import { applyProjection, validateCameraShift, CAMERA_LENS_FIELDS } from './camera.js';-import { normalizeAgentLook, environmentPatchWithSetup, environmentLinksLights, agentEnvironmentMap } from './agent-look.js';+import { normalizeAgentLook, environmentPatchWithSetup, environmentLinksLights, agentEnvironmentMap, VOLUME_FOG_FIELDS } from './agent-look.js';import { agentSceneModule, agentSceneModuleLoaded } from './agent-scene-modules.js';import { MESH_SMOOTH_ANGLE_DEFAULT, CURVE_TEXT_LIMITS, AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';import { ALL_LIGHTS_MASK, MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';@@ -1531,7 +1531,8 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {const nestedField = lookField === 'environment' ? 'volumeFog' : lookField === 'effects' ? 'bloom' : null;const merged = { ...candidate[lookField], ...(lookField === 'environment' ? environmentPatchWithSetup(patch) : patch) };if (nestedField && Object.hasOwn(patch, nestedField)) {- knownKeys(patch[nestedField], Object.keys(candidate[lookField][nestedField]), nestedField);+ const nestedKeys = nestedField === 'volumeFog' ? [...Object.keys(candidate[lookField][nestedField]), ...VOLUME_FOG_FIELDS] : Object.keys(candidate[lookField][nestedField]);+ knownKeys(patch[nestedField], nestedKeys, nestedField);merged[nestedField] = { ...candidate[lookField][nestedField], ...patch[nestedField] };}candidate[lookField] = merged;diff --git a/tests/line-art.test.js b/tests/line-art.test.jsindex 302a5f81..d9b472ef 100644--- a/tests/line-art.test.js+++ b/tests/line-art.test.js@@ -105,15 +105,15 @@ test('installLineArt needs render passes first and leaves a frame without lines});test('the MCP scene_create schema accepts lines (or null) and a material toon', async () => {- const server = createAgentMcpServer({ async close() {} });+ const server = createAgentMcpServer({ async close() {}, async capabilities() { return { scene: {}, phase: 'idle' }; } });const client = new Client({ name: '67js-line-art-test', version: '1' });const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();await server.connect(serverTransport);await client.connect(clientTransport);- const { tools } = await client.listTools();- const environment = tools.find(tool => tool.name === 'scene_create').inputSchema.properties.recipe.properties.environment;- const options = environment.properties.lines.anyOf;- assert.deepEqual(options.map(option => option.type).sort(), ['null', 'object']);+ const outline = (await client.callTool({ name: 'scene_capabilities', arguments: { topic: 'environment' } })).structuredContent.fields;+ assert.match(JSON.stringify(outline['lines?']), /null/);+ const material = (await client.callTool({ name: 'scene_capabilities', arguments: { topic: 'materialFields' } })).structuredContent.fields;+ assert.ok(material['toon?']);await client.close();await server.close();});diff --git a/tests/mcp-camera-lights.test.js b/tests/mcp-camera-lights.test.jsindex af0667be..faa7dbe8 100644--- a/tests/mcp-camera-lights.test.js+++ b/tests/mcp-camera-lights.test.js@@ -24,7 +24,7 @@ function baseRecipe(extra = {}) {async function connect(context) {let scene;const runtime = {- async capabilities() { return {}; },+ async capabilities() { return { scene: {}, phase: 'idle' }; },async create({ recipe }) {scene = createAgentScene(recipe);return { revision: scene.revision };@@ -52,23 +52,12 @@ function lightArray(count, make) {return Array.from({ length: count }, (_, index) => make(index));}-function findProperty(node, name) {- if (!node || typeof node !== 'object') return null;- if (node.properties?.[name]) return node.properties[name];- for (const child of Object.values(node)) {- const found = findProperty(child, name);- if (found) return found;- }- return null;-}-test('the MCP light caps are the engine light limits', async context => {const { client } = await connect(context);- const { tools } = await client.listTools();- const create = tools.find(tool => tool.name === 'scene_create');+ const outline = (await client.callTool({ name: 'scene_capabilities', arguments: { topic: 'environment' } })).structuredContent.fields;const limits = { pointLights: MAX_POINT_LIGHTS, spotLights: MAX_SPOT_LIGHTS, areaLights: MAX_AREA_LIGHTS };for (const [field, limit] of Object.entries(limits)) {- assert.equal(findProperty(create.inputSchema, field).maxItems, limit, `${field} cap in scene_create`);+ assert.equal(outline[`${field}?`].length, `{..${limit}}`, `${field} cap in the environment topic`);}});diff --git a/tests/mcp-environment-schema.test.js b/tests/mcp-environment-schema.test.jsindex 2cea1aa5..8f3a2680 100644--- a/tests/mcp-environment-schema.test.js+++ b/tests/mcp-environment-schema.test.js@@ -37,7 +37,7 @@ function findSetEnvironmentSchema(node) {}async function withMcpClient(use) {- const server = createAgentMcpServer({ async close() {} });+ const server = createAgentMcpServer({ async close() {}, async capabilities() { return { scene: {}, phase: 'idle' }; } });const client = new Client({ name: '67js-environment-schema-test', version: '1' });const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();await server.connect(serverTransport);@@ -58,22 +58,24 @@ function toolSchema(tools, name) {return tools.find(tool => tool.name === name).inputSchema;}-// scene_create publishes the one full environment schema; the other tools name it.+// Every tool lists the same short environment; scene_capabilities topic environment outlines the full schema.async function mcpEnvironmentFields() {- const environment = toolSchema(await listedTools(), 'scene_create').properties.recipe.properties.environment;- assert.ok(environment?.properties, 'scene_create no longer publishes recipe.environment');- return Object.keys(environment.properties);+ return withMcpClient(async client => {+ const outline = (await client.callTool({ name: 'scene_capabilities', arguments: { topic: 'environment' } })).structuredContent.fields;+ return Object.keys(outline).filter(key => key !== '_' && key !== '$defs').map(key => key.replace(/[?]$/, ''));+ });}-test('scene_apply and scene_create_asset point to the environment schema in scene_create instead of repeating it', async () => {+test('every tool lists a short environment that names the capabilities topic instead of repeating the fields', async () => {const tools = await listedTools();const references = [findSetEnvironmentSchema(toolSchema(tools, 'scene_apply')),toolSchema(tools, 'scene_create_asset').properties.recipe.properties.environment,+ toolSchema(tools, 'scene_create').properties.recipe.properties.environment,];for (const reference of references) {- assert.equal(reference.properties, undefined);- assert.match(reference.description, /recipe.environment in scene_create/);+ assert.match(reference.description, /scene_capabilities environment/);+ assert.ok(Object.keys(reference.properties).length < 10);}});@@ -113,6 +115,25 @@ function coplanarRecipe() {};}+test('set-environment accepts every optional volume fog field on a recipe that set none', () => {+ const scene = createAgentScene(coplanarRecipe());+ const fields = { scatterOctaves: 2, multiScatter: 0.5, multiExtinction: 0.4, multiAnisotropy: 0.3, keyTransmittance: 0.6, surfaceTransmittance: 0.7, detailOctaves: 2, detailAmount: 0.3, warp: 1, contrast: 1.2, profileSoftness: 0.4, keyScattering: 2 };+ for (const [field, value] of Object.entries(fields)) {+ const fresh = createAgentScene(coplanarRecipe());+ fresh.apply([{ type: 'set-environment', environment: { volumeFog: { [field]: value } } }], { expectedRevision: fresh.revision });+ assert.ok(Object.hasOwn(fresh.environment.volumeFog, field), field);+ }+ scene.apply([{ type: 'set-environment', environment: { volumeFog: fields } }], { expectedRevision: scene.revision });+ assert.equal(scene.environment.volumeFog.scatterOctaves, fields.scatterOctaves);+});++test('the MCP schema accepts the opt-in fog fields', async () => {+ await withMcpClient(async client => {+ const result = await client.callTool({ name: 'scene_apply', arguments: { expectedRevision: 0, operations: [{ type: 'set-environment', environment: { volumeFog: { scatterOctaves: 2, multiScatter: 0.5 } } }] } });+ assert.doesNotMatch(result.content[0].text, /Unrecognized|Unknown volumeFog/);+ });+});+test('set-environment accepts ground, viewTransform and resolveCoplanar', () => {const scene = createAgentScene(coplanarRecipe());scene.apply([{ type: 'set-environment', environment: { ground: false, viewTransform: 'agx', resolveCoplanar: 'offset' } }], { expectedRevision: scene.revision });diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.jsindex ad00e622..dc289d8c 100644--- a/tests/mcp-tools.test.js+++ b/tests/mcp-tools.test.js@@ -28,7 +28,7 @@ async function connect(context) {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 capabilities() { return { scene: AGENT_SCENE_CAPABILITIES, phase: 'idle', availableIn: 'test' }; },async create({ recipe: input }) {calls++;scene = createAgentScene(input);@@ -149,13 +149,16 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'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', 'curve', 'text', 'terrain', 'grid', 'mesh']);- assert.ok(variants.every(variant => variant.additionalProperties === false));- assert.equal(recipeSchema.properties.environment.additionalProperties, false);- assert.equal(recipeSchema.properties.environment.properties.pointLights.maxItems, 16);- assert.equal(recipeSchema.properties.effects.additionalProperties, false);+ // The tool lists the common fields; the strict schema still validates and scene_capabilities serves the full outline.+ assert.deepEqual(recipeSchema.properties.geometries.items.properties.type.enum, ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'terrain', 'grid', 'mesh']);+ assert.ok(recipeSchema.properties.environment.properties.setup);assert.equal(recipeSchema.properties.shadow.additionalProperties, false);+ for (const topic of ['geometries', 'environment', 'effects', 'motion', 'physics', 'cloth', 'armatures', 'materialFields', 'meshEdit', 'meshStack']) {+ const answer = (await client.callTool({ name: 'scene_capabilities', arguments: { topic } })).structuredContent;+ assert.ok(answer.fields, `${topic} has an outline of its fields`);+ }+ assert.equal((await client.callTool({ name: 'scene_capabilities', arguments: { topic: 'meshEdit.bevel' } })).structuredContent.fields.op, '"bevel"');+ assert.equal((await client.callTool({ name: 'scene_capabilities', arguments: { topic: 'nope' } })).isError, true);const look = tools.find(tool => tool.name === 'scene_look');assert.equal(look.annotations.readOnlyHint, true);assert.equal(look.inputSchema.properties.width.maximum, 1024);@@ -461,9 +464,10 @@ test('relations off leaves the relations field and the relations capabilities ouassert.ok((await schemaOf(true)).includes('"relations"'), `${toolName} offers relations by default`);assert.ok(!(await schemaOf(false)).includes('"relations"'), `${toolName} must not offer relations`);}- const capabilitiesOf = async relations => (await clients[relations].callTool({ name: 'scene_capabilities', arguments: {} })).structuredContent.scene;- assert.ok('relations' in await capabilitiesOf(true));- assert.deepEqual(Object.keys(await capabilitiesOf(false)), ['rigging']);+ const sceneTopicsOf = async relations => (await clients[relations].callTool({ name: 'scene_capabilities', arguments: {} })).structuredContent.topics.scene;+ assert.ok((await sceneTopicsOf(true)).includes('relations'));+ assert.ok(!(await sceneTopicsOf(false)).includes('relations'));+ assert.ok((await sceneTopicsOf(false)).includes('rigging'));});test('SDK dynamic batches create resources, reject dangling edits, and restore scene membership', async context => {diff --git a/tests/other-clients.test.js b/tests/other-clients.test.jsindex 507ff89c..d50224f4 100644--- a/tests/other-clients.test.js+++ b/tests/other-clients.test.js@@ -50,7 +50,7 @@ test('every tool accepts an empty-argument call only when it has no required fietest('strict-mode and subset gaps are the known ones, so a new kind of gap is noticed', () => {const knownGaps = {- 'openai-strict': ['optional-properties', 'keyword-oneOf', 'keyword-prefixItems', 'any-value-schema', 'keyword-propertyNames', 'nesting-depth'],+ 'openai-strict': ['optional-properties', 'additional-properties-not-false', 'keyword-oneOf', 'keyword-prefixItems', 'any-value-schema', 'keyword-propertyNames', 'nesting-depth'],'gemini-subset': ['keyword-const', 'keyword-oneOf', 'keyword-$ref', 'any-value-schema', 'keyword-propertyNames', 'keyword-exclusiveMinimum', 'keyword-exclusiveMaximum'],};const summary = summarizeFindings(findings);diff --git a/tests/tool-cost-growth.test.js b/tests/tool-cost-growth.test.jsindex cf04fa19..2d42cbbd 100644--- a/tests/tool-cost-growth.test.js+++ b/tests/tool-cost-growth.test.js@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import test from 'node:test';import { readAcceptedBundles } from '../scripts/size-base.mjs';-import { budgetsFrom, ceilingProblems, compareCostsToBase, costAllowance, costsFrom } from '../scripts/tool-cost-growth.mjs';+import { budgetsFrom, ceilingProblems, compareCostsToBase, costAllowance, costsFrom, hardCeilingProblems } from '../scripts/tool-cost-growth.mjs';const report = {schemaTotal: { bytes: 20000 },@@ -61,6 +61,16 @@ test('release ceilings are listed as problems, and a release resets them', () =>assert.equal(reset.schemaOtherToolBytes, 4000);});+test('absolute ceilings fail the total, a large tool, any other tool and the default capabilities answer', () => {+ const ceilings = { schemaTotalBytes: 19000, schemaToolBytes: { scene_create: 12500 }, schemaOtherToolBytes: 7000, resultBytes: { scene_capabilities: 250 } };+ const problems = hardCeilingProblems(costsFrom(report), ceilings);+ assert.equal(problems.length, 2 + 1);+ assert.match(problems[0], /tool-total is 20000 bytes, over its absolute ceiling of 19000 by 1000/);+ assert.match(problems[1], /tool:scene_apply is 8000 bytes, over its absolute ceiling of 7000 by 1000/);+ assert.match(problems[2], /result:scene_capabilities is 300 bytes, over its absolute ceiling of 250 by 50/);+ assert.deepEqual(hardCeilingProblems(costsFrom(report), { ...ceilings, schemaTotalBytes: 20000, schemaOtherToolBytes: 8000, resultBytes: {} }), []);+});+function runGit(folder, ...args) {const identity = ['-c', 'user.name=Test', '-c', '[email protected]', '-c', 'commit.gpgsign=false', '-c', 'core.autocrlf=false'];const result = spawnSync('git', [...identity, ...args], { cwd: folder, encoding: 'utf8' });