Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(codex): bound schema validation and certify post-journey state

Alfredo Lopez6fa2d0c834ac
diff --git a/codex-llm-proxy/test/codexTransport.conformance.test.ts b/codex-llm-proxy/test/codexTransport.conformance.test.ts
index 5ab5f96df..b9782d8df 100644
--- a/codex-llm-proxy/test/codexTransport.conformance.test.ts
+++ b/codex-llm-proxy/test/codexTransport.conformance.test.ts
@@ -625,7 +625,11 @@ describe('streamCodexCompletion', () => {
},
{ role: 'tool' as const, content: 'ok', toolCallId: 'call-1' },
],
- tools: [{ name: 'echo', description: 'echo', parameters: {} }],
+ tools: Array.from({ length: 250 }, (_, index) => ({
+ name: index === 0 ? 'echo' : `approved_tool_${index}`,
+ description: `Approved tool ${index}`,
+ parameters: { type: 'object', properties: { x: { type: 'integer' } } },
+ })),
generation: { toolChoice: 'auto' as const },
transportHints: { promptCacheKey: 'sess-1' },
}
@@ -656,6 +660,8 @@ describe('streamCodexCompletion', () => {
const body = JSON.parse(String(fetchFn.mock.calls[0]?.[1]?.body)) as Record<string, unknown>
expect(body.instructions).toBe('be brief')
expect(body.store).toBe(false)
+ expect(body.tools).toEqual(request.tools.map(tool => ({ type: 'function', ...tool })))
+ expect(body.parallel_tool_calls).toBe(true)
expect(body.tool_choice).toBe('auto')
expect(body.prompt_cache_key).toBe('sess-1')
expect(body.input).toEqual([
diff --git a/docs/architecture/codex-subscription-transport-contract.md b/docs/architecture/codex-subscription-transport-contract.md
index 41615aebe..4b8c650a2 100644
--- a/docs/architecture/codex-subscription-transport-contract.md
+++ b/docs/architecture/codex-subscription-transport-contract.md
@@ -97,6 +97,27 @@ only the sender is insufficient. For rollback, restore the old sender first,
drain outstanding incompatible attempts, then restore older validators. An old
sender reintroduces the known connector exclusion and is not a correction.
+### Selected MCP argument validation
+
+The Host validates selected MCP arguments before approval and rechecks the live
+schema immediately before dispatch. Missing `$schema` uses JSON Schema 2020-12;
+explicit draft-07 and 2019-09 are also supported. Unsupported dialects and
+unresolved references fail explicitly. Validation never coerces types, applies
+defaults, removes arguments, or loads remote references.
+
+Compilation and evaluation run in disposable Node workers, outside the Host
+event loop. Each operation has a two-second deadline and V8 heap/stack limits;
+these are not a total-process RSS guarantee. Inputs are bounded to 256 KiB per
+schema/argument document, 10,000 nodes and depth 64. At most four workers may be
+active; saturation fails validation instead of building an unbounded queue.
+Worker startup adds latency and is not claimed as a quota optimization. A
+successful validation waits for worker teardown before releasing its caller.
+Schema or argument changes during validation prevent dispatch.
+
+Deployment readiness checks after a combined apply do not enforce the ordering
+above. The infrastructure rollout barrier remains a separate release dependency;
+this document alone does not certify mixed-version deployment safety.
+
## Errors
Stable codes: `insufficient_scope`, `no_grant`, `model_not_allowed`,
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 8d9c2ddb2..e8f24ccb6 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.324",
+ "version": "0.1.325",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.324",
+ "version": "0.1.325",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 05b5b2722..468d8879a 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.324",
+ "version": "0.1.325",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/core/adapters/__tests__/boundedSchemaValidation.test.ts b/mcp-host/src/core/adapters/__tests__/boundedSchemaValidation.test.ts
new file mode 100644
index 000000000..63f4a44d2
--- /dev/null
+++ b/mcp-host/src/core/adapters/__tests__/boundedSchemaValidation.test.ts
@@ -0,0 +1,114 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { EventEmitter, once } from 'node:events'
+import { Worker } from 'node:worker_threads'
+import { boundedJson, validateBoundedSchema } from '../boundedSchemaValidation'
+
+vi.mock('node:worker_threads', async importOriginal => {
+ const actual = await importOriginal<typeof import('node:worker_threads')>()
+ return {
+ ...actual,
+ Worker: vi.fn(function (...args: ConstructorParameters<typeof actual.Worker>) {
+ return new actual.Worker(...args)
+ }),
+ }
+})
+
+afterEach(async () => {
+ vi.useRealTimers()
+ // Validation resolves promptly; worker capacity is released asynchronously on exit.
+ const exits = vi.mocked(Worker).mock.results.flatMap(result => {
+ const worker = result.value as Worker | undefined
+ return worker && typeof worker.threadId === 'number' && worker.threadId !== -1
+ ? [once(worker, 'exit')]
+ : []
+ })
+ await Promise.all(exits)
+ vi.clearAllMocks()
+})
+
+describe('bounded MCP schema validation', () => {
+ it.each([
+ undefined,
+ 'http://json-schema.org/draft-07/schema#',
+ 'https://json-schema.org/draft/2019-09/schema',
+ 'https://json-schema.org/draft/2020-12/schema',
+ ])('validates without coercion for %s', async dialect => {
+ const schema = boundedJson({
+ ...(dialect ? { $schema: dialect } : {}),
+ type: 'object',
+ properties: { count: { type: 'integer', default: 1 } },
+ required: ['count'],
+ additionalProperties: false,
+ })
+ expect(await validateBoundedSchema(schema, boundedJson({ count: 1 }))).toBe(true)
+ expect(await validateBoundedSchema(schema, boundedJson({ count: '1' }))).toBe(false)
+ expect(await validateBoundedSchema(schema, boundedJson({}))).toBe(false)
+ expect(await validateBoundedSchema(schema, boundedJson({ count: 1, extra: true }))).toBe(false)
+ })
+
+ it('fails closed for unsupported schemas and external references', async () => {
+ for (const schema of [
+ { $schema: 'https://example.invalid/schema' },
+ { $ref: 'https://example.invalid/schema' },
+ { $async: true, type: 'object' },
+ ])
+ expect(await validateBoundedSchema(boundedJson(schema), '{}')).toBe(false)
+ })
+
+ it('bounds input and does not call accessors or serialization hooks', () => {
+ const getter = vi.fn(() => 'value')
+ expect(() =>
+ boundedJson({
+ get value() {
+ return getter()
+ },
+ })
+ ).toThrow()
+ expect(getter).not.toHaveBeenCalled()
+ expect(() => boundedJson('x'.repeat(256 * 1024 + 1))).toThrow()
+ const cyclic: Record<string, unknown> = {}
+ cyclic.self = cyclic
+ expect(() => boundedJson(cyclic)).toThrow()
+ expect(() => boundedJson({ toJSON: () => ({}) })).toThrow()
+ })
+
+ it('fails closed at capacity until cancelled workers actually exit', async () => {
+ vi.useFakeTimers()
+ const workers = Array.from({ length: 4 }, () => {
+ const worker = new EventEmitter() as EventEmitter & { terminate: ReturnType<typeof vi.fn> }
+ worker.terminate = vi.fn(async () => 1)
+ vi.mocked(Worker).mockImplementationOnce(function () {
+ return worker as unknown as Worker
+ })
+ return worker
+ })
+ const pending = workers.map(() => validateBoundedSchema('{}', '{}'))
+ expect(await validateBoundedSchema('{}', '{}')).toBe(false)
+ expect(Worker).toHaveBeenCalledTimes(4)
+ await vi.advanceTimersByTimeAsync(2_000)
+ expect(await Promise.all(pending)).toEqual([false, false, false, false])
+ expect(await validateBoundedSchema('{}', '{}')).toBe(false)
+ expect(Worker).toHaveBeenCalledTimes(4)
+ for (const worker of workers) worker.emit('exit', 1)
+ })
+
+ it('terminates a benign stalled worker on deadline while the Host timer runs', async () => {
+ vi.useFakeTimers()
+ const stalled = new EventEmitter() as EventEmitter & { terminate: ReturnType<typeof vi.fn> }
+ stalled.terminate = vi.fn(async () => {
+ stalled.emit('exit', 1)
+ return 1
+ })
+ vi.mocked(Worker).mockImplementationOnce(function () {
+ return stalled as unknown as Worker
+ })
+ const hostTick = vi.fn()
+ setTimeout(hostTick, 10)
+ const result = validateBoundedSchema('{}', '{}')
+ await vi.advanceTimersByTimeAsync(10)
+ expect(hostTick).toHaveBeenCalledOnce()
+ await vi.advanceTimersByTimeAsync(2_000)
+ expect(await result).toBe(false)
+ expect(stalled.terminate).toHaveBeenCalledOnce()
+ })
+})
diff --git a/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts b/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts
index 389c15cc8..a66467c40 100644
--- a/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts
+++ b/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts
@@ -1,8 +1,14 @@
import { describe, expect, it, vi } from 'vitest'
import type { Tool, ToolRegistry } from '../../interfaces'
import type { ToolOutput } from '../../types'
+import { validateBoundedSchema } from '../boundedSchemaValidation'
import { CompositeToolRegistry, McpToolRegistryAdapter } from '../toolRegistryAdapter'
+vi.mock('../boundedSchemaValidation', async importOriginal => {
+ const actual = await importOriginal<typeof import('../boundedSchemaValidation')>()
+ return { ...actual, validateBoundedSchema: vi.fn(actual.validateBoundedSchema) }
+})
+
function createMockTool(
toolName: string,
opts: { sanitize?: boolean; approval?: boolean; output?: string } = {}
@@ -350,3 +356,43 @@ describe('McpToolRegistryAdapter', () => {
expect(output.attachments?.[0].dataBase64).toBe('c2VjcmV0LWJhc2U2NA==')
})
})
+
+describe('MCP dispatch freshness across asynchronous validation', () => {
+ it.each(['schema', 'arguments', 'removed'] as const)(
+ 'rejects %s changes while the validator waits',
+ async change => {
+ const schema: Record<string, unknown> = { type: 'object' }
+ const args: Record<string, unknown> = {}
+ let present = true
+ const manager = {
+ getAllTools: () =>
+ present
+ ? [
+ {
+ name: 'alpha__read',
+ serverName: 'alpha',
+ description: 'Read',
+ inputSchema: schema,
+ },
+ ]
+ : [],
+ callTool: vi.fn(async () => ({ result: { content: [] }, isError: false })),
+ }
+ const tool = new McpToolRegistryAdapter(manager as any).get('alpha__read')!
+ let complete!: (valid: boolean) => void
+ vi.mocked(validateBoundedSchema).mockImplementationOnce(
+ () =>
+ new Promise(resolve => {
+ complete = resolve
+ })
+ )
+ const pending = tool.execute(args)
+ if (change === 'schema') schema.required = ['recordId']
+ if (change === 'arguments') args.changed = true
+ if (change === 'removed') present = false
+ complete(true)
+ expect((await pending).is_error).toBe(true)
+ expect(manager.callTool).not.toHaveBeenCalled()
+ }
+ )
+})
diff --git a/mcp-host/src/core/adapters/boundedSchemaValidation.ts b/mcp-host/src/core/adapters/boundedSchemaValidation.ts
new file mode 100644
index 000000000..816744bab
--- /dev/null
+++ b/mcp-host/src/core/adapters/boundedSchemaValidation.ts
@@ -0,0 +1,146 @@
+import { Worker } from 'node:worker_threads'
+
+const MAX_BYTES = 256 * 1024
+const MAX_NODES = 10_000
+const MAX_DEPTH = 64
+const DEADLINE_MS = 2_000
+const MAX_WORKERS = 4
+let activeWorkers = 0
+
+/** Bound cloning/serialization before crossing the worker boundary. Catalog and
+ * argument inputs are JSON data; reject accessors, cycles and non-JSON values.
+ * No toJSON hook is called and no caller-owned value is mutated. */
+export function boundedJson(value: unknown): string {
+ let nodes = 0
+ let characters = 0
+ const ancestors = new Set<object>()
+ function clone(input: unknown, depth: number): unknown {
+ if (++nodes > MAX_NODES || depth > MAX_DEPTH) throw new Error('JSON limit')
+ if (typeof input === 'string') {
+ characters += input.length
+ if (characters > MAX_BYTES) throw new Error('JSON limit')
+ return input
+ }
+ if (input === null || typeof input === 'boolean') return input
+ if (typeof input === 'number' && Number.isFinite(input)) return input
+ if (!input || typeof input !== 'object' || ancestors.has(input)) throw new Error('JSON type')
+ const array = Array.isArray(input)
+ if (
+ !array &&
+ Object.getPrototypeOf(input) !== Object.prototype &&
+ Object.getPrototypeOf(input) !== null
+ )
+ throw new Error('JSON type')
+ if (array && input.length > MAX_NODES) throw new Error('JSON limit')
+ ancestors.add(input)
+ const output: Record<string, unknown> | unknown[] = array ? [] : Object.create(null)
+ let entries = 0
+ for (const key in input) {
+ if (!Object.hasOwn(input, key)) continue
+ if (array && key !== String(entries)) throw new Error('JSON array')
+ entries++
+ characters += key.length
+ if (characters > MAX_BYTES) throw new Error('JSON limit')
+ const property = Object.getOwnPropertyDescriptor(input, key)!
+ if (!('value' in property)) throw new Error('JSON accessor')
+ Object.defineProperty(output, key, {
+ value: clone(property.value, depth + 1),
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ })
+ }
+ if (array && entries !== input.length) throw new Error('JSON array')
+ ancestors.delete(input)
+ return output
+ }
+ const serialized = JSON.stringify(clone(value, 0))
+ if (Buffer.byteLength(serialized) > MAX_BYTES) throw new Error('JSON limit')
+ return serialized
+}
+
+// Trusted, static CommonJS worker program works in both source tests and tsc
+// output. Only Ajv compile/evaluation executes here; no remote ref loader exists.
+const WORKER_SOURCE = `
+const { parentPort, workerData } = require('node:worker_threads');
+try {
+ const schema = JSON.parse(workerData.schema);
+ const params = JSON.parse(workerData.params);
+ const dialect = typeof schema.$schema === 'string' ? schema.$schema.replace(/#$/, '') : undefined;
+ const index = dialect === undefined || dialect === 'https://json-schema.org/draft/2020-12/schema' ? 2
+ : dialect === 'https://json-schema.org/draft/2019-09/schema' ? 1
+ : dialect === 'http://json-schema.org/draft-07/schema' ? 0 : -1;
+ if (index < 0) throw new Error('Unsupported schema');
+ const module = require(workerData.modules[index]);
+ const Ajv = module.default || module;
+ const ajv = new Ajv({ strict: false, allErrors: false, coerceTypes: false,
+ useDefaults: false, removeAdditional: false, validateFormats: false });
+ const validate = ajv.compile(schema);
+ parentPort.postMessage(!('$async' in validate) && validate(params) === true);
+} catch { parentPort.postMessage(false); }
+`
+
+/** One disposable worker per validation, no unbounded queue or schema cache.
+ * Capacity remains reserved until the worker actually exits, including timeout
+ * cancellation. Resource exhaustion, startup errors and invalid replies fail closed.
+ * No schema, arguments or Ajv diagnostics are returned to the Host. */
+export async function validateBoundedSchema(schema: string, params: string): Promise<boolean> {
+ if (
+ Buffer.byteLength(schema) > MAX_BYTES ||
+ Buffer.byteLength(params) > MAX_BYTES ||
+ activeWorkers >= MAX_WORKERS
+ )
+ return false
+ activeWorkers++
+ return new Promise<boolean>(resolve => {
+ let worker: Worker
+ let done = false
+ const finish = (valid: boolean) => {
+ if (done) return
+ done = true
+ clearTimeout(timer)
+ // Successful sequential calls wait for capacity to be released on exit.
+ if (valid && worker) {
+ void worker.terminate().then(
+ () => resolve(true),
+ () => resolve(false)
+ )
+ } else {
+ resolve(false)
+ if (worker)
+ void worker.terminate().catch(() => {
+ /* Exit retains capacity ownership. */
+ })
+ }
+ }
+ const timer = setTimeout(() => finish(false), DEADLINE_MS)
+ try {
+ worker = new Worker(WORKER_SOURCE, {
+ eval: true,
+ workerData: {
+ schema,
+ params,
+ modules: [
+ require.resolve('ajv'),
+ require.resolve('ajv/dist/2019'),
+ require.resolve('ajv/dist/2020'),
+ ],
+ },
+ resourceLimits: {
+ maxOldGenerationSizeMb: 64,
+ maxYoungGenerationSizeMb: 16,
+ stackSizeMb: 4,
+ },
+ })
+ worker.once('message', message => finish(message === true))
+ worker.once('error', () => finish(false))
+ worker.once('exit', () => {
+ activeWorkers--
+ finish(false)
+ })
+ } catch {
+ activeWorkers--
+ finish(false)
+ }
+ })
+}
diff --git a/mcp-host/src/core/adapters/toolRegistryAdapter.ts b/mcp-host/src/core/adapters/toolRegistryAdapter.ts
index 812acd661..6a1da2b7e 100644
--- a/mcp-host/src/core/adapters/toolRegistryAdapter.ts
+++ b/mcp-host/src/core/adapters/toolRegistryAdapter.ts
@@ -1,54 +1,9 @@
-import Ajv, { type ValidateFunction } from 'ajv'
-import Ajv2019 from 'ajv/dist/2019'
-import Ajv2020 from 'ajv/dist/2020'
import { serverNameOf } from '../../capabilities/toolCatalogTools'
import { logger } from '../../logger'
import { McpManager } from '../../mcp/manager'
import { Tool, ToolRegistry } from '../interfaces'
import { Attachment, ToolDefinition, ToolOutput, ValidationResult } from '../types'
-
-// Compile only selected schemas, sharing across per-turn adapter refreshes.
-// Weak keys release removed catalog entries. The serialized comparison also
-// invalidates a validator if an in-memory schema is updated in place.
-const mcpValidators = new WeakMap<
- object,
- { serialized: string; validate: ValidateFunction | null }
->()
-
-function selectedSchemaValidator(schema: Record<string, unknown>): ValidateFunction | null {
- const serialized = JSON.stringify(schema)
- const cached = mcpValidators.get(schema)
- if (cached?.serialized === serialized) return cached.validate
- let validate: ValidateFunction | null = null
- try {
- // An empty fragment denotes the same JSON Schema meta-schema URI.
- const dialect =
- typeof schema.$schema === 'string' ? schema.$schema.replace(/#$/, '') : undefined
- // MCP defines an omitted $schema as JSON Schema 2020-12.
- const Constructor =
- dialect === undefined || dialect === 'https://json-schema.org/draft/2020-12/schema'
- ? Ajv2020
- : dialect === 'https://json-schema.org/draft/2019-09/schema'
- ? Ajv2019
- : Ajv
- // Isolate each schema's $id namespace. Synchronous compile has no remote
- // reference loader; schema validation must never fetch a URL or alter args.
- const ajv = new Constructor({
- strict: false,
- allErrors: false,
- coerceTypes: false,
- useDefaults: false,
- removeAdditional: false,
- validateFormats: false,
- })
- validate = ajv.compile(schema)
- if ('$async' in validate) validate = null
- } catch {
- // Unresolved references/unsupported dialects are explicit validation errors.
- }
- mcpValidators.set(schema, { serialized, validate })
- return validate
-}
+import { boundedJson, validateBoundedSchema } from './boundedSchemaValidation'
function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' && !Array.isArray(value)
@@ -151,32 +106,53 @@ class McpToolAdapter implements Tool {
requiresApproval() {
return false
}
- validateParams(params: Record<string, unknown>): ValidationResult {
- const live = this.mcpManager
+ private liveTool() {
+ return this.mcpManager
.getAllTools()
.find(tool => tool.name === this.fullName && serverNameOf(tool) === this.serverName)
- if (!live) return { is_valid: false, errors: ['MCP tool is no longer available.'] }
+ }
+
+ private async validateCurrent(params: Record<string, unknown>) {
+ const live = this.liveTool()
+ const rejected: ValidationResult = {
+ is_valid: false,
+ errors: ['Arguments or current MCP schema could not be validated; describe the tool again.'],
+ }
try {
- const schema = live.inputSchema
- if (!schema || typeof schema !== 'object' || Array.isArray(schema)) {
- return { is_valid: false, errors: ['MCP tool schema is invalid or unsupported.'] }
- }
- const validate = selectedSchemaValidator(schema)
- if (!validate)
- return { is_valid: false, errors: ['MCP tool schema is invalid or unsupported.'] }
- return validate(params)
- ? { is_valid: true, errors: [] }
- : {
- is_valid: false,
- errors: [
- 'Arguments do not match the current MCP tool schema; describe the tool again.',
- ],
- }
+ if (!live || !asRecord(live.inputSchema)) return { result: rejected }
+ const schemaJson = boundedJson(live.inputSchema)
+ const paramsJson = boundedJson(params)
+ if (!(await validateBoundedSchema(schemaJson, paramsJson))) return { result: rejected }
+ return { result: { is_valid: true, errors: [] } as ValidationResult, schemaJson, paramsJson }
} catch {
// Never include raw schemas, arguments or validator diagnostics in errors.
- return { is_valid: false, errors: ['MCP tool schema is invalid or unsupported.'] }
+ return { result: rejected }
}
}
+
+ private validationStillCurrent(
+ checked: Awaited<ReturnType<McpToolAdapter['validateCurrent']>>,
+ params: Record<string, unknown>
+ ): boolean {
+ try {
+ const live = this.liveTool()
+ return (
+ checked.result.is_valid &&
+ !!live &&
+ boundedJson(live.inputSchema) === checked.schemaJson &&
+ boundedJson(params) === checked.paramsJson
+ )
+ } catch {
+ return false
+ }
+ }
+
+ async validateParams(params: Record<string, unknown>): Promise<ValidationResult> {
+ const checked = await this.validateCurrent(params)
+ return this.validationStillCurrent(checked, params)
+ ? checked.result
+ : { is_valid: false, errors: ['MCP validation failed or tool changed during validation.'] }
+ }
traceDescriptor() {
// `sourceRef` is the tool-lane guardrail's `server` identity (provenance.ts),
// so a `server=` deny rule matches on THIS value. It used to be sliced off the
@@ -196,10 +172,12 @@ class McpToolAdapter implements Tool {
try {
// An approval may have been suspended with an older adapter/schema.
// Resolve the live schema again immediately before manager dispatch.
- const validation = this.validateParams(params)
- if (!validation.is_valid) {
+ const checked = await this.validateCurrent(params)
+ // No await between the freshness check and manager dispatch: catalog or
+ // argument changes during worker evaluation cannot authorize this call.
+ if (!this.validationStillCurrent(checked, params)) {
return {
- content: validation.errors.join(' '),
+ content: 'MCP validation failed or tool changed during validation.',
duration_ms: Date.now() - startTime,
is_error: true,
}
diff --git a/mcp-host/src/core/interfaces.ts b/mcp-host/src/core/interfaces.ts
index 4515a4fb7..66f53aae0 100644
--- a/mcp-host/src/core/interfaces.ts
+++ b/mcp-host/src/core/interfaces.ts
@@ -94,7 +94,7 @@ export interface Tool {
requiresApproval(): boolean
/** Optional live parameter validation, run before approval and rechecked by
* the implementation at dispatch when its schema can change while suspended. */
- validateParams?(params: Record<string, unknown>): ValidationResult
+ validateParams?(params: Record<string, unknown>): ValidationResult | Promise<ValidationResult>
/**
* Safe, producer-owned classification for governed replay. This must never
* include tool arguments or output. Native tools may omit it and are then
diff --git a/mcp-host/src/core/orchestration/__tests__/approvedToolsLifecycle.integration.test.ts b/mcp-host/src/core/orchestration/__tests__/approvedToolsLifecycle.integration.test.ts
index 248015392..411101734 100644
--- a/mcp-host/src/core/orchestration/__tests__/approvedToolsLifecycle.integration.test.ts
+++ b/mcp-host/src/core/orchestration/__tests__/approvedToolsLifecycle.integration.test.ts
@@ -1,11 +1,11 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
-import Ajv2020 from 'ajv/dist/2020'
import { TaskExecutor, type TaskExecutorDeps } from '../../../agent/taskExecutor'
import { config as appConfig } from '../../../config'
import { TaskLifecycle } from '../../../lifecycle/taskLifecycle'
import type { SingleTurnProvider } from '../../../llm/types'
import { McpManager } from '../../../mcp/manager'
import type { Task } from '../../../queue/types'
+import * as boundedValidation from '../../adapters/boundedSchemaValidation'
import { CompositeToolRegistry, McpToolRegistryAdapter } from '../../adapters/toolRegistryAdapter'
import { makeFakeConversation } from '../../conversation/__testing__/makeFakeConversation'
import { ConversationManager } from '../../conversation/conversation'
@@ -287,9 +287,9 @@ describe('approved catalog across presentation and lifecycle', () => {
})
it.each([83, 250])(
- 'compiles only the selected schema out of %i and reuses validation without mutating arguments',
+ 'validates only the selected schema out of %i across repeated calls without mutating arguments',
async count => {
- const compile = vi.spyOn(Ajv2020.prototype, 'compile')
+ const compile = vi.spyOn(boundedValidation, 'validateBoundedSchema')
try {
const { manager, registry, config } = await setup(count)
const target = 'alpha__record__read_000'
@@ -307,7 +307,13 @@ describe('approved catalog across presentation and lifecycle', () => {
const second = await executeToolCalls([bridgeCall(target, 'second', args)], config, 1)
expect(first.toolResults[0].is_error).toBe(false)
expect(second.toolResults[0].is_error).toBe(false)
- expect(compile).toHaveBeenCalledTimes(1)
+ expect(compile).toHaveBeenCalled()
+ expect(
+ compile.mock.calls.every(
+ ([schema]) =>
+ JSON.stringify(JSON.parse(schema)) === JSON.stringify(definition.inputSchema)
+ )
+ ).toBe(true)
expect(args).toEqual({})
const coerced = await executeToolCalls(
[bridgeCall(target, 'wrong-type', { limit: '3' })],
@@ -316,7 +322,13 @@ describe('approved catalog across presentation and lifecycle', () => {
)
expect(coerced.toolResults[0].is_error).toBe(true)
expect(remote.calls).toHaveBeenCalledTimes(2)
- expect(compile).toHaveBeenCalledTimes(1)
+ expect(compile).toHaveBeenCalled()
+ expect(
+ compile.mock.calls.every(
+ ([schema]) =>
+ JSON.stringify(JSON.parse(schema)) === JSON.stringify(definition.inputSchema)
+ )
+ ).toBe(true)
} finally {
compile.mockRestore()
}
@@ -342,7 +354,7 @@ describe('approved catalog across presentation and lifecycle', () => {
const result = await executeToolCalls([bridgeCall(target)], config, 0)
expect(result.pendingApproval).toBeUndefined()
expect(result.toolResults[0].is_error).toBe(true)
- expect(result.toolResults[0].content).toContain('schema is invalid or unsupported')
+ expect(result.toolResults[0].content).toContain('MCP validation failed')
expect(result.toolResults[0].content.length).toBeLessThan(150)
expect(result.toolResults[0].content).not.toContain('unresolvable.example')
expect(remote.calls).not.toHaveBeenCalled()
@@ -419,7 +431,7 @@ describe('approved catalog across presentation and lifecycle', () => {
const { manager, registry } = await setup()
const target = 'alpha__record__read_000'
const captured = registry.get(target)!
- expect(captured.validateParams!({})).toMatchObject({ is_valid: true })
+ expect(await captured.validateParams!({})).toMatchObject({ is_valid: true })
const schema = manager.getAllTools().find(tool => tool.name === target)!.inputSchema
Object.assign(schema, { properties: { recordId: { type: 'string' } }, required: ['recordId'] })
const rejected = await captured.execute({})
@@ -535,7 +547,7 @@ describe('approved catalog across presentation and lifecycle', () => {
message => message.role === 'tool' && message.tool_call_id === call.id
)
if (decision === 'schema-change')
- expect(result?.content).toContain('current MCP tool schema')
+ expect(result?.content).toContain('MCP validation failed')
else if (decision === 'revoke')
expect(result?.content).toMatch(/not found|not available/i)
else expect(result?.content).toContain('receipt:alpha:record__read_082')
diff --git a/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts b/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts
index e1d91bdd3..26052d950 100644
--- a/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts
+++ b/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts
@@ -224,7 +224,7 @@ export async function executeToolCalls(
let validation = config.toolOutputProcessor.beforeExecution(call.name, call.arguments)
if (validation.is_valid) {
validation =
- config.toolRegistry.get(call.name)?.validateParams?.(call.arguments) ?? validation
+ (await config.toolRegistry.get(call.name)?.validateParams?.(call.arguments)) ?? validation
}
if (!validation.is_valid) {
events.emit({
diff --git a/scripts/minikube/t2.sh b/scripts/minikube/t2.sh
index 59430ef0b..6cf2d23e0 100755
--- a/scripts/minikube/t2.sh
+++ b/scripts/minikube/t2.sh
@@ -531,6 +531,9 @@ main() {
run_np08_hcc_authorization
run_healthcheck_if_requested
run_playwright_if_requested
+ # Journeys may mutate the owned profile under the inherited lease. Certify
+ # the restored runtime after them, not only the state before they ran.
+ run_final_preflight
# Health and Playwright run after the planner's initial ownership scan. A
# forward can disappear, be replaced, or lose its binding during either
# journey, so the exact PID/start-time/argv record must be revalidated before
diff --git a/scripts/tests/test-minikube-t2-contract.sh b/scripts/tests/test-minikube-t2-contract.sh
index 2c8ec0a33..5e00e25a5 100755
--- a/scripts/tests/test-minikube-t2-contract.sh
+++ b/scripts/tests/test-minikube-t2-contract.sh
@@ -342,6 +342,13 @@ grep -Fq 'T2_T0_STATUS=NOT_RUN' "$T2"
grep -Fq 'T2_T1_STATUS=NOT_RUN' "$T2"
grep -Fq 'T2_HEALTHCHECK_COMMAND' "$T2"
grep -Fq 'minikube-t2-runtime' "$ROOT/Makefile"
+post_journey_preflight_line="$(grep -nFx ' run_final_preflight' "$T2" | tail -1 | cut -d: -f1)"
+journey_line="$(grep -nFx ' run_playwright_if_requested' "$T2" | tail -1 | cut -d: -f1)"
+if [ -z "$post_journey_preflight_line" ] || [ -z "$journey_line" ] ||
+ [ "$post_journey_preflight_line" -le "$journey_line" ]; then
+ echo 'FAIL: T2 must revalidate exact-head runtime after the journey' >&2
+ exit 1
+fi
post_runtime_process_check_line="$(grep -nF 'if ! t2_process_check; then' "$T2" | tail -1 | cut -d: -f1)"
complete_pass_line="$(grep -nF 't2_evidence_write complete PASS' "$T2" | tail -1 | cut -d: -f1)"
if [ -z "$post_runtime_process_check_line" ] || [ -z "$complete_pass_line" ] ||