diff --git a/docs/design/tool-input-validation.md b/docs/design/tool-input-validation.md new file mode 100644 index 00000000..6d2d7157 --- /dev/null +++ b/docs/design/tool-input-validation.md @@ -0,0 +1,39 @@ +# Tool input validation at the execution boundary + +Tool arguments are checked against the declared JSON Schema before execution, +including after global hooks, per-tool hooks, approval rewrites and derived task +observation inputs. Nested properties, array elements, string and numeric bounds, +composition keywords and document-local references are enforced. Draft-07 is the +default dialect; an explicit `$schema` can select draft-2019-09 or draft-2020-12. +Invalid, unsupported, asynchronous or unresolved schemas block the call. Schema +validation never downloads referenced documents. + +Existing parameter-name compatibility runs first: for example `timeout_ms` can +satisfy a declared `timeoutMs`, and `file_path` can satisfy a declared `path`. +Validation does not apply JSON Schema defaults, coerce types or remove extra +properties. Extra fields remain accepted unless the tool schema rejects them. +This keeps approval inputs and third-party MCP payloads intact. + +SDK `Tool` accepts an optional `inputZodSchema` with a structural synchronous +`safeParse(input)` interface; Moss does not depend on Zod. A successful result +must be `{ success: true, data }`; a rejected result has `success: false`. +Explicit parser normalization such as trimming or coercion is allowed, but the +normalized object must still satisfy the full JSON Schema. A parser must be pure +and idempotent because each execution boundary rechecks input. Moss verifies +idempotence on an isolated copy and blocks a transform that changes a second +time. A thrown or asynchronous parser blocks the call. Parser output that is not +an object also blocks the call. + +Errors identify schema rules without copying rejected values, dynamic object +keys, arbitrary parser messages or compiler exception text. Tool implementations +still own device availability, permission checks, state-dependent constraints and +post-condition verification; JSON Schema success does not prove a device action +succeeded. + +Run `node scripts/verify/cli.mjs --stage tool-input-schema` for the offline +execution-boundary probe. It is also included in `npm run verify`. The probe uses +no-op implementations and performs no provider requests or device operations. + +SDK change: `Tool.inputZodSchema` is an additive optional field. Inputs that +violate previously declared but unenforced JSON Schema constraints now fail +before execution; this is an intentional validation tightening. diff --git a/package-lock.json b/package-lock.json index 9c02e588..25cb9e53 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,8 @@ "hasInstallScript": true, "license": "MIT", "dependencies": { + "ajv": "8.20.0", + "ajv-formats": "3.0.1", "ink": "^7.1.1", "micromatch": "^4.0.8", "picocolors": "^1.1.1", @@ -599,22 +601,38 @@ } }, "node_modules/ajv": { - "version": "6.15.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", - "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", - "dev": true, + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", "license": "MIT", "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" }, "funding": { "type": "github", "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, "node_modules/ansi-escapes": { "version": "7.3.0", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", @@ -1014,6 +1032,30 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/eslint/node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/eslint/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, "node_modules/espree": { "version": "11.2.0", "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz", @@ -1082,7 +1124,6 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, "license": "MIT" }, "node_modules/fast-json-stable-stringify": { @@ -1099,6 +1140,22 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/file-entry-cache": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", @@ -1368,10 +1425,9 @@ "license": "MIT" }, "node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "license": "MIT" }, "node_modules/json-stable-stringify-without-jsonify": { @@ -1652,6 +1708,15 @@ "react": "^19.2.0" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/restore-cursor": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", diff --git a/package.json b/package.json index f94517ab..1bf924f8 100644 --- a/package.json +++ b/package.json @@ -77,6 +77,8 @@ "examples": "node scripts/verify/cli.mjs --stage examples" }, "dependencies": { + "ajv": "8.20.0", + "ajv-formats": "3.0.1", "ink": "^7.1.1", "micromatch": "^4.0.8", "picocolors": "^1.1.1", diff --git a/scripts/verify/cli.mjs b/scripts/verify/cli.mjs index 4d968f5f..ef8291e5 100644 --- a/scripts/verify/cli.mjs +++ b/scripts/verify/cli.mjs @@ -95,6 +95,7 @@ import { stage as loopPruneStage } from './stages/loop-prune.mjs'; import { stage as loopFollowStage } from './stages/loop-follow.mjs'; import { stage as loopCheckTimeoutStage } from './stages/loop-check-timeout.mjs'; import { stage as taskObservationStage } from './stages/task-observation.mjs'; +import { stage as toolInputSchemaStage } from './stages/tool-input-schema.mjs'; import { stage as editRecoveryStage } from './stages/edit-recovery.mjs'; import { stage as loopHealthStage } from './stages/loop-health.mjs'; import { stage as runTestsVerdictStage } from './stages/run-tests-verdict.mjs'; @@ -208,6 +209,7 @@ const STAGES = new Map( loopFollowStage, loopCheckTimeoutStage, taskObservationStage, + toolInputSchemaStage, editRecoveryStage, loopHealthStage, runTestsVerdictStage, @@ -251,6 +253,7 @@ const STAGES = new Map( const ORDER = [...STAGES.keys()]; const FAST_GATE = [ + 'tool-input-schema', 'edit-recovery', 'static', 'smoke', diff --git a/scripts/verify/stages/tool-input-schema.mjs b/scripts/verify/stages/tool-input-schema.mjs new file mode 100644 index 00000000..8bb18b5b --- /dev/null +++ b/scripts/verify/stages/tool-input-schema.mjs @@ -0,0 +1,22 @@ +import path from 'node:path'; +import { captureProcess } from '../lib/proc.mjs'; + +export const stage = { + name: 'tool-input-schema', + requires: ['build'], + description: 'Recursive tool schemas and optional parsers guard the actual execution boundary', + async run(context) { + const result = await captureProcess( + process.execPath, + [path.join(context.root, 'scripts/verify/tool-input-schema.mjs')], + { cwd: context.root, env: { ...process.env, MOSS_NO_RDK_DOCS: '1' }, timeoutMs: 30000 } + ); + if (result.timedOut || result.status !== 0) + return { + ok: false, + detail: `probe exited ${String(result.status ?? result.signal)}\n${result.stdout}${result.stderr}`, + }; + console.log(result.stdout.trim()); + return { ok: true }; + }, +}; diff --git a/scripts/verify/tool-input-schema.mjs b/scripts/verify/tool-input-schema.mjs new file mode 100644 index 00000000..70aca3a8 --- /dev/null +++ b/scripts/verify/tool-input-schema.mjs @@ -0,0 +1,319 @@ +#!/usr/bin/env node +/** Offline checks of the real tool execution boundary; no tool side effects or provider requests. */ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const root = path.resolve(import.meta.dirname, '../..'); +const load = (relative) => import(pathToFileURL(path.join(root, 'dist', relative)).href); +await load('safety/tool-output-redact.js'); +const { validateToolInputObject, registerPreToolHook, clearPreToolHooksForTests } = await load( + 'core/tools/tool-pipeline.js' +); +const { executeOneToolCall } = await load('core/tools/execute-tool-call.js'); +const { ToolHookRegistry } = await load('core/tools/tool-hooks.js'); +const { buildProviderToolDeclarations } = await load('core/loop/agent-loop-context-prep.js'); +let checks = 0; +const ok = (label) => console.log(`[tool-input-schema] ok ${++checks} ${label}`); +const make = (schema, extra = {}) => ({ + name: 'schema_probe', + description: 'Validate an input without running any real action.', + inputSchema: schema, + execute: async () => 'probe_noop', + ...extra, +}); +const nested = { + type: 'object', + properties: { + timeoutMs: { type: 'integer', minimum: 3, maximum: 20 }, + topics: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 } }, + image: { + type: 'object', + properties: { kind: { const: 'url' }, url: { type: 'string', format: 'uri' } }, + required: ['kind', 'url'], + additionalProperties: false, + }, + }, + required: ['timeoutMs', 'topics', 'image'], + additionalProperties: false, +}; +const good = { + timeoutMs: 8, + topics: ['/image_raw'], + image: { kind: 'url', url: 'https://example.invalid/image' }, +}; +const tool = make(nested); +for (const input of [ + { ...good, topics: [123] }, + { ...good, topics: [''] }, + { ...good, timeoutMs: 2 }, + { ...good, timeoutMs: 21 }, + { ...good, image: {} }, + { ...good, image: { ...good.image, secret: 'credential-value' } }, + { ...good, image: { kind: 'url', url: 'not a URI' } }, + { ...good, unexpected: true }, +]) + assert.equal(validateToolInputObject(tool, input).ok, false); +assert.equal(validateToolInputObject(tool, good).ok, true); +ok('recursive arrays, object fields, ranges, formats and extra properties'); + +const aliasTool = make({ + type: 'object', + properties: { timeoutMs: { type: 'integer' }, path: { type: 'string' } }, + required: ['timeoutMs', 'path'], + additionalProperties: false, +}); +assert.deepEqual(validateToolInputObject(aliasTool, { timeout_ms: 5, file_path: 'a' }), { + ok: true, + value: { timeoutMs: 5, path: 'a' }, +}); +const permissive = make({ type: 'object', properties: {} }); +assert.deepEqual(validateToolInputObject(permissive, { extra: 1 }).value, { extra: 1 }); +const noMutation = make({ type: 'object', properties: { count: { type: 'integer', default: 2 } } }); +const blank = {}; +assert.equal(validateToolInputObject(noMutation, blank).ok, true); +assert.deepEqual(blank, {}); +assert.equal(validateToolInputObject(noMutation, { count: '2' }).ok, false); +ok('aliases remain accepted; defaults, coercion and extra-key removal stay disabled'); + +const combinators = make({ + type: 'object', + properties: { + remotePath: { type: 'string' }, + remote_path: { type: 'string' }, + localPath: { type: 'string' }, + attachmentId: { type: 'string' }, + }, + allOf: [ + { anyOf: [{ required: ['remotePath'] }, { required: ['remote_path'] }] }, + { anyOf: [{ required: ['localPath'] }, { required: ['attachmentId'] }] }, + ], +}); +assert.equal(validateToolInputObject(combinators, {}).ok, false); +assert.equal( + validateToolInputObject(combinators, { remote_path: '/a', attachmentId: 'a' }).ok, + true +); +assert.equal( + validateToolInputObject(combinators, { + remotePath: '/a', + remote_path: '/b', + localPath: 'a', + attachmentId: 'a', + }).ok, + true +); +const union = make({ + type: 'object', + properties: { value: { oneOf: [{ type: 'string' }, { type: 'integer' }] } }, +}); +assert.equal(validateToolInputObject(union, { value: true }).ok, false); +const refs = make({ + type: 'object', + properties: { value: { $ref: '#/$defs/positive' } }, + $defs: { positive: { type: 'number', exclusiveMinimum: 0 } }, +}); +assert.equal(validateToolInputObject(refs, { value: 0 }).ok, false); +assert.equal(validateToolInputObject(refs, { value: 1 }).ok, true); +ok('anyOf/allOf/oneOf and document-local references'); + +for (const schema of [ + combinators.inputSchema, + refs.inputSchema, + { + type: 'object', + properties: { + command: { type: 'string' }, + timeout_ms: { type: 'number' }, + workingDir: { type: 'string' }, + }, + minProperties: 3, + additionalProperties: false, + }, + { + type: 'object', + properties: { command: { type: 'string' }, workingDir: { type: 'string' } }, + propertyNames: { pattern: 'working|command' }, + }, + { + type: 'object', + properties: { command: { $dynamicRef: '#entry' }, workingDir: { type: 'string' } }, + }, + { + type: 'object', + properties: { command: { $recursiveRef: '#' }, workingDir: { type: 'string' } }, + }, + { + type: 'object', + properties: { command: { type: 'string' }, requiredByHost: { type: 'string' } }, + required: ['requiredByHost'], + }, +]) { + const sameNameTool = { ...make(schema), name: 'exec' }; + for (const contextWindowTokens of [32000, 200000]) { + const wire = buildProviderToolDeclarations([sameNameTool], { contextWindowTokens })[0] + .parameters; + assert.deepEqual(wire, schema); + } +} +ok('lean and wide provider declarations retain composition, references and host-required fields'); + +for (const [dialect, props] of [ + ['https://json-schema.org/draft/2019-09/schema', { items: { type: 'integer' } }], + [ + 'https://json-schema.org/draft/2020-12/schema', + { prefixItems: [{ type: 'integer' }], items: false }, + ], +]) { + const dialectTool = make({ + $schema: dialect, + type: 'object', + properties: { values: { type: 'array', ...props } }, + }); + assert.equal(validateToolInputObject(dialectTool, { values: [1] }).ok, true); + assert.equal(validateToolInputObject(dialectTool, { values: ['wrong'] }).ok, false); +} +ok('explicit 2019-09 and 2020-12 dialects are validated'); + +for (const schema of [ + { type: 'object', properties: { value: { type: 'not-a-type' } } }, + { type: 'object', properties: { value: { $ref: 'https://example.invalid/never-load' } } }, + { type: 'object', properties: {}, $async: true }, + { type: 'object', properties: { value: { type: () => 'string' } } }, +]) + assert.equal(validateToolInputObject(make(schema), {}).ok, false); +const mutableSchema = { type: 'object', properties: { value: { type: 'string' } } }; +const mutableTool = make(mutableSchema); +assert.equal(validateToolInputObject(mutableTool, { value: 'x' }).ok, true); +mutableSchema.properties.value.minLength = 2; +assert.equal(validateToolInputObject(mutableTool, { value: 'x' }).ok, false); +ok('invalid, asynchronous and unresolved schemas fail closed; changed schemas recompile'); + +const parser = { + safeParse: (input) => + typeof input.value === 'string' || typeof input.value === 'number' + ? { success: true, data: { ...input, value: Number(input.value) } } + : { success: false, error: { issues: [{ message: 'credential-value' }] } }, +}; +const parsedTool = make( + { type: 'object', properties: { value: { type: 'integer', minimum: 1 } }, required: ['value'] }, + { inputZodSchema: parser } +); +assert.deepEqual(validateToolInputObject(parsedTool, { value: '2' }), { + ok: true, + value: { value: 2 }, +}); +assert.equal(validateToolInputObject(parsedTool, { value: '0' }).ok, false); +assert.match( + validateToolInputObject(parsedTool, { value: false }).message, + /properties\/value\/type/ +); +const badParser = make( + { type: 'object', properties: {} }, + { + inputZodSchema: { safeParse: () => ({ success: false, error: new Error('credential-value') }) }, + } +); +assert.equal(validateToolInputObject(badParser, {}).ok, false); +assert.ok(!validateToolInputObject(badParser, {}).message.includes('credential-value')); +const thrownParser = make( + { type: 'object', properties: {} }, + { + inputZodSchema: { + safeParse: () => { + throw new Error('credential-value'); + }, + }, + } +); +assert.equal(validateToolInputObject(thrownParser, {}).ok, false); +assert.ok(!validateToolInputObject(thrownParser, {}).message.includes('credential-value')); +const asyncParser = make( + { type: 'object', properties: {} }, + { + inputZodSchema: { + safeParse: async () => { + throw new Error('credential-value'); + }, + }, + } +); +assert.equal(validateToolInputObject(asyncParser, {}).ok, false); +await new Promise((resolve) => setImmediate(resolve)); +const driftParser = make( + { type: 'object', properties: { value: { type: 'integer' } } }, + { + inputZodSchema: { safeParse: (input) => ({ success: true, data: { value: input.value + 1 } }) }, + } +); +assert.equal(validateToolInputObject(driftParser, { value: 1 }).ok, false); +const mutatingParser = make( + { type: 'object', properties: { value: { type: 'integer' } } }, + { + inputZodSchema: { + safeParse: (input) => { + input.value++; + return { success: true, data: input }; + }, + }, + } +); +const untouched = { value: 1 }; +assert.equal(validateToolInputObject(mutatingParser, untouched).ok, false); +assert.deepEqual(untouched, { value: 1 }); +ok('explicit pure parser normalization is checked against JSON Schema and must be idempotent'); + +let executed = 0; +const invoke = async (input, options = {}) => + executeOneToolCall( + { id: 'schema-call', name: tool.name, input }, + { + toolsForRun: [ + { + ...tool, + execute: async () => { + executed++; + return 'probe_noop'; + }, + }, + ], + toolCtx: { workspaceDir: root, sessionKey: 'schema-probe' }, + sessionKey: 'schema-probe', + abortSignal: new AbortController().signal, + toolTimeoutMs: 1000, + enableHeartbeat: false, + heartbeatIntervalMs: 1000, + skipHeartbeatToolNames: new Set(), + push: () => {}, + ...options, + } + ); +assert.equal((await invoke({ ...good, topics: [123] })).kind, 'pre-blocked'); +const remove = registerPreToolHook(async () => ({ ok: true, input: { ...good, timeoutMs: 0 } })); +assert.equal((await invoke(good)).kind, 'pre-blocked'); +remove(); +const hooks = new ToolHookRegistry(); +hooks.registerPre({ + name: 'rewrite', + priority: 1, + check: async () => ({ action: 'modify', input: { ...good, image: {} } }), +}); +assert.equal((await invoke(good, { toolHooks: hooks })).kind, 'pre-blocked'); +assert.equal( + ( + await invoke(good, { + checkToolApproval: async () => ({ + approved: true, + decision: 'allow-once', + updatedInput: { ...good, topics: [123] }, + }), + }) + ).kind, + 'pre-blocked' +); +assert.equal(executed, 0); +assert.equal((await invoke(good)).isError, false); +assert.equal(executed, 1); +clearPreToolHooksForTests(); +ok('direct calls and global/tool/approval rewrites are checked before execution'); +console.log(`[tool-input-schema] ${checks} groups passed`); diff --git a/src/core/tools/tiny-window-tools.ts b/src/core/tools/tiny-window-tools.ts index 19d96106..51e741db 100644 --- a/src/core/tools/tiny-window-tools.ts +++ b/src/core/tools/tiny-window-tools.ts @@ -86,6 +86,24 @@ const TINY_WINDOW_TOOL_PROPERTIES: Readonly> = list_directory: ['path', 'depth'], }; +function containsSchemaReference(value: unknown, seen = new WeakSet()): boolean { + if (!value || typeof value !== 'object' || seen.has(value)) return false; + seen.add(value); + if (['$ref', '$dynamicRef', '$recursiveRef'].some((key) => key in value)) return true; + return Object.values(value).some((child) => containsSchemaReference(child, seen)); +} + +const SIMPLE_OBJECT_SCHEMA_KEYS = new Set([ + 'type', + 'properties', + 'required', + 'additionalProperties', + 'description', + 'title', + '$schema', + '$id', +]); + export function compactToolSchema( name: string, schema: Record | undefined @@ -94,6 +112,16 @@ export function compactToolSchema( if (!keep || !schema || typeof schema !== 'object') return schema; const properties = schema.properties; if (!properties || typeof properties !== 'object') return schema; + // SDK hosts can reuse these names with a different contract. Do not hide a + // required field or break cross-field constraints / reference targets. + if ( + (Array.isArray(schema.required) && schema.required.some((key) => !keep.includes(key))) || + Object.keys(schema).some((key) => !SIMPLE_OBJECT_SCHEMA_KEYS.has(key)) || + (schema.additionalProperties !== undefined && + typeof schema.additionalProperties !== 'boolean') || + containsSchemaReference(schema) + ) + return schema; const pruned: Record = {}; for (const key of keep) { const value = (properties as Record)[key]; diff --git a/src/core/tools/tool-input-schema.ts b/src/core/tools/tool-input-schema.ts new file mode 100644 index 00000000..bf3944fe --- /dev/null +++ b/src/core/tools/tool-input-schema.ts @@ -0,0 +1,82 @@ +import { Ajv, type ErrorObject, type Options, type ValidateFunction } from 'ajv'; +import { Ajv2019 } from 'ajv/dist/2019.js'; +import { Ajv2020 } from 'ajv/dist/2020.js'; +import addFormats from 'ajv-formats'; + +const options: Options = { + strict: false, + strictNumbers: true, + allErrors: false, + ownProperties: true, + coerceTypes: false, + useDefaults: false, + removeAdditional: false, + addUsedSchema: false, + logger: false, +}; +const dialects = [new Ajv(options), new Ajv2019(options), new Ajv2020(options)]; +for (const dialect of dialects) addFormats.default(dialect); + +type Compiled = { ok: true; validate: ValidateFunction } | { ok: false }; +const cache = new WeakMap(); + +function compile(schema: Record): Compiled { + try { + const fingerprint = JSON.stringify(schema, (_key, value: unknown) => { + if (['function', 'symbol', 'bigint'].includes(typeof value)) { + throw new Error('Schema must be JSON serializable'); + } + return value; + }); + const cached = cache.get(schema); + if (cached?.fingerprint === fingerprint) return cached.compiled; + // Snapshot mutable host schemas, and do not retain dynamically registered + // tool schemas in Ajv's process-wide cache after compilation. + const snapshot = JSON.parse(fingerprint) as Record; + const dialectName = String(snapshot.$schema ?? ''); + const dialect = dialectName.includes('/2020-12/') + ? dialects[2] + : dialectName.includes('/2019-09/') + ? dialects[1] + : dialects[0]; + let compiled: Compiled; + try { + const validate = dialect.compile(snapshot); + compiled = '$async' in validate ? { ok: false } : { ok: true, validate }; + } finally { + dialect.removeSchema(snapshot); + } + cache.set(schema, { fingerprint, compiled }); + return compiled; + } catch { + // Neither schema content nor arbitrary compiler exception text is safe to + // expose. Unresolved references fail here; no remote loader is configured. + return { ok: false }; + } +} + +function validationMessage(name: string, error: ErrorObject | undefined): string { + // schemaPath identifies a declared field/rule. instancePath and params can + // include user-controlled object keys; never copy rejected values or keys. + const location = (error?.schemaPath ?? '#').slice(0, 200); + const rule = + error?.keyword === 'enum' ? 'must be one of the declared enum values' : error?.keyword; + return `${name}: tool input violates JSON Schema at ${location} (${rule ?? 'validation'})`; +} + +export function validateToolJsonSchema( + name: string, + schema: Record, + input: Record +): { ok: true } | { ok: false; message: string } { + const compiled = compile(schema); + if (!compiled.ok) return { ok: false, message: `${name}: invalid or unsupported input schema` }; + try { + if (!compiled.validate(input)) { + return { ok: false, message: validationMessage(name, compiled.validate.errors?.[0]) }; + } + return { ok: true }; + } catch { + return { ok: false, message: `${name}: tool input could not be validated` }; + } +} diff --git a/src/core/tools/tool-pipeline.ts b/src/core/tools/tool-pipeline.ts index 106181c8..0f8267b7 100644 --- a/src/core/tools/tool-pipeline.ts +++ b/src/core/tools/tool-pipeline.ts @@ -1,4 +1,6 @@ import type { Tool } from './tool-types.js'; +import { isDeepStrictEqual } from 'node:util'; +import { validateToolJsonSchema } from './tool-input-schema.js'; export type PreToolHookContext = { toolName: string; @@ -85,61 +87,51 @@ export function validateToolInputObject( return { ok: false, message: `${tool.name}: tool input must be a JSON object` }; } const obj = input as Record; - const schema = tool.inputSchema as - | { - type?: string; - required?: string[]; - properties?: Record; - } - | undefined; + const schema = tool.inputSchema; if (!schema || schema.type !== 'object') { - return { ok: true, value: obj }; - } - const props = schema.properties; - // Snap before the required check so `{ timeOutMs: 5000 }` can satisfy - // `required: ['timeout_ms']`. - const value = props ? snapParamAliases(obj, props) : obj; - const required = schema.required ?? []; - for (const key of required) { - if (!(key in value) || value[key] === undefined) { - return { ok: false, message: `${tool.name}: missing required parameter "${key}"` }; - } + return { ok: false, message: `${tool.name}: invalid or unsupported input schema` }; } - if (props) { - for (const key of Object.keys(value)) { - const spec = props[key]; - if (!spec) continue; - const v = value[key]; - if (v === undefined) continue; - if (spec.enum !== undefined && spec.enum.length > 0) { - if (!spec.enum.some((e) => Object.is(e, v))) { - // Name the allowed values: "must be one of the enum values" made the - // model guess a second time. - return { - ok: false, - message: - `${tool.name}: parameter "${key}" must be one of ` + - `${spec.enum.map((e) => JSON.stringify(e)).join(', ')} (got ${JSON.stringify(v)})`, - }; - } - continue; + const props = schema.properties as Record; + // Alias compatibility precedes both parsers and recursive schema validation. + let value = props ? snapParamAliases(obj, props) : obj; + if (tool.inputZodSchema) { + const parserFailure = () => { + const jsonCheck = validateToolJsonSchema(tool.name, schema, value); + return jsonCheck.ok + ? { ok: false as const, message: `${tool.name}: tool input failed its input parser` } + : jsonCheck; + }; + try { + const parsed = tool.inputZodSchema.safeParse(structuredClone(value)); + if (parsed && typeof parsed === 'object' && 'then' in parsed) { + // JS hosts can violate the synchronous parser interface. Consume a + // rejected promise without awaiting it or letting it reach execution. + void Promise.resolve(parsed as unknown).catch(() => undefined); + return parserFailure(); + } + if ( + !parsed.success || + parsed.data === null || + typeof parsed.data !== 'object' || + Array.isArray(parsed.data) + ) { + return parserFailure(); + } + const stable = tool.inputZodSchema.safeParse(structuredClone(parsed.data)); + if (stable && typeof stable === 'object' && 'then' in stable) { + void Promise.resolve(stable as unknown).catch(() => undefined); + return parserFailure(); + } + if (!stable.success || !isDeepStrictEqual(parsed.data, stable.data)) { + return { ok: false, message: `${tool.name}: input parser must be idempotent` }; } - if (!spec.type) continue; - const t = spec.type; - if (t === 'string' && typeof v !== 'string') - return { ok: false, message: `${tool.name}: parameter "${key}" should be string` }; - if (t === 'number' && (typeof v !== 'number' || Number.isNaN(v))) - return { ok: false, message: `${tool.name}: parameter "${key}" should be number` }; - if (t === 'integer' && (typeof v !== 'number' || !Number.isInteger(v))) - return { ok: false, message: `${tool.name}: parameter "${key}" should be integer` }; - if (t === 'boolean' && typeof v !== 'boolean') - return { ok: false, message: `${tool.name}: parameter "${key}" should be boolean` }; - if (t === 'array' && !Array.isArray(v)) - return { ok: false, message: `${tool.name}: parameter "${key}" should be array` }; - if (t === 'object' && (v === null || typeof v !== 'object' || Array.isArray(v))) - return { ok: false, message: `${tool.name}: parameter "${key}" should be object` }; + value = parsed.data as Record; + } catch { + return parserFailure(); } } + const checked = validateToolJsonSchema(tool.name, schema, value); + if (!checked.ok) return checked; return { ok: true, value }; } diff --git a/src/core/tools/tool-types.ts b/src/core/tools/tool-types.ts index 28ba4d07..c72ab2ec 100644 --- a/src/core/tools/tool-types.ts +++ b/src/core/tools/tool-types.ts @@ -318,6 +318,18 @@ export interface Tool { required?: string[]; }; + /** + * Optional synchronous parser (for example a Zod schema). Explicit parser + * coercion/normalization is allowed; its object output must still satisfy + * inputSchema. The parser must be pure and idempotent: execution boundaries + * revalidate after hooks and approval rewrites. No Zod dependency is needed. + */ + inputZodSchema?: { + safeParse( + input: unknown + ): { success: true; data: unknown } | { success: false; error?: unknown }; + }; + normalizeInput?: (input: TInput, ctx?: Pick) => TInput; execute: (input: TInput, ctx: ToolContext) => Promise; executeStructured?: (input: TInput, ctx: ToolContext) => Promise;