mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
perf(mcp/providers): eliminate ErrorEvidenceTransport double-encoding and redundant deep-clones (#13495)
* perf(mcp/providers): eliminate ErrorEvidenceTransport double-encoding and redundant deep-clones (#13493) * fix(mcp): preserve projected error encoding through SDK results
This commit is contained in:
1 parent
9a85100b59
commit
5b63cf16ee
9 files changed
+137
-27
No files matched your search
@@ -434,11 +434,7 @@ export const normalizeUnblobReport = (
|
||||
if (detail !== null)
|
||||
for (const problem of detail.extraction_reports) {
|
||||
diagnostics.push(
|
||||
extractionDiagnostic(
|
||||
path,
|
||||
detail.handler_name,
|
||||
jsonValueSchema.parse(problem),
|
||||
),
|
||||
extractionDiagnostic(path, detail.handler_name, problem),
|
||||
);
|
||||
}
|
||||
addBlobOrigin(path, parsed.id, {
|
||||
|
||||
@@ -36,7 +36,7 @@ import {
|
||||
swiftLargeStringLiteralOmissionSchema,
|
||||
} from "../domain/native/swiftStringLiteral.js";
|
||||
import { functionBodyEntryAgrees } from "../domain/native/functionBody.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { ownedJsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import type { EvidenceLocation } from "../domain/evidence.js";
|
||||
import {
|
||||
relationshipCoverageSchema,
|
||||
@@ -112,7 +112,7 @@ export const parseGhidraFunctionInput = (
|
||||
const parsed = inputSchemas[operation].safeParse(value);
|
||||
return parsed.success
|
||||
? ok(
|
||||
jsonObjectSchema.parse(
|
||||
ownedJsonObjectSchema.parse(
|
||||
Object.fromEntries(
|
||||
Object.entries(parsed.data).filter(
|
||||
([, value]) => value !== undefined,
|
||||
|
||||
@@ -90,7 +90,7 @@ import {
|
||||
providerRetryAction,
|
||||
type ProviderOperationHealth,
|
||||
} from "../domain/providerOperationHealth.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { ownedJsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { ConfigurationError } from "../domain/configurationErrors.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
@@ -1098,7 +1098,7 @@ export const createGhidraProviderClient = (input: {
|
||||
? ok(
|
||||
projectExecution(
|
||||
operation,
|
||||
jsonValueSchema.parse(attested.value),
|
||||
ownedJsonValueSchema.parse(attested.value),
|
||||
observation,
|
||||
),
|
||||
)
|
||||
@@ -1294,7 +1294,7 @@ export const createGhidraProviderClient = (input: {
|
||||
...executionMetadata,
|
||||
rawResult: called.value,
|
||||
};
|
||||
normalized = jsonValueSchema.parse({
|
||||
normalized = ownedJsonValueSchema.parse({
|
||||
...normalized,
|
||||
metadata_recovery: metadata,
|
||||
});
|
||||
|
||||
@@ -57,6 +57,7 @@ import { createEvidence } from "../domain/evidence.js";
|
||||
import { ownedJsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import {
|
||||
mcpResponseOverflowProjection,
|
||||
projectedErrorEncoding,
|
||||
type ToolResultDelivery,
|
||||
} from "./ToolResultDelivery.js";
|
||||
import { toolReturnsTargetContent } from "../contracts/toolEffects.js";
|
||||
@@ -502,9 +503,12 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer {
|
||||
input,
|
||||
normalized(context as ServerContext),
|
||||
);
|
||||
return await (this.analysisSettings === undefined
|
||||
const result = await (this.analysisSettings === undefined
|
||||
? invoke()
|
||||
: this.analysisSettings.run(invoke));
|
||||
if (request !== undefined)
|
||||
request.projectedErrorEncoding = projectedErrorEncoding(result);
|
||||
return result;
|
||||
} finally {
|
||||
request?.finishHandler();
|
||||
}
|
||||
@@ -799,7 +803,7 @@ class ErrorEvidenceTransport implements Transport {
|
||||
id !== undefined && this.pendingToolLists.has(id);
|
||||
try {
|
||||
const publish = async (): Promise<void> => {
|
||||
const recovered = this.recoverProtocolError(message, tool);
|
||||
const recovered = this.recoverProtocolError(message, tool, request);
|
||||
const advertised = rewritesOutputSchemas
|
||||
? presentOutputSchemasForToolsList(
|
||||
recovered,
|
||||
@@ -892,6 +896,7 @@ class ErrorEvidenceTransport implements Transport {
|
||||
private recoverError(
|
||||
message: JSONRPCMessage,
|
||||
tool: string | undefined,
|
||||
request: McpToolRequest | undefined,
|
||||
): JSONRPCMessage {
|
||||
if (
|
||||
!isJSONRPCResultResponse(message) ||
|
||||
@@ -905,8 +910,19 @@ class ErrorEvidenceTransport implements Transport {
|
||||
const targetContent =
|
||||
carriesTargetContentMarker(message.result) ||
|
||||
(tool !== undefined && toolReturnsTargetContent(tool));
|
||||
// SDK validation failures have no structured carrier. Size their existing
|
||||
// text-only result without serializing the complete JSON-RPC message.
|
||||
// The SDK can project a new result object. Reuse only the handler encoding
|
||||
// for this request whose text and delivery requirements survived projection.
|
||||
const preencoded = request?.projectedErrorEncoding;
|
||||
const [content] = message.result.content;
|
||||
if (
|
||||
preencoded !== undefined &&
|
||||
preencoded.budgetBytes === budget &&
|
||||
preencoded.targetContent === targetContent &&
|
||||
message.result.content.length === 1 &&
|
||||
content?.type === "text" &&
|
||||
content.text === preencoded.text
|
||||
)
|
||||
return message;
|
||||
const isStructured = message.result.structuredContent !== undefined;
|
||||
const structured = isStructured
|
||||
? ownedJsonObjectSchema.parse(message.result.structuredContent)
|
||||
@@ -1190,8 +1206,9 @@ class ErrorEvidenceTransport implements Transport {
|
||||
private recoverProtocolError(
|
||||
message: JSONRPCMessage,
|
||||
tool: string | undefined,
|
||||
request: McpToolRequest | undefined,
|
||||
): JSONRPCMessage {
|
||||
const recovered = this.recoverError(message, tool);
|
||||
const recovered = this.recoverError(message, tool, request);
|
||||
if (
|
||||
!isJSONRPCErrorResponse(recovered) ||
|
||||
tool === undefined ||
|
||||
|
||||
@@ -14,12 +14,14 @@ import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
import { callerAnalysisParameters } from "../application/AnalysisInput.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { ProjectedErrorEncoding } from "./ToolResultDelivery.js";
|
||||
|
||||
const currentRequest = new AsyncLocalStorage<McpToolRequest>();
|
||||
|
||||
/** One SDK request owns validation, cancellation and its publication boundary. */
|
||||
export class McpToolRequest {
|
||||
readonly cancellation = new AbortController();
|
||||
projectedErrorEncoding?: ProjectedErrorEncoding | undefined;
|
||||
readonly #parameterSelections = new WeakMap<
|
||||
object,
|
||||
{
|
||||
|
||||
@@ -159,6 +159,20 @@ const overflowNextStep = (
|
||||
};
|
||||
|
||||
/** Immutable encoding and recovery policy shared by one MCP server. */
|
||||
/** The encoding already computed by `ToolResultDelivery` for a structured error result. */
|
||||
export interface ProjectedErrorEncoding {
|
||||
readonly budgetBytes: number;
|
||||
readonly targetContent: boolean;
|
||||
readonly text: string;
|
||||
}
|
||||
|
||||
const projectedErrorEncodings = new WeakMap<object, ProjectedErrorEncoding>();
|
||||
|
||||
/** Return the `ToolResultDelivery` encoding stamped on this exact error result, if any. */
|
||||
export const projectedErrorEncoding = (
|
||||
result: object,
|
||||
): ProjectedErrorEncoding | undefined => projectedErrorEncodings.get(result);
|
||||
|
||||
export class ToolResultDelivery {
|
||||
readonly maximumResponseBytes: number;
|
||||
readonly resultBudgetBytes: number;
|
||||
@@ -465,12 +479,19 @@ export class ToolResultDelivery {
|
||||
}
|
||||
// The transport retains an oversized projected error before replacing it
|
||||
// with a recoverable delivery constraint, using this same budget.
|
||||
return {
|
||||
const result: CallToolResult = {
|
||||
content: encoded.ok ? [{ type: "text", text: encoded.text }] : [],
|
||||
structuredContent,
|
||||
isError: true,
|
||||
...(targetContent ? { _meta: TARGET_CONTENT_RESULT_META } : {}),
|
||||
};
|
||||
if (encoded.ok)
|
||||
projectedErrorEncodings.set(result, {
|
||||
budgetBytes: this.resultBudgetBytes,
|
||||
targetContent,
|
||||
text: encoded.text,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
private successResult(
|
||||
|
||||
@@ -134,11 +134,7 @@ import { toolContract } from "../contracts/toolContracts.js";
|
||||
import { redactExplicitFailure } from "../domain/explicitSensitiveFailure.js";
|
||||
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
jsonValueSchema,
|
||||
ownedJsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "../domain/jsonValue.js";
|
||||
import { ownedJsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import {
|
||||
readGuidanceSection,
|
||||
searchGuidance,
|
||||
@@ -460,7 +456,7 @@ const analysisViewOverflowSource = (input: unknown): JsonValue | undefined => {
|
||||
const jsonValueResult = <Error>(
|
||||
result: Result<unknown, Error>,
|
||||
): Result<JsonValue, Error> =>
|
||||
result.ok ? ok(jsonValueSchema.parse(result.value)) : result;
|
||||
result.ok ? ok(ownedJsonValueSchema.parse(result.value)) : result;
|
||||
|
||||
type Bind<Service> = (
|
||||
service: Service,
|
||||
|
||||
@@ -25,7 +25,7 @@ import type {
|
||||
ClientFeatureAvailability,
|
||||
ToolAvailability,
|
||||
} from "../contracts/toolOutputSchemaPrimitives.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { ownedJsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { createServerIdentity } from "../process/ServerIdentity.js";
|
||||
import { mcpClientMetadata } from "./mcpClientMetadata.js";
|
||||
import type { AvailabilityPolicy } from "../application/CapabilityInventory.js";
|
||||
@@ -130,7 +130,7 @@ export const readSessionStatus = async (
|
||||
if (!(cause instanceof AnalysisError)) throw cause;
|
||||
return err(cause);
|
||||
}
|
||||
const statusObject = jsonObjectSchema.parse(status);
|
||||
const statusObject = ownedJsonObjectSchema.parse(status);
|
||||
// Availability is derived from the complete provider facts: an
|
||||
// advertised composed tool still depends on direct operations the
|
||||
// registration hides. Advertisement narrows only the public report.
|
||||
@@ -199,7 +199,7 @@ const projectSessionStatus = (options: {
|
||||
readonly serverIdentity: ReturnType<typeof createServerIdentity>;
|
||||
readonly clientFeatures: ClientFeatureAvailability;
|
||||
}) =>
|
||||
jsonObjectSchema.parse({
|
||||
ownedJsonObjectSchema.parse({
|
||||
...options.status,
|
||||
detail: options.detail,
|
||||
...(options.detail === "summary"
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import {
|
||||
Client,
|
||||
InMemoryTransport,
|
||||
isInitializeRequest,
|
||||
SUPPORTED_PROTOCOL_VERSIONS,
|
||||
} from "@modelcontextprotocol/client";
|
||||
import {
|
||||
STDIO_DEFAULT_MAX_BUFFER_SIZE,
|
||||
type CallToolResult,
|
||||
} from "@modelcontextprotocol/server";
|
||||
import { expect, it } from "vitest";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
|
||||
@@ -13,6 +18,7 @@ import { EvidenceIntegrityError } from "../../../src/domain/evidenceErrors.js";
|
||||
import type { Evidence } from "../../../src/domain/evidence.js";
|
||||
import { err, ok } from "../../../src/domain/result.js";
|
||||
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
|
||||
import * as toolResultEncoding from "../../../src/server/toolResultEncoding.js";
|
||||
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
|
||||
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
|
||||
|
||||
@@ -37,6 +43,78 @@ const failureWithName = (
|
||||
targetContent,
|
||||
);
|
||||
|
||||
it.each(SUPPORTED_PROTOCOL_VERSIONS)(
|
||||
"reuses a projected error through MCP %s and re-encodes budget or provenance mismatches",
|
||||
async (version) => {
|
||||
const server = new EvidenceMcpServer(
|
||||
{ name: "projected-error-server", version: "1" },
|
||||
{ capabilities: {} },
|
||||
undefined,
|
||||
delivery,
|
||||
);
|
||||
const smaller = createToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE / 2);
|
||||
server.registerTool(
|
||||
"record_unknown",
|
||||
{ inputSchema: z.object({}) },
|
||||
async () => failureWithName(0),
|
||||
);
|
||||
server.registerTool(
|
||||
"export_evidence_bundle",
|
||||
{ inputSchema: z.object({}) },
|
||||
async () => failureWithName(0, false, smaller),
|
||||
);
|
||||
server.registerTool(
|
||||
"list_strings",
|
||||
{ inputSchema: z.object({}) },
|
||||
async () => failureWithName(0),
|
||||
);
|
||||
const client = new Client(
|
||||
{ name: "projected-error-client", version: "1" },
|
||||
{ jsonSchemaValidator: createMcpSchemaValidation() },
|
||||
);
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const send = clientTransport.send.bind(clientTransport);
|
||||
const initialize = vi
|
||||
.spyOn(clientTransport, "send")
|
||||
.mockImplementation((message, options) =>
|
||||
send(
|
||||
isInitializeRequest(message)
|
||||
? {
|
||||
...message,
|
||||
params: { ...message.params, protocolVersion: version },
|
||||
}
|
||||
: message,
|
||||
options,
|
||||
),
|
||||
);
|
||||
const encode = vi.spyOn(toolResultEncoding, "encodeToolResult");
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
expect(client.getNegotiatedProtocolVersion()).toBe(version);
|
||||
for (const [name, encodings] of [
|
||||
["record_unknown", 1],
|
||||
["export_evidence_bundle", 2],
|
||||
["list_strings", 2],
|
||||
] as const) {
|
||||
encode.mockClear();
|
||||
const result = await client.callTool({ name, arguments: {} });
|
||||
expect(parseMcpToolError(result)).toMatchObject({
|
||||
error: { code: "invalid_request" },
|
||||
});
|
||||
expect(encode).toHaveBeenCalledTimes(encodings);
|
||||
if (name === "list_strings")
|
||||
expect(result._meta).toEqual(UNTRUSTED_TARGET_CONTENT);
|
||||
}
|
||||
} finally {
|
||||
initialize.mockRestore();
|
||||
encode.mockRestore();
|
||||
await Promise.all([client.close(), server.close()]);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// The delivered error carries its JSON once, as text, so only a diagnostic
|
||||
// larger than the whole budget is oversized.
|
||||
const oversizedFailure = () =>
|
||||
|
||||
Reference in new issue
Block a user