From 7a2e8da4959d73f88365aec6de48859dd6a6346e Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:42:23 -0500 Subject: [PATCH] perf(mcp): index tool contracts, skip unadvertised projection, parallelize status probes, and stream tool result sizing (#13263) * perf(mcp): index tool contracts, skip unadvertised projection, parallelize status probes, and stream tool result sizing * fix(mcp): await readiness before session status and defer omission worklist --- src/contracts/toolContracts.ts | 26 +++- src/server/EvidenceMcpServerCore.ts | 35 +++-- ...oolResultDelivery.partialRetention.test.ts | 137 +++++++++++++++++- src/server/ToolResultDelivery.ts | 81 +++++++---- src/server/contractToolBindings.ts | 28 +++- src/server/sessionStatusTool.ts | 2 + src/server/toolResultEncoding.test.ts | 84 +++++++++++ src/server/toolResultEncoding.ts | 79 +++++++++- 8 files changed, 402 insertions(+), 70 deletions(-) diff --git a/src/contracts/toolContracts.ts b/src/contracts/toolContracts.ts index 6609854e13..1b3321fee0 100644 --- a/src/contracts/toolContracts.ts +++ b/src/contracts/toolContracts.ts @@ -131,20 +131,30 @@ export const TOOL_CONTRACTS: readonly CatalogContract[] = Object.values( CATALOG_CONTRACT_GROUPS, ).flat(); +/** Public tool contract paired with its canonical catalog index. */ +export interface ToolContractEntry { + readonly contract: CatalogContract; + readonly index: number; +} + +const TOOL_CONTRACTS_BY_NAME: ReadonlyMap = new Map( + TOOL_CONTRACTS.map((contract, index) => [contract.name, { contract, index }]), +); + +/** Resolve a public contract entry in catalog order in O(1). */ +export const toolContractEntry = ( + name: string, +): ToolContractEntry | undefined => TOOL_CONTRACTS_BY_NAME.get(name); + /** Resolve a public contract by name while retaining its exact schema types. */ export const toolContract = < Name extends (typeof TOOL_CONTRACTS)[number]["name"], >( name: Name, ): Extract<(typeof TOOL_CONTRACTS)[number], { readonly name: Name }> => { - const contract = TOOL_CONTRACTS.find( - ( - candidate, - ): candidate is Extract< - (typeof TOOL_CONTRACTS)[number], - { readonly name: Name } - > => candidate.name === name, - ); + const contract = TOOL_CONTRACTS_BY_NAME.get(name)?.contract as + | Extract<(typeof TOOL_CONTRACTS)[number], { readonly name: Name }> + | undefined; if (contract === undefined) throw new Error(`Missing tool contract: ${name}`); return contract; }; diff --git a/src/server/EvidenceMcpServerCore.ts b/src/server/EvidenceMcpServerCore.ts index ec1e1b021a..97019bb229 100644 --- a/src/server/EvidenceMcpServerCore.ts +++ b/src/server/EvidenceMcpServerCore.ts @@ -445,21 +445,24 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer { ): RegisteredTool { if (canReferenceInlineEvidence(config.inputSchema)) this.registerEvidenceReferenceAlternative(name); - const presented = this.presentInput(name, config); - const registeredConfig = { - ...config, - ...(presented.description === undefined - ? {} - : { description: presented.description }), - ...(presented.inputSchema === undefined - ? {} - : { - inputSchema: captureInputValidation( - name, - presented.inputSchema as StandardSchemaWithJSON, - ), - }), - }; + const advertised = this.advertisesTool(name); + const presented = advertised ? this.presentInput(name, config) : config; + const registeredConfig = advertised + ? { + ...config, + ...(presented.description === undefined + ? {} + : { description: presented.description }), + ...(presented.inputSchema === undefined + ? {} + : { + inputSchema: captureInputValidation( + name, + presented.inputSchema as StandardSchemaWithJSON, + ), + }), + } + : config; const scoped = async (input: never, context: never) => { const request = currentMcpToolRequest(); request?.beginHandler(); @@ -498,7 +501,7 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer { registeredConfig as never, scoped as never, ); - if (!this.advertisesTool(name)) registered.disable(); + if (!advertised) registered.disable(); return registered; } diff --git a/src/server/ToolResultDelivery.partialRetention.test.ts b/src/server/ToolResultDelivery.partialRetention.test.ts index 2b2ced599f..2adfe32cf4 100644 --- a/src/server/ToolResultDelivery.partialRetention.test.ts +++ b/src/server/ToolResultDelivery.partialRetention.test.ts @@ -1,6 +1,7 @@ import { unknownTarget } from "../domain/targetIdentity.js"; -import { expect, it } from "vitest"; +import { describe, expect, it } from "vitest"; +import type { JsonValue } from "../domain/jsonValue.js"; import { AnalysisOutputError } from "../domain/analysisErrorCore.js"; import { createEvidence, type Evidence } from "../domain/evidence.js"; import { err } from "../domain/result.js"; @@ -77,3 +78,137 @@ it("does not reference a retained record the ledger did not name", () => { retention: "unknown", }); }); + +const trackedInlineObservation = (bodyLength: number) => { + let reads = 0; + const evidenceRecord: Record = { + evidence_id: `ev_${String(bodyLength)}`, + }; + Object.defineProperty(evidenceRecord, "probe", { + enumerable: true, + get() { + reads += 1; + return "x".repeat(bodyLength); + }, + }); + return { + observation: { + kind: "inline-evidence", + retention: "unknown", + evidence: evidenceRecord, + } satisfies JsonValue, + reads: () => reads, + }; +}; + +describe("error delivery omission worklist", () => { + it("does not measure omission candidates when the initial error fits", () => { + const partial = trackedInlineObservation(64); + const completed = trackedInlineObservation(128); + const result = new ToolResultDelivery( + 1024 * 1024, + ).toDetailedErrorToolResult( + new AnalysisOutputError("observe", "fitting failure"), + { + partial_observation: partial.observation, + completed_observation: completed.observation, + }, + false, + ); + expect(result.content).toHaveLength(1); + expect(partial.reads()).toBe(1); + expect(completed.reads()).toBe(1); + }); + + it("skips candidate sizing when an oversized error has a single unretained candidate", () => { + const partial = trackedInlineObservation(4096); + const result = new ToolResultDelivery(4096).toDetailedErrorToolResult( + new AnalysisOutputError("observe", "oversized single-candidate failure"), + { partial_observation: partial.observation }, + false, + ); + expect(result.content).toHaveLength(1); + expect(partial.reads()).toBe(1); + expect( + ( + result.structuredContent as { + error: { details: Record }; + } + ).error.details, + ).toMatchObject({ + partial_observation_omitted: { + reason: "mcp-response-limit", + retention: "unknown", + evidence_id: "ev_4096", + }, + }); + }); + + it("sizes multiple oversized candidates once and omits the largest first", () => { + const smaller = trackedInlineObservation(512); + const larger = trackedInlineObservation(4096); + const result = new ToolResultDelivery(4096).toDetailedErrorToolResult( + new AnalysisOutputError("observe", "oversized multi-candidate failure"), + { + partial_observation: smaller.observation, + completed_observation: larger.observation, + }, + false, + ); + expect(result.content).toHaveLength(1); + expect(larger.reads()).toBe(2); + expect( + ( + result.structuredContent as { + error: { details: Record }; + } + ).error.details, + ).toMatchObject({ + partial_observation: { + kind: "inline-evidence", + retention: "unknown", + }, + completed_observation_omitted: { + reason: "mcp-response-limit", + retention: "unknown", + evidence_id: "ev_4096", + source_closure: "not-established", + }, + }); + }); + + it("omits multiple oversized candidates across iterations without re-measuring sizes", () => { + const first = trackedInlineObservation(1600); + const second = trackedInlineObservation(1800); + const result = new ToolResultDelivery(3072).toDetailedErrorToolResult( + new AnalysisOutputError("observe", "multi-iteration failure"), + { + partial_observation: first.observation, + completed_observation: second.observation, + }, + false, + ); + expect(result.content).toHaveLength(1); + expect(first.reads()).toBe(3); + expect(second.reads()).toBe(3); + expect( + ( + result.structuredContent as { + error: { details: Record }; + } + ).error.details, + ).toMatchObject({ + partial_observation_omitted: { + reason: "mcp-response-limit", + retention: "unknown", + evidence_id: "ev_1600", + }, + completed_observation_omitted: { + reason: "mcp-response-limit", + retention: "unknown", + evidence_id: "ev_1800", + source_closure: "not-established", + }, + }); + }); +}); diff --git a/src/server/ToolResultDelivery.ts b/src/server/ToolResultDelivery.ts index 55b148d991..91e8f1ab08 100644 --- a/src/server/ToolResultDelivery.ts +++ b/src/server/ToolResultDelivery.ts @@ -422,40 +422,57 @@ export class ToolResultDelivery { "error-text", targetContent, ); - let candidateProjection = projected; - while (!encoded.ok) { - const limit = encoded; - const candidates = [...unretainedEvidenceCandidates(candidateProjection)] - .map((candidate) => ({ - candidate, - size: errorTextWireBytes(candidate.value, this.resultBudgetBytes), - })) - .sort((left, right) => right.size - left.size); - let next: AnalysisErrorProjection | undefined; - for (const { candidate } of candidates) { - const compact = omitUnretainedEvidenceFromError( - candidateProjection, - limit, - candidate, - ); - if (compact === undefined) continue; - next ??= 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) { + let candidateProjection = projected; + const rawCandidates = [ + ...unretainedEvidenceCandidates(candidateProjection), + ]; + const remaining = + rawCandidates.length <= 1 + ? rawCandidates + : rawCandidates + .map((candidate) => ({ + candidate, + size: errorTextWireBytes( + candidate.value, + this.resultBudgetBytes, + ), + })) + .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; + } } + if (encoded.ok) break; + if (next === undefined) break; + candidateProjection = next; + remaining.splice(nextIndex, 1); } - if (encoded.ok) break; - if (next === undefined) break; - candidateProjection = next; } // The transport retains an oversized projected error before replacing it // with a recoverable delivery constraint, using this same budget. diff --git a/src/server/contractToolBindings.ts b/src/server/contractToolBindings.ts index a6a8ed57d6..4ae915da7f 100644 --- a/src/server/contractToolBindings.ts +++ b/src/server/contractToolBindings.ts @@ -13,7 +13,10 @@ import type { EvidenceWriter, } from "../application/investigation/InvestigationRecordPort.js"; import type { AnalysisViewRequest } from "../domain/analysisView/analysisViewRequest.js"; -import { TOOL_CONTRACTS } from "../contracts/toolContracts.js"; +import { + toolContractEntry, + type TOOL_CONTRACTS, +} from "../contracts/toolContracts.js"; import type { ToolContract } from "../contracts/toolContractTypes.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import type { Evidence } from "../domain/evidence.js"; @@ -541,11 +544,22 @@ export const registerContractTools = ( > // The table's exact per-name types are checked where it is written. > = bindings as never; - const unbound = new Set(Object.keys(table)); - for (const contract of TOOL_CONTRACTS) { - const binding = table[contract.name]; + const matched: { + readonly contract: (typeof TOOL_CONTRACTS)[number]; + readonly index: number; + readonly binding: NonNullable<(typeof table)[string]>; + }[] = []; + const unbound: string[] = []; + for (const name of Object.keys(table)) { + const binding = table[name]; if (binding === undefined) continue; - unbound.delete(contract.name); + const entry = toolContractEntry(name); + if (entry === undefined) unbound.push(name); + else + matched.push({ contract: entry.contract, index: entry.index, binding }); + } + matched.sort((left, right) => left.index - right.index); + for (const { contract, binding } of matched) { if ( binding.provider !== undefined && binding.provider.operation !== contract.name @@ -661,8 +675,8 @@ export const registerContractTools = ( present(await handler(input, context)), ); } - if (unbound.size > 0) + if (unbound.length > 0) throw invariantViolation( - `MCP tool bindings name no registered contract: ${[...unbound].join(", ")}`, + `MCP tool bindings name no registered contract: ${unbound.join(", ")}`, ); }; diff --git a/src/server/sessionStatusTool.ts b/src/server/sessionStatusTool.ts index ea9e93ec6d..a1e00fcaf7 100644 --- a/src/server/sessionStatusTool.ts +++ b/src/server/sessionStatusTool.ts @@ -119,6 +119,8 @@ export const readSessionStatus = async ( context.mcpReq.signal, (family) => server.advertisesFamily(family), ); + // Snapshot the session only after readiness inspection finishes so + // session changes occurring before probe completion are reflected. status = await session.status({ signal: context.mcpReq.signal, detail: input.detail, diff --git a/src/server/toolResultEncoding.test.ts b/src/server/toolResultEncoding.test.ts index c0ca0a6c59..39229b99b7 100644 --- a/src/server/toolResultEncoding.test.ts +++ b/src/server/toolResultEncoding.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import { fc, it as fcIt } from "@fast-check/vitest"; import type { JsonValue } from "../domain/jsonValue.js"; import { @@ -125,3 +126,86 @@ describe("error text wire size", () => { ); }); }); + +describe("zero-allocation escaped JSON measurement parity", () => { + fcIt.prop([fc.string({ unit: "binary-ascii" })])( + "matches JSON.stringify and Buffer.byteLength across ASCII control and punctuation ranges", + (sample) => { + const candidate = { value: sample }; + const wire = JSON.stringify(projectedResult(candidate)); + const expected = Buffer.byteLength(wire); + const encoded = encodeToolResult(candidate, expected); + expect(encoded).toEqual({ + ok: true, + text: JSON.stringify(candidate), + bytes: expected, + }); + expect(encodeToolResult(candidate, expected - 1)).toMatchObject({ + ok: false, + bytesAtLeast: expected, + constraint: "receive-buffer", + }); + }, + ); + + fcIt.prop([ + fc.array( + fc.oneof( + fc.integer({ min: 0x00, max: 0x7f }), + fc.integer({ min: 0x80, max: 0x7ff }), + fc.integer({ min: 0x800, max: 0xffff }), + fc.integer({ min: 0xd800, max: 0xdfff }), + ), + { maxLength: 64 }, + ), + ])( + "matches JSON.stringify across arbitrary UTF-16 code units including unpaired surrogates", + (units) => { + const sample = String.fromCharCode(...units); + const candidate = { [sample]: sample }; + const wire = JSON.stringify(projectedResult(candidate)); + const expected = Buffer.byteLength(wire); + const encoded = encodeToolResult(candidate, expected); + expect(encoded).toEqual({ + ok: true, + text: JSON.stringify(candidate), + bytes: expected, + }); + expect(encodeToolResult(candidate, expected - 1)).toMatchObject({ + ok: false, + bytesAtLeast: expected, + }); + }, + ); + + it("matches every single C0 control character, non-BMP pair, and reversed surrogate edge case", () => { + const allControlChars = Array.from({ length: 32 }, (_, c) => + String.fromCharCode(c), + ).join(""); + const edgeStrings = [ + allControlChars, + '"\\/\b\f\n\r\t\x7f', + "\ud800", + "\udfff", + "\udfff\ud800", + "\ud800a\udfff", + "\ud83d\ude80\ud800\ud83d\ude80", + "é߀𐍈😀\ud800end", + ]; + for (const sample of edgeStrings) { + const candidate = { sample }; + const expected = Buffer.byteLength( + JSON.stringify(projectedResult(candidate)), + ); + expect(encodeToolResult(candidate, expected)).toEqual({ + ok: true, + text: JSON.stringify(candidate), + bytes: expected, + }); + expect(encodeToolResult(candidate, expected - 1)).toMatchObject({ + ok: false, + bytesAtLeast: expected, + }); + } + }); +}); diff --git a/src/server/toolResultEncoding.ts b/src/server/toolResultEncoding.ts index 7bd057ff15..6b1a0841df 100644 --- a/src/server/toolResultEncoding.ts +++ b/src/server/toolResultEncoding.ts @@ -91,6 +91,76 @@ export const measureMcpResultWithinBudget = ( return { ok: true, bytes }; }; +const measureJsonPart = ( + part: string, +): { + readonly rawBytes: number; + readonly escapedBytes: number; + readonly escapedCodeUnits: number; +} => { + let rawBytes = 0; + let escapedBytes = 0; + let escapedCodeUnits = 0; + const length = part.length; + for (let i = 0; i < length; i += 1) { + const code = part.charCodeAt(i); + if (code < 0x80) { + rawBytes += 1; + if ( + code === 0x22 || + code === 0x5c || + code === 0x08 || + code === 0x09 || + code === 0x0a || + code === 0x0c || + code === 0x0d + ) { + escapedBytes += 2; + escapedCodeUnits += 2; + } else if (code < 0x20) { + escapedBytes += 6; + escapedCodeUnits += 6; + } else { + escapedBytes += 1; + escapedCodeUnits += 1; + } + continue; + } + if (code < 0x800) { + rawBytes += 2; + escapedBytes += 2; + escapedCodeUnits += 1; + continue; + } + if (code >= 0xd800 && code <= 0xdbff) { + if (i + 1 < length) { + const next = part.charCodeAt(i + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + rawBytes += 4; + escapedBytes += 4; + escapedCodeUnits += 2; + i += 1; + continue; + } + } + rawBytes += 3; + escapedBytes += 6; + escapedCodeUnits += 6; + continue; + } + if (code >= 0xdc00 && code <= 0xdfff) { + rawBytes += 3; + escapedBytes += 6; + escapedCodeUnits += 6; + continue; + } + rawBytes += 3; + escapedBytes += 3; + escapedCodeUnits += 1; + } + return { rawBytes, escapedBytes, escapedCodeUnits }; +}; + /** Account for the delivered JSON representations before allocating the complete text. */ export const encodeToolResult = ( value: JsonValue, @@ -105,12 +175,9 @@ export const encodeToolResult = ( (targetContent ? TARGET_CONTENT_META_BYTES : 0); let codeUnits = bytes; for (const part of bufferedJsonParts(jsonParts(value))) { - const escapedPart = JSON.stringify(part); - bytes += - (structured ? Buffer.byteLength(part) : 0) + - Buffer.byteLength(escapedPart) - - 2; - codeUnits += (structured ? part.length : 0) + escapedPart.length - 2; + const measured = measureJsonPart(part); + bytes += (structured ? measured.rawBytes : 0) + measured.escapedBytes; + codeUnits += (structured ? part.length : 0) + measured.escapedCodeUnits; if (bytes > budgetBytes || codeUnits > MCP_RESULT_STRING_LIMIT) return { ok: false,