Files
rea/src/server/EvidenceMcpServer.ts
T
Lluís Ariño 85e124253a feat(server): frame analysis-target content as untrusted data (#1908)
* feat(server): frame analysis-target content as untrusted data

Strings, decompiled code, page text, scripts, captures and logs returned
by REA originate from the analysed target, which can embed text aimed at
the agent. Nothing marked that content, so a prompt injection inside a
binary or page could steer the agent toward tools that run code.

- Server instructions now state that target-derived tool output is data,
  never instructions, and that any request in it to run, install,
  download or send something is a prompt-injection attempt to report.
- Tool contracts declare returnsTargetContent. It is on by default; only
  seven tools whose results hold REA session state or caller-supplied
  values (binary_session, close_binary, export_evidence_bundle,
  record_unknown, update_unknown, inspect_adb_client,
  inspect_apktool_client) are audited exceptions, so new tools start
  marked.
- Successful results of marked tools carry
  _meta.provenance = { untrusted_content: true, source: "analysis_target" }.
  content and structuredContent are unchanged, and the response budget
  accounts for the fixed marker bytes.

Tests cover the encoding and budget accounting, the audited exception
list against the contract catalog, and an in-memory MCP client that sees
the instructions and the marker on a marked tool but not on
binary_session.

* fix(server): mark failed target-content results as untrusted too

The untrusted provenance marker was attached only on the success branch
of ToolResultDelivery, but failures can carry target-derived text as
well: error messages, captured output, and partial observations such as
the terminal frames a failed capture_process_scenario retains in
partial_observation. A host gating later process or device actions on the
marker would have treated an adversarial error payload as trusted.

Every error path in src/server now carries the failing tool's provenance:
- toErrorToolResult and toRecordedPartialErrorToolResult take the tool's
  target-content flag explicitly, so each caller is audited by the type
  checker; toCallToolResult, toEvidenceToolResult (recording failure), the
  response-budget error that replaces an oversized success, and the
  Electron partial-evidence path pass contract.returnsTargetContent.
- Admission failures in runAdmittedToolOperation resolve the flag from the
  tool name through the new toolReturnsTargetContent, the same predicate
  the contract metadata uses; unknown names stay marked.
- The transport's oversized-error replacement keeps the original's marker
  and counts it in its budget check, matching the projected error.
- Errors the MCP SDK builds itself (input validation, thrown handlers) are
  marked in the transport for target-content tools only.

Error encoding accounts for the marker bytes exactly as success encoding
does. docs/mcp-contracts.md now states that error results carry the
marker. Tests cover marked and unmarked error results, the
capture_process_scenario partial-observation errors in-process and over
the SDK transport, the recorded partial-evidence path, the budget
replacement, the oversized-error replacement, and SDK validation errors
for a marked and a content-free tool.

* fix(contracts): mark session status, close and client probes as target content

The content-free exception set was audited against successful results
only. Now that failures carry the marker too, every exception was
re-audited against its error paths with one question: can the result
include text produced by an external process, provider or device, or
stored content REA did not author?

Removed from TARGET_CONTENT_FREE_TOOLS:
- close_binary: a failed provider cleanup (GhidraClient cleanup error via
  createGhidraDiagnostics) projects the launcher's captured stdout and
  stderr, which can contain target-derived log text.
- binary_session: capability status reports runtime unavailability as the
  provider error message (ProviderAdapterError and similar), and the
  provider candidate and Android availability diagnostics include probe
  output such as the apktool stderr excerpt.
- inspect_adb_client: the success result carries the version and
  installed path parsed from `adb version` stdout, and a failed probe
  keeps a stderr_excerpt.
- inspect_apktool_client: the success result carries the first line of
  the launcher's `--version` output, and a failed probe keeps a
  stderr_excerpt.
- update_unknown: the new revision carries forward the stored question
  and domain, which an imported evidence bundle can supply; list_unknowns
  and get_evidence_bundle already return that data marked.

The set now holds only export_evidence_bundle (path, byte and record
counts; failures are filesystem, cancellation, or a fixed integrity
message) and record_unknown (the caller's input plus REA-computed ids
and digests; registry errors project only a reason code).

The conformance test pins the reduced set and asserts each removed tool
is marked. Tests that used binary_session as the unmarked example now use
record_unknown. docs/mcp-contracts.md lists the remaining exceptions and
why the removed tools stay marked.

* fix(contracts): include target-content policy in the catalog identity

createToolCatalog() and CATALOG_IDENTITY.tools projected every
client-visible contract field except returnsTargetContent. Because the
untrusted-content framing left schemas, effects, prompts, CLI names and
the package version unchanged, a same-version MCP process started before
the update digested equal to the new server and binary_session reported
it aligned although it never emits _meta.provenance.

Project the flag as returns_target_content in both the digested tool
catalog and CATALOG_IDENTITY.tools, and export createCatalogDigests so a
boundary test proves that toggling the flag on one tool changes the
tools and combined digests.
2026-10-13 06:06:02 +09:00

339 lines
12 KiB
TypeScript

import { AsyncLocalStorage } from "node:async_hooks";
import {
McpServer,
isCallToolResult,
isJSONRPCRequest,
isJSONRPCNotification,
isJSONRPCResultResponse,
type Implementation,
type Icon,
type JSONRPCMessage,
type McpServerOptions,
type RegisteredTool,
type RequestId,
type ScopeChallengeHandler,
type StandardSchemaWithJSON,
type ToolAnnotations,
type ToolCallback,
type Transport,
type TransportSendOptions,
} from "@modelcontextprotocol/server";
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
import { compactAdvertisedInputSchema } from "../contracts/compactInputSchema.js";
import { transformAdvertisedInputJsonSchema } from "../contracts/toolSchemaMetadata.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { createEvidence } from "../domain/evidence.js";
import { jsonObjectSchema } from "../domain/jsonValue.js";
import type { ToolResultDelivery } from "./toolResult.js";
import { toolReturnsTargetContent } from "../contracts/toolEffects.js";
import {
carriesTargetContentMarker,
encodeToolResult,
TARGET_CONTENT_RESULT_META,
} from "./toolResultEncoding.js";
/** Compact advertised input schemas within this per-schema byte budget. */
export interface CompactInputSchemaPresentation {
readonly budgetBytes: number;
}
const currentRequestSignal = new AsyncLocalStorage<AbortSignal>();
/** Signal for the completion request currently being dispatched by the SDK. */
export const currentMcpRequestSignal = (): AbortSignal | undefined =>
currentRequestSignal.getStore();
/** A Zod schema whose standard interface exposes a JSON Schema projection. */
const hasAdvertisedInputJsonSchema = (value: unknown): boolean => {
if (typeof value !== "object" || value === null) return false;
const standard = Reflect.get(value, "~standard");
if (typeof standard !== "object" || standard === null) return false;
const jsonSchema = Reflect.get(standard, "jsonSchema");
return (
typeof jsonSchema === "object" &&
jsonSchema !== null &&
Reflect.get(jsonSchema, "input") !== undefined
);
};
/** Bind oversized MCP error recovery to this server's Evidence ledger. */
export class EvidenceMcpServer extends McpServer {
constructor(
info: Implementation,
options: McpServerOptions,
private readonly recordEvidence:
| EvidenceWriter["recordEvidence"]
| undefined,
readonly delivery: ToolResultDelivery,
private readonly compactPresentation:
| CompactInputSchemaPresentation
| undefined = undefined,
) {
super(info, options);
}
/**
* Compact the advertised input schema of every registered tool when the
* compact profile is active. The registered canonical schema, its parser,
* and output schemas are untouched; only the advertised JSON Schema
* projection is rendered within the provider's per-schema size budget.
* The signatures mirror the SDK's registrations so call sites keep their
* inferred handler argument types.
*/
override registerTool<
OutputArgs extends StandardSchemaWithJSON,
InputArgs extends StandardSchemaWithJSON | undefined = undefined,
>(
name: string,
config: {
title?: string;
description?: string;
inputSchema?: InputArgs;
outputSchema?: OutputArgs;
annotations?: ToolAnnotations;
icons?: Icon[];
scopeChallenge?: ScopeChallengeHandler;
_meta?: Record<string, unknown>;
},
callback: ToolCallback<InputArgs>,
): RegisteredTool {
const budget = this.compactPresentation?.budgetBytes;
const inputSchema =
budget !== undefined &&
config !== undefined &&
hasAdvertisedInputJsonSchema(config.inputSchema)
? transformAdvertisedInputJsonSchema(
config.inputSchema as Parameters<
typeof transformAdvertisedInputJsonSchema
>[0],
(projected) =>
compactAdvertisedInputSchema(projected, budget).schema,
)
: undefined;
return super.registerTool(
name,
(inputSchema === undefined
? config
: { ...config, inputSchema }) as never,
callback as never,
);
}
/** Preserve the SDK transport lifecycle while retaining oversized errors. */
override connect(transport: Transport): Promise<void> {
return super.connect(
new ErrorEvidenceTransport(transport, this.recordEvidence, this.delivery),
);
}
}
class ErrorEvidenceTransport implements Transport {
onclose: Transport["onclose"];
onerror: Transport["onerror"];
onmessage: Transport["onmessage"];
readonly hasPerRequestStream?: boolean;
private readonly pendingTools = new Map<RequestId, string>();
private readonly pendingCompletions = new Map<RequestId, AbortController>();
constructor(
private readonly transport: Transport,
private readonly recordEvidence:
| EvidenceWriter["recordEvidence"]
| undefined,
private readonly delivery: ToolResultDelivery,
) {
if (transport.hasPerRequestStream !== undefined)
this.hasPerRequestStream = transport.hasPerRequestStream;
transport.onmessage = (message, extra) => {
if (
isJSONRPCRequest(message) &&
message.method === "tools/call" &&
typeof message.params?.["name"] === "string"
)
this.pendingTools.set(message.id, message.params["name"]);
if (isJSONRPCRequest(message) && message.method === "completion/complete")
this.pendingCompletions.set(message.id, new AbortController());
// The SDK suppresses replies after cancellation, so send() cannot release
// this bookkeeping. Keep transport authentication outside retained data.
if (
isJSONRPCNotification(message) &&
message.method === "notifications/cancelled"
) {
const id = message.params?.["requestId"];
if (typeof id === "string" || typeof id === "number") {
this.pendingTools.delete(id);
this.pendingCompletions.get(id)?.abort();
this.pendingCompletions.delete(id);
}
}
const completion =
isJSONRPCRequest(message) && message.method === "completion/complete"
? this.pendingCompletions.get(message.id)
: undefined;
if (completion === undefined) this.onmessage?.(message, extra);
else
currentRequestSignal.run(completion.signal, () =>
this.onmessage?.(message, extra),
);
};
transport.onerror = (error) => this.onerror?.(error);
transport.onclose = () => {
this.pendingTools.clear();
for (const completion of this.pendingCompletions.values())
completion.abort();
this.pendingCompletions.clear();
this.onclose?.();
};
}
get sessionId(): string | undefined {
return this.transport.sessionId;
}
set sessionId(value: string | undefined) {
this.transport.sessionId = value;
}
start(): Promise<void> {
return this.transport.start();
}
async close(): Promise<void> {
try {
await this.transport.close();
} finally {
this.pendingTools.clear();
for (const completion of this.pendingCompletions.values())
completion.abort();
this.pendingCompletions.clear();
}
}
setProtocolVersion(version: string): void {
this.transport.setProtocolVersion?.(version);
}
setSupportedProtocolVersions(versions: string[]): void {
this.transport.setSupportedProtocolVersions?.(versions);
}
async send(
message: JSONRPCMessage,
options?: TransportSendOptions,
): Promise<void> {
const id =
"id" in message &&
(typeof message.id === "string" || typeof message.id === "number")
? message.id
: undefined;
const tool = id === undefined ? undefined : this.pendingTools.get(id);
try {
const recovered = this.recoverError(message, tool);
if (
isJSONRPCResultResponse(recovered) &&
isCallToolResult(recovered.result) &&
recovered.result.isError === true
) {
// Keep the complete typed JSON in content. Error projections are not
// success outputSchema data; oversized recovery must consume their
// private structured carrier before it is removed from the wire.
const { structuredContent: _diagnostic, ...result } = recovered.result;
// Errors the SDK builds itself (input validation, a thrown handler)
// bypass ToolResultDelivery; mark them for target-content tools too.
const marked =
tool !== undefined &&
toolReturnsTargetContent(tool) &&
!carriesTargetContentMarker(result)
? {
...result,
_meta: { ...result._meta, ...TARGET_CONTENT_RESULT_META },
}
: result;
await this.transport.send({ ...recovered, result: marked }, options);
} else await this.transport.send(recovered, options);
} finally {
if (!isJSONRPCRequest(message) && id !== undefined) {
this.pendingTools.delete(id);
this.pendingCompletions.delete(id);
}
}
}
private recoverError(
message: JSONRPCMessage,
tool: string | undefined,
): JSONRPCMessage {
if (
!isJSONRPCResultResponse(message) ||
!isCallToolResult(message.result) ||
message.result.isError !== true ||
message.result.structuredContent === undefined
)
return message;
const structured = jsonObjectSchema.parse(message.result.structuredContent);
const budget = this.delivery.resultBudgetBytes;
// Count the provenance marker exactly as the projected error did, and keep
// it on the replacement: the retained original may hold target content.
const targetContent = carriesTargetContentMarker(message.result);
// The delivered error omits structuredContent, so only its text counts.
const encoded = encodeToolResult(structured, budget, "text", targetContent);
if (encoded.ok) return message;
const operation = tool ?? "mcp_tool_error";
const originalError = analysisErrorProjectionSchema.safeParse(
structured["error"],
);
// Retain the already projected diagnostic. Transport authentication and raw
// request arguments are deliberately excluded: the application owns their
// explicit sensitivity policy, and its error projection is authoritative.
const evidence = createEvidence(
undefined,
{ id: "rea-mcp", name: "REA MCP delivery", version: "1" },
{
operation: "mcp_tool_error",
parameters: { tool_name: operation },
result: structured,
rawResult: jsonObjectSchema.parse(message.result),
},
);
const recorded = this.recordEvidence?.(evidence);
const retained = recorded !== undefined && recorded.ok;
const failure = new AnalysisResourceConstraintError(
operation,
"transport",
"The tool failed, but its complete error response exceeds the MCP response budget.",
{
boundary: "mcp-response",
...(originalError.success
? { original_error_code: originalError.data.code }
: {}),
result_budget_bytes: budget,
response_bytes_at_least: encoded.bytesAtLeast,
constraint: encoded.constraint,
...(retained
? {
evidence_reference: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
}
: { retention: recorded === undefined ? "unavailable" : "failed" }),
...(recorded !== undefined && !recorded.ok
? { retention_error: projectAnalysisError(recorded.error) }
: {}),
},
{
remediationAction: retained
? "Export the retained original error through export_evidence_bundle to a caller-selected path. The connection remains usable."
: "Restart REA with a larger REA_MCP_MAX_RESPONSE_BYTES and matching client receive buffer, then retry. The original error could not be retained by this server.",
},
);
return {
...message,
result: this.delivery.toErrorToolResult(failure, targetContent),
};
}
}