Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Load allowlisted addons in the MCP server (#985)

Nguyen Xuan An6cffcb8f96f1
diff --git a/SECURITY.md b/SECURITY.md
index c6674081..1f922eb2 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -12,7 +12,7 @@ Only the latest published version of `@codepawlhq/67js` gets security fixes.
The MCP server takes input from AI agents, and that input can come from a prompt injection. The server must therefore hold these limits:
-- It runs no code that a tool call supplies.
+- It runs no code that a tool call supplies. One startup exception exists: `--addons <folder>` with `--allow-addon <package>` loads the named npm packages from that folder into the preview page. The person who starts the server chooses them, never a tool call, and an addon runs with the full rights of the preview page. The server serves only the allowlisted packages' own files, requires each to pass the addon contract, and refuses any real path outside the folder ([docs/addons.md](docs/addons.md#the-mcp-server-and-addons)).
- It reads assets only from the configured catalog, and it fetches no remote URLs for assets.
- It writes render output and GLB exports (`scene_export_glb`, under `exports/`, server-chosen names) only to the configured jobs folder.
- It bounds every collection, count and size before it allocates memory.
diff --git a/changes/985-allowlist.md b/changes/985-allowlist.md
new file mode 100644
index 00000000..fb968f11
--- /dev/null
+++ b/changes/985-allowlist.md
@@ -0,0 +1 @@
+- The MCP server loads third-party addons the owner allowlists at startup (`--addons`, `--allow-addon`) and recipes accept the controller and camera kinds they register (#985)
diff --git a/changes/985-allowlist.size.md b/changes/985-allowlist.size.md
new file mode 100644
index 00000000..a6fc2bbe
--- /dev/null
+++ b/changes/985-allowlist.size.md
@@ -0,0 +1 @@
+- entry:player: unregister and list functions let the host take back a kind an addon did not declare (#985)
diff --git a/docs/addons.md b/docs/addons.md
index 9f363165..ac12d3cb 100644
--- a/docs/addons.md
+++ b/docs/addons.md
@@ -4,7 +4,7 @@ A code addon is an npm package that extends 67js through the extension points it
## Security
-A code addon runs with the full rights of your page or Node process: it can read files, use the network and change anything in the scene. The MCP server never loads one from a tool call. Install only addons you trust, and read what an addon does before you add it.
+A code addon runs with the full rights of your page or Node process: it can read files, use the network and change anything in the scene. The MCP server loads one only when its owner allowlists it at startup ([below](#the-mcp-server-and-addons)), never from a tool call. Install only addons you trust, and read what an addon does before you add it.
## The contract
@@ -45,6 +45,20 @@ Kinds and formats cannot be replaced once registered, so pick a name that is unl
Copy [templates/addon-starter](https://github.com/codepawl/67.js/tree/main/templates/addon-starter). It registers a `hover` controller kind, has a test written with `node:test`, and passes the check below. Export a function that registers, rather than registering on import, so the host decides when.
+The entry module also exports `registerAddon()`, which a host calls once to register the addon's kinds (the starter shows it).
+
+## The MCP server and addons
+
+The person who starts the MCP server may allow addons:
+
+```sh
+67js-mcp --addons /abs/path/to/folder --allow-addon 67js-addon-starter --allow-addon @scope/other
+```
+
+The folder holds `node_modules` with the packages installed (`npm install` there). The server looks for each name only in `<folder>/node_modules/<name>` and refuses a real path (links included) outside the folder. Each addon must pass `67js-addon-check` against the running 67js version, declare a `bundleBytes` of at most 2 MiB, and be one self-contained ES module (the page serves only that package's own `.js` and `.mjs` files, and maps `@codepawlhq/67js` and `@codepawlhq/67js/addons/*` to the page's own engine modules). The server calls its `registerAddon()` in the preview page. Only the `registerController` and `registerCameraRig` points are checked there: a kind registered under a point the addon did not declare is taken back and the addon is skipped.
+
+An addon that fails is skipped with the reason on stderr and in `scene_capabilities` topic `addons`; the server keeps running. Tools only use the kinds a loaded addon registered: set `game.player.controller` or `game.camera` to the kind name. The page still runs under `script-src 'self'` plus the hash of one import map, and no tool can add, name or change an addon.
+
## Test one
Run your own tests with `@codepawlhq/67js` installed as a dev dependency next to the peer entry. Then check the contract:
diff --git a/docs/mcp.md b/docs/mcp.md
index 1fdd5e7e..cc487c7d 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -64,6 +64,8 @@ Asset IDs bind file contents through SHA-256. Changed files require a runtime re
Catalog imports retain supported textures, skins, morphs and animation clips.
The catalog takes self-contained GLB only. Poly Haven and similar sites ship a glTF folder (`.gltf`, `.bin` and textures): bundle it first with one command, then put the result in the catalog directory: `npx @gltf-transform/cli copy tree_01_1k.gltf tree_01.glb`. A recipe places a catalog asset with an `asset` node field (see [the scene guide](agent-scene.md#placed-catalog-assets)).
+`--addons` selects an absolute folder that holds `node_modules`, and each `--allow-addon <package name>` (repeat it, at most 16 times) allows one addon package from it ([third-party addons](addons.md#the-mcp-server-and-addons)). Only these two options choose addons, at startup. A tool call cannot load, name or change one. An addon that is not installed there, fails the addon contract, does not allow the running 67js version, declares an entry file above 2 MiB, resolves to a real path outside the folder, or registers a kind it did not declare is skipped with a one-line reason on stderr, and the server keeps running. `scene_capabilities` topic `addons` lists the loaded and skipped addons and the kinds each registered. A recipe may then use a registered controller or camera kind in `game.player.controller` and `game.camera`; the error for an unknown name lists the available ones.
+
These launch options remain outside tool arguments.
The process runs below normal priority to reduce interference with other work.
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 9450de09..392cfcfc 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -10,7 +10,7 @@ import { installMeshBlend, normalizeBlend } from '../src/mesh-blend.js';
import { installCoplanarDiagnostics } from '../src/coplanar-overlap.js';
import { applyProjection } from '../src/camera.js';
import { mat4 } from 'gl-matrix';
-import { listControllerKinds, listCameraRigKinds, unregisterControllerKind, unregisterCameraRigKind } from '../src/player.js';
+import { listAddedControllerKinds, listAddedCameraRigKinds, listControllerKinds, listCameraRigKinds, unregisterControllerKind, unregisterCameraRigKind } from '../src/player.js';
import { resolveAgentShadow, agentEnvironmentMap } from '../src/agent-look.js';
import { agentSceneModule, agentSceneModuleLoaded } from '../src/agent-scene-modules.js';
import { agentGroundPlacement, createAgentGround, placeAgentGround, FLOOR_COLOR } from '../src/agent-ground.js';
@@ -843,6 +843,8 @@ function takeBackKinds(before, registries) {
}
async function loadAddonModule({ url, name, extensionPoints }) {
+ const { setAddedGameKinds } = await import('../src/game-setup.js');
+ setAddedGameKinds(() => ({ controllers: listAddedControllerKinds(), cameraRigs: listAddedCameraRigKinds() }));
const before = Object.fromEntries(ADDON_KIND_REGISTRIES.map(registry => [registry.field, registry.list()]));
try {
const entry = await import(/* @vite-ignore */ url);
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 0669abd8..5015a924 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -18,6 +18,7 @@ import { PATH_TRACER_CAPABILITIES } from '../src/path-tracer-capabilities.js';
import { chooseDenoiser, finishWithOidn } from './agent-path-trace-denoise.mjs';
import { createNativeSequence } from './agent-native-sequence.mjs';
import { chooseNativeInstancing, chooseNativeKernel, chooseTraceBackend, createNativeTracerLocator, isNativeTimeLimitError, traceFrameNative, traceTexelsNative } from './agent-native-trace.mjs';
+import { addonCapabilities, addonFileFor, addonImportMap } from './mcp-addons.mjs';
import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';
import { geometryOnlyGlb } from './agent-query-asset.mjs';
import { AGENT_ASSET_LIMITS, assertCombinedAssetBytes } from '../src/agent-asset-limits.js';
@@ -74,7 +75,7 @@ function bakeAfterOperations(operations) {
const SYNC_TOLERANCE_SECONDS = 0.05;
// The preview page imports engine chunks that sit beside the package entries, one folder above preview.js.
const ENGINE_CHUNK_URL = /^\/[\w.-]+\.js$/;
-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>';
+const pageHtml = importMapScript => '<!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>' + importMapScript + '<script type="module" src="/preview.js"></script></body></html>';
/** Local, serialized browser preview. No browser is launched until scene creation. */
// Optional peer dependencies the page loads from the host's node_modules. Rapier ships its WASM inside rapier.mjs.
@@ -85,7 +86,7 @@ const VENDOR_FILES = Object.freeze({
});
export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browser: browserPath, memory = 192, assets: assetRoot,
- jobs: jobRoot, ffmpeg = 'ffmpeg', audio: audioRoot, openPage = openInDefaultBrowser,
+ jobs: jobRoot, ffmpeg = 'ffmpeg', audio: audioRoot, openPage = openInDefaultBrowser, addons: addonSet = { addons: [], skipped: [] },
previewUrl = new URL(/* @vite-ignore */ '../build/mcp/preview.js', import.meta.url) } = {}) {
if (!['gpu', 'cpu'].includes(backend)) {
throw new RangeError('backend must be gpu or cpu.');
@@ -103,6 +104,11 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
if (jobRoot !== undefined && (typeof jobRoot !== 'string' || !isAbsolute(jobRoot))) {
throw new TypeError('Job root must be an explicit absolute directory path.');
}
+ const importMapScript = addonSet.addons.length === 0 ? '' : `<script type="importmap">${JSON.stringify(addonImportMap(packageMetadata.exports))}</script>`;
+ // The one inline script is the import map; its hash is allowed so script-src stays 'self'. No addons, no hash.
+ const importMapHash = addonSet.addons.length === 0 ? '' : ` 'sha256-${createHash('sha256').update(importMapScript.slice(importMapScript.indexOf('>') + 1, -'</script>'.length)).digest('base64')}'`;
+ const registeredByAddon = {};
+ const refusedAddons = [];
const audioLibrary = audioRoot === undefined ? undefined : createAudioLibrary(audioRoot);
if (typeof ffmpeg !== 'string' || !ffmpeg || (ffmpeg !== 'ffmpeg' && (!isAbsolute(ffmpeg) || !existsSync(ffmpeg)))) {
throw new TypeError('FFmpeg must be on PATH or configured with an existing absolute executable path.');
@@ -272,6 +278,37 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
});
}
+ // Only files inside an allowlisted addon's own package folder, found by the index it was given at startup.
+ function serveAddonFile(url, response) {
+ const path = addonFileFor(addonSet.addons, url.split('?')[0]);
+ if (path === null) {
+ response.writeHead(404);
+ response.end();
+ return;
+ }
+ readFile(path).then(bytes => {
+ response.setHeader('Content-Type', 'application/javascript; charset=utf-8');
+ response.end(bytes);
+ }, () => {
+ response.writeHead(404);
+ response.end();
+ });
+ }
+
+ // Loads each allowlisted addon in the page. One that fails is skipped with its reason; the others stay.
+ async function loadAddons() {
+ for (const [index, addon] of addonSet.addons.entries()) {
+ try {
+ const added = await page.evaluate(input => window.__agentPreview.loadAddon(input), { url: `/addons/${index}/${addon.entry}`, name: addon.name, extensionPoints: addon.extensionPoints });
+ registeredByAddon[addon.name] = added;
+ } catch (error) {
+ const reason = String(error.message).replace(/^page\.evaluate: /, '').split('\n')[0];
+ refusedAddons.push({ name: addon.name, reason });
+ console.error(`67js addon ${addon.name} skipped: ${reason}`);
+ }
+ }
+ }
+
// Mesh booleans load Manifold and recipe physics loads Rapier, both optional peer dependencies, from the host's
// node_modules. Without one the page gets a 404 and the edit reports the install command.
function serveVendorFile({ resolve, type }, response) {
@@ -309,7 +346,11 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
return;
}
response.setHeader('Cache-Control', 'no-store');
- response.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; connect-src 'self' blob:");
+ response.setHeader('Content-Security-Policy', `default-src 'none'; script-src 'self' 'wasm-unsafe-eval'${importMapHash}; style-src 'unsafe-inline'; img-src data: blob:; connect-src 'self' blob:`);
+ if (request.method === 'GET' && request.url.startsWith('/addons/')) {
+ serveAddonFile(request.url, response);
+ return;
+ }
const vendor = request.method === 'GET' ? VENDOR_FILES[request.url] : undefined;
if (vendor) {
serveVendorFile(vendor, response);
@@ -325,7 +366,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
return;
}
response.setHeader('Content-Type', request.url === '/' ? 'text/html; charset=utf-8' : 'application/javascript; charset=utf-8');
- response.end(request.url === '/' ? html : code);
+ response.end(request.url === '/' ? pageHtml(importMapScript) : code);
});
httpServer.on('upgrade', (request, socket, head) => {
const accepted = isPreviewHost(request.headers.host, httpServer.address().port)
@@ -360,6 +401,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
});
await page.goto(origin);
await page.waitForFunction(() => Boolean(window.__agentPreview));
+ await loadAddons();
phase = 'ready';
} catch (error) {
phase = 'failed';
@@ -812,6 +854,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
glbExport: { maximumBytes: MAXIMUM_GLB_BYTES, maximumKept: MAXIMUM_KEPT_GLBS, maximumTextureSize: 4096 },
records: jobRoot ? (await jobs()).list().map(record => ({ jobId: record.jobId, state: record.state,
sourceRevision: record.sourceRevision, progress: record.progress })) : [] },
+ addons: addonCapabilities({ addons: addonSet.addons.filter(addon => !refusedAddons.some(refused => refused.name === addon.name)), skipped: addonSet.skipped, registered: registeredByAddon, refused: refusedAddons }),
unsupported: ['remote asset providers', 'arbitrary code execution', 'imported morph track authoring'],
};
},
diff --git a/scripts/capabilities-topics.mjs b/scripts/capabilities-topics.mjs
index 667cc8b0..61e3b370 100644
--- a/scripts/capabilities-topics.mjs
+++ b/scripts/capabilities-topics.mjs
@@ -5,7 +5,7 @@ import * as z from 'zod/v4';
import { outlineSchema, unionBranches } from './schema-outline.mjs';
import { AGENT_TOOL_EXAMPLES } from './tool-examples.mjs';
-const RUNTIME_SECTIONS = ['sceneLimits', 'preview', 'review', 'assets', 'jobs', 'unsupported'];
+const RUNTIME_SECTIONS = ['sceneLimits', 'preview', 'review', 'assets', 'jobs', 'addons', 'unsupported'];
const SUMMARY_LENGTH = 110;
// Scalars (booleans and numbers) of the scene capabilities share one topic instead of one each.
const FLAGS_TOPIC = 'flags';
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index bd94ae3d..997917b1 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -16,6 +16,7 @@ import { MATERIAL_PATTERN_TYPES, MATERIAL_MAPPINGS, LIGHTING_SETUP_NAMES, RENDER
import { MATERIAL_LAYER_SCALAR_RANGES, MATERIAL_LAYER_COLOR_RANGES } from '../src/material-layers.js';
import { SUBSURFACE_RANGES } from '../src/subsurface-limits.js';
import { responseFormatField, chosenFormat, conciseReview, conciseJobStatus, conciseJobResult, withoutNotes } from './mcp-response-format.mjs';
+import { resolveAddons } from './mcp-addons.mjs';
import { createCallLogger, CALL_LOG_ENVIRONMENT_VARIABLE } from './mcp-call-log.mjs';
import { startUpdateCheck, updateNoticeText, describeUpdateCheck } from '../src/mcp-update-check.js';
import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from '../src/light-limits.js';
@@ -985,14 +986,19 @@ export async function runCheckUpdateCli({ version = packageMetadata.version } =
export async function runMcpCli({ argumentsValue = process.argv.slice(2),
previewUrl = new URL(/* @vite-ignore */ '../build/mcp/preview.js', import.meta.url), version = packageMetadata.version } = {}) {
const options = { backend: 'gpu', memory: 192 };
+ const allowedAddonNames = [];
for (let index = 0; index < argumentsValue.length; index += 2) {
const name = argumentsValue[index];
const value = argumentsValue[index + 1];
- if (!['--backend', '--browser', '--memory', '--assets', '--jobs', '--ffmpeg', '--audio', '--branches', '--relations'].includes(name) || value === undefined) {
- throw new Error(`Use --backend cpu|gpu, --browser <local executable path>, --memory <32..${MAXIMUM_MEMORY_MIB} MiB>, --assets <absolute GLB directory>, --jobs <absolute private output directory>, --ffmpeg <absolute executable>, --audio <absolute folder of .wav, .mp3, .ogg or .flac files for video jobs>, --branches on|off and --relations on|off (both default on).`);
+ if (!['--backend', '--browser', '--memory', '--assets', '--jobs', '--ffmpeg', '--audio', '--branches', '--relations', '--addons', '--allow-addon'].includes(name) || value === undefined) {
+ throw new Error(`Use --addons <absolute folder with node_modules> with one --allow-addon <package name> for each allowed addon (repeatable, chosen only here), --backend cpu|gpu, --browser <local executable path>, --memory <32..${MAXIMUM_MEMORY_MIB} MiB>, --assets <absolute GLB directory>, --jobs <absolute private output directory>, --ffmpeg <absolute executable>, --audio <absolute folder of .wav, .mp3, .ogg or .flac files for video jobs>, --branches on|off and --relations on|off (both default on).`);
}
- options[name.slice(2)] = name === '--memory' ? Number(value) : value;
+ if (name === '--allow-addon') allowedAddonNames.push(value);
+ else options[name.slice(2)] = name === '--memory' ? Number(value) : value;
}
+ const addonSet = resolveAddons({ folder: options.addons, names: allowedAddonNames, version });
+ for (const { name, reason } of addonSet.skipped) console.error(`67js addon ${name} skipped: ${reason}`);
+ options.addons = addonSet;
if (!['cpu', 'gpu'].includes(options.backend) || !Number.isInteger(options.memory) || options.memory < 32 || options.memory > MAXIMUM_MEMORY_MIB) {
throw new Error(`Backend must be cpu or gpu, and memory must be an integer from 32 to ${MAXIMUM_MEMORY_MIB} MiB.`);
}
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index ca3c37c5..a17d2e33 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -55,6 +55,9 @@ Variants: `scene_apply` with a `branch` name, compare in one `scene_review` (a `
- Characters and creatures: recipe `armatures` plus `skin` per mesh node, `motion.ik`, imported GLBs through the
`asset` node field and `scene_asset_catalog`. Physics, cloth, particles and hair are recipe sections.
`scene_inspect` reports their results; read those instead of guessing from a picture.
+- Third-party controller or camera kinds exist only when the server owner started it with `--addons` and `--allow-addon`:
+ read `scene_capabilities` topic `addons` for the names, then set `game.player.controller` or `game.camera` to one.
+ You cannot load an addon from a tool.
- A GLB for Blender: `scene_export_glb` (needs `--jobs`), it returns a path.
## Finish
diff --git a/src/game-setup.js b/src/game-setup.js
index 757f1a75..77bdf5bc 100644
--- a/src/game-setup.js
+++ b/src/game-setup.js
@@ -1,6 +1,5 @@
import { validateGameRules } from './game-rules.js';
import { normalizeGameAnimation } from './game-animation.js';
-import { listControllerKinds, listCameraRigKinds } from './player.js';
// The `game` section of a scene recipe: which node the player controls, how, with what camera and input, and the rules
// that decide when the game is won. It is plain data. The runtime in src/game.js reads it; nothing in it is code.
@@ -19,9 +18,13 @@ export const GAME_SETUP_LIMITS = Object.freeze({
maxPathPoints: 256,
});
-// The fixed names, then any kind an allowlisted addon registered at runtime (see docs/addons.md).
-export const gameControllerNames = () => [...new Set([...GAME_CONTROLLERS, ...listControllerKinds()])];
-export const gameCameraNames = () => [...new Set([...GAME_CAMERAS, ...listCameraRigKinds()])];
+// The fixed names, then any kind a host registered at runtime, such as an allowlisted addon (docs/addons.md). The host gives
+// a function returning { controllers, cameraRigs } here, so this module does not pull the player code with it.
+let addedKinds = () => ({});
+export function setAddedGameKinds(source) {
+ addedKinds = source;
+}
+const withAdded = (fixed, added = []) => [...new Set([...fixed, ...added])];
const SETUP_FIELDS = ['player', 'camera', 'input', 'physics', 'ground', 'rules', 'npcs'];
const PLAYER_FIELDS = ['node', 'controller', 'walkSpeed', 'runSpeed', 'jumpSpeed', 'maximumSpeed', 'footOffset', 'animation'];
@@ -55,7 +58,7 @@ function boundedNumber(value, fallback, minimum, maximum, path) {
return value;
}
-function normalizePlayer(player, nodeIds, nodes) {
+function normalizePlayer(player, nodeIds, nodes, controllerNames) {
requireRecord(player, 'player');
rejectUnknownFields(player, PLAYER_FIELDS, 'player');
if (typeof player.node !== 'string' || !nodeIds.has(player.node)) {
@@ -64,7 +67,7 @@ function normalizePlayer(player, nodeIds, nodes) {
}
const normalized = {
node: player.node,
- controller: chooseName(player.controller, gameControllerNames(), 'character', 'player.controller'),
+ controller: chooseName(player.controller, controllerNames, 'character', 'player.controller'),
walkSpeed: boundedNumber(player.walkSpeed, 3, 0, GAME_SETUP_LIMITS.maxSpeed, 'player.walkSpeed'),
runSpeed: boundedNumber(player.runSpeed, 6, 0, GAME_SETUP_LIMITS.maxSpeed, 'player.runSpeed'),
jumpSpeed: boundedNumber(player.jumpSpeed, 7, 0, GAME_SETUP_LIMITS.maxJumpSpeed, 'player.jumpSpeed'),
@@ -141,15 +144,16 @@ function normalizeRules(rules, playerNode) {
* a normalised copy with every default filled in. The rules document is checked by validateGameRules. Errors name the field and say what to pass.
*/
export function normalizeGameSetup(game, nodeSource) {
+ const added = addedKinds();
const nodes = Array.isArray(nodeSource) ? nodeSource : [];
const nodeIds = Array.isArray(nodeSource) ? new Set(nodeSource.map(node => node.id)) : nodeSource;
requireRecord(game, 'game');
rejectUnknownFields(game, SETUP_FIELDS, 'game');
- const player = normalizePlayer(game.player, nodeIds, nodes);
+ const player = normalizePlayer(game.player, nodeIds, nodes, withAdded(GAME_CONTROLLERS, added.controllers));
if (game.physics !== undefined && typeof game.physics !== 'boolean') fail('physics', `must be true or false, got ${JSON.stringify(game.physics)}.`);
const normalized = {
player,
- camera: chooseName(game.camera, gameCameraNames(), 'follow', 'camera'),
+ camera: chooseName(game.camera, withAdded(GAME_CAMERAS, added.cameraRigs), 'follow', 'camera'),
input: chooseName(game.input, GAME_INPUT_PRESETS, 'keyboard', 'input'),
physics: game.physics ?? false,
ground: boundedNumber(game.ground, 0, -GAME_SETUP_LIMITS.maxGround, GAME_SETUP_LIMITS.maxGround, 'ground'),
diff --git a/src/player.js b/src/player.js
index a49a415b..bb96de06 100644
--- a/src/player.js
+++ b/src/player.js
@@ -852,6 +852,15 @@ export function unregisterCameraRigKind(kind) {
return unregister('unregisterCameraRigKind', rigFactories, BUILT_IN_RIGS, kind);
}
+// The kinds registered after load (by a game or an allowlisted addon), without the built-in ones.
+export function listAddedControllerKinds() {
+ return listControllerKinds().filter(kind => !BUILT_IN_CONTROLLERS.has(kind));
+}
+
+export function listAddedCameraRigKinds() {
+ return listCameraRigKinds().filter(kind => !BUILT_IN_RIGS.has(kind));
+}
+
export function createController(kind, options = {}) {
const controller = build('createController', controllerFactories, kind, options);
const hasState = controller?.state && Array.isArray(controller.state.position);
diff --git a/templates/addon-starter/src/index.js b/templates/addon-starter/src/index.js
index 4f035168..e93e747f 100644
--- a/templates/addon-starter/src/index.js
+++ b/templates/addon-starter/src/index.js
@@ -27,3 +27,8 @@ export function registerHoverController(kind = 'hover') {
registerController(kind, createHoverController);
return kind;
}
+
+// The hook an MCP server calls once after it loads this package (docs/addons.md).
+export function registerAddon() {
+ registerHoverController();
+}
diff --git a/tests/mcp-addons.test.js b/tests/mcp-addons.test.js
new file mode 100644
index 00000000..b69485d0
--- /dev/null
+++ b/tests/mcp-addons.test.js
@@ -0,0 +1,189 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+import { resolveAddons, addonFileFor, addonImportMap, MAXIMUM_ADDON_BUNDLE_BYTES } from '../scripts/mcp-addons.mjs';
+import { runMcpCli } from '../scripts/mcp-server.mjs';
+import { VERSION } from '../src/version.js';
+
+const serverEntry = new URL('../bin/67js-mcp.mjs', import.meta.url).pathname.replace(/^\/(\w:)/, '$1');
+const starterFolder = new URL('../templates/addon-starter', import.meta.url).pathname.replace(/^\/(\w:)/, '$1');
+const hasBuild = existsSync(new URL('../build/mcp/preview.js', import.meta.url));
+
+// A folder with the starter installed under node_modules, after `change` edits its package.json and files.
+function installStarter(change = () => {}, name = '67js-addon-starter') {
+ const folder = mkdtempSync(join(tmpdir(), 'addons-test-'));
+ const packageFolder = join(folder, 'node_modules', ...name.split('/'));
+ mkdirSync(join(packageFolder, '..'), { recursive: true });
+ cpSync(starterFolder, packageFolder, { recursive: true });
+ const path = join(packageFolder, 'package.json');
+ const pack = JSON.parse(readFileSync(path, 'utf8'));
+ pack.name = name;
+ change(pack, packageFolder);
+ writeFileSync(path, JSON.stringify(pack));
+ return folder;
+}
+
+function skippedReason(folder, name = '67js-addon-starter') {
+ const { addons, skipped } = resolveAddons({ folder, names: [name], version: VERSION });
+ assert.deepEqual(addons, []);
+ assert.equal(skipped.length, 1);
+ return skipped[0].reason;
+}
+
+test('the starter addon passes when it is allowlisted and installed inside the folder', () => {
+ const folder = installStarter();
+ const { addons, skipped } = resolveAddons({ folder, names: ['67js-addon-starter'], version: VERSION });
+ assert.deepEqual(skipped, []);
+ assert.equal(addons[0].name, '67js-addon-starter');
+ assert.equal(addons[0].entry, 'src/index.js');
+ assert.deepEqual(addons[0].extensionPoints, ['registerController']);
+});
+
+test('an addon that is installed but not listed is never loaded or served', () => {
+ const folder = installStarter();
+ const { addons, skipped } = resolveAddons({ folder, names: [], version: VERSION });
+ assert.deepEqual(addons, []);
+ assert.deepEqual(skipped, []);
+ assert.equal(addonFileFor(addons, '/addons/0/src/index.js'), null);
+});
+
+test('an addon that is listed but not installed names the install command', () => {
+ const folder = installStarter();
+ assert.match(skippedReason(folder, 'missing-addon'), /missing-addon is listed with --allow-addon but is not installed.*npm install missing-addon/);
+});
+
+test('an addon that fails the contract is skipped with the contract errors', () => {
+ const folder = installStarter(pack => { delete pack.keywords; });
+ assert.match(skippedReason(folder), /fails the addon contract: .*67js-addon/);
+});
+
+test('an addon whose range excludes the running 67js version is skipped', () => {
+ const folder = installStarter(pack => { pack['67js'].range = '>=0.1.0 <0.2.0'; });
+ assert.match(skippedReason(folder), /does not allow 67js/);
+});
+
+test('an addon that declares more than the bundle bound is skipped', () => {
+ const folder = installStarter(pack => { pack['67js'].bundleBytes = MAXIMUM_ADDON_BUNDLE_BYTES + 1; });
+ assert.match(skippedReason(folder), /above the server bound/);
+});
+
+test('a package whose real path is outside the addons folder is refused', context => {
+ const outside = installStarter();
+ const folder = mkdtempSync(join(tmpdir(), 'addons-test-'));
+ mkdirSync(join(folder, 'node_modules'));
+ try {
+ symlinkSync(join(outside, 'node_modules', '67js-addon-starter'), join(folder, 'node_modules', '67js-addon-starter'), 'junction');
+ } catch (error) {
+ context.skip(`cannot create a link here: ${error.message}`);
+ return;
+ }
+ assert.match(skippedReason(folder), /outside the addons folder/);
+});
+
+test('a file inside an addon that links outside the package is not served', context => {
+ const folder = installStarter();
+ const outsideFile = join(folder, 'secret.js');
+ writeFileSync(outsideFile, 'export default 1;');
+ const { addons } = resolveAddons({ folder, names: ['67js-addon-starter'], version: VERSION });
+ const linked = join(addons[0].folder, 'src', 'linked.js');
+ try {
+ symlinkSync(outsideFile, linked);
+ } catch (error) {
+ context.skip(`cannot create a link here: ${error.message}`);
+ return;
+ }
+ assert.equal(addonFileFor(addons, '/addons/0/src/linked.js'), null);
+ assert.equal(addonFileFor(addons, '/addons/0/../../secret.js'), null);
+ assert.equal(addonFileFor(addons, '/addons/0/package.json'), null);
+ assert.ok(addonFileFor(addons, '/addons/0/src/index.js'));
+ assert.equal(addonFileFor(addons, '/addons/1/src/index.js'), null);
+});
+
+test('startup options are checked and the import map covers the addon entries', () => {
+ assert.throws(() => resolveAddons({ names: ['x'], version: VERSION }), /--allow-addon needs --addons/);
+ assert.throws(() => resolveAddons({ folder: 'relative', names: [], version: VERSION }), /absolute path/);
+ const { imports } = addonImportMap({ '.': './build/67.module.js', './addons/player': './build/player.js', './standalone': './build/x.js' });
+ assert.deepEqual(imports, { '@codepawlhq/67js': '/67.module.js', '@codepawlhq/67js/addons/player': '/player.js' });
+});
+
+test('the server parser takes --allow-addon more than once and keeps the error style', async () => {
+ await assert.rejects(runMcpCli({ argumentsValue: ['--allow-addon', 'a'], version: VERSION }), /--allow-addon needs --addons/);
+ await assert.rejects(runMcpCli({ argumentsValue: ['--allow-addon'], version: VERSION }), /Use --addons <absolute folder with node_modules>/);
+});
+
+function textOf(result) {
+ return (result.content ?? []).map(part => part.text ?? '').join('\n');
+}
+
+function recipeWithController(controller) {
+ 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: 'creature', geometry: 'cube', material: 'blue' }],
+ game: { player: { node: 'creature', controller } },
+ };
+}
+
+async function connect(context, folder, names) {
+ const args = [serverEntry, '--backend', 'cpu', '--addons', folder, ...names.flatMap(name => ['--allow-addon', name])];
+ const transport = new StdioClientTransport({ command: process.execPath, args, stderr: 'pipe' });
+ const client = new Client({ name: 'addons-test', version: '1.0.0' });
+ await client.connect(transport);
+ context.after(async () => {
+ await client.close();
+ rmSync(folder, { recursive: true, force: true });
+ });
+ return client;
+}
+
+test('the allowlisted starter loads in the page and its hover controller works through scene_create', { skip: !hasBuild && 'run npm run build first', timeout: 120000 }, async context => {
+ const client = await connect(context, installStarter(), ['67js-addon-starter']);
+ const refused = await client.callTool({ name: 'scene_create', arguments: { recipe: recipeWithController('boat') } });
+ assert.equal(refused.isError, true);
+ assert.match(textOf(refused), /Use one of: .*character.*vehicle.*hover/);
+ const created = await client.callTool({ name: 'scene_create', arguments: { recipe: recipeWithController('hover') } });
+ assert.notEqual(created.isError, true, textOf(created));
+ const exported = await client.callTool({ name: 'scene_export_recipe', arguments: {} });
+ assert.equal(exported.structuredContent.recipe.game.player.controller, 'hover');
+ const topic = await client.callTool({ name: 'scene_capabilities', arguments: { topic: 'addons' } });
+ const report = topic.structuredContent?.value ?? JSON.parse(textOf(topic)).value;
+ assert.equal(report.loaded[0].name, '67js-addon-starter');
+ assert.deepEqual(report.loaded[0].registered.controllers, ['hover']);
+ assert.deepEqual(report.skipped, []);
+});
+
+test('an addon that registers a point it did not declare is refused and its kind taken back', { skip: !hasBuild && 'run npm run build first', timeout: 120000 }, async context => {
+ const folder = installStarter(pack => { pack['67js'].extensionPoints = ['userPass']; });
+ const client = await connect(context, folder, ['67js-addon-starter']);
+ const created = await client.callTool({ name: 'scene_create', arguments: { recipe: recipeWithController('hover') } });
+ assert.equal(created.isError, true);
+ const topic = await client.callTool({ name: 'scene_capabilities', arguments: { topic: 'addons' } });
+ const report = topic.structuredContent?.value ?? JSON.parse(textOf(topic)).value;
+ assert.deepEqual(report.loaded, []);
+ assert.match(report.skipped[0].reason, /registered registerController \(hover\) but .* does not declare it/);
+});
+
+test('no tool argument can name an addon path or load one', { skip: !hasBuild && 'run npm run build first', timeout: 120000 }, async context => {
+ const client = await connect(context, installStarter(), []);
+ for (const [name, args] of [
+ ['scene_create', { recipe: recipeWithController('hover'), addons: ['67js-addon-starter'] }],
+ ['scene_capabilities', { topic: 'addons', addon: '/tmp/evil.js' }],
+ ]) {
+ let failed = false;
+ try {
+ const result = await client.callTool({ name, arguments: args });
+ failed = result.isError === true;
+ } catch {
+ failed = true;
+ }
+ assert.ok(failed, `${name} must reject an addon argument`);
+ }
+ const created = await client.callTool({ name: 'scene_create', arguments: { recipe: recipeWithController('hover') } });
+ assert.equal(created.isError, true, 'a kind from an addon that was not allowed must not exist');
+ assert.match(textOf(created), /Use one of: character, vehicle/);
+});