Merge pull request #461 from morluto/agent/comprehensive-repository-audit
fix: harden evidence lifecycle and MCP contracts
This commit is contained in:
+151
-77
@@ -96,84 +96,46 @@ const installSessionToolAvailability = (
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Construct one MCP server without acquiring subprocess resources.
|
||||
* Supplying a session adds target lifecycle tools; omitting it retains the
|
||||
* fixed-target seam used by focused tests and embedders.
|
||||
*/
|
||||
export const createServer = (
|
||||
analysis: AnalysisOperationPort,
|
||||
session?: BinarySessionPort,
|
||||
options: CreateServerOptions = {},
|
||||
): McpServer => {
|
||||
const startedAt = new Date().toISOString();
|
||||
const logger = options.logger ?? silentLogger;
|
||||
const permissionAuthority =
|
||||
options.permissionAuthority?.createConnectionAuthority();
|
||||
const processCaptureStateCodec =
|
||||
createRequestStateCodec<ProcessCaptureElicitationState>({
|
||||
key: randomBytes(32),
|
||||
ttlSeconds: PROCESS_CAPTURE_ELICITATION_POLICY.stateTtlSeconds,
|
||||
});
|
||||
const server = new McpServer(
|
||||
{
|
||||
name: PRODUCT_IDENTITY.mcpServerKey,
|
||||
version: PRODUCT_IDENTITY.packageVersion,
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
tools: { listChanged: true },
|
||||
resources: { listChanged: true, subscribe: true },
|
||||
},
|
||||
inputRequired: {
|
||||
maxRounds: 3,
|
||||
roundTimeoutMs: PROCESS_CAPTURE_ELICITATION_POLICY.roundTimeoutMs,
|
||||
},
|
||||
requestState: { verify: processCaptureStateCodec.verify },
|
||||
instructions:
|
||||
session === undefined
|
||||
? ACTIVE_TARGET_INSTRUCTIONS
|
||||
: TARGET_FREE_INSTRUCTIONS,
|
||||
},
|
||||
);
|
||||
const dynamicTools = installSessionToolAvailability(server, session, options);
|
||||
server.server.onclose = () => {
|
||||
permissionAuthority?.clearSessionGrants();
|
||||
};
|
||||
if (dynamicTools !== undefined)
|
||||
server.server.oninitialized = () => server.sendToolListChanged();
|
||||
session?.onAvailabilityChanged?.(() => server.sendToolListChanged());
|
||||
registerServerIdentityResource(server, startedAt);
|
||||
const toolLogger = logger.child({ layer: "server" });
|
||||
const { activeTarget, recordEvidence, recordEvidenceWithUnknown } =
|
||||
createSessionRecorders(server, session);
|
||||
const processCaptureElicitation = {
|
||||
stateCodec: processCaptureStateCodec,
|
||||
supported: (context: {
|
||||
readonly mcpReq: {
|
||||
readonly envelope?: Readonly<Record<string, unknown>>;
|
||||
};
|
||||
}) => {
|
||||
const envelope = context.mcpReq.envelope;
|
||||
const version = envelope?.[PROTOCOL_VERSION_META_KEY];
|
||||
const capabilities = envelope?.[CLIENT_CAPABILITIES_META_KEY];
|
||||
return (
|
||||
typeof version === "string" &&
|
||||
PROCESS_CAPTURE_ELICITATION_POLICY.protocolVersions.some(
|
||||
(supported) => supported === version,
|
||||
) &&
|
||||
isRecord(capabilities) &&
|
||||
isRecord(capabilities.elicitation) &&
|
||||
capabilities.elicitation.form !== undefined
|
||||
);
|
||||
},
|
||||
now: Date.now,
|
||||
consumedNonces: new Map<string, number>(),
|
||||
};
|
||||
type ProcessCaptureElicitation = {
|
||||
readonly stateCodec: ReturnType<
|
||||
typeof createRequestStateCodec<ProcessCaptureElicitationState>
|
||||
>;
|
||||
readonly supported: (context: {
|
||||
readonly mcpReq: {
|
||||
readonly envelope?: Readonly<Record<string, unknown>>;
|
||||
};
|
||||
}) => boolean;
|
||||
readonly now: typeof Date.now;
|
||||
readonly consumedNonces: Map<string, number>;
|
||||
};
|
||||
|
||||
const createProcessCaptureElicitation = (
|
||||
stateCodec: ProcessCaptureElicitation["stateCodec"],
|
||||
): ProcessCaptureElicitation => ({
|
||||
stateCodec,
|
||||
supported: (context) => {
|
||||
const envelope = context.mcpReq.envelope;
|
||||
const version = envelope?.[PROTOCOL_VERSION_META_KEY];
|
||||
const capabilities = envelope?.[CLIENT_CAPABILITIES_META_KEY];
|
||||
return (
|
||||
typeof version === "string" &&
|
||||
PROCESS_CAPTURE_ELICITATION_POLICY.protocolVersions.some(
|
||||
(supported) => supported === version,
|
||||
) &&
|
||||
isRecord(capabilities) &&
|
||||
isRecord(capabilities.elicitation) &&
|
||||
capabilities.elicitation.form !== undefined
|
||||
);
|
||||
},
|
||||
now: Date.now,
|
||||
consumedNonces: new Map<string, number>(),
|
||||
});
|
||||
|
||||
const createOptionalProviderLoader = (options: CreateServerOptions) => {
|
||||
let optionalProviders:
|
||||
| ReturnType<NonNullable<CreateServerOptions["loadOptionalProviders"]>>
|
||||
| undefined;
|
||||
const loadOptionalProviders = () => {
|
||||
return () => {
|
||||
optionalProviders ??= options
|
||||
.loadOptionalProviders?.()
|
||||
.catch((cause: unknown) => {
|
||||
@@ -182,7 +144,43 @@ export const createServer = (
|
||||
});
|
||||
return optionalProviders;
|
||||
};
|
||||
const lazyTools = new LazyToolCatalog(
|
||||
};
|
||||
|
||||
const createLazyToolCatalog = ({
|
||||
server,
|
||||
analysis,
|
||||
session,
|
||||
options,
|
||||
toolLogger,
|
||||
permissionAuthority,
|
||||
activeTarget,
|
||||
recordEvidence,
|
||||
recordEvidenceWithUnknown,
|
||||
availabilityPolicy,
|
||||
startedAt,
|
||||
processCaptureElicitation,
|
||||
}: {
|
||||
readonly server: McpServer;
|
||||
readonly analysis: AnalysisOperationPort;
|
||||
readonly session: BinarySessionPort | undefined;
|
||||
readonly options: CreateServerOptions;
|
||||
readonly toolLogger: Logger;
|
||||
readonly permissionAuthority: PermissionAuthority | undefined;
|
||||
readonly activeTarget: ReturnType<
|
||||
typeof createSessionRecorders
|
||||
>["activeTarget"];
|
||||
readonly recordEvidence: ReturnType<
|
||||
typeof createSessionRecorders
|
||||
>["recordEvidence"];
|
||||
readonly recordEvidenceWithUnknown: ReturnType<
|
||||
typeof createSessionRecorders
|
||||
>["recordEvidenceWithUnknown"];
|
||||
readonly availabilityPolicy: CreateServerOptions["availabilityPolicy"];
|
||||
readonly startedAt: string;
|
||||
readonly processCaptureElicitation: ProcessCaptureElicitation;
|
||||
}): LazyToolCatalog => {
|
||||
const loadOptionalProviders = createOptionalProviderLoader(options);
|
||||
return new LazyToolCatalog(
|
||||
server,
|
||||
async (kind) => {
|
||||
const needsObservationProviders =
|
||||
@@ -210,7 +208,7 @@ export const createServer = (
|
||||
activeTarget,
|
||||
recordEvidence,
|
||||
recordEvidenceWithUnknown,
|
||||
availabilityPolicy: dynamicTools?.policy,
|
||||
availabilityPolicy,
|
||||
startedAt,
|
||||
processCaptureElicitation,
|
||||
},
|
||||
@@ -218,6 +216,82 @@ export const createServer = (
|
||||
},
|
||||
session !== undefined,
|
||||
);
|
||||
};
|
||||
|
||||
const createMcpServer = (
|
||||
processCaptureStateCodec: ProcessCaptureElicitation["stateCodec"],
|
||||
session: BinarySessionPort | undefined,
|
||||
): McpServer =>
|
||||
new McpServer(
|
||||
{
|
||||
name: PRODUCT_IDENTITY.mcpServerKey,
|
||||
version: PRODUCT_IDENTITY.packageVersion,
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
tools: { listChanged: true },
|
||||
resources: { listChanged: true, subscribe: true },
|
||||
},
|
||||
inputRequired: {
|
||||
maxRounds: 3,
|
||||
roundTimeoutMs: PROCESS_CAPTURE_ELICITATION_POLICY.roundTimeoutMs,
|
||||
},
|
||||
requestState: { verify: processCaptureStateCodec.verify },
|
||||
instructions:
|
||||
session === undefined
|
||||
? ACTIVE_TARGET_INSTRUCTIONS
|
||||
: TARGET_FREE_INSTRUCTIONS,
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Construct one MCP server without acquiring subprocess resources.
|
||||
* Supplying a session adds target lifecycle tools; omitting it retains the
|
||||
* fixed-target seam used by focused tests and embedders.
|
||||
*/
|
||||
export const createServer = (
|
||||
analysis: AnalysisOperationPort,
|
||||
session?: BinarySessionPort,
|
||||
options: CreateServerOptions = {},
|
||||
): McpServer => {
|
||||
const startedAt = new Date().toISOString();
|
||||
const logger = options.logger ?? silentLogger;
|
||||
const permissionAuthority =
|
||||
options.permissionAuthority?.createConnectionAuthority();
|
||||
const processCaptureStateCodec =
|
||||
createRequestStateCodec<ProcessCaptureElicitationState>({
|
||||
key: randomBytes(32),
|
||||
ttlSeconds: PROCESS_CAPTURE_ELICITATION_POLICY.stateTtlSeconds,
|
||||
});
|
||||
const server = createMcpServer(processCaptureStateCodec, session);
|
||||
const dynamicTools = installSessionToolAvailability(server, session, options);
|
||||
server.server.onclose = () => {
|
||||
permissionAuthority?.clearSessionGrants();
|
||||
};
|
||||
if (dynamicTools !== undefined)
|
||||
server.server.oninitialized = () => server.sendToolListChanged();
|
||||
session?.onAvailabilityChanged?.(() => server.sendToolListChanged());
|
||||
registerServerIdentityResource(server, startedAt);
|
||||
const toolLogger = logger.child({ layer: "server" });
|
||||
const { activeTarget, recordEvidence, recordEvidenceWithUnknown } =
|
||||
createSessionRecorders(server, session);
|
||||
const processCaptureElicitation = createProcessCaptureElicitation(
|
||||
processCaptureStateCodec,
|
||||
);
|
||||
const lazyTools = createLazyToolCatalog({
|
||||
server,
|
||||
analysis,
|
||||
session,
|
||||
options,
|
||||
toolLogger,
|
||||
permissionAuthority,
|
||||
activeTarget,
|
||||
recordEvidence,
|
||||
recordEvidenceWithUnknown,
|
||||
availabilityPolicy: dynamicTools?.policy,
|
||||
startedAt,
|
||||
processCaptureElicitation,
|
||||
});
|
||||
lazyTools.register();
|
||||
registerGuidedPrompts(server, analysis, session);
|
||||
if (session !== undefined) {
|
||||
|
||||
@@ -10,11 +10,15 @@ import {
|
||||
exportEvidenceBundleInputSchema,
|
||||
importEvidenceBundleInputSchema,
|
||||
listUnknownsInputSchema,
|
||||
releaseEvidenceBundleInputSchema,
|
||||
snapshotEvidenceBundleInputSchema,
|
||||
SESSION_TOOL_CONTRACTS,
|
||||
verifyUnknownResolutionInputSchema,
|
||||
} from "../contracts/toolContracts.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import type {
|
||||
EvidenceBundle,
|
||||
EvidenceFilePolicy,
|
||||
} from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
@@ -35,6 +39,7 @@ interface EvidenceToolRegistration {
|
||||
readonly exportContract: (typeof SESSION_TOOL_CONTRACTS)[3];
|
||||
readonly importContract: (typeof SESSION_TOOL_CONTRACTS)[4];
|
||||
readonly snapshotContract: (typeof SESSION_TOOL_CONTRACTS)[19];
|
||||
readonly releaseContract: (typeof SESSION_TOOL_CONTRACTS)[20];
|
||||
readonly filePolicy: EvidenceFilePolicy;
|
||||
readonly permissionAuthority?: PermissionAuthority;
|
||||
}
|
||||
@@ -46,6 +51,72 @@ export const registerEvidenceTools = (
|
||||
registerExportEvidenceTool(registration);
|
||||
registerImportEvidenceTool(registration);
|
||||
registerSnapshotEvidenceTool(registration);
|
||||
registerReleaseEvidenceTool(registration);
|
||||
};
|
||||
|
||||
const registerReleaseEvidenceTool = ({
|
||||
server,
|
||||
session,
|
||||
releaseContract,
|
||||
permissionAuthority,
|
||||
}: EvidenceToolRegistration): void => {
|
||||
server.registerTool(
|
||||
releaseContract.name,
|
||||
toolRegistrationOptions(releaseContract),
|
||||
async (input) => {
|
||||
const parsed = safeParseToolInput(
|
||||
releaseEvidenceBundleInputSchema,
|
||||
input,
|
||||
releaseContract.name,
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, releaseContract);
|
||||
const denied = await authorizeEvidenceWrite({
|
||||
authority: permissionAuthority,
|
||||
operationIdentity: `release_evidence:${parsed.value.bundle_digest}`,
|
||||
});
|
||||
if (denied !== undefined)
|
||||
return toCallToolResult(denied, releaseContract);
|
||||
const released = session.releaseEvidenceBundle(
|
||||
parsed.value.bundle_digest,
|
||||
);
|
||||
if (released)
|
||||
void server.server
|
||||
.sendResourceUpdated({
|
||||
uri: `rea://evidence-bundle/${parsed.value.bundle_digest}`,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return toCallToolResult(
|
||||
ok({
|
||||
bundle_digest: parsed.value.bundle_digest,
|
||||
released,
|
||||
}),
|
||||
releaseContract,
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const authorizeEvidenceWrite = async ({
|
||||
authority,
|
||||
operationIdentity,
|
||||
}: {
|
||||
readonly authority: PermissionAuthority | undefined;
|
||||
readonly operationIdentity: string;
|
||||
}): Promise<Result<never, AnalysisError> | undefined> => {
|
||||
if (authority === undefined) return undefined;
|
||||
const authorized = await authority.authorize(
|
||||
{
|
||||
capability: "evidence_write",
|
||||
roots: [],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: operationIdentity,
|
||||
},
|
||||
"write",
|
||||
);
|
||||
return authorized.ok ? undefined : permissionFailure(authorized);
|
||||
};
|
||||
|
||||
const registerExportEvidenceTool = ({
|
||||
@@ -119,6 +190,8 @@ const registerSnapshotEvidenceTool = ({
|
||||
bytes: snapshot.value.bytes,
|
||||
records: snapshot.value.records,
|
||||
unknowns: snapshot.value.unknowns,
|
||||
scope: snapshot.value.scope,
|
||||
survives_session: snapshot.value.survivesSession,
|
||||
bundle_uri: snapshot.value.uri,
|
||||
} as const;
|
||||
return toCallToolResult(ok(value), snapshotContract, {
|
||||
@@ -162,11 +235,20 @@ const registerImportEvidenceTool = ({
|
||||
if (denied !== undefined) return toCallToolResult(denied, importContract);
|
||||
const loaded = await readEvidenceBundle(path, filePolicy);
|
||||
if (!loaded.ok) return toCallToolResult(loaded, importContract);
|
||||
const retainedUnknownRevisions = new Set(
|
||||
session
|
||||
.exportEvidenceBundle()
|
||||
.unknowns.map((unknown) => unknownRevisionKey(unknown)),
|
||||
);
|
||||
const imported = session.importEvidenceBundle(loaded.value);
|
||||
return imported.ok
|
||||
? toCallToolResult(
|
||||
ok({
|
||||
imported: imported.value,
|
||||
unknowns_added: loaded.value.unknowns.filter(
|
||||
(unknown) =>
|
||||
!retainedUnknownRevisions.has(unknownRevisionKey(unknown)),
|
||||
).length,
|
||||
total: session.exportEvidenceBundle().records.length,
|
||||
}),
|
||||
importContract,
|
||||
@@ -176,6 +258,10 @@ const registerImportEvidenceTool = ({
|
||||
);
|
||||
};
|
||||
|
||||
const unknownRevisionKey = (
|
||||
unknown: EvidenceBundle["unknowns"][number],
|
||||
): string => `${unknown.unknown_id}:${String(unknown.revision)}`;
|
||||
|
||||
interface EvidenceAuthorizationInput {
|
||||
readonly authority: PermissionAuthority | undefined;
|
||||
readonly capability: "evidence_read" | "evidence_write";
|
||||
@@ -210,15 +296,12 @@ interface UnknownToolRegistration {
|
||||
}
|
||||
|
||||
/** Register residual-unknown query and mutation tools. */
|
||||
export const registerUnknownTools = ({
|
||||
const registerListUnknownsTool = ({
|
||||
server,
|
||||
session,
|
||||
contracts,
|
||||
}: UnknownToolRegistration): void => {
|
||||
const listContract = contracts[14];
|
||||
const recordContract = contracts[15];
|
||||
const updateContract = contracts[16];
|
||||
const verifyContract = contracts[17];
|
||||
server.registerTool(
|
||||
listContract.name,
|
||||
toolRegistrationOptions(listContract),
|
||||
@@ -267,6 +350,14 @@ export const registerUnknownTools = ({
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const registerRecordUnknownTool = ({
|
||||
server,
|
||||
session,
|
||||
contracts,
|
||||
}: UnknownToolRegistration): void => {
|
||||
const recordContract = contracts[15];
|
||||
server.registerTool(
|
||||
recordContract.name,
|
||||
toolRegistrationOptions(recordContract),
|
||||
@@ -291,6 +382,14 @@ export const registerUnknownTools = ({
|
||||
: toCallToolResult(result, recordContract);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const registerUpdateUnknownTool = ({
|
||||
server,
|
||||
session,
|
||||
contracts,
|
||||
}: UnknownToolRegistration): void => {
|
||||
const updateContract = contracts[16];
|
||||
server.registerTool(
|
||||
updateContract.name,
|
||||
toolRegistrationOptions(updateContract),
|
||||
@@ -321,6 +420,14 @@ export const registerUnknownTools = ({
|
||||
: toCallToolResult(result, updateContract);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const registerVerifyUnknownTool = ({
|
||||
server,
|
||||
session,
|
||||
contracts,
|
||||
}: UnknownToolRegistration): void => {
|
||||
const verifyContract = contracts[17];
|
||||
server.registerTool(
|
||||
verifyContract.name,
|
||||
toolRegistrationOptions(verifyContract),
|
||||
@@ -340,6 +447,15 @@ export const registerUnknownTools = ({
|
||||
);
|
||||
};
|
||||
|
||||
export const registerUnknownTools = (
|
||||
registration: UnknownToolRegistration,
|
||||
): void => {
|
||||
registerListUnknownsTool(registration);
|
||||
registerRecordUnknownTool(registration);
|
||||
registerUpdateUnknownTool(registration);
|
||||
registerVerifyUnknownTool(registration);
|
||||
};
|
||||
|
||||
const permissionFailure = (
|
||||
failure: Awaited<ReturnType<PermissionAuthority["authorize"]>>,
|
||||
): Result<never, AnalysisError> => {
|
||||
|
||||
@@ -329,8 +329,8 @@ const registerContextTools = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
): void => {
|
||||
const navigationContract = SESSION_TOOL_CONTRACTS[20];
|
||||
const addressContract = SESSION_TOOL_CONTRACTS[21];
|
||||
const navigationContract = SESSION_TOOL_CONTRACTS[21];
|
||||
const addressContract = SESSION_TOOL_CONTRACTS[22];
|
||||
server.registerTool(
|
||||
navigationContract.name,
|
||||
toolRegistrationOptions(navigationContract),
|
||||
@@ -401,6 +401,7 @@ export const registerSessionTools = (
|
||||
reconstructionContract,
|
||||
] = SESSION_TOOL_CONTRACTS;
|
||||
const snapshotContract = SESSION_TOOL_CONTRACTS[19];
|
||||
const releaseContract = SESSION_TOOL_CONTRACTS[20];
|
||||
registerLifecycleTools({
|
||||
server,
|
||||
session,
|
||||
@@ -423,6 +424,7 @@ export const registerSessionTools = (
|
||||
exportContract,
|
||||
importContract,
|
||||
snapshotContract,
|
||||
releaseContract,
|
||||
filePolicy: evidenceFilePolicy,
|
||||
...(options.permissionAuthority === undefined
|
||||
? {}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import { applyToolInputJsonSchemaOverride } from "../contracts/toolSchemaJsonOverrides.js";
|
||||
|
||||
const ADVERTISED_INPUT_SCHEMAS = new WeakMap<
|
||||
z.ZodObject,
|
||||
@@ -60,7 +61,10 @@ const advertisedInputJsonSchema = (
|
||||
): Readonly<Record<string, unknown>> =>
|
||||
cachedJsonSchema(ADVERTISED_INPUT_SCHEMAS, contract.inputSchema, () => ({
|
||||
...describeProperties(
|
||||
closeObjectSchemas(inputJsonSchema(contract.inputSchema)),
|
||||
applyToolInputJsonSchemaOverride(
|
||||
contract.name,
|
||||
closeObjectSchemas(inputJsonSchema(contract.inputSchema)),
|
||||
),
|
||||
),
|
||||
examples: contract.examples.map(({ input }) => input),
|
||||
}));
|
||||
|
||||
Reference in New Issue
Block a user