Skip to content

3D engine that AI agents drive

Name the valid key in unrecognized-key errors (#2048)

Nguyen Xuan Andda6b8c8cf48
diff --git a/changes/2048.md b/changes/2048.md
new file mode 100644
index 00000000..5d271252
--- /dev/null
+++ b/changes/2048.md
@@ -0,0 +1 @@
+- An unrecognized key in a tool call now names the valid key to use, such as `translation` for `position`, and says where lights and sizes live (#2048)
diff --git a/scripts/mcp-input-errors.mjs b/scripts/mcp-input-errors.mjs
index 5e0aad43..049a781b 100644
--- a/scripts/mcp-input-errors.mjs
+++ b/scripts/mcp-input-errors.mjs
@@ -3,14 +3,97 @@ import { describeReceived } from '../src/field-error.js';
const ISSUES_WITH_A_REJECTED_VALUE = new Set(['too_big', 'too_small', 'invalid_value', 'invalid_format', 'not_multiple_of']);
+// Names an agent reaches for that the recipe spells differently. A synonym whose target is a valid key at that level
+// becomes a "did you mean"; the others point at the place the thing lives.
+const KEY_SYNONYMS = {
+ position: { key: 'translation' },
+ metalness: { key: 'metallic' },
+ tags: { key: 'tag' },
+ size: { advice: 'geometries are unit solids, so size a part with the "scale" of its node' },
+ radius: { advice: 'geometries are unit solids, so size a part with the "scale" of its node' },
+ lights: { advice: 'point, spot and area lights are environment.pointLights, environment.spotLights and environment.areaLights (scene_capabilities environment)' },
+};
+
+const MAXIMUM_TYPO_DISTANCE = 2;
+
+function editDistance(first, second) {
+ let previousRow = Array.from({ length: second.length + 1 }, (_, index) => index);
+ for (let firstIndex = 1; firstIndex <= first.length; firstIndex++) {
+ const row = [firstIndex];
+ for (let secondIndex = 1; secondIndex <= second.length; secondIndex++) {
+ const substitution = previousRow[secondIndex - 1] + (first[firstIndex - 1] === second[secondIndex - 1] ? 0 : 1);
+ row.push(Math.min(previousRow[secondIndex] + 1, row[secondIndex - 1] + 1, substitution));
+ }
+ previousRow = row;
+ }
+ return previousRow[second.length];
+}
+
+function closestValidKey(rejectedKey, validKeys) {
+ let best;
+ let bestDistance = Infinity;
+ for (const validKey of validKeys) {
+ const distance = editDistance(rejectedKey.toLowerCase(), validKey.toLowerCase());
+ if (distance < bestDistance) {
+ best = validKey;
+ bestDistance = distance;
+ }
+ }
+ return bestDistance <= Math.min(MAXIMUM_TYPO_DISTANCE, Math.floor(rejectedKey.length / 2)) ? best : undefined;
+}
+
+// At most one suggestion per rejected key, so a long error stays short.
+export function suggestionForRejectedKey(rejectedKey, validKeys) {
+ const synonym = Object.hasOwn(KEY_SYNONYMS, rejectedKey) ? KEY_SYNONYMS[rejectedKey] : undefined;
+ if (synonym?.key && validKeys.includes(synonym.key)) {
+ return `Use "${synonym.key}" instead of "${rejectedKey}".`;
+ }
+ const closest = closestValidKey(rejectedKey, validKeys);
+ if (closest) {
+ return `Use "${closest}" instead of "${rejectedKey}".`;
+ }
+ if (synonym?.advice) {
+ return `For "${rejectedKey}": ${synonym.advice}.`;
+ }
+ return undefined;
+}
+
+function unrecognizedKeysMessage(issue, wording) {
+ const validKeys = Object.keys(issue.inst?._zod?.def?.shape ?? {});
+ const suggestions = issue.keys.map(key => suggestionForRejectedKey(key, validKeys)).filter(Boolean);
+ if (suggestions.length === 0) {
+ return undefined;
+ }
+ return `${wording}. ${suggestions.join(' ')}`;
+}
+
+// A field that takes a number while a sibling takes the colour an agent passed.
+const COLOUR_SIBLINGS = { emission: 'emissiveColor' };
+
+function wrongTypeMessage(issue, wording) {
+ const fieldName = issue.path?.at(-1);
+ const sibling = typeof fieldName === 'string' && Object.hasOwn(COLOUR_SIBLINGS, fieldName) ? COLOUR_SIBLINGS[fieldName] : undefined;
+ if (issue.expected === 'number' && Array.isArray(issue.input) && sibling) {
+ return `${wording}. ${fieldName} takes one number (a multiplier); for an RGB colour use ${sibling}.`;
+ }
+ return undefined;
+}
+
// The SDK prefixes each schema message with the field path (recipe.materials.0.color.2). The English wording says what
-// was expected ("Too big: expected number to be <=1") but not what arrived, so the received value is added here.
+// was expected ("Too big: expected number to be <=1") but not what arrived, so the received value is added here, and an
+// unrecognized key names the valid key it was probably meant to be.
function messageWithReceivedValue(issue) {
const wording = z.locales.en().localeError(issue);
const text = typeof wording === 'string' ? wording : wording?.message;
if (!text) {
return undefined;
}
+ if (issue.code === 'unrecognized_keys') {
+ return unrecognizedKeysMessage(issue, text);
+ }
+ if (issue.code === 'invalid_type') {
+ return wrongTypeMessage(issue, text);
+ }
if (ISSUES_WITH_A_REJECTED_VALUE.has(issue.code) && Object.hasOwn(issue, 'input')) {
return `${text} (got ${describeReceived(issue.input)})`;
}
diff --git a/tests/mcp-unknown-key-hints.test.js b/tests/mcp-unknown-key-hints.test.js
new file mode 100644
index 00000000..f0901860
--- /dev/null
+++ b/tests/mcp-unknown-key-hints.test.js
@@ -0,0 +1,66 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { Client } from '@modelcontextprotocol/client';
+import { InMemoryTransport } from '@modelcontextprotocol/server';
+import { createAgentMcpServer } from '../scripts/mcp-server.mjs';
+import { suggestionForRejectedKey } from '../scripts/mcp-input-errors.mjs';
+
+// The schema refuses these recipes before the runtime is called, so the runtime needs no methods.
+async function connect(context) {
+ const server = createAgentMcpServer({ activeSessionId: () => null, async close() {} });
+ const client = new Client({ name: 'unknown-key-hints-test', version: '1' });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ context.after(async () => {
+ await client.close();
+ await server.close();
+ });
+ return client;
+}
+
+const COLOUR_RECIPE = {
+ format: 'crucible.scene', schemaVersion: 1,
+ materials: [{ id: 'red', emission: [1, 0.6, 0.2] }],
+ nodes: [{ id: 'floor', material: 'red' }],
+};
+
+async function refusalText(client, recipe) {
+ try {
+ const result = await client.callTool({ name: 'scene_create', arguments: { recipe } });
+ return result.content.map(part => part.text ?? '').join('\n');
+ } catch (error) {
+ return error.message;
+ }
+}
+
+const GUESSED_RECIPE = {
+ format: 'crucible.scene', schemaVersion: 1,
+ geometries: [{ id: 'floor', type: 'box', size: [6, 0.1, 6] }, { id: 'ball', type: 'sphere', radius: 0.5 }],
+ materials: [{ id: 'red', color: [0.8, 0.1, 0.1], metalness: 0.5, tags: ['water'] }],
+ nodes: [{ id: 'floor', geometry: 'floor', material: 'red', position: [0, 0, 0] }],
+ lights: [{ type: 'directional' }],
+};
+
+test('an unrecognized key in a recipe names the valid key or the place it lives', async context => {
+ const client = await connect(context);
+ const text = await refusalText(client, GUESSED_RECIPE);
+ assert.match(text, /Use "translation" instead of "position"/);
+ assert.match(text, /Use "metallic" instead of "metalness"/);
+ assert.match(text, /Use "tag" instead of "tags"/);
+ assert.match(text, /For "lights": .*environment\.pointLights/);
+ assert.match(text, /For "size": .*"scale" of its node/);
+ assert.match(text, /For "radius": .*"scale" of its node/);
+});
+
+test('a colour passed to a numeric field points at the colour sibling', async context => {
+ const client = await connect(context);
+ const text = await refusalText(client, COLOUR_RECIPE);
+ assert.match(text, /emission takes one number.*use emissiveColor/);
+});
+
+test('a misspelt key gets its nearest valid key and an unrelated key gets nothing', () => {
+ assert.match(suggestionForRejectedKey('rougness', ['roughness', 'metallic']), /Use "roughness" instead of "rougness"/);
+ assert.equal(suggestionForRejectedKey('banana', ['roughness', 'metallic']), undefined);
+ assert.equal(suggestionForRejectedKey('constructor', ['roughness']), undefined);
+});