diff --git a/scripts/generate-error-schema.mjs b/scripts/generate-error-schema.mjs index 483ff76312..d6b41a43b1 100644 --- a/scripts/generate-error-schema.mjs +++ b/scripts/generate-error-schema.mjs @@ -1,7 +1,7 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { analysisErrorJsonSchema } from "../dist/contracts/errorSchemas.js"; +import { analysisErrorJsonSchema } from "../dist/contracts/analysisErrorJsonSchema.js"; import { analysisErrorCatalogue } from "../dist/domain/analysisErrorClassification.js"; import { hopperErrorCatalogue } from "../dist/hopper/HopperErrors.js"; import { formatGeneratedFile } from "./lib/format-generated-file.mjs"; diff --git a/src/cli/decimalTokenPattern.ts b/src/cli/decimalTokenPattern.ts index 07e1b30e1f..c7b973f384 100644 --- a/src/cli/decimalTokenPattern.ts +++ b/src/cli/decimalTokenPattern.ts @@ -48,20 +48,37 @@ const openEndedPattern = (minimum: number): string => { * it never rejects a token the parser admits. */ export const decimalTokenPattern = (domain: z.ZodNumber): string => { - const schema = z.toJSONSchema(domain); - const minimum = Math.max( - 0, - Math.ceil(schema.minimum ?? 0), - typeof schema.exclusiveMinimum === "number" - ? Math.floor(schema.exclusiveMinimum) + 1 - : 0, - ); - const maximum = Math.min( - Math.floor(schema.maximum ?? Infinity), - typeof schema.exclusiveMaximum === "number" - ? Math.ceil(schema.exclusiveMaximum) - 1 - : Infinity, - ); + let minimum = + domain.minValue !== null && domain.minValue > 0 + ? Math.ceil(domain.minValue) + : 0; + let maximum = + domain.maxValue !== null && domain.maxValue < Infinity + ? Math.floor(domain.maxValue) + : Infinity; + for (const check of domain._zod.def.checks ?? []) { + const def = check._zod.def as { + readonly check?: string; + readonly value?: unknown; + readonly inclusive?: boolean; + }; + if (typeof def.value !== "number") continue; + if (def.check === "greater_than") { + minimum = Math.max( + minimum, + def.inclusive === false + ? Math.floor(def.value) + 1 + : Math.ceil(def.value), + ); + } else if (def.check === "less_than") { + maximum = Math.min( + maximum, + def.inclusive === false + ? Math.ceil(def.value) - 1 + : Math.floor(def.value), + ); + } + } // Non-integer floors and ceilings have no safe-integer range to publish. if (!Number.isSafeInteger(minimum)) return "^[0-9]+$"; if (maximum === Infinity) return openEndedPattern(minimum); diff --git a/src/cliDecimalTokenPattern.test.ts b/src/cliDecimalTokenPattern.test.ts index 458c18ccda..956b55d058 100644 --- a/src/cliDecimalTokenPattern.test.ts +++ b/src/cliDecimalTokenPattern.test.ts @@ -3,6 +3,7 @@ import { Ajv2020 } from "ajv/dist/2020.js"; import { z } from "zod"; import { expect, it } from "vitest"; +import { decimalTokenPattern } from "./cli/decimalTokenPattern.js"; import { cliDecimalField } from "./cli/options.js"; it("keeps advertised decimal bounds aligned across decimal-width transitions", () => { @@ -102,3 +103,51 @@ it("keeps a positive floor when the domain has no ceiling", () => { expect(validate("")).toBe(false); } }); + +it("derives decimal token bounds matching z.toJSONSchema across ZodNumber shapes", () => { + const domains = [ + z.number(), + z.number().int(), + z.int32(), + z.uint32(), + z.number().min(5).max(10), + z.number().gt(0).lt(100), + z.number().positive(), + z.number().nonnegative(), + z.number().min(1.5).max(9.5), + z.number().gt(1.5).lt(9.5), + z.number().max(-1), + z.number().min(10).max(5), + ] as const; + for (const domain of domains) { + const schema = z.toJSONSchema(domain); + const expectedMin = Math.max( + 0, + Math.ceil(schema.minimum ?? 0), + typeof schema.exclusiveMinimum === "number" + ? Math.floor(schema.exclusiveMinimum) + 1 + : 0, + ); + const expectedMax = Math.min( + Math.floor(schema.maximum ?? Infinity), + typeof schema.exclusiveMaximum === "number" + ? Math.ceil(schema.exclusiveMaximum) - 1 + : Infinity, + ); + const regex = new RegExp(decimalTokenPattern(domain), "u"); + if (expectedMin > expectedMax) { + expect(regex.test("0")).toBe(false); + expect(regex.test("5")).toBe(false); + continue; + } + if (Number.isSafeInteger(expectedMin)) { + expect(regex.test(String(expectedMin))).toBe(true); + if (expectedMin > 0) + expect(regex.test(String(expectedMin - 1))).toBe(false); + } + if (Number.isSafeInteger(expectedMax)) { + expect(regex.test(String(expectedMax))).toBe(true); + expect(regex.test(String(expectedMax + 1))).toBe(false); + } + } +}); diff --git a/src/contracts/analysisErrorJsonSchema.ts b/src/contracts/analysisErrorJsonSchema.ts new file mode 100644 index 0000000000..fbbbcc73d2 --- /dev/null +++ b/src/contracts/analysisErrorJsonSchema.ts @@ -0,0 +1,8 @@ +import { z } from "zod"; + +import { analysisErrorProjectionSchema } from "../domain/analysisErrorProjectionSchema.js"; + +/** JSON Schema document used by generated API documentation and clients. */ +export const analysisErrorJsonSchema = z.toJSONSchema( + analysisErrorProjectionSchema, +); diff --git a/src/contracts/errorSchemas.ts b/src/contracts/errorSchemas.ts index 6033fead4f..68efaab61e 100644 --- a/src/contracts/errorSchemas.ts +++ b/src/contracts/errorSchemas.ts @@ -28,8 +28,3 @@ export const analysisCliErrorEnvelopeSchema = z }); } }); - -/** JSON Schema document used by generated API documentation and clients. */ -export const analysisErrorJsonSchema = z.toJSONSchema( - analysisErrorProjectionSchema, -); diff --git a/src/contracts/toolInputReferences.test.ts b/src/contracts/toolInputReferences.test.ts index da60955349..52757ea4d9 100644 --- a/src/contracts/toolInputReferences.test.ts +++ b/src/contracts/toolInputReferences.test.ts @@ -1,6 +1,6 @@ import { Ajv, type Options } from "ajv"; import { Ajv2020 } from "ajv/dist/2020.js"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { z } from "zod"; import { applicationFeatureSeedSchema } from "../domain/javascript/javascriptFeatureTraceSchemas.js"; @@ -55,10 +55,22 @@ it.each(drafts)( }); const options = { target, libraryOptions: { reused: "ref" as const } }; for (const sharedFirst of [false, true]) { - const wrapped = transformAdvertisedInputJsonSchema(canonical, transform); + const seed = transform( + canonical["~standard"].jsonSchema.input({ target }), + ); + const resolveCached = vi.fn(() => seed); + const wrapped = transformAdvertisedInputJsonSchema( + canonical, + transform, + resolveCached, + ); const project = wrapped["~standard"].jsonSchema.input; - if (sharedFirst) project(options); + if (sharedFirst) { + project(options); + expect(resolveCached).not.toHaveBeenCalled(); + } const advertised = project({ target }); + expect(advertised).toBe(seed); expect(JSON.stringify(advertised)).not.toContain('"$ref":'); expect(advertised).toEqual( transform(canonical["~standard"].jsonSchema.input({ target })), @@ -69,6 +81,7 @@ it.each(drafts)( transform(canonical["~standard"].jsonSchema.input(options)), ); expect(project({ target })).toBe(advertised); + expect(resolveCached).toHaveBeenCalledExactlyOnceWith(target); } }, ); diff --git a/src/contracts/toolSchemaMetadata.ts b/src/contracts/toolSchemaMetadata.ts index dd1aee09e5..79500aa237 100644 --- a/src/contracts/toolSchemaMetadata.ts +++ b/src/contracts/toolSchemaMetadata.ts @@ -277,6 +277,7 @@ export const omitAdvertisedOutputJsonSchema = ( export const transformAdvertisedInputJsonSchema = ( schema: Schema, transform: (projected: Record) => Record, + resolveCached?: (target: string) => Record | undefined, ): Schema => { const standard = Reflect.get(schema as object, "~standard"); if (!isRecord(standard)) return schema; @@ -293,6 +294,11 @@ export const transformAdvertisedInputJsonSchema = ( if (cacheable) { const cached = byTarget.get(target); if (cached !== undefined) return cached; + const seeded = resolveCached?.(target); + if (seeded !== undefined) { + byTarget.set(target, seeded); + return seeded; + } } const projected = (project as (options: unknown) => unknown)(options); const transformed = isRecord(projected) ? transform(projected) : projected; diff --git a/src/server/EvidenceMcpServer.test.ts b/src/server/EvidenceMcpServer.test.ts index 3e2d68b462..830a5d7c4a 100644 --- a/src/server/EvidenceMcpServer.test.ts +++ b/src/server/EvidenceMcpServer.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { Client, InMemoryTransport, @@ -677,6 +677,52 @@ describe("SDK argument name guidance", () => { }); }); +it("reuses the tool registration input projection across SDK listings", async () => { + const server = new EvidenceMcpServer( + { name: "input-projection-server", version: "1" }, + { capabilities: {} }, + undefined, + createToolResultDelivery(4096), + ); + const schema = z.strictObject({ value: z.string() }); + const standard = schema["~standard"]; + const input = vi.fn(standard.jsonSchema.input); + Object.defineProperty(schema, "~standard", { + value: { ...standard, jsonSchema: { ...standard.jsonSchema, input } }, + }); + server.registerTool( + "counted_input", + { description: "Count input projections", inputSchema: schema }, + async () => ({ content: [] }), + ); + expect(input).toHaveBeenCalledExactlyOnceWith({ target: "draft-2020-12" }); + + const client = new Client({ name: "input-projection-client", version: "1" }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const serving = serveStdio(() => server, { transport: serverTransport }); + try { + await client.connect(clientTransport); + const first = await client.listTools(); + expect(first.tools).toMatchObject([ + { + name: "counted_input", + description: "Count input projections", + inputSchema: { + type: "object", + properties: { value: { type: "string" } }, + required: ["value"], + }, + }, + ]); + expect(input).toHaveBeenCalledTimes(1); + expect(await client.listTools()).toEqual(first); + expect(input).toHaveBeenCalledTimes(1); + } finally { + await Promise.all([client.close(), serving.close()]); + } +}); + it("skips object-root output schema projection on output=off while keeping runtime validation and legacy wrapping", async () => { const server = new EvidenceMcpServer( { name: "output-off-skip-test", version: "1" }, diff --git a/src/server/EvidenceMcpServerCore.ts b/src/server/EvidenceMcpServerCore.ts index 0f23e82b7a..a892abca16 100644 --- a/src/server/EvidenceMcpServerCore.ts +++ b/src/server/EvidenceMcpServerCore.ts @@ -533,19 +533,32 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer { const { input } = this.presentation; if (inputSchema === undefined || !hasAdvertisedInputJsonSchema(inputSchema)) return config; + let draft2020: + | { + readonly description: string | undefined; + readonly inputSchema: Record | undefined; + } + | undefined; + const projectDraft2020 = () => { + if (draft2020 !== undefined) return draft2020; + const projected = (inputSchema as StandardSchemaWithJSON)[ + "~standard" + ].jsonSchema.input({ target: "draft-2020-12" }); + draft2020 = isRecord(projected) + ? advertiseToolInput(description, projected, input) + : { description, inputSchema: undefined }; + return draft2020; + }; return { - ...this.describeTool(name, () => { - const projected = (inputSchema as StandardSchemaWithJSON)[ - "~standard" - ].jsonSchema.input({ target: "draft-2020-12" }); - return isRecord(projected) - ? advertiseToolInput(description, projected, input).description - : description; - }), + ...this.describeTool(name, () => projectDraft2020().description), inputSchema: transformAdvertisedInputJsonSchema( inputSchema, (projected) => advertiseToolInput(description, projected, input).inputSchema, + (target) => + target === "draft-2020-12" + ? projectDraft2020().inputSchema + : undefined, ), }; } diff --git a/src/server/ToolResultDelivery.partialRetention.test.ts b/src/server/ToolResultDelivery.partialRetention.test.ts index 2adfe32cf4..f30d95cd73 100644 --- a/src/server/ToolResultDelivery.partialRetention.test.ts +++ b/src/server/ToolResultDelivery.partialRetention.test.ts @@ -190,7 +190,7 @@ describe("error delivery omission worklist", () => { ); expect(result.content).toHaveLength(1); expect(first.reads()).toBe(3); - expect(second.reads()).toBe(3); + expect(second.reads()).toBe(2); expect( ( result.structuredContent as { diff --git a/src/server/ToolResultDelivery.ts b/src/server/ToolResultDelivery.ts index b4cb9e552b..4434271b8c 100644 --- a/src/server/ToolResultDelivery.ts +++ b/src/server/ToolResultDelivery.ts @@ -439,38 +439,28 @@ export class ToolResultDelivery { })) .sort((left, right) => right.size - left.size) .map(({ candidate }) => candidate); - while (!encoded.ok && remaining.length > 0) { - const limit = encoded; - let next: AnalysisErrorProjection | undefined; - let nextIndex = -1; - for (const [index, candidate] of remaining.entries()) { - const compact = omitUnretainedEvidenceFromError( - candidateProjection, - limit, - candidate, - ); - if (compact === undefined) continue; - if (next === undefined) { - next = compact; - nextIndex = index; - } - const content = { error: compact }; - const compactEncoded = encodeToolResult( - content, - this.resultBudgetBytes, - "error-text", - targetContent, - ); - if (compactEncoded.ok) { - structuredContent = content; - encoded = compactEncoded; - break; - } + let index = 0; + while (!encoded.ok && index < remaining.length) { + const compact = omitUnretainedEvidenceFromError( + candidateProjection, + encoded, + remaining[index]!, + ); + index += 1; + if (compact === undefined) continue; + candidateProjection = compact; + const content = { error: compact }; + const compactEncoded = encodeToolResult( + content, + this.resultBudgetBytes, + "error-text", + targetContent, + ); + if (compactEncoded.ok) { + structuredContent = content; + encoded = compactEncoded; + break; } - if (encoded.ok) break; - if (next === undefined) break; - candidateProjection = next; - remaining.splice(nextIndex, 1); } } // The transport retains an oversized projected error before replacing it diff --git a/src/server/providerOperationToolHandler.ts b/src/server/providerOperationToolHandler.ts index 4061dcbf65..8850552cb4 100644 --- a/src/server/providerOperationToolHandler.ts +++ b/src/server/providerOperationToolHandler.ts @@ -19,7 +19,7 @@ import type { ToolContract } from "../contracts/toolContractTypes.js"; import { ok } from "../domain/result.js"; import type { RecoveryAdmission } from "../application/investigation/InvestigationRetention.js"; import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; -import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js"; +import { ownedJsonObjectSchema, type JsonValue } from "../domain/jsonValue.js"; import type { EvidenceMcpServer } from "./EvidenceMcpServer.js"; import { mcpProgressReporter } from "./mcpProgress.js"; import { logToolExecution } from "./toolLogging.js"; @@ -84,7 +84,7 @@ export const createProviderOperationToolHandler = input: unknown, context: ServerContext, ): Promise => { - const resolved = jsonObjectSchema.parse(input); + const resolved = ownedJsonObjectSchema.parse(input); const parameters = currentMcpToolRequest()?.callerParameters( contract.name, diff --git a/tests/conformance/contracts/analysisErrorProjection.test.ts b/tests/conformance/contracts/analysisErrorProjection.test.ts index 2dea9887e2..fc8110e4af 100644 --- a/tests/conformance/contracts/analysisErrorProjection.test.ts +++ b/tests/conformance/contracts/analysisErrorProjection.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import { Ajv2020 } from "ajv/dist/2020.js"; import { ProcessCaptureError } from "../../../src/process/capture/ProcessCaptureError.js"; -import { analysisErrorJsonSchema } from "../../../src/contracts/errorSchemas.js"; +import { analysisErrorJsonSchema } from "../../../src/contracts/analysisErrorJsonSchema.js"; import { analysisErrorProjectionSchema } from "../../../src/domain/analysisErrorProjectionSchema.js"; import { ArtifactOperationError } from "../../../src/domain/artifactOperationError.js"; import { EvidenceFileError } from "../../../src/domain/evidenceErrors.js";