fix(mcp): deliver tool errors within advertised schema contracts

Retain complete typed JSON error content while omitting non-conforming
structured errors at the public transport boundary. Recover oversized
diagnostics into Evidence before removing their private structured carrier.
Update schema-validated client readers and cover actual stdio delivery.

Closes #1261

Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
This commit is contained in:
N0zoM1z0
2026-10-09 12:26:27 +00:00
parent c8544b1574
commit da606ff777
50 changed files with 295 additions and 139 deletions
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -67,8 +68,8 @@ for (const { jarConfigured, setting } of [
arguments: { path: apk },
});
expect(response.isError).toBe(true);
expect(response.structuredContent).toEqual({ error: cliResult.json });
expect(JSON.stringify(response.structuredContent)).toContain(setting);
expect(parseMcpToolError(response)).toEqual({ error: cliResult.json });
expect(JSON.stringify(parseMcpToolError(response))).toContain(setting);
},
);
@@ -92,8 +93,8 @@ cliTest.skipIf(process.platform !== "linux")(
arguments: { path },
});
expect(response.isError).toBe(true);
expect(response.structuredContent).toEqual({ error: cliResult.json });
expect(JSON.stringify(response.structuredContent)).toContain(
expect(parseMcpToolError(response)).toEqual({ error: cliResult.json });
expect(JSON.stringify(parseMcpToolError(response))).toContain(
"REA_BINWALK_COMMAND",
);
},
@@ -145,8 +146,8 @@ cliTest(
arguments: { path, output_directory: join(root, "output") },
});
expect(response.isError).toBe(true);
expect(response.structuredContent).toEqual({ error: cliResult.json });
expect(JSON.stringify(response.structuredContent)).toContain(
expect(parseMcpToolError(response)).toEqual({ error: cliResult.json });
expect(JSON.stringify(parseMcpToolError(response))).toContain(
"REA_WAKARU_COMMAND",
);
},
@@ -183,7 +184,7 @@ cliTest(
});
expect(result.exitCode).toBe(1);
expect(response.isError).toBe(true);
expect(response.structuredContent).toEqual({ error: result.json });
expect(parseMcpToolError(response)).toEqual({ error: result.json });
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
+4 -6
View File
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
@@ -164,7 +165,7 @@ it("retains an oversized selected observation and keeps subsequent views usable"
}),
}),
})
.parse(response.structuredContent).error.details
.parse(parseMcpToolError(response)).error.details
.reported_limits.evidence_reference;
expect(
session.evidenceById(reference.evidence_id)?.normalized_result,
@@ -222,11 +223,8 @@ it("returns a JavaScript summary without graph payloads from a retained referenc
view: { kind: "summary" },
},
});
expect(stale).toMatchObject({
isError: true,
structuredContent: {
error: { details: { reason: "missing" } },
},
expect(parseMcpToolError(stale)).toMatchObject({
error: { details: { reason: "missing" } },
});
});
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import type { Client } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
@@ -178,16 +179,13 @@ async function assertRejectedEvidenceReferences(
application: record,
},
});
expect(rejected).toMatchObject({
isError: true,
structuredContent: {
// A recorded Evidence with the wrong operation or predicate is an
// invalid caller input, not a provider failure.
error: {
code: "invalid_request",
category: "invalid_input",
retryable: true,
},
expect(parseMcpToolError(rejected)).toMatchObject({
// A recorded Evidence with the wrong operation or predicate is an
// invalid caller input, not a provider failure.
error: {
code: "invalid_request",
category: "invalid_input",
retryable: true,
},
});
}
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -62,7 +63,7 @@ it("inspects a standalone keyed archive through MCP with original object identit
arguments: { path: "other.plist" },
});
expect(rejected.isError).toBe(true);
expect(rejected.structuredContent).toMatchObject({
expect(parseMcpToolError(rejected)).toMatchObject({
error: {
code: "invalid_request",
details: {
@@ -81,7 +82,7 @@ it("inspects a standalone keyed archive through MCP with original object identit
arguments: { root: "missing" },
});
expect(missingRoot.isError).toBe(true);
expect(missingRoot.structuredContent).toMatchObject({
expect(parseMcpToolError(missingRoot)).toMatchObject({
error: {
code: "invalid_request",
details: {
+2 -1
View File
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -62,7 +63,7 @@ it.each([
arguments: {},
});
expect(result.isError).toBe(true);
expect(result.structuredContent).toEqual({
expect(parseMcpToolError(result)).toEqual({
error: {
code: "artifact_integrity_mismatch",
category: "integrity_mismatch",
+2 -1
View File
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, expect, it } from "vitest";
import { z } from "zod";
@@ -275,7 +276,7 @@ it("does not attach to a target outside the request's allowed origin scope", asy
},
});
expect(result.isError).toBe(true);
expect(result.structuredContent).toMatchObject({
expect(parseMcpToolError(result)).toMatchObject({
error: {
details: {
operation: "inspect_web_page",
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -130,7 +131,7 @@ describe("bundle comparison MCP integration", () => {
},
});
expect(result.isError).toBe(true);
expect(result.structuredContent).toMatchObject({
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "evidence_integrity_mismatch",
message: expect.stringContaining(
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { chmod, mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -107,7 +108,7 @@ it("traces dylib resolution for an opened app bundle and rejects a changed targe
arguments: {},
});
expect(changed.isError).toBe(true);
expect(JSON.stringify(changed.structuredContent)).toContain("integrity");
expect(JSON.stringify(parseMcpToolError(changed))).toContain("integrity");
});
});
@@ -126,7 +127,7 @@ it("rejects targets that are not Mach-O", async () => {
arguments: {},
});
expect(called.isError).toBe(true);
expect(called.structuredContent).toMatchObject({
expect(parseMcpToolError(called)).toMatchObject({
error: { code: "unsupported_target", category: "unsupported_target" },
});
});
@@ -153,7 +154,7 @@ it("reports target kinds that artifact operations cannot inspect as unsupported"
const open = { name: "open_binary", arguments: { path } };
expect((await client.callTool(open)).isError, path).not.toBe(true);
const called = await client.callTool({ name: operation, arguments: {} });
expect(called.structuredContent, operation).toMatchObject({
expect(parseMcpToolError(called), operation).toMatchObject({
error: {
code: "unsupported_target",
message: expect.stringContaining(`${operation} at ${path}`),
@@ -230,7 +231,7 @@ it.skipIf(process.getuid?.() === 0)(
arguments: {},
});
expect(called.isError).toBe(true);
expect(JSON.stringify(called.structuredContent)).toMatch(
expect(JSON.stringify(parseMcpToolError(called))).toMatch(
/Permission denied \(EACCES\)/u,
);
} finally {
@@ -442,7 +443,7 @@ it("reports caller-selected roots that cannot be traced as invalid input", async
arguments: { roots: ["Contents/MacOS/App", root] },
});
expect(called.isError, root).toBe(true);
expect(called.structuredContent, root).toMatchObject({
expect(parseMcpToolError(called), root).toMatchObject({
error: {
code: "invalid_request",
details: {
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { afterEach, describe, expect, it } from "vitest";
import {
@@ -109,7 +110,7 @@ describe("enhanced MCP tools", () => {
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toBe(
JSON.stringify(result.structuredContent),
JSON.stringify(parseMcpToolError(result)),
);
});
});
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { afterEach, describe, expect, it } from "vitest";
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
@@ -26,7 +27,7 @@ describe("analyze_function MCP producer validation", () => {
expect(result.isError).toBe(true);
expect(result.content).toContainEqual({
type: "text",
text: JSON.stringify(result.structuredContent),
text: JSON.stringify(parseMcpToolError(result)),
});
});
@@ -55,7 +56,7 @@ describe("analyze_function MCP producer validation", () => {
expect(result.isError).toBe(true);
expect(result.content).toContainEqual({
type: "text",
text: JSON.stringify(result.structuredContent),
text: JSON.stringify(parseMcpToolError(result)),
});
});
});
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { afterEach, describe, expect, it } from "vitest";
import { closeEnhancedToolResources, connect } from "./enhancedToolsHarness.js";
@@ -41,7 +42,7 @@ describe("enhanced MCP input validation", () => {
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toBe(
JSON.stringify(result.structuredContent),
JSON.stringify(parseMcpToolError(result)),
);
});
});
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import type { CallToolResult } from "@modelcontextprotocol/server";
import {
jsonValueSchema,
@@ -40,6 +41,8 @@ export const closeEnhancedToolResources = async (): Promise<void> => {
};
export const jsonResult = (result: CallToolResult): JsonValue => {
if (result.isError === true)
return jsonValueSchema.parse(parseMcpToolError(result));
if (result.structuredContent === undefined)
throw new Error("Tool result omitted structured content");
const structured = jsonValueSchema.safeParse(result.structuredContent);
+2 -1
View File
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { describe, expect, it } from "vitest";
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
@@ -52,7 +53,7 @@ it("rejects contradictory annotation readback across the provider and MCP bounda
},
});
expect(reply.isError).toBe(true);
expect(reply.structuredContent).toMatchObject({
expect(parseMcpToolError(reply)).toMatchObject({
error: { code: "unreadable_output" },
});
}
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { expect, it } from "vitest";
import { logCliCommand } from "../../../src/cliLogging.js";
@@ -66,7 +67,7 @@ it("preserves queue failure diagnostics through the provider, CLI adapter and SD
arguments: {},
});
expect(mcp.isError).toBe(true);
expect(mcp.structuredContent).toMatchObject({ error: parsed });
expect(parseMcpToolError(mcp)).toMatchObject({ error: parsed });
expect(mcp.content).toContainEqual(
expect.objectContaining({
type: "text",
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { expect, it } from "vitest";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { ok } from "../../../src/domain/result.js";
@@ -98,11 +99,11 @@ it("rejects contradictory provider output before emitting MCP Evidence", async (
arguments: probe.arguments,
});
expect(rejected.isError, probe.name).toBe(true);
expect(rejected.structuredContent).toMatchObject({
expect(parseMcpToolError(rejected)).toMatchObject({
error: { code: "unreadable_output" },
});
expect(rejected.structuredContent).not.toHaveProperty("evidence_id");
expect(rejected.structuredContent).not.toHaveProperty("result");
expect(parseMcpToolError(rejected)).not.toHaveProperty("evidence_id");
expect(parseMcpToolError(rejected)).not.toHaveProperty("result");
}
} finally {
await harness.close();
+2 -1
View File
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { describe, expect, it } from "vitest";
import { connectGhidraMcp } from "./ghidraMcpHarness.js";
@@ -28,7 +29,7 @@ describe("Ghidra MCP capability routing", () => {
arguments: { address: "0x1000", comment: "must not mutate" },
});
expect(denied.isError).toBe(true);
expect(denied.structuredContent).toMatchObject({
expect(parseMcpToolError(denied)).toMatchObject({
error: {
code: "capability_unavailable",
category: "unsupported_provider",
+4 -5
View File
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -230,11 +231,8 @@ const verifyManagedCatalogAndNativeWorkflow = async (
],
},
});
expect(wrong).toMatchObject({
isError: true,
structuredContent: {
error: { code: "evidence_integrity_mismatch" },
},
expect(parseMcpToolError(wrong)).toMatchObject({
error: { code: "evidence_integrity_mismatch" },
});
};
@@ -446,6 +444,7 @@ const verifyImport = async (
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (result.isError === true) return parseMcpToolError(result);
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -258,7 +259,7 @@ it.each([
});
expect(called.isError).toBe(true);
expect(called.structuredContent).toMatchObject({
expect(parseMcpToolError(called)).toMatchObject({
error: {
code: expectedCode,
details: {
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -40,7 +41,7 @@ it("rejects changed signature targets through MCP and accepts reopening the new
arguments: {},
});
expect(changed.isError).toBe(true);
expect(changed.structuredContent).toMatchObject({
expect(parseMcpToolError(changed)).toMatchObject({
error: { code: "artifact_changed", details: { path } },
});
expect((await open()).isError).not.toBe(true);
+2 -1
View File
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { Ajv2020 } from "ajv/dist/2020.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, describe, expect, it } from "vitest";
@@ -140,7 +141,7 @@ describe("official Hopper proxy tools", () => {
expect(result.isError).toBe(true);
expect(result.content[0]).toEqual({
type: "text",
text: JSON.stringify(result.structuredContent),
text: JSON.stringify(parseMcpToolError(result)),
});
});
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { McpServer } from "@modelcontextprotocol/server";
@@ -138,7 +139,7 @@ mcpTest.for(failedAdapters)(
arguments: example.input,
});
expect(unavailable.isError).toBe(true);
expect(unavailable.structuredContent).toMatchObject({
expect(parseMcpToolError(unavailable)).toMatchObject({
error: {
details: {
provider_id: providerId,
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import {
STDIO_DEFAULT_MAX_BUFFER_SIZE,
@@ -9,7 +10,8 @@ import { z } from "zod";
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
import type { EvidenceWriter } from "../../../src/application/investigation/InvestigationRecordPort.js";
import { EvidenceIntegrityError } from "../../../src/domain/evidenceErrors.js";
import { err } from "../../../src/domain/result.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 { toErrorToolResult } from "../../../src/server/toolResult.js";
@@ -26,6 +28,7 @@ const oversizedFailure = () =>
const exerciseDeliveryFailure = async (
recordEvidence: EvidenceWriter["recordEvidence"] | undefined,
retention: "retained" | "unavailable" | "failed",
) => {
const server = new EvidenceMcpServer(
{ name: "oversized-error-test", version: "1" },
@@ -54,7 +57,8 @@ const exerciseDeliveryFailure = async (
arguments: {},
});
expect(failure.isError).toBe(true);
expect(failure.structuredContent).toMatchObject({
expect(failure.structuredContent).toBeUndefined();
expect(parseMcpToolError(failure)).toMatchObject({
error: {
code: "resource_constraint",
details: {
@@ -73,8 +77,8 @@ const exerciseDeliveryFailure = async (
}),
}),
})
.parse(failure.structuredContent).error.details.reported_limits;
expect(failure.structuredContent).toMatchObject({
.parse(parseMcpToolError(failure)).error.details.reported_limits;
expect(parseMcpToolError(failure)).toMatchObject({
error: {
details: {
reported_limits: {
@@ -83,11 +87,17 @@ const exerciseDeliveryFailure = async (
},
},
});
expect(reportedLimits).not.toHaveProperty("evidence_reference");
expect(reportedLimits.retention).toBe(
recordEvidence === undefined ? "unavailable" : "failed",
);
if (recordEvidence !== undefined)
if (retention === "retained") {
expect(reportedLimits.evidence_reference).toMatchObject({
kind: "retained-evidence",
evidence_id: expect.any(String),
});
expect(reportedLimits).not.toHaveProperty("retention");
} else {
expect(reportedLimits).not.toHaveProperty("evidence_reference");
expect(reportedLimits.retention).toBe(retention);
}
if (retention === "failed")
expect(reportedLimits.retention_error).toMatchObject({
code: "evidence_integrity_mismatch",
});
@@ -106,10 +116,27 @@ const exerciseDeliveryFailure = async (
};
it("keeps the SDK connection usable when oversized-error retention is unavailable or fails", async () => {
await exerciseDeliveryFailure(undefined);
await exerciseDeliveryFailure(() =>
err(
new EvidenceIntegrityError("fixture ledger rejected the Evidence record"),
),
await exerciseDeliveryFailure(undefined, "unavailable");
await exerciseDeliveryFailure(
() =>
err(
new EvidenceIntegrityError(
"fixture ledger rejected the Evidence record",
),
),
"failed",
);
});
it("retains the complete oversized diagnostic before removing its private structured carrier", async () => {
const retained: Evidence[] = [];
await exerciseDeliveryFailure((evidence) => {
retained.push(evidence);
return ok("added");
}, "retained");
expect(retained).toHaveLength(1);
expect(retained[0]?.normalized_result).toEqual(
oversizedFailure().structuredContent,
);
expect(retained[0]?.raw_result).toEqual(oversizedFailure());
});
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -70,7 +71,7 @@ it("names differing comparison contract fields through MCP and the CLI", async (
),
expected: ["working_directory"],
};
expect(response.structuredContent).toMatchObject({
expect(parseMcpToolError(response)).toMatchObject({
error: { code: "invalid_request", details: { issues: [issue] } },
});
@@ -97,7 +98,7 @@ it("names the stale capture that exceeds max_capture_age_ms", async () => {
},
});
expect(response.isError).toBe(true);
expect(response.structuredContent).toMatchObject({
expect(parseMcpToolError(response)).toMatchObject({
error: {
code: "invalid_request",
details: {
@@ -146,7 +147,7 @@ it("names the side and constraint when Evidence is not a usable capture", async
name: "compare_process_captures",
arguments: { left: unrelated, right: capture },
});
expect(wrongKind.structuredContent).toMatchObject({
expect(parseMcpToolError(wrongKind)).toMatchObject({
error: {
code: "invalid_request",
details: {
@@ -170,7 +171,7 @@ it("names the side and constraint when Evidence is not a usable capture", async
right: { ...capture, parameters: { side: "changed" } },
},
});
expect(tampered.structuredContent).toMatchObject({
expect(parseMcpToolError(tampered)).toMatchObject({
error: {
code: "evidence_integrity_mismatch",
message: expect.stringContaining(
@@ -189,7 +190,7 @@ it("names the side and constraint when Evidence is not a usable capture", async
name: "compare_process_captures",
arguments: { left: capture, right: invalidResult },
});
expect(malformed.structuredContent).toMatchObject({
expect(parseMcpToolError(malformed)).toMatchObject({
error: {
code: "evidence_integrity_mismatch",
message: expect.stringContaining(
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -294,7 +295,7 @@ for (const name of providerNames)
for (const { expected: _expected, ...call } of consumerCalls(invalid)) {
const response = await client.callTool(call);
expect(response.isError, call.name).toBe(true);
expect(response.structuredContent, call.name).toMatchObject({
expect(parseMcpToolError(response), call.name).toMatchObject({
error: { code: "invalid_request" },
});
}
@@ -333,7 +334,7 @@ it("separately rejects a tampered digest before admission to any consumer or ses
)) {
const response = await client.callTool(call);
expect(response.isError, call.name).toBe(true);
expect(response.structuredContent).toMatchObject({
expect(parseMcpToolError(response)).toMatchObject({
error: { code: "invalid_request" },
});
}
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -233,4 +234,6 @@ const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({
});
const structured = (result: CallToolResult): Record<string, unknown> =>
z.record(z.string(), z.unknown()).parse(result.structuredContent);
result.isError === true
? parseMcpToolError(result)
: z.record(z.string(), z.unknown()).parse(result.structuredContent);
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
@@ -42,7 +43,7 @@ describe("reconstruction coverage MCP", () => {
},
});
expect(unknown.isError).toBe(true);
expect(unknown.structuredContent).toMatchObject({
expect(parseMcpToolError(unknown)).toMatchObject({
error: {
code: "invalid_request",
details: {
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, expect, it } from "vitest";
import { Ajv2020 } from "ajv/dist/2020.js";
@@ -136,15 +137,12 @@ it("keeps references session-scoped and expires them when close_binary clears th
},
};
const foreign = await second.client.callTool(request);
expect(foreign).toMatchObject({
isError: true,
structuredContent: {
error: {
details: {
evidence_id: application.evidence_id,
reason: "missing",
actual: null,
},
expect(parseMcpToolError(foreign)).toMatchObject({
error: {
details: {
evidence_id: application.evidence_id,
reason: "missing",
actual: null,
},
},
});
@@ -156,10 +154,9 @@ it("keeps references session-scoped and expires them when close_binary clears th
arguments: {},
});
expect(closed.isError).not.toBe(true);
expect(await first.client.callTool(request)).toMatchObject({
isError: true,
structuredContent: { error: { details: { reason: "missing" } } },
});
expect(parseMcpToolError(await first.client.callTool(request))).toMatchObject(
{ error: { details: { reason: "missing" } } },
);
for (const harness of [first, second]) {
const portable = await harness.client.callTool({
name: "trace_application_feature",
@@ -199,11 +196,8 @@ it("preserves validation for the referenced record's operation, predicate, and s
application: retained(record.evidence_id),
},
});
expect(response).toMatchObject({
isError: true,
structuredContent: {
error: { code: "invalid_request", category: "invalid_input" },
},
expect(parseMcpToolError(response)).toMatchObject({
error: { code: "invalid_request", category: "invalid_input" },
});
}
const tampered = {
+2 -1
View File
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -285,7 +286,7 @@ describe("active-target availability over MCP", () => {
name: "inspect_macho",
arguments: {},
});
expect(call.structuredContent).toMatchObject({
expect(parseMcpToolError(call)).toMatchObject({
error: { code: "target_unavailable" },
});
await openTarget(client, plist);
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, expect, it } from "vitest";
@@ -37,6 +38,7 @@ const text = (result: CallToolResult): string => {
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (result.isError === true) return parseMcpToolError(result);
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
@@ -61,7 +63,7 @@ it("projects remote failures without provider or bridge details", async () => {
category: "execution_failure",
},
});
expect(text(result)).toBe(JSON.stringify(result.structuredContent));
expect(text(result)).toBe(JSON.stringify(parseMcpToolError(result)));
});
it("lets the SDK validate a tool call before invoking its handler", async () => {
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, expect, it } from "vitest";
@@ -68,6 +69,7 @@ const providerWithCapabilities = (
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (result.isError === true) return parseMcpToolError(result);
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, expect, it } from "vitest";
@@ -35,6 +36,7 @@ const connect = async (analysis: AnalysisOperationPort) => {
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (result.isError === true) return parseMcpToolError(result);
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
+2
View File
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { readFile, realpath, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -492,6 +493,7 @@ const text = (result: CallToolResult): string => {
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (result.isError === true) return parseMcpToolError(result);
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
+2
View File
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -151,6 +152,7 @@ export const snapshotAndRecordUnknown = async (
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (result.isError === true) return parseMcpToolError(result);
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
@@ -0,0 +1,50 @@
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
import { z } from "zod";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
it("delivers typed tool failures without violating the advertised success schema over stdio", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-tool-error-schema-"));
onTestFinished(() => rm(root, { recursive: true, force: true }));
const missing = join(root, "not-present.bin");
const { client, call } = await connectLocalToolsMcp();
const tools = (await client.listTools()).tools;
const failures: string[] = [];
const requests = [
{ name: "list_documents", arguments: {} },
{ name: "open_binary", arguments: { path: missing } },
{
name: "analyze_javascript_application",
arguments: { input_path: missing },
},
{ name: "inspect_artifact", arguments: {} },
];
for (const request of requests) {
const tool = tools.find(({ name }) => name === request.name);
if (tool?.outputSchema === undefined)
throw new Error(`${request.name} omitted its output schema`);
const reply = await client.callTool(request);
const diagnostic = parseMcpToolError(reply);
expect(diagnostic.error.message, request.name).not.toBe("");
if ("path" in request.arguments || "input_path" in request.arguments)
expect(JSON.stringify(diagnostic), request.name).toContain(missing);
if (reply.structuredContent !== undefined) {
const validate = new Ajv2020({
strict: false,
validateFormats: false,
}).compile(z.record(z.string(), z.unknown()).parse(tool.outputSchema));
if (!validate(reply.structuredContent)) failures.push(request.name);
}
}
expect(failures).toEqual([]);
const successful = await call("get_evidence_bundle", {});
expect(successful.isError).not.toBe(true);
expect(successful.structuredContent).toBeDefined();
await client.ping();
});
@@ -1,3 +1,4 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
@@ -93,7 +94,7 @@ it("publishes valid SDK schemas and retains historical inline Evidence with the
arguments: { ...args, sensitive_values: ["secret"], mysecret: true },
});
expect(invalidSensitive.isError).toBe(true);
expect(invalidSensitive.structuredContent).toMatchObject({
expect(parseMcpToolError(invalidSensitive)).toMatchObject({
error: { code: "invalid_request", details: { issues: [{ path: [] }] } },
});
expect(JSON.stringify(invalidSensitive)).not.toContain("secret");
+1 -5
View File
@@ -47,11 +47,7 @@ export async function connectLocalToolsMcp() {
const call = async (name: string, arguments_: Record<string, unknown>) => {
const response = await client.callTool({ name, arguments: arguments_ });
const validate = validators.get(name);
if (
response.isError !== true &&
response.structuredContent !== undefined &&
validate !== undefined
)
if (response.structuredContent !== undefined && validate !== undefined)
expect(
validate(response.structuredContent),
JSON.stringify(validate.errors),
+16
View File
@@ -0,0 +1,16 @@
import type { CallToolResult } from "@modelcontextprotocol/server";
import { expect } from "vitest";
import { z } from "zod";
import { analysisErrorProjectionSchema } from "../../src/contracts/errorSchemas.js";
/** Read and validate the complete typed diagnostic in an MCP tool failure. */
export function parseMcpToolError(result: CallToolResult) {
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
if (text?.type !== "text") throw new Error("Tool error omitted text content");
return z
.object({ error: analysisErrorProjectionSchema })
.strict()
.parse(JSON.parse(text.text));
}