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.

fix(editor): the MCP field-write door coerces and validates, never writes garbage

yhh0d8684a42c63
diff --git a/desktop/electron/importAssets.ts b/desktop/electron/importAssets.ts
index f8997ede3..441398cc6 100644
--- a/desktop/electron/importAssets.ts
+++ b/desktop/electron/importAssets.ts
@@ -33,10 +33,22 @@ function relInRoot(root: string, abs: string): string | null {
return rel.replace(/\\/g, '/');
}
+/** Canonical creation extension per meta type — the inverse of {@link EXT_TO_TYPE},
+ * with the JSON spelling preferred where several extensions share a type. */
+const TYPE_TO_EXT: Record<string, string> = (() => {
+ const inv: Record<string, string> = {};
+ for (const [ext, type] of Object.entries(EXT_TO_TYPE)) if (!(type in inv)) inv[type] = ext;
+ return { ...inv, tilemap: '.tmj', bitmapFont: '.bmfont' };
+})();
+
/**
* Create a new asset file in `destDir` with `content` + a fresh `.meta` (uuid + the
* given type), deduping the name so it never clobbers. Returns the new project-
- * relative path. Powers the Content Browser "New …" menu (e.g. New Scene).
+ * relative path. Powers the Content Browser "New …" menu (e.g. New Scene) and the
+ * MCP create_asset door. A bare stem gets the type's canonical extension — an
+ * extensionless file would still register (the meta carries the type) but breaks
+ * every consumer that types by extension; a type/extension mismatch is incoherent
+ * on disk, so both are loud errors rather than silent writes.
*/
export async function createAsset(
root: string,
@@ -47,7 +59,22 @@ export async function createAsset(
): Promise<string> {
const absDir = resolveInRoot(root, destDir);
await mkdir(absDir, { recursive: true });
- const name = uniqueName(absDir, baseName);
+ let named = baseName;
+ if (!path.extname(named)) {
+ const ext = TYPE_TO_EXT[type];
+ if (!ext) {
+ throw new Error(
+ `unknown asset type "${type}" — pass a baseName with an extension, or one of: ${Object.keys(TYPE_TO_EXT).join(', ')}`,
+ );
+ }
+ named += ext;
+ } else {
+ const extType = metaTypeFor(named);
+ if (extType && extType !== type) {
+ throw new Error(`type "${type}" does not match extension "${path.extname(named)}" (which is "${extType}")`);
+ }
+ }
+ const name = uniqueName(absDir, named);
const abs = path.join(absDir, name);
await writeFile(abs, content, 'utf8');
await writeFile(abs + META_EXT, JSON.stringify(mintMeta(type), null, 2) + '\n', 'utf8');
diff --git a/desktop/scripts/editor-mcp-tools.mjs b/desktop/scripts/editor-mcp-tools.mjs
index 58101c802..402312d6c 100644
--- a/desktop/scripts/editor-mcp-tools.mjs
+++ b/desktop/scripts/editor-mcp-tools.mjs
@@ -82,10 +82,15 @@ export const TOOLS = [
schema: obj({ id: { type: 'number' }, name: { type: 'string' } }, ['id', 'name']),
method: 'renameEntity', args: (i) => [i.id, i.name] },
{ 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).',
+ description: 'Set a component field (undoable). The field\'s DECLARED inspector type wins (see get_inspector: number, bool, string, vec2, vec3, angle, color, enum, select, flags, gradient, curve, dimension, asset) — `type` is advisory. Vecs take [x, y(, z)] number arrays, colors "#rrggbbaa" hex or {r,g,b,a} 0..1, assets a project-relative path or @uuid ref. Unknown components/fields and malformed values are errors, never silent writes.',
schema: obj({
entity: { type: 'number' }, component: { type: 'string' }, key: { type: 'string' },
- type: { type: 'string' }, value: {},
+ type: { type: 'string' },
+ // A real type union — with a bare {} here, MCP clients treat the param as
+ // schema-less and serialize the value to raw JSON TEXT ("[16, 16]"), which
+ // then has to be parsed back editor-side (coerceFieldValue does, but a
+ // typed schema lets well-behaved clients send real JSON in the first place).
+ value: { type: ['number', 'string', 'boolean', 'array', 'object', 'null'] },
}, ['entity', 'component', 'key', 'type', 'value']),
method: 'setField', args: (i) => [i.entity, i.component, i.key, i.type, i.value] },
{ name: 'add_component', write: true,
@@ -170,7 +175,7 @@ export const TOOLS = [
js: (i) => `window.__estellaEditor.createSceneFile(${JSON.stringify(i.destDir)})
.then((p) => window.__estellaEditor.refreshAssets().then(() => p))` },
{ name: 'create_asset', write: true,
- description: 'Create a text asset file under a project-relative directory with the given content (types the editor knows: scene, inputmap, locale, fsm, bt, timeline, animclip, tileset, material, shader, prefab...). Returns its project-relative path, immediately referenceable (the registry refresh happens before this resolves).',
+ description: 'Create a text asset file under a project-relative directory with the given content. `type` is the meta vocabulary: scene, prefab, shader, material, animclip (.esanim), animation (.estimeline), tileset, statemachine (.esfsm), behaviortree (.esbt), locale, inputmap, tilemap (.tmj). A bare baseName gets the type\'s canonical extension appended. Returns the project-relative path, immediately referenceable (the registry refresh happens before this resolves).',
schema: obj({
destDir: { type: 'string' }, baseName: { type: 'string' },
content: { type: 'string' }, type: { type: 'string' },
@@ -259,6 +264,7 @@ function typeMatches(spec, val) {
: t === 'number' ? typeof val === 'number'
: t === 'string' ? typeof val === 'string'
: t === 'boolean' ? typeof val === 'boolean'
+ : t === 'array' ? Array.isArray(val)
: t === 'object' ? (val !== null && typeof val === 'object')
: true);
}
diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.ts
index 13e0dc992..2b6fe44eb 100644
--- a/desktop/src/engine/EditorControlSurface.ts
+++ b/desktop/src/engine/EditorControlSurface.ts
@@ -63,6 +63,86 @@ export function setAssetRefProblemResolver(fn: AssetRefProblemResolver | null):
assetRefProblem = fn;
}
+/**
+ * Coerce an automation-supplied field value into the shape the declared
+ * inspector type stores. Accepts the value both as real JSON (an array for a
+ * vec) and as JSON TEXT (what MCP clients send for schema-loose params), plus
+ * the `{x, y}` object spelling get_inspector-style reads suggest. Anything that
+ * doesn't coerce cleanly throws — the automation door must never write garbage.
+ */
+export function coerceFieldValue(
+ declared: InspectorFieldType,
+ key: string,
+ value: InspectorFieldValue,
+): InspectorFieldValue {
+ const fail = (expected: string): never => {
+ throw new Error(`field "${key}" (${declared}) expects ${expected}, got ${JSON.stringify(value)}`);
+ };
+ const parseJsonText = (s: string): unknown => {
+ try {
+ return JSON.parse(s);
+ } catch {
+ return fail('valid JSON');
+ }
+ };
+ switch (declared) {
+ case 'number':
+ case 'enum':
+ case 'flags': {
+ const n = Number(value);
+ return Number.isFinite(n) ? n : fail('a number');
+ }
+ case 'angle': {
+ const n = Number(value);
+ return Number.isFinite(n) ? n : fail('degrees as a number');
+ }
+ case 'bool':
+ // String forms arrive from text transports; "false"/"0" must not read truthy.
+ return typeof value === 'string' ? !['false', '0', ''].includes(value.trim().toLowerCase()) : Boolean(value);
+ case 'string':
+ case 'select':
+ case 'asset':
+ return typeof value === 'string' ? value : String(value);
+ case 'vec2':
+ case 'vec3': {
+ const n = declared === 'vec2' ? 2 : 3;
+ let v: unknown = value;
+ if (typeof v === 'string') v = parseJsonText(v);
+ if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
+ const o = v as Record<string, unknown>;
+ v = n === 2 ? [o.x, o.y] : [o.x, o.y, o.z];
+ }
+ if (!Array.isArray(v) || v.length < n || v.slice(0, n).some((c) => typeof c !== 'number' || !Number.isFinite(c))) {
+ return fail(`${n} numbers (e.g. ${n === 2 ? '[16, 16]' : '[0, 0, 0]'})`);
+ }
+ return (n === 2 ? [v[0], v[1]] : [v[0], v[1], v[2]]) as InspectorFieldValue;
+ }
+ case 'color': {
+ let v: unknown = value;
+ if (typeof v === 'string' && /^\s*[[{]/.test(v)) v = parseJsonText(v);
+ if (typeof v === 'string') return v; // #rrggbb / #rrggbbaa hex — the control's native form
+ if (v !== null && typeof v === 'object') {
+ const o = v as Record<string, unknown>;
+ if ([o.r, o.g, o.b].every((c) => typeof c === 'number')) {
+ const hex = (c: unknown): string =>
+ Math.round(Math.min(1, Math.max(0, c as number)) * 255).toString(16).padStart(2, '0');
+ return `#${hex(o.r)}${hex(o.g)}${hex(o.b)}${hex(typeof o.a === 'number' ? o.a : 1)}`;
+ }
+ }
+ return fail('a "#rrggbbaa" hex string or { r, g, b, a } with 0..1 channels');
+ }
+ case 'gradient':
+ case 'curve':
+ case 'dimension': {
+ const v = typeof value === 'string' ? parseJsonText(value) : value;
+ if (v === null || typeof v !== 'object') return fail('a structural object');
+ return v as InspectorFieldValue;
+ }
+ default:
+ return value;
+ }
+}
+
/** The session parts the surface needs (the EditorSession satisfies this). */
export interface SurfaceSession {
model: SceneModelImpl;
@@ -160,14 +240,38 @@ export class EditorControlSurfaceImpl {
renameEntity(id: EntityId, name: string): void {
this.s.commands.renameEntity(id, name);
}
+ /**
+ * The automation field write (MCP / headless). Unlike the UI path — which
+ * builds its values from the inspector controls it rendered — a remote caller
+ * can name a component or key that doesn't exist and encode the value as raw
+ * JSON text (MCP clients serialize schema-loose params as strings, so a
+ * `[16, 16]` vec2 arrives as the STRING "[16, 16]"). Resolve the field's
+ * DECLARED inspector type and coerce the value against it, and reject unknown
+ * components/keys loudly — a string destructured as a vec writes silent
+ * garbage into the model.
+ */
setField(
entity: EntityId,
component: string,
key: string,
- type: InspectorFieldType,
+ _type: InspectorFieldType, // advisory — the declared inspector type wins
value: InspectorFieldValue,
): void {
- this.s.commands.setField(entity, component, key, type, value);
+ const comps = this.s.query.readInspector(entity);
+ const comp = comps.find((c) => c.name === component);
+ if (!comp) {
+ const has = comps.map((c) => c.name).join(', ');
+ throw new Error(`component "${component}" is not on entity ${entity}${has ? ` (has: ${has})` : ''}`);
+ }
+ // The enable toggle is surfaced in the component header, not in `fields` —
+ // but it is still a writable bool field to automation.
+ const declared: InspectorFieldType | undefined =
+ comp.fields.find((f) => f.key === key)?.type ?? (comp.enable?.key === key ? 'bool' : undefined);
+ if (!declared) {
+ const keys = [...comp.fields.map((f) => f.key), ...(comp.enable ? [comp.enable.key] : [])];
+ throw new Error(`"${component}" has no field "${key}" (fields: ${keys.join(', ')})`);
+ }
+ this.s.commands.setField(entity, component, key, declared, coerceFieldValue(declared, key, value));
}
/** Add a component (by schema name) to an entity — the Details "Add Component" door. */
addComponent(entity: EntityId, component: string): void {
diff --git a/desktop/tests/editor-control-surface.test.ts b/desktop/tests/editor-control-surface.test.ts
index 52439132f..44580ed77 100644
--- a/desktop/tests/editor-control-surface.test.ts
+++ b/desktop/tests/editor-control-surface.test.ts
@@ -107,6 +107,30 @@ describe.skipIf(!HAS_WASM)('EditorControlSurface (headless World)', () => {
expect(host.ticks).toBe(3);
});
+ it('setField coerces JSON-text and object spellings against the DECLARED field type', () => {
+ const id = S.surface.addEntity()!;
+ const e = S.model.runtimeFor(id)!;
+ S.surface.addComponent(id, 'Sprite');
+ // Schema-loose MCP clients serialize a vec2 to its JSON text — it must land
+ // as numbers, never be indexed per-character.
+ S.surface.setField(id, 'Sprite', 'size', 'vec2', '[16, 16]');
+ expect(host.world.get(e, Sprite).size).toMatchObject({ x: 16, y: 16 });
+ S.surface.setField(id, 'Sprite', 'size', 'vec2', { x: 24, y: 32 } as never);
+ expect(host.world.get(e, Sprite).size).toMatchObject({ x: 24, y: 32 });
+ // Numeric fields coerce string digits; the caller's `type` hint is advisory
+ // (an honest 'int' must not bypass the declared 'number' conversion).
+ S.surface.setField(id, 'Sprite', 'layer', 'number', '5');
+ expect(host.world.get(e, Sprite).layer).toBe(5);
+ });
+
+ it('setField rejects unknown components, unknown keys, and malformed values loudly', () => {
+ const id = S.surface.addEntity()!;
+ S.surface.addComponent(id, 'Sprite');
+ expect(() => S.surface.setField(id, 'Rigidbody2D', 'mass', 'number', 1)).toThrow(/not on entity/);
+ expect(() => S.surface.setField(id, 'Sprite', 'size.x', 'number', 16)).toThrow(/no field/);
+ expect(() => S.surface.setField(id, 'Sprite', 'size', 'vec2', 'garbage')).toThrow(/expects/);
+ });
+
it('getDiagnostics flags a required-empty field (Details parity) and clears when set', () => {
const id = S.surface.addEntity()!;
S.surface.addComponent(id, 'Sprite'); // Sprite.texture is required, defaults empty
diff --git a/desktop/tests/import-assets.test.ts b/desktop/tests/import-assets.test.ts
index 8c3738ad1..91c4a8b25 100644
--- a/desktop/tests/import-assets.test.ts
+++ b/desktop/tests/import-assets.test.ts
@@ -93,4 +93,19 @@ describe('createAsset', () => {
expect(rel).toBe('assets/ai/patrol.esfsm');
expect(meta(path.join(root, rel)).type).toBe('statemachine');
});
+
+ it('a bare stem gets the type\'s canonical extension (the MCP door passes no extension)', async () => {
+ const rel = await createAsset(root, 'assets/animations', 'walk', '{"frames":[]}', 'animclip');
+ expect(rel).toBe('assets/animations/walk.esanim');
+ expect(meta(path.join(root, rel)).type).toBe('animclip');
+ });
+
+ it('a bare stem with an unknown type is a loud error, not an extensionless file', async () => {
+ await expect(createAsset(root, 'assets', 'thing', '{}', 'nonsense')).rejects.toThrow(/unknown asset type/);
+ expect(existsSync(path.join(root, 'assets/thing'))).toBe(false);
+ });
+
+ it('a type/extension mismatch is a loud error (incoherent on disk)', async () => {
+ await expect(createAsset(root, 'assets', 'walk.esanim', '{}', 'scene')).rejects.toThrow(/does not match/);
+ });
});