3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Name the accepted shapes in union field errors (#2093)
Nguyen Xuan An882b9ffe7f61
diff --git a/changes/2093.md b/changes/2093.mdnew file mode 100644index 00000000..76d14d36--- /dev/null+++ b/changes/2093.md@@ -0,0 +1 @@+- MCP tool inputs built from a union (a texture `resolution` of 256, 512 or 1024, a field expression such as `instances.where`) now answer a wrong value with the field path, the value received and every accepted shape, for example `expected 256, 512 or 1024 (got 2048)`, instead of a bare `Invalid input` (#2093).diff --git a/changes/2093.size.md b/changes/2093.size.mdnew file mode 100644index 00000000..a28c493f--- /dev/null+++ b/changes/2093.size.md@@ -0,0 +1 @@+Tool cost: none of the tool schemas change, only the error text an agent reads after a failed call, so the schema bytes stay the same. The MCP bundle grows by about 3 KB for `scripts/mcp-union-errors.mjs`, which is worth it because a bare "Invalid input" left agents guessing the allowed values.diff --git a/scripts/mcp-input-errors.mjs b/scripts/mcp-input-errors.mjsindex 5e0aad43..b679bdc7 100644--- a/scripts/mcp-input-errors.mjs+++ b/scripts/mcp-input-errors.mjs@@ -1,11 +1,16 @@import * as z from 'zod/v4';import { describeReceived } from '../src/field-error.js';+import { describeUnionIssue } from './mcp-union-errors.mjs';const ISSUES_WITH_A_REJECTED_VALUE = new Set(['too_big', 'too_small', 'invalid_value', 'invalid_format', 'not_multiple_of']);// 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.function messageWithReceivedValue(issue) {+ const unionMessage = describeUnionIssue(issue);+ if (unionMessage) {+ return unionMessage;+ }const wording = z.locales.en().localeError(issue);const text = typeof wording === 'string' ? wording : wording?.message;if (!text) {diff --git a/scripts/mcp-union-errors.mjs b/scripts/mcp-union-errors.mjsnew file mode 100644index 00000000..e51242ff--- /dev/null+++ b/scripts/mcp-union-errors.mjs@@ -0,0 +1,133 @@+import { describeReceived } from '../src/field-error.js';++const MAXIMUM_NAMED_KEYS = 6;+const CAPABILITIES_TOPIC_PATTERN = /scene_capabilities [A-Za-z]+/;++function withArticle(noun) {+ return /^[aeiou]/.test(noun) ? `an ${noun}` : `a ${noun}`;+}++function describeLiteralValues(values) {+ return values.map((value) => (typeof value === 'string' ? `"${value}"` : String(value)));+}++// One accepted shape of a union as a short phrase. Returns undefined for a schema this does not know, and the caller+// then leaves the message as the schema library words it. Literal options come back as { literals } so that several+// of them read as one list ("256, 512 or 1024").+function describeOption(option) {+ const definition = option?.def;+ switch (definition?.type) {+ case 'literal':+ return { literals: describeLiteralValues(definition.values) };+ case 'enum':+ return { literals: describeLiteralValues(Object.values(definition.entries)) };+ case 'number':+ case 'int':+ return { phrase: 'a number' };+ case 'string':+ return { phrase: 'a string' };+ case 'boolean':+ return { phrase: 'a boolean' };+ case 'null':+ return { phrase: 'null' };+ case 'record':+ return { phrase: 'an object' };+ case 'array':+ return { phrase: 'an array' };+ case 'tuple':+ return { phrase: describeTuple(definition.items) };+ case 'object':+ return { phrase: describeObject(definition.shape) };+ case 'optional':+ case 'nullable':+ case 'default':+ return describeOption(definition.innerType);+ default:+ return undefined;+ }+}++function describeTuple(items) {+ const itemTypes = new Set(items.map((item) => item?.def?.type));+ if (itemTypes.size === 1 && itemTypes.has('number')) {+ return `an array of ${items.length} numbers`;+ }+ return `an array of ${items.length} items`;+}++function describeObject(shape) {+ const keys = Object.keys(shape ?? {});+ if (keys.length === 0 || keys.length > MAXIMUM_NAMED_KEYS) {+ return 'an object';+ }+ return `an object with ${keys.join(', ')}`;+}++function joinWithOr(parts) {+ if (parts.length <= 1) {+ return parts.join('');+ }+ return `${parts.slice(0, -1).join(', ')} or ${parts[parts.length - 1]}`;+}++function describeAcceptedShapes(options) {+ const literals = [];+ const phrases = [];+ for (const option of options) {+ const described = describeOption(option);+ if (!described) {+ return undefined;+ }+ if (described.literals) {+ literals.push(...described.literals);+ } else if (!phrases.includes(described.phrase)) {+ phrases.push(described.phrase);+ }+ }+ const parts = [...phrases];+ if (literals.length > 0) {+ parts.push(joinWithOr(literals));+ }+ return joinWithOr(parts);+}++// A branch "got further" when it matched the kind of value and failed deeper (a wrong length, a field inside the+// object), not when it only said the value is the wrong kind.+function branchGotFurther(branchIssues) {+ return branchIssues.length > 0 && branchIssues.some((inner) => !((inner.code === 'invalid_type' || inner.code === 'invalid_value') && inner.path.length === 0));+}++function describeClosestBranch(branches) {+ const furtherBranches = branches.filter(branchGotFurther);+ if (furtherBranches.length !== 1) {+ return '';+ }+ const inner = furtherBranches[0].find((candidate) => candidate.message);+ if (!inner) {+ return '';+ }+ const location = inner.path.length > 0 ? `${inner.path.join('.')}: ` : '';+ return `; closest shape: ${location}${inner.message}`;+}++// Words an invalid_union issue (a field built with z.union of plain options) as "Invalid input: expected <shapes>+// (got <value>)", with the one branch that matched the value's kind named when there is exactly one, and a pointer to+// the capabilities topic when the field's description names one. Returns undefined when the issue is not a union this+// can describe, so the library's own wording stays for everything else.+export function describeUnionIssue(issue) {+ if (issue.code !== 'invalid_union' || issue.discriminator !== undefined || !Array.isArray(issue.errors)) {+ return undefined;+ }+ const options = issue.inst?.def?.options ?? issue.inst?.options;+ if (!Array.isArray(options) || options.length === 0) {+ return undefined;+ }+ const accepted = describeAcceptedShapes(options);+ if (!accepted) {+ return undefined;+ }+ const topic = CAPABILITIES_TOPIC_PATTERN.exec(issue.inst?.description ?? '')?.[0];+ const pointer = topic ? `; see ${topic}` : '';+ const received = Object.hasOwn(issue, 'input') ? ` (got ${describeReceived(issue.input)})` : '';+ return `Invalid input: expected ${accepted}${received}${describeClosestBranch(issue.errors)}${pointer}`;+}diff --git a/scripts/preflight.mjs b/scripts/preflight.mjsindex 344b4e60..26e9233e 100644--- a/scripts/preflight.mjs+++ b/scripts/preflight.mjs@@ -27,7 +27,7 @@ export const PROTECTED_FILES = Object.freeze({const userFacingPattern = /^(src|bin|packages|skills)\//;const shippedCodePattern = /^(src|bin|packages)\/|^package(-lock)?\.json$|^(config\/)?vite\.lib\.config\.js$|^scripts\/(build-mcp|vite-cook-optional)\.mjs$/;-const toolCodePattern = /^(src\/agent-|src\/mcp|bin\/)|^scripts\/(build-mcp|measure-tool-cost|check-tool-cost|mcp-server|mcp-input-errors|capabilities-topics|tool-examples)/;+const toolCodePattern = /^(src\/agent-|src\/mcp|bin\/)|^scripts\/(build-mcp|measure-tool-cost|check-tool-cost|mcp-server|mcp-(input|union)-errors|capabilities-topics|tool-examples)/;const linkedTextPattern = /\.(md|html)$/;const blenderAddonPattern = /^packages\/blender-addon\//;diff --git a/tests/mcp-union-errors.test.js b/tests/mcp-union-errors.test.jsnew file mode 100644index 00000000..24e24a28--- /dev/null+++ b/tests/mcp-union-errors.test.js@@ -0,0 +1,105 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import * as z from 'zod/v4';+import { Client } from '@modelcontextprotocol/client';+import { InMemoryTransport } from '@modelcontextprotocol/server';+import { createAgentMcpServer } from '../scripts/mcp-server.mjs';+import { describeUnionIssue } from '../scripts/mcp-union-errors.mjs';++async function withClient(check) {+ const server = createAgentMcpServer({ async close() {}, activeSessionId() { return null; } });+ const client = new Client({ name: 'mcp-union-errors-test', version: '1' });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);+ try {+ return await check(client);+ } finally {+ await client.close();+ }+}++async function createSceneError(client, recipePart) {+ const recipe = { format: 'crucible.scene', schemaVersion: 1, materials: [], nodes: [], ...recipePart };+ const result = await client.callTool({ name: 'scene_create', arguments: { recipe } });+ assert.equal(result.isError, true);+ return result.content[0].text;+}++test('a union of literals names the allowed values and the value received', async () => {+ await withClient(async (client) => {+ const text = await createSceneError(client, { materials: [{ id: 'm', color: [1, 1, 1], pattern: { type: 'bricks', resolution: 2048 } }] });+ assert.match(text, /recipe\.materials\.0\.pattern\.resolution: Invalid input: expected 256, 512 or 1024 \(got 2048\)/);+ });+});++test('a field expression names every accepted shape and where the operators are listed', async () => {+ await withClient(async (client) => {+ const instances = { scatter: { count: 3, min: [0, 0, 0], max: [1, 1, 1] }, where: 'abc' };+ const text = await createSceneError(client, { nodes: [{ id: 'n', geometry: 'g', material: 'm', instances }] });+ assert.match(text, /recipe\.nodes\.0\.instances\.where: Invalid input: expected a number, a boolean, an array of 3 numbers or an object \(got "abc"\); see scene_capabilities fieldExpressions/);+ });+});++test('a long rejected value is cut in a union error', () => {+ const schema = z.union([z.literal(1), z.literal(2)]);+ const issue = schema.safeParse('x'.repeat(200)).error.issues[0];+ const message = describeUnionIssue({ ...issue, input: "x".repeat(200), inst: schema });+ assert.match(message, /\(got "x+\.\.\.\)$/);+});++test('errors that are not plain unions keep their exact wording', async () => {+ await withClient(async (client) => {+ assert.match(await createSceneError(client, { materials: [{ id: 'paint', color: [0.5, 0.5, 2] }] }), /recipe\.materials\.0\.color\.2: Too big: expected number to be <=1 \(got 2\)/);+ assert.match(await createSceneError(client, { materials: [{ id: 'paint', color: 'red' }] }), /recipe\.materials\.0\.color: Invalid input: expected tuple, received string/);+ assert.match(await createSceneError(client, { nodes: [{ id: 'n', unknownField: 1 }] }), /recipe\.nodes\.0: Unrecognized key: "unknownField"/);+ assert.match(await createSceneError(client, { nodes: [{ id: 7 }] }), /recipe\.nodes\.0\.id: Invalid input: expected string, received number/);+ });+});++test('discriminated unions and unions the formatter cannot describe keep the library wording', () => {+ const discriminated = z.discriminatedUnion('type', [z.strictObject({ type: z.literal('box') }), z.strictObject({ type: z.literal('ball') })]);+ const discriminatedIssue = discriminated.safeParse({ type: 'cone' }).error.issues[0];+ assert.equal(describeUnionIssue({ ...discriminatedIssue, inst: discriminated }), undefined);+ const opaque = z.union([z.number(), z.custom(() => false)]);+ const opaqueIssue = opaque.safeParse('x').error.issues[0];+ assert.equal(describeUnionIssue({ ...opaqueIssue, inst: opaque }), undefined);+});++function collectUnions(node, path, found) {+ if (!node || typeof node !== 'object') {+ return;+ }+ const options = node.anyOf ?? node.oneOf;+ if (Array.isArray(options)) {+ found.push({ path, options });+ }+ for (const [key, child] of Object.entries(node)) {+ collectUnions(child, `${path}.${key}`, found);+ }+}++// A nullable field is an anyOf of the value and null in JSON Schema, but the validator reports it as a plain type error.+function isNullable(union) {+ return union.options.length === 2 && union.options.some((option) => option.type === 'null');+}++function isDescribable(option) {+ return option && (option.const !== undefined || option.enum || option.type || option.anyOf || option.oneOf);+}++test('every union in a tool input schema is made of shapes the formatter can name', async () => {+ await withClient(async (client) => {+ const { tools } = await client.listTools();+ const undescribable = [];+ for (const tool of tools) {+ const unions = [];+ collectUnions(tool.inputSchema, tool.name, unions);+ for (const union of unions) {+ if (!isNullable(union) && !union.options.every(isDescribable)) {+ undescribable.push(union.path);+ }+ }+ }+ assert.deepEqual(undescribable, [], 'these unions would answer a bad value with a bare "Invalid input"; give each option a type');+ });+});