Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): one MCP server, node-front stdio - and it works on Windows

yhh10c6d79e23ba
diff --git a/.github/workflows/publish-mcp.yml b/.github/workflows/publish-mcp.yml
deleted file mode 100644
index 70caa77f8..000000000
--- a/.github/workflows/publish-mcp.yml
+++ /dev/null
@@ -1,38 +0,0 @@
-name: Publish MCP Server
-
-on:
- push:
- tags:
- - 'mcp-v*'
- workflow_dispatch:
-
-jobs:
- publish:
- name: Publish to GitHub Packages
- runs-on: ubuntu-latest
- permissions:
- contents: read
- packages: write
-
- steps:
- - uses: actions/checkout@v4
-
- - name: Setup Node.js
- uses: actions/setup-node@v4
- with:
- node-version: '22'
- registry-url: 'https://npm.pkg.github.com'
-
- - name: Install dependencies
- working-directory: tools/mcp-server
- run: npm install
-
- - name: Build
- working-directory: tools/mcp-server
- run: npm run build
-
- - name: Publish
- working-directory: tools/mcp-server
- run: npm publish
- env:
- NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/desktop/README.md b/desktop/README.md
index f859a4dc0..2fd2a31b0 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -68,7 +68,8 @@ public/ wasm runtime, bundled SDK, example projects (served at web root
- **Runtime** — the SDK + `esengine.wasm` boot into a `<canvas>` in `Viewport`; the
editor drives the world through `EditorControlSurface` (also exposed to headless
- automation and AI agents over an MCP server, `electron/mcp/`).
+ automation and AI agents over an MCP server: `pnpm editor:mcp`, see
+ `scripts/editor-mcp.mjs`; mutating tools need `ESTELLA_MCP_ALLOW_WRITES=1`).
- **Scenes & assets** — `ProjectStore` opens a project from disk and the Electron main
process watches it (`fs` + `chokidar`); the `ContentBrowser` browses and creates assets.
- **Inspector** — `Details` is generated from the engine's reflection metadata:
diff --git a/desktop/electron/mcp/server.mjs b/desktop/electron/mcp/server.mjs
deleted file mode 100644
index 2af6416b8..000000000
--- a/desktop/electron/mcp/server.mjs
+++ /dev/null
@@ -1,251 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file Editor MCP server (docs/REARCH_EDITOR_AUTOMATION.md P2).
- *
- * Exposes the editor's EditorControlSurface as MCP tools + resources so an agent
- * can open a scene, mutate it, advance frames, and read back the scene tree and
- * the rendered viewport. It is a TRANSPORT ADAPTER over the surface, not a
- * parallel API: it hosts the proven headless render host (static-serves dist/,
- * opens a show:false window on headless.html) and maps each MCP call to
- * `window.__estellaHeadless.api.<method>` via executeJavaScript — the same path
- * the verify runner uses.
- *
- * Transport: stdio (an agent spawns this as a subprocess). stdout carries ONLY
- * JSON-RPC; every log goes to stderr so the protocol stream stays clean.
- *
- * Permission: reads + observation always allowed; mutations are gated behind
- * ESTELLA_MCP_ALLOW_WRITES so an agent can't silently rewrite a project.
- */
-import { app, BrowserWindow } from 'electron';
-import http from 'node:http';
-import { readFile } from 'node:fs/promises';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { Server } from '@modelcontextprotocol/sdk/server/index.js';
-import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
-import {
- ListToolsRequestSchema,
- CallToolRequestSchema,
- ListResourcesRequestSchema,
- ReadResourceRequestSchema,
-} from '@modelcontextprotocol/sdk/types.js';
-
-const DIST = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'dist');
-const ALLOW_WRITES = process.env.ESTELLA_MCP_ALLOW_WRITES === '1';
-const W = Number(process.env.ESTELLA_MCP_W) || 1280;
-const H = Number(process.env.ESTELLA_MCP_H) || 720;
-
-// stdout is the JSON-RPC channel — keep ALL diagnostics on stderr.
-const log = (...a) => process.stderr.write('[mcp] ' + a.join(' ') + '\n');
-app.commandLine.appendSwitch('enable-unsafe-swiftshader');
-process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
-
-const MIME = {
- '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
- '.css': 'text/css', '.json': 'application/json', '.esscene': 'application/json',
- '.wasm': 'application/wasm', '.png': 'image/png', '.jpg': 'image/jpeg',
- '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2', '.svg': 'image/svg+xml',
-};
-
-function serveDist() {
- const server = http.createServer(async (req, res) => {
- try {
- const rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '') || 'index.html';
- const abs = path.join(DIST, rel);
- if (!abs.startsWith(DIST)) {
- res.writeHead(403).end();
- return;
- }
- const bytes = await readFile(abs);
- res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream' });
- res.end(bytes);
- } catch {
- res.writeHead(404).end('not found');
- }
- });
- return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));
-}
-
-// Render the viewport to a top-down PNG (base64) for an MCP image content block.
-// Runs in the renderer (has document): captureViewport returns bottom-up GL rows,
-// so flip Y into a 2D canvas before toDataURL.
-const CAPTURE_PNG = `(() => {
- const c = window.__estellaHeadless.api.captureViewport();
- const { rgba, width, height } = c;
- const cv = document.createElement('canvas'); cv.width = width; cv.height = height;
- const ctx = cv.getContext('2d');
- const img = ctx.createImageData(width, height);
- for (let y = 0; y < height; y++) {
- const src = (height - 1 - y) * width * 4;
- img.data.set(rgba.subarray(src, src + width * 4), y * width * 4);
- }
- ctx.putImageData(img, 0, 0);
- return cv.toDataURL('image/png').split(',')[1];
-})()`;
-
-const text = (t) => ({ content: [{ type: 'text', text: String(t) }] });
-const errorResult = (msg) => ({ content: [{ type: 'text', text: msg }], isError: true });
-
-// — Tool catalog. Each maps to a surface call run in the renderer. `write` tools
-// need ESTELLA_MCP_ALLOW_WRITES. Prescriptive descriptions state when to call. —
-const TOOLS = [
- {
- name: 'editor_load_scene',
- description: 'Load a scene (.esscene) into the editor World, resolving asset refs via the texture manifest. Call this first to set up a known scene before stepping or capturing.',
- inputSchema: {
- type: 'object', additionalProperties: false, required: ['scene'],
- properties: {
- scene: { type: 'string', description: 'Scene URL served by the editor, e.g. /scenes/sprite-rendering.esscene' },
- manifest: { type: 'string', description: 'Optional uuid→texture manifest URL' },
- },
- },
- run: (exec, a) =>
- exec(`window.__estellaHeadless.api.loadScene(${JSON.stringify(a.scene)}${a.manifest ? `, ${JSON.stringify(a.manifest)}` : ''})`)
- .then((n) => text(`loaded ${n} entities`)),
- },
- {
- name: 'editor_step',
- description: 'Advance the engine by N fixed-delta frames (no wall-clock) so a following capture is reproducible. Call after loading a scene and before capturing.',
- inputSchema: {
- type: 'object', additionalProperties: false,
- properties: {
- frames: { type: 'integer', minimum: 1, description: 'Frames to advance (default 1)' },
- dt: { type: 'number', description: 'Seconds per frame (default 1/60)' },
- },
- },
- run: (exec, a) =>
- exec(`window.__estellaHeadless.api.step(${Number(a.frames) || 1}, ${Number(a.dt) || 1 / 60})`).then(() => text('ok')),
- },
- {
- name: 'editor_get_scene_tree',
- description: 'Read the scene outliner tree (entity ids, names, kinds, hierarchy) as JSON.',
- inputSchema: { type: 'object', additionalProperties: false, properties: {} },
- run: (exec) => exec(`JSON.stringify(window.__estellaHeadless.api.getSceneTree())`).then(text),
- },
- {
- name: 'editor_get_inspector',
- description: 'Read the full editable inspector model (components + fields) for one entity, as JSON.',
- inputSchema: {
- type: 'object', additionalProperties: false, required: ['entity'],
- properties: { entity: { type: 'integer', description: 'Entity id from the scene tree' } },
- },
- run: (exec, a) => exec(`JSON.stringify(window.__estellaHeadless.api.getInspector(${Number(a.entity)}))`).then(text),
- },
- {
- name: 'editor_get_stats',
- description: 'Read live engine stats (entity count) as JSON.',
- inputSchema: { type: 'object', additionalProperties: false, properties: {} },
- run: (exec) => exec(`JSON.stringify(window.__estellaHeadless.api.getStats())`).then(text),
- },
- {
- name: 'editor_capture_viewport',
- description: 'Render the current viewport and return it as a PNG image, so you can SEE what the editor drew. Step the scene first for a settled frame.',
- inputSchema: { type: 'object', additionalProperties: false, properties: {} },
- run: (exec) => exec(CAPTURE_PNG).then((b64) => ({ content: [{ type: 'image', data: b64, mimeType: 'image/png' }] })),
- },
- {
- name: 'editor_add_entity',
- description: 'Spawn a new empty entity (with a Transform). Returns its id. Undoable. Requires write permission.',
- inputSchema: { type: 'object', additionalProperties: false, properties: {} },
- write: true,
- run: (exec) => exec(`window.__estellaHeadless.api.addEntity()`).then((id) => text(`entity ${id}`)),
- },
- {
- name: 'editor_set_field',
- description: 'Write one inspector field on a component (e.g. Transform.position). Undoable. Requires write permission.',
- inputSchema: {
- type: 'object', additionalProperties: false,
- required: ['entity', 'component', 'key', 'type', 'value'],
- properties: {
- entity: { type: 'integer' },
- component: { type: 'string', description: 'Component name, e.g. Transform' },
- key: { type: 'string', description: 'Field key, e.g. position' },
- type: { type: 'string', enum: ['number', 'bool', 'string', 'vec2', 'vec3', 'angle', 'color'] },
- value: { description: 'Value matching the field type (vec2/vec3 = number array, color = hex string)' },
- },
- },
- write: true,
- run: (exec, a) =>
- exec(`window.__estellaHeadless.api.setField(${Number(a.entity)}, ${JSON.stringify(a.component)}, ${JSON.stringify(a.key)}, ${JSON.stringify(a.type)}, ${JSON.stringify(a.value)})`).then(() => text('ok')),
- },
-];
-
-const RESOURCES = [
- { uri: 'editor://scene/tree', name: 'Scene tree', mimeType: 'application/json', code: `JSON.stringify(window.__estellaHeadless.api.getSceneTree())` },
- { uri: 'editor://stats', name: 'Engine stats', mimeType: 'application/json', code: `JSON.stringify(window.__estellaHeadless.api.getStats())` },
-];
-
-function buildMcpServer(exec) {
- const server = new Server(
- { name: 'estella-editor', version: '0.1.0' },
- { capabilities: { tools: {}, resources: {} } },
- );
-
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
- tools: TOOLS.filter((t) => !t.write || ALLOW_WRITES).map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),
- }));
-
- server.setRequestHandler(CallToolRequestSchema, async (req) => {
- const tool = TOOLS.find((t) => t.name === req.params.name);
- if (!tool) return errorResult(`unknown tool: ${req.params.name}`);
- if (tool.write && !ALLOW_WRITES) return errorResult(`tool ${tool.name} needs write permission (set ESTELLA_MCP_ALLOW_WRITES=1)`);
- try {
- return await tool.run(exec, req.params.arguments ?? {});
- } catch (e) {
- return errorResult(`${tool.name} failed: ${String((e && e.message) || e)}`);
- }
- });
-
- server.setRequestHandler(ListResourcesRequestSchema, async () => ({
- resources: RESOURCES.map(({ uri, name, mimeType }) => ({ uri, name, mimeType })),
- }));
-
- server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
- const r = RESOURCES.find((x) => x.uri === req.params.uri);
- if (!r) throw new Error(`unknown resource: ${req.params.uri}`);
- const t = await exec(r.code);
- return { contents: [{ uri: r.uri, mimeType: r.mimeType, text: String(t) }] };
- });
-
- return server;
-}
-
-app.whenReady().then(async () => {
- // Boot the headless host in the background; the MCP transport connects first so
- // the handshake / tools.list answer instantly, and tool calls await the host.
- let win = null;
- const hostReady = (async () => {
- const httpServer = await serveDist();
- const url = `http://127.0.0.1:${httpServer.address().port}/headless.html?w=${W}&h=${H}`;
- win = new BrowserWindow({ show: false, width: W, height: H, webPreferences: { offscreen: false } });
- win.webContents.on('console-message', (...args) => {
- const msg = args.map((x) => (x && typeof x === 'object' ? x.message ?? '' : String(x))).join(' ');
- if (/error|fail|unwind|exception/i.test(msg)) log('[renderer]', msg.slice(0, 200));
- });
- await win.loadURL(url);
- await win.webContents.executeJavaScript('window.__estellaHeadless.ready', true);
- log(`headless host ready (writes ${ALLOW_WRITES ? 'ENABLED' : 'disabled'})`);
- return win;
- })();
- hostReady.catch((e) => log('host boot failed:', String((e && e.stack) || e)));
-
- const exec = async (code) => {
- const w = await hostReady;
- return w.webContents.executeJavaScript(code, true);
- };
-
- try {
- await buildMcpServer(exec).connect(new StdioServerTransport());
- log('mcp server connected on stdio');
- } catch (e) {
- log('fatal:', String((e && e.stack) || e));
- app.quit();
- }
-});
-
-// Keep the process alive for the stdio session; exit when stdin closes (client gone).
-process.stdin.on('close', () => app.quit());
-app.on('window-all-closed', () => {
- /* keep running for stdio */
-});
diff --git a/desktop/electron/mcp/smoke.mjs b/desktop/electron/mcp/smoke.mjs
deleted file mode 100644
index 3ae5dda47..000000000
--- a/desktop/electron/mcp/smoke.mjs
+++ /dev/null
@@ -1,84 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file MCP smoke test (docs/REARCH_EDITOR_AUTOMATION.md P2). Run by node: spawns
- * the Electron-hosted editor MCP server over stdio (the way a real MCP
- * client would), then lists tools/resources and drives a load → step →
- * read tree → capture → mutate round-trip, asserting each. Proves the MCP
- * transport correctly exposes the editor surface end-to-end.
- */
-import { Client } from '@modelcontextprotocol/sdk/client/index.js';
-import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const here = path.dirname(fileURLToPath(import.meta.url));
-const electronBin = path.resolve(here, '..', '..', 'node_modules', '.bin', 'electron');
-const serverPath = path.resolve(here, 'server.mjs');
-
-const checks = [];
-const check = (name, cond, detail = '') => {
- checks.push({ name, ok: !!cond });
- console.log(`${cond ? '✓' : '✗'} ${name}${detail ? ' → ' + detail : ''}`);
-};
-
-const transport = new StdioClientTransport({
- command: electronBin,
- args: [serverPath],
- env: { ...process.env, ESTELLA_MCP_ALLOW_WRITES: '1' },
- stderr: 'inherit',
-});
-const client = new Client({ name: 'estella-smoke', version: '0.0.0' }, { capabilities: {} });
-
-try {
- await client.connect(transport);
-
- const { tools } = await client.listTools();
- const names = tools.map((t) => t.name);
- check(
- 'listTools includes core tools',
- ['editor_load_scene', 'editor_step', 'editor_capture_viewport', 'editor_get_scene_tree'].every((n) => names.includes(n)),
- names.join(','),
- );
- check('write tool exposed under ALLOW_WRITES', names.includes('editor_add_entity'));
-
- const load = await client.callTool({
- name: 'editor_load_scene',
- arguments: { scene: '/scenes/sprite-rendering.esscene', manifest: '/scenes/sprite-rendering.textures.json' },
- });
- check('load_scene returns an entity count', /loaded \d+ entities/.test(load.content?.[0]?.text ?? ''), load.content?.[0]?.text);
-
- await client.callTool({ name: 'editor_step', arguments: { frames: 30 } });
-
- const tree = await client.callTool({ name: 'editor_get_scene_tree' });
- let treeLen = 0;
- try {
- treeLen = JSON.parse(tree.content[0].text).length;
- } catch {
- /* leave 0 */
- }
- check('get_scene_tree returns nodes', treeLen > 0, `${treeLen} roots`);
-
- const cap = await client.callTool({ name: 'editor_capture_viewport' });
- const img = cap.content?.[0];
- check(
- 'capture_viewport returns a PNG image block',
- img?.type === 'image' && img?.mimeType === 'image/png' && (img?.data?.length ?? 0) > 100,
- `${img?.data?.length ?? 0} base64 chars`,
- );
-
- const add = await client.callTool({ name: 'editor_add_entity' });
- check('add_entity (write) spawns an entity', /entity \d+/.test(add.content?.[0]?.text ?? ''), add.content?.[0]?.text);
-
- const { resources } = await client.listResources();
- check('listResources includes scene tree', resources.some((r) => r.uri === 'editor://scene/tree'));
- const res = await client.readResource({ uri: 'editor://scene/tree' });
- check('readResource(scene/tree) returns json', (res.contents?.[0]?.text?.length ?? 0) > 2);
-} catch (e) {
- check('connect + drive the server', false, String((e && e.stack) || e));
-} finally {
- await client.close().catch(() => {});
- const failed = checks.filter((c) => !c.ok);
- console.log(`\n[mcp:smoke] ${failed.length === 0 ? 'PASS' : 'FAIL'} — ${checks.length - failed.length}/${checks.length}`);
- process.exit(failed.length === 0 ? 0 : 1);
-}
diff --git a/desktop/package.json b/desktop/package.json
index 36dc490e3..35dcc57a3 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -17,8 +17,8 @@
"test": "vitest run",
"test:watch": "vitest",
"verify:render": "vite build && electron scripts/headless-verify.mjs",
- "editor:mcp": "electron scripts/editor-mcp.mjs",
- "editor:mcp:build": "vite build && electron scripts/editor-mcp.mjs",
+ "editor:mcp": "node scripts/editor-mcp.mjs",
+ "editor:mcp:build": "vite build && node scripts/editor-mcp.mjs",
"editor:mcp:e2e": "vite build && node scripts/editor-mcp-e2e.mjs",
"editor:shot": "vite build && electron .",
"verify:render:spine": "vite build && ESTELLA_VERIFY_SCENE=/scenes/spine-test.esscene ESTELLA_VERIFY_MANIFEST=/scenes/spine-test.textures.json electron scripts/headless-verify.mjs",
@@ -54,8 +54,6 @@
"verify:render:ysort": "vite build && ESTELLA_VERIFY_YSORT=1 ESTELLA_VERIFY_SCENE=/scenes/ysort.esscene ESTELLA_VERIFY_MANIFEST=/scenes/ysort.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":30},{\\\"x\\\":0.5,\\\"y\\\":0.25,\\\"rgb\\\":[255,0,0],\\\"tol\\\":30},{\\\"x\\\":0.5,\\\"y\\\":0.75,\\\"rgb\\\":[0,255,0],\\\"tol\\\":30}]\" electron scripts/headless-verify.mjs",
"verify:render:ysort:off": "vite build && ESTELLA_VERIFY_SCENE=/scenes/ysort.esscene ESTELLA_VERIFY_MANIFEST=/scenes/ysort.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0],\\\"tol\\\":30}]\" electron scripts/headless-verify.mjs",
"verify:smoke": "vite build && electron scripts/headless-smoke.mjs",
- "mcp": "electron electron/mcp/server.mjs",
- "mcp:smoke": "vite build && node electron/mcp/smoke.mjs",
"verify:render:tilemap:hex": "vite build && ESTELLA_VERIFY_SCENE=/scenes/tilemap-hex.esscene ESTELLA_VERIFY_MANIFEST=/scenes/tilemap-hex.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=6 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.40,\\\"y\\\":0.40,\\\"rgb\\\":[255,0,0]},{\\\"x\\\":0.60,\\\"y\\\":0.40,\\\"rgb\\\":[0,255,0]},{\\\"x\\\":0.50,\\\"y\\\":0.55,\\\"rgb\\\":[0,0,255]},{\\\"x\\\":0.70,\\\"y\\\":0.55,\\\"rgb\\\":[255,255,0]}]\" electron scripts/headless-verify.mjs",
"verify:render:mesh2d": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mesh2d.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mesh2d.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=4 ESTELLA_VERIFY_EXPECT='[{\"x\":0.30,\"y\":0.556,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.70,\"y\":0.556,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.30,\"y\":0.40,\"rgb\":[255,0,0],\"tol\":40}]' electron scripts/headless-verify.mjs",
"verify:render:parallax:shape": "vite build && ESTELLA_VERIFY_SCENE=/scenes/parallax-shape.esscene ESTELLA_VERIFY_MANIFEST=/scenes/parallax-shape.textures.json ESTELLA_VERIFY_STEPS=4 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":40},{\\\"x\\\":0.25,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0],\\\"tol\\\":40}]\" electron scripts/headless-verify.mjs",
diff --git a/desktop/scripts/editor-mcp-e2e.mjs b/desktop/scripts/editor-mcp-e2e.mjs
index 82b7eefb6..d8deb653e 100644
--- a/desktop/scripts/editor-mcp-e2e.mjs
+++ b/desktop/scripts/editor-mcp-e2e.mjs
@@ -12,9 +12,13 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
const DESKTOP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
-const electron = path.join(DESKTOP, 'node_modules', '.bin', 'electron');
-const child = spawn(electron, ['scripts/editor-mcp.mjs'], { cwd: DESKTOP, stdio: ['pipe', 'pipe', 'pipe'] });
+// The server front is plain node (the Electron half is spawned by the front itself).
+const child = spawn(process.execPath, ['scripts/editor-mcp.mjs'], {
+ cwd: DESKTOP,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ env: { ...process.env, ESTELLA_MCP_ALLOW_WRITES: '1' },
+});
let buf = '';
const waiters = new Map();
@@ -66,6 +70,34 @@ try {
if (!Array.isArray(parsed) || parsed.length === 0) fail('get_scene_tree returned no nodes');
console.log(`get_scene_tree OK — ${parsed.length} root nodes`);
+ // Write path (server spawned with ESTELLA_MCP_ALLOW_WRITES=1): spawn + mutate.
+ const add = await rpc(5, 'tools/call', { name: 'add_entity', arguments: {} });
+ const newId = Number(add.result?.content?.[0]?.text);
+ if (add.result?.isError || !Number.isFinite(newId)) fail(`add_entity error: ${add.result?.content?.[0]?.text}`);
+ console.log('add_entity OK — id', newId);
+ const set = await rpc(6, 'tools/call', {
+ name: 'set_field',
+ arguments: { entity: newId, component: 'Transform', key: 'position', type: 'vec3', value: [64, 32, 0] },
+ });
+ if (set.result?.isError) fail(`set_field error: ${set.result?.content?.[0]?.text}`);
+ console.log('set_field OK');
+
+ // Observation: a stepped frame captures as a real PNG image content block.
+ await rpc(7, 'tools/call', { name: 'step', arguments: { frames: 2 } });
+ const cap = await rpc(8, 'tools/call', { name: 'capture_viewport', arguments: {} });
+ const img = cap.result?.content?.[0];
+ if (cap.result?.isError || img?.type !== 'image' || img?.mimeType !== 'image/png' || (img?.data?.length ?? 0) < 100)
+ fail(`capture_viewport did not return a PNG image block (${JSON.stringify(img)?.slice(0, 120)})`);
+ console.log(`capture_viewport OK — ${img.data.length} base64 chars`);
+
+ // Resources: list + read the scene tree as an MCP resource.
+ const resList = await rpc(9, 'resources/list', {});
+ const uris = (resList.result?.resources ?? []).map((r) => r.uri);
+ if (!uris.includes('editor://scene/tree')) fail(`resources/list missing scene tree: ${uris}`);
+ const resRead = await rpc(10, 'resources/read', { uri: 'editor://scene/tree' });
+ if ((resRead.result?.contents?.[0]?.text?.length ?? 0) < 3) fail('resources/read returned no JSON');
+ console.log('resources OK — list + read scene tree');
+
console.log('\nE2E PASS — MCP server drives EditorControlSurface end-to-end');
child.kill();
process.exit(0);
diff --git a/desktop/scripts/editor-mcp-host.mjs b/desktop/scripts/editor-mcp-host.mjs
new file mode 100644
index 000000000..d9bb91a3f
--- /dev/null
+++ b/desktop/scripts/editor-mcp-host.mjs
@@ -0,0 +1,122 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file editor-mcp-host.mjs — the Electron half of the editor MCP server.
+ *
+ * Boots the SAME headless render host the render-verify runner uses (serves dist/,
+ * opens headless.html, which publishes EditorControlSurface on `window.__estellaHeadless`)
+ * and exposes ONE internal HTTP endpoint on 127.0.0.1 — POST /exec — that marshals a
+ * surface call (or a renderer-code snippet) into the renderer via executeJavaScript.
+ *
+ * The MCP protocol itself lives in the plain-node front (editor-mcp.mjs). It cannot
+ * live here: an Electron main process never receives piped stdin on Windows (it ends
+ * immediately), so an Electron-hosted StdioServerTransport is structurally dead on
+ * one of our three platforms. The front owns stdio; this host only executes.
+ *
+ * Auth: every request must carry the token the front passed via ESTELLA_MCP_TOKEN
+ * (the socket binds to loopback, the token keeps other local processes out).
+ * Readiness: prints `MCP_HOST_READY {"port":N}` on stdout once the engine is up.
+ */
+import { app, BrowserWindow } from 'electron';
+import http from 'node:http';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const DIST = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist');
+const TOKEN = process.env.ESTELLA_MCP_TOKEN;
+const PARENT_PID = Number(process.env.ESTELLA_MCP_PARENT_PID) || 0;
+const W = Number(process.env.ESTELLA_MCP_W) || 1280;
+const H = Number(process.env.ESTELLA_MCP_H) || 720;
+
+app.commandLine.appendSwitch('enable-unsafe-swiftshader'); // GPU-less WebGL2 fallback
+process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
+const log = (...a) => process.stderr.write(`[editor-mcp-host] ${a.join(' ')}\n`);
+
+if (!TOKEN) {
+ log('FATAL: ESTELLA_MCP_TOKEN is required (spawn this host through editor-mcp.mjs)');
+ app.exit(1);
+}
+
+const MIME = {
+ '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
+ '.css': 'text/css', '.json': 'application/json', '.esscene': 'application/json',
+ '.wasm': 'application/wasm', '.png': 'image/png', '.jpg': 'image/jpeg',
+ '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2', '.svg': 'image/svg+xml',
+};
+
+function serveDist() {
+ const server = http.createServer(async (req, res) => {
+ try {
+ const rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '') || 'index.html';
+ const abs = path.join(DIST, rel);
+ if (!abs.startsWith(DIST)) { res.writeHead(403).end(); return; }
+ const bytes = await readFile(abs);
+ res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream' });
+ res.end(bytes);
+ } catch { res.writeHead(404).end('not found'); }
+ });
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));
+}
+
+const readBody = (req) => new Promise((resolve, reject) => {
+ const chunks = [];
+ req.on('data', (c) => chunks.push(c));
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
+ req.on('error', reject);
+});
+
+// Keep the process alive on the hidden window (this is a long-running host).
+app.on('window-all-closed', () => {});
+
+app.whenReady().then(async () => {
+ try {
+ const assets = await serveDist();
+ const url = `http://127.0.0.1:${assets.address().port}/headless.html?w=${W}&h=${H}`;
+ const win = new BrowserWindow({ show: false, width: W, height: H, webPreferences: { offscreen: false } });
+ win.webContents.on('console-message', (...args) => {
+ const msg = args.map((a) => (a && typeof a === 'object' ? a.message ?? '' : String(a))).join(' ');
+ if (/error|fail|unwind|exception|webgl/i.test(msg)) log('[renderer]', msg.slice(0, 240));
+ });
+ await win.loadURL(url);
+ await win.webContents.executeJavaScript('window.__estellaHeadless.ready', true);
+ log('headless engine ready');
+
+ // The exec endpoint: marshal a surface call ({method, args}) or a renderer-code
+ // snippet ({js}) into the headless renderer. `undefined` args become the JS
+ // `undefined` literal so the surface's default parameters apply.
+ const exec = http.createServer(async (req, res) => {
+ const reply = (code, body) => {
+ res.writeHead(code, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(body));
+ };
+ if (req.method !== 'POST' || req.url !== '/exec') return reply(404, { ok: false, error: 'not found' });
+ if (req.headers['x-estella-mcp-token'] !== TOKEN) return reply(403, { ok: false, error: 'bad token' });
+ try {
+ const { method, args, js } = JSON.parse(await readBody(req));
+ const code = js ?? `window.__estellaHeadless.api.${method}(${(args ?? [])
+ .map((a) => (a === undefined ? 'undefined' : JSON.stringify(a)))
+ .join(',')})`;
+ const result = await win.webContents.executeJavaScript(code, true);
+ reply(200, { ok: true, hasResult: result !== undefined, result: result === undefined ? null : result });
+ } catch (e) {
+ reply(200, { ok: false, error: String((e && e.message) || e) });
+ }
+ });
+ await new Promise((resolve) => exec.listen(0, '127.0.0.1', resolve));
+
+ // The front reads this line to learn the port; everything else goes to stderr.
+ process.stdout.write(`MCP_HOST_READY ${JSON.stringify({ port: exec.address().port })}\n`);
+
+ // Insurance against an orphaned host: if the front dies without killing us
+ // (SIGKILL), notice the parent pid vanishing and exit.
+ if (PARENT_PID) {
+ setInterval(() => {
+ try { process.kill(PARENT_PID, 0); } catch { app.exit(0); }
+ }, 10_000).unref();
+ }
+ } catch (e) {
+ log('FATAL', String((e && e.stack) || e));
+ app.exit(1);
+ }
+});
diff --git a/desktop/scripts/editor-mcp-tools.mjs b/desktop/scripts/editor-mcp-tools.mjs
index 35224377c..f4592c359 100644
--- a/desktop/scripts/editor-mcp-tools.mjs
+++ b/desktop/scripts/editor-mcp-tools.mjs
@@ -2,21 +2,47 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file editor-mcp-tools.mjs
- * The editor MCP tool registry. Each tool maps 1:1 to an EditorControlSurface
- * method, so the MCP server adds NO new editor truth — it is a transport over
- * the surface (exactly what EditorControlSurface.ts:7-9 anticipated). Kept
- * dependency-free (JSON-Schema + light manual validation, no zod import) so the
- * dispatch unit-tests without Electron and resolves under vite/vitest; the
- * Electron entry (editor-mcp.mjs) supplies the executeJavaScript driver and the
+ * The editor MCP tool registry — the ONE catalog every MCP entry serves.
+ * Each tool maps 1:1 to an EditorControlSurface method, so the MCP server
+ * adds NO new editor truth — it is a transport over the surface (exactly
+ * what EditorControlSurface.ts:7-9 anticipated). Kept dependency-free
+ * (JSON-Schema + light manual validation, no zod import) so the dispatch
+ * unit-tests without Electron and resolves under vite/vitest; the Electron
+ * entry (editor-mcp.mjs) supplies the executeJavaScript driver and the
* MCP SDK wiring. See docs/REARCH_EDITOR_ARCH.md §11.
+ *
+ * Two tool shapes:
+ * - method tools: `{ method, args(input) }` → driver(method, args) — a surface call.
+ * - renderer-code tools: `{ js(input) }` → driver.js(code) — for routines that
+ * need the renderer's DOM (canvas PNG encode); still surface-only underneath.
+ *
+ * Mutating tools carry `write: true` and are hidden + refused unless the host
+ * enables writes (ESTELLA_MCP_ALLOW_WRITES=1) — an agent can observe by default
+ * but cannot silently rewrite a scene.
*/
const obj = (properties, required = []) => ({ type: 'object', properties, required });
+// Render the viewport to a base64 PNG. Runs in the renderer (needs document):
+// captureViewport returns bottom-up GL rows, so flip Y into a 2D canvas first.
+const CAPTURE_PNG_JS = `(() => {
+ const c = window.__estellaHeadless.api.captureViewport();
+ const { rgba, width, height } = c;
+ const cv = document.createElement('canvas'); cv.width = width; cv.height = height;
+ const ctx = cv.getContext('2d');
+ const img = ctx.createImageData(width, height);
+ for (let y = 0; y < height; y++) {
+ const src = (height - 1 - y) * width * 4;
+ img.data.set(rgba.subarray(src, src + width * 4), y * width * 4);
+ }
+ ctx.putImageData(img, 0, 0);
+ return cv.toDataURL('image/png').split(',')[1];
+})()`;
+
/** name → { description, schema (JSON Schema), method (surface), args(input)→[] }. */
export const TOOLS = [
{ name: 'load_scene',
- description: 'Load a scene (and optional asset manifest) into the headless World; returns the spawned entity count.',
+ description: 'Load a scene (and optional asset manifest) into the headless World; returns the spawned entity count. Call first to set up a known scene.',
schema: obj({ sceneUrl: { type: 'string' }, manifestUrl: { type: 'string' } }, ['sceneUrl']),
method: 'loadScene', args: (i) => [i.sceneUrl, i.manifestUrl] },
{ name: 'get_scene_tree',
@@ -28,27 +54,39 @@ export const TOOLS = [
{ name: 'get_inspector',
description: "An entity's components and fields — the Details-panel data.",
schema: obj({ entity: { type: 'number' } }, ['entity']), method: 'getInspector', args: (i) => [i.entity] },
+ { name: 'get_field_value',
+ description: "One component field's current value (null if the field does not exist).",
+ schema: obj({ entity: { type: 'number' }, component: { type: 'string' }, key: { type: 'string' } },
+ ['entity', 'component', 'key']),
+ method: 'getFieldValue', args: (i) => [i.entity, i.component, i.key] },
{ name: 'serialize_scene',
description: 'The full lossless scene JSON (the model truth).',
schema: obj({}), method: 'serializeScene', args: () => [] },
- { name: 'add_entity',
- description: 'Create a new entity; returns its id.',
+ { name: 'add_entity', write: true,
+ description: 'Create a new empty entity (with a Transform); returns its id.',
schema: obj({}), method: 'addEntity', args: () => [] },
- { name: 'delete_entity',
+ { name: 'delete_entity', write: true,
description: 'Delete an entity.',
schema: obj({ id: { type: 'number' } }, ['id']), method: 'deleteEntity', args: (i) => [i.id] },
- { name: 'rename_entity',
+ { name: 'duplicate_entity', write: true,
+ description: 'Duplicate an entity (subtree); returns the new id.',
+ schema: obj({ id: { type: 'number' } }, ['id']), method: 'duplicateEntity', args: (i) => [i.id] },
+ { name: 'rename_entity', write: true,
description: 'Rename an entity.',
schema: obj({ id: { type: 'number' }, name: { type: 'string' } }, ['id', 'name']),
method: 'renameEntity', args: (i) => [i.id, i.name] },
- { name: 'set_field',
+ { name: 'set_field', write: true,
description: 'Set a component field (undoable). `type` is the inspector field type (e.g. float, int, bool, string, vec2, vec3, color, enum).',
schema: obj({
entity: { type: 'number' }, component: { type: 'string' }, key: { type: 'string' },
type: { type: 'string' }, value: {},
}, ['entity', 'component', 'key', 'type', 'value']),
method: 'setField', args: (i) => [i.entity, i.component, i.key, i.type, i.value] },
- { name: 'set_parent',
+ { name: 'set_entity_xy', write: true,
+ description: 'Move an entity to a world position (x, y) — converts to parent-local under the hood (undoable).',
+ schema: obj({ id: { type: 'number' }, x: { type: 'number' }, y: { type: 'number' } }, ['id', 'x', 'y']),
+ method: 'setEntityXY', args: (i) => [i.id, i.x, i.y] },
+ { name: 'set_parent', write: true,
description: 'Re-parent an entity in the transform hierarchy (parent=null → scene root).',
schema: obj({ id: { type: 'number' }, parent: { type: ['number', 'null'] } }, ['id', 'parent']),
method: 'setParent', args: (i) => [i.id, i.parent] },
@@ -58,24 +96,46 @@ export const TOOLS = [
{ name: 'get_selection',
description: 'The primary selected entity id, or null.',
schema: obj({}), method: 'getSelection', args: () => [] },
+ { name: 'pick',
+ description: 'Viewport pick: the entity a click at (clientX, clientY) would select, or null.',
+ schema: obj({ clientX: { type: 'number' }, clientY: { type: 'number' } }, ['clientX', 'clientY']),
+ method: 'pick', args: (i) => [i.clientX, i.clientY] },
{ name: 'set_run_mode',
description: 'Enter or leave play mode (playing=true runs gameplay; Stop rebuilds the edit World).',
schema: obj({ playing: { type: 'boolean' }, paused: { type: 'boolean' } }, ['playing']),
method: 'setRunMode', args: (i) => [i.playing, i.paused] },
{ name: 'step',
- description: 'Advance the engine by N fixed-dt frames deterministically (no rAF).',
+ description: 'Advance the engine by N fixed-dt frames deterministically (no rAF). Step before capturing for a settled frame.',
schema: obj({ frames: { type: 'number' }, dt: { type: 'number' } }),
method: 'step', args: (i) => [i.frames, i.dt] },
+ { name: 'resize_viewport',
+ description: 'Resize the render canvas (the engine follows on the next stepped frame).',
+ schema: obj({ width: { type: 'number' }, height: { type: 'number' } }, ['width', 'height']),
+ method: 'resizeViewport', args: (i) => [i.width, i.height] },
+ { name: 'capture_viewport',
+ description: 'Render the current viewport and return it as a PNG image, so you can SEE what the editor drew. Step first for a settled frame.',
+ schema: obj({}), js: () => CAPTURE_PNG_JS, image: true },
{ name: 'get_stats',
description: 'Live counts: entity count + last frame draw calls (cheap render evidence).',
schema: obj({}), method: 'getStats', args: () => [] },
- { name: 'undo', description: 'Undo the last edit.', schema: obj({}), method: 'undo', args: () => [] },
- { name: 'redo', description: 'Redo the last undone edit.', schema: obj({}), method: 'redo', args: () => [] },
+ { name: 'get_subsystems',
+ description: 'Lifecycle + liveness of every engine subsystem (physics, audio, …): phase and activity.',
+ schema: obj({}), method: 'getSubsystems', args: () => [] },
+ { name: 'undo', write: true, description: 'Undo the last edit.', schema: obj({}), method: 'undo', args: () => [] },
+ { name: 'redo', write: true, description: 'Redo the last undone edit.', schema: obj({}), method: 'redo', args: () => [] },
+];
+
+/** MCP resources — read-only surface views an MCP client can subscribe to. */
+export const RESOURCES = [
+ { uri: 'editor://scene/tree', name: 'Scene tree', mimeType: 'application/json', method: 'getSceneTree' },
+ { uri: 'editor://stats', name: 'Engine stats', mimeType: 'application/json', method: 'getStats' },
];
-/** The MCP `tools/list` payload — name, description, JSON-Schema inputSchema. */
-export function listTools() {
- return TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.schema }));
+/** The MCP `tools/list` payload — name, description, JSON-Schema inputSchema.
+ * Without `allowWrites`, mutating tools are omitted entirely (not just refused). */
+export function listTools(allowWrites = false) {
+ return TOOLS.filter((t) => !t.write || allowWrites)
+ .map((t) => ({ name: t.name, description: t.description, inputSchema: t.schema }));
}
function typeMatches(spec, val) {
@@ -103,13 +163,23 @@ function validate(schema, raw) {
}
/**
- * Validate `rawInput`, invoke the surface via `driver(method, args)`, and wrap the
- * result as an MCP CallToolResult. A validation failure or a driver throw becomes an
- * `isError` result rather than crashing the server.
+ * Validate `rawInput`, invoke the surface via the driver, and wrap the result as
+ * an MCP CallToolResult. Method tools call `driver(method, args)`; renderer-code
+ * tools call `driver.js(code)`. A gated write without permission, a validation
+ * failure, or a driver throw becomes an `isError` result rather than a crash.
*/
-export async function runTool(tool, driver, rawInput) {
+export async function runTool(tool, driver, rawInput, allowWrites = true) {
try {
+ if (tool.write && !allowWrites) {
+ throw new Error(`tool ${tool.name} mutates the scene — start the server with ESTELLA_MCP_ALLOW_WRITES=1`);
+ }
const input = validate(tool.schema, rawInput);
+ if (tool.js) {
+ const data = await driver.js(tool.js(input));
+ return tool.image
+ ? { content: [{ type: 'image', data, mimeType: 'image/png' }] }
+ : { content: [{ type: 'text', text: String(data) }] };
+ }
const result = await driver(tool.method, tool.args(input));
return { content: [{ type: 'text', text: result === undefined ? 'ok' : JSON.stringify(result) }] };
} catch (err) {
diff --git a/desktop/scripts/editor-mcp.mjs b/desktop/scripts/editor-mcp.mjs
index 166869b73..be88fe570 100644
--- a/desktop/scripts/editor-mcp.mjs
+++ b/desktop/scripts/editor-mcp.mjs
@@ -1,94 +1,115 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file editor-mcp.mjs — the editor MCP server (headless host).
+ * @file editor-mcp.mjs — the editor MCP server (stdio front, plain node).
*
- * An Electron entry that boots the SAME headless render host the render-verify runner
- * uses (serves dist/, opens headless.html, which publishes EditorControlSurface on
- * `window.__estellaHeadless`), then runs an MCP server over stdio whose tools are the
- * surface methods (see editor-mcp-tools.mjs). So an MCP client (an AI agent) can drive
- * the real editor surface headlessly — load/inspect/edit scenes, step, read stats —
- * with no live Electron UI. The surface stays the single source of truth; this is a
- * transport over it (EditorControlSurface.ts:7-9). Requires a built dist/ (vite build).
+ * An MCP client (an AI agent) spawns this with node; it spawns the Electron half
+ * (editor-mcp-host.mjs — the proven headless render host publishing
+ * EditorControlSurface) and serves the MCP tool registry (editor-mcp-tools.mjs)
+ * over stdio, forwarding each call to the host's loopback /exec endpoint.
+ *
+ * Split on purpose: an Electron main process never receives piped stdin on
+ * Windows, so the MCP protocol must live in a plain-node process. The surface
+ * stays the single source of truth; registry + this transport add no editor
+ * truth of their own (EditorControlSurface.ts:7-9).
*
* stdout is the MCP JSON-RPC channel — ALL logging goes to stderr.
+ * Mutating tools require ESTELLA_MCP_ALLOW_WRITES=1 (hidden + refused otherwise).
*/
-import { app, BrowserWindow } from 'electron';
-import http from 'node:http';
-import { readFile } from 'node:fs/promises';
+import { spawn } from 'node:child_process';
+import { randomBytes } from 'node:crypto';
import path from 'node:path';
+import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
-import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
-import { TOOLS, listTools, runTool } from './editor-mcp-tools.mjs';
-
-const DIST = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist');
-const W = Number(process.env.ESTELLA_MCP_W) || 1280;
-const H = Number(process.env.ESTELLA_MCP_H) || 720;
+import {
+ ListToolsRequestSchema,
+ CallToolRequestSchema,
+ ListResourcesRequestSchema,
+ ReadResourceRequestSchema,
+} from '@modelcontextprotocol/sdk/types.js';
+import { TOOLS, RESOURCES, listTools, runTool } from './editor-mcp-tools.mjs';
-app.commandLine.appendSwitch('enable-unsafe-swiftshader'); // GPU-less WebGL2 fallback
-process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const ALLOW_WRITES = process.env.ESTELLA_MCP_ALLOW_WRITES === '1';
const log = (...a) => process.stderr.write(`[editor-mcp] ${a.join(' ')}\n`);
-const MIME = {
- '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
- '.css': 'text/css', '.json': 'application/json', '.esscene': 'application/json',
- '.wasm': 'application/wasm', '.png': 'image/png', '.jpg': 'image/jpeg',
- '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2', '.svg': 'image/svg+xml',
-};
+// Under plain node the electron package's export IS the binary path — works on
+// every platform (the .bin/ shim is a sh script Windows cannot spawn).
+const electron = createRequire(import.meta.url)('electron');
+const token = randomBytes(24).toString('hex');
-function serveDist() {
- const server = http.createServer(async (req, res) => {
- try {
- const rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '') || 'index.html';
- const abs = path.join(DIST, rel);
- if (!abs.startsWith(DIST)) { res.writeHead(403).end(); return; }
- const bytes = await readFile(abs);
- res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream' });
- res.end(bytes);
- } catch { res.writeHead(404).end('not found'); }
- });
- return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));
-}
+const host = spawn(electron, [path.join(HERE, 'editor-mcp-host.mjs')], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: {
+ ...process.env,
+ ESTELLA_MCP_TOKEN: token,
+ ESTELLA_MCP_PARENT_PID: String(process.pid),
+ },
+});
+host.stderr.on('data', (d) => process.stderr.write(d));
+host.on('exit', (code) => {
+ log(`host exited (${code}) — shutting down`);
+ process.exit(code === 0 ? 0 : 1);
+});
+const killHost = () => { try { host.kill(); } catch { /* already gone */ } };
+process.on('exit', killHost);
+process.stdin.on('close', () => { killHost(); process.exit(0); });
-// Keep the process alive on the hidden window (this is a long-running server).
-app.on('window-all-closed', () => {});
+// Wait for the host's readiness line to learn the /exec port.
+const port = await new Promise((resolve, reject) => {
+ let buf = '';
+ const timer = setTimeout(() => reject(new Error('host did not become ready in 120s')), 120_000);
+ host.stdout.on('data', (d) => {
+ buf += d.toString();
+ const m = /^MCP_HOST_READY (\{.*\})$/m.exec(buf);
+ if (m) {
+ clearTimeout(timer);
+ resolve(JSON.parse(m[1]).port);
+ }
+ });
+}).catch((e) => {
+ log('FATAL', e.message);
+ killHost();
+ process.exit(1);
+});
+log(`host ready on 127.0.0.1:${port} (writes ${ALLOW_WRITES ? 'ENABLED' : 'disabled'})`);
-app.whenReady().then(async () => {
- try {
- const server = await serveDist();
- const url = `http://127.0.0.1:${server.address().port}/headless.html?w=${W}&h=${H}`;
- const win = new BrowserWindow({ show: false, width: W, height: H, webPreferences: { offscreen: false } });
- win.webContents.on('console-message', (...args) => {
- const msg = args.map((a) => (a && typeof a === 'object' ? a.message ?? '' : String(a))).join(' ');
- if (/error|fail|unwind|exception|webgl/i.test(msg)) log('[renderer]', msg.slice(0, 240));
- });
- await win.loadURL(url);
- await win.webContents.executeJavaScript('window.__estellaHeadless.ready', true);
- log('headless engine ready');
+async function post(body) {
+ const res = await fetch(`http://127.0.0.1:${port}/exec`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-estella-mcp-token': token },
+ body: JSON.stringify(body),
+ });
+ const out = await res.json();
+ if (!out.ok) throw new Error(out.error);
+ return out.hasResult ? out.result : undefined;
+}
- // Marshal a surface call into the headless renderer. `undefined` args become the JS
- // `undefined` literal so the surface's default parameters apply.
- const driver = (method, args) =>
- win.webContents.executeJavaScript(
- `window.__estellaHeadless.api.${method}(${(args ?? [])
- .map((a) => (a === undefined ? 'undefined' : JSON.stringify(a)))
- .join(',')})`,
- true,
- );
+// The registry's driver: surface method calls + renderer-code snippets.
+const driver = (method, args) => post({ method, args });
+driver.js = (js) => post({ js });
- const mcp = new Server({ name: 'estella-editor', version: '0.1.0' }, { capabilities: { tools: {} } });
- mcp.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: listTools() }));
- mcp.setRequestHandler(CallToolRequestSchema, async (req) => {
- const tool = TOOLS.find((t) => t.name === req.params.name);
- if (!tool) return { content: [{ type: 'text', text: `unknown tool: ${req.params.name}` }], isError: true };
- return runTool(tool, driver, req.params.arguments);
- });
- await mcp.connect(new StdioServerTransport());
- log('MCP server connected over stdio');
- } catch (e) {
- log('FATAL', String((e && e.stack) || e));
- app.exit(1);
- }
+const mcp = new Server(
+ { name: 'estella-editor', version: '0.2.0' },
+ { capabilities: { tools: {}, resources: {} } },
+);
+mcp.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: listTools(ALLOW_WRITES) }));
+mcp.setRequestHandler(CallToolRequestSchema, async (req) => {
+ const tool = TOOLS.find((t) => t.name === req.params.name);
+ if (!tool) return { content: [{ type: 'text', text: `unknown tool: ${req.params.name}` }], isError: true };
+ return runTool(tool, driver, req.params.arguments, ALLOW_WRITES);
+});
+mcp.setRequestHandler(ListResourcesRequestSchema, async () => ({
+ resources: RESOURCES.map(({ uri, name, mimeType }) => ({ uri, name, mimeType })),
+}));
+mcp.setRequestHandler(ReadResourceRequestSchema, async (req) => {
+ const r = RESOURCES.find((x) => x.uri === req.params.uri);
+ if (!r) throw new Error(`unknown resource: ${req.params.uri}`);
+ const value = await driver(r.method, []);
+ return { contents: [{ uri: r.uri, mimeType: r.mimeType, text: JSON.stringify(value) }] };
});
+
+await mcp.connect(new StdioServerTransport());
+log('MCP server connected over stdio');
diff --git a/desktop/tests/editor-mcp-tools.test.ts b/desktop/tests/editor-mcp-tools.test.ts
index 34d967537..32d259360 100644
--- a/desktop/tests/editor-mcp-tools.test.ts
+++ b/desktop/tests/editor-mcp-tools.test.ts
@@ -2,17 +2,20 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect, vi } from 'vitest';
// @ts-expect-error — plain-.mjs tool registry shared with the Electron MCP entry.
-import { TOOLS, runTool, listTools } from '../scripts/editor-mcp-tools.mjs';
+import { TOOLS, RESOURCES, runTool, listTools } from '../scripts/editor-mcp-tools.mjs';
// The editor MCP server is a transport over EditorControlSurface: each tool maps to one
// surface method. These cover the pure dispatch layer (no Electron) — the Electron entry
// only supplies the executeJavaScript driver.
describe('editor MCP tool registry', () => {
- it('every tool has a unique name, a surface method, and an args builder', () => {
+ it('every tool has a unique name and either a surface method or renderer code', () => {
const names = new Set<string>();
- for (const t of TOOLS as Array<{ name: string; method: string; args: unknown }>) {
- expect(typeof t.method).toBe('string');
- expect(typeof t.args).toBe('function');
+ for (const t of TOOLS as Array<{ name: string; method?: string; args?: unknown; js?: unknown }>) {
+ if (t.js) expect(typeof t.js).toBe('function');
+ else {
+ expect(typeof t.method).toBe('string');
+ expect(typeof t.args).toBe('function');
+ }
expect(names.has(t.name)).toBe(false);
names.add(t.name);
}
@@ -54,11 +57,48 @@ describe('editor MCP tool registry', () => {
});
it('listTools advertises every tool with a description + JSON-Schema inputSchema', () => {
- const listed = listTools();
+ const listed = listTools(true);
expect(listed.map((t: { name: string }) => t.name)).toEqual((TOOLS as Array<{ name: string }>).map((t) => t.name));
for (const t of listed as Array<{ description: string; inputSchema: { type: string } }>) {
expect(typeof t.description).toBe('string');
expect(t.inputSchema.type).toBe('object');
}
});
+
+ it('listTools without write permission omits mutating tools but keeps reads', () => {
+ const readOnly = listTools(false).map((t: { name: string }) => t.name);
+ expect(readOnly).toContain('get_scene_tree');
+ expect(readOnly).toContain('capture_viewport');
+ expect(readOnly).not.toContain('set_field');
+ expect(readOnly).not.toContain('add_entity');
+ expect(readOnly.length).toBeLessThan(listTools(true).length);
+ });
+
+ it('runTool refuses a write tool without permission (driver not called)', async () => {
+ const driver = vi.fn();
+ const setField = TOOLS.find((t: { name: string }) => t.name === 'set_field');
+ const res = await runTool(setField, driver, {
+ entity: 1, component: 'Transform', key: 'position.x', type: 'float', value: 5,
+ }, false);
+ expect(res.isError).toBe(true);
+ expect(res.content[0].text).toContain('ESTELLA_MCP_ALLOW_WRITES');
+ expect(driver).not.toHaveBeenCalled();
+ });
+
+ it('a renderer-code tool runs via driver.js and wraps the result as an image', async () => {
+ const driver = vi.fn() as unknown as { js: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);
+ driver.js = vi.fn(async () => 'aWFtYXBuZw==');
+ const capture = TOOLS.find((t: { name: string }) => t.name === 'capture_viewport');
+ const res = await runTool(capture, driver, {});
+ expect(driver.js).toHaveBeenCalledWith(expect.stringContaining('captureViewport'));
+ expect(res.content[0]).toEqual({ type: 'image', data: 'aWFtYXBuZw==', mimeType: 'image/png' });
+ });
+
+ it('every resource maps to a surface method with a JSON mime', () => {
+ for (const r of RESOURCES as Array<{ uri: string; method: string; mimeType: string }>) {
+ expect(r.uri.startsWith('editor://')).toBe(true);
+ expect(typeof r.method).toBe('string');
+ expect(r.mimeType).toBe('application/json');
+ }
+ });
});