From 33557c4715a5230d2df19b29b3a54de92efdd7f7 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:28:20 +0800 Subject: [PATCH] refactor(mcp): bind the application workflows through an application binding kind on the shared table (#11578) Thirteen application tools (feature and semantic traces, version, endpoint, source-to-bundle and export-shape comparisons, API contract, NTFS journal and Playwright trace inspections, the obligation ledger and the three mobile graph projections) each had a bespoke registration repeating admission, retention checks, logging, source retention, unknown recording and view delivery. The shared table gains an application binding kind: a workflow that returns the completed Evidence, its sources and its residual unknown, and an optional view selector. One handler runs it under analysis admission, refuses a view or summary before running when the complete Evidence cannot be retained, delivers a failure's partial Evidence, and stages the view against the completed Evidence before recording (deliverApplicationExecution, moved from registerApplicationTools/helpers.ts). The comparison unknowns and the ledger's request resolution move to src/application/ApplicationToolExecutions.ts with their exact question text, so recorded unknown identities do not change. --- .../bespoke-mcp-tool-registration.json | 11 -- src/application/ApplicationToolExecutions.ts | 163 ++++++++++++++++++ src/server/contractToolBindings.ts | 103 ++++++++--- src/server/contractToolHandler.ts | 76 ++++++++ src/server/createServer.ts | 5 +- src/server/deliverApplicationExecution.ts | 84 +++++++++ src/server/registerApplicationTools.ts | 29 +--- .../registerApplicationTools/apiContract.ts | 62 ------- .../compareEndpoints.ts | 60 ------- .../compareExportShapes.ts | 63 ------- .../compareSourceToBundle.ts | 64 ------- .../compareVersions.ts | 60 ------- .../registerApplicationTools/helpers.ts | 137 --------------- .../registerApplicationTools/ntfsJournal.ts | 54 ------ .../obligationLedger.ts | 63 ------- .../playwrightTrace.ts | 64 ------- .../projectMobileApplicationGraph.ts | 94 ---------- .../registerApplicationTools/traceFeature.ts | 61 ------- .../traceSemantics.ts | 56 ------ src/server/registerApplicationTools/types.ts | 14 +- src/server/serviceToolBindings.ts | 144 ++++++++++++++++ .../boundary/mcp/featureTraceViewsMcp.test.ts | 16 +- 22 files changed, 563 insertions(+), 920 deletions(-) create mode 100644 src/application/ApplicationToolExecutions.ts create mode 100644 src/server/deliverApplicationExecution.ts delete mode 100644 src/server/registerApplicationTools/apiContract.ts delete mode 100644 src/server/registerApplicationTools/compareEndpoints.ts delete mode 100644 src/server/registerApplicationTools/compareExportShapes.ts delete mode 100644 src/server/registerApplicationTools/compareSourceToBundle.ts delete mode 100644 src/server/registerApplicationTools/compareVersions.ts delete mode 100644 src/server/registerApplicationTools/helpers.ts delete mode 100644 src/server/registerApplicationTools/ntfsJournal.ts delete mode 100644 src/server/registerApplicationTools/obligationLedger.ts delete mode 100644 src/server/registerApplicationTools/playwrightTrace.ts delete mode 100644 src/server/registerApplicationTools/projectMobileApplicationGraph.ts delete mode 100644 src/server/registerApplicationTools/traceFeature.ts delete mode 100644 src/server/registerApplicationTools/traceSemantics.ts diff --git a/scripts/verify/baselines/bespoke-mcp-tool-registration.json b/scripts/verify/baselines/bespoke-mcp-tool-registration.json index f485603bac..2e10bce629 100644 --- a/scripts/verify/baselines/bespoke-mcp-tool-registration.json +++ b/scripts/verify/baselines/bespoke-mcp-tool-registration.json @@ -1,17 +1,6 @@ { - "src/server/registerApplicationTools/apiContract.ts": 1, - "src/server/registerApplicationTools/compareEndpoints.ts": 1, - "src/server/registerApplicationTools/compareExportShapes.ts": 1, - "src/server/registerApplicationTools/compareSourceToBundle.ts": 1, - "src/server/registerApplicationTools/compareVersions.ts": 1, "src/server/registerApplicationTools/coverage.ts": 1, "src/server/registerApplicationTools/environmentBundle.ts": 1, - "src/server/registerApplicationTools/ntfsJournal.ts": 1, - "src/server/registerApplicationTools/obligationLedger.ts": 1, - "src/server/registerApplicationTools/playwrightTrace.ts": 1, - "src/server/registerApplicationTools/projectMobileApplicationGraph.ts": 1, - "src/server/registerApplicationTools/traceFeature.ts": 1, - "src/server/registerApplicationTools/traceSemantics.ts": 1, "src/server/registerBinaryDiagnosticsTools.ts": 1, "src/server/registerBrowserScenarioTool.ts": 1, "src/server/registerBrowserTools.ts": 8, diff --git a/src/application/ApplicationToolExecutions.ts b/src/application/ApplicationToolExecutions.ts new file mode 100644 index 0000000000..d450abd131 --- /dev/null +++ b/src/application/ApplicationToolExecutions.ts @@ -0,0 +1,163 @@ +import type { AnalysisError } from "../domain/analysisErrorBase.js"; +import type { Evidence } from "../domain/evidence.js"; +import type { RecordUnknownInput } from "../domain/residualUnknown.js"; +import { ok, type Result } from "../domain/result.js"; +import type { ExecutionOptions } from "../ports/AnalysisProvider.js"; +import type { ArtifactResourceScope } from "../resources/index.js"; +import type { EvidenceLookup } from "./EvidenceInputResolver.js"; +import type { EvidenceWorkflowExecution } from "./investigation/EvidenceWorkflowExecution.js"; +import type { InvestigationWorkflowExecution } from "./investigation/InvestigationWorkflows.js"; +import { + compareApplicationVersionsEvidence, + compareJavaScriptExportShapesEvidence, + executeSourceToBundleComparison, +} from "./javascript/JavaScriptApplicationWorkflowService.js"; +import { buildResolvedReconstructionObligationLedgerEvidence } from "./ReconstructionObligationLedgerService.js"; +import { resolveReconstructionObligationLedgerRequest } from "./ReconstructionObligationLedgerRequest.js"; + +type Options = Pick; + +type ComparisonUnknownKind = + | "application-version-comparison" + | "javascript-export-shape" + | "source-to-bundle-comparison"; + +const mapResult = ( + result: Result, + map: (value: Value) => Mapped, +): Result => + result.ok ? ok(map(result.value)) : result; + +/** A completed workflow whose result leaves nothing for the session to track. */ +export const settledExecution = ({ + evidence, + sources, +}: EvidenceWorkflowExecution): InvestigationWorkflowExecution => ({ + evidence, + sources, + unknown: undefined, +}); + +/** An inspection of caller-named files, which reads no session-held Evidence. */ +export const inspectionExecution = ( + inspected: Result, +): Result => + mapResult(inspected, (evidence) => + settledExecution({ evidence, sources: [] }), + ); + +const comparisonUnknown = ( + evidence: Evidence, + kind: ComparisonUnknownKind, +): RecordUnknownInput => ({ + // Scope unknown identity to the comparison while keeping exact replays stable. + question: `${ + kind === "application-version-comparison" + ? "Which application entities remain unmatched or ambiguous across these versions?" + : kind === "source-to-bundle-comparison" + ? "Which historical source files remain unmatched or ambiguously mapped to the shipped bundle?" + : "Which selected JavaScript export return shapes remain dynamic, incomplete, or ambiguously paired?" + } (comparison ${evidence.evidence_id})`, + severity: "medium", + domain: kind, + supporting_evidence_ids: [evidence.evidence_id], + contradicting_evidence_ids: [], + required_authority: "shipped-artifact", + required_confidence: "observed", + required_environment: null, + recommended_probes: [ + { + operation: "analyze_javascript_application", + rationale: + "Repeat static reconstruction with complete artifacts and source maps when available.", + }, + ...(kind === "application-version-comparison" + ? [ + { + operation: "reconcile_javascript_runtime", + rationale: + "Add passive runtime Evidence without promoting it to static fact.", + }, + ] + : []), + ], + relationships: [], +}); + +const comparisonExecution = ( + { evidence, sources }: EvidenceWorkflowExecution, + unresolved: ComparisonUnknownKind | undefined, +): InvestigationWorkflowExecution => ({ + evidence, + sources, + unknown: + unresolved === undefined + ? undefined + : comparisonUnknown(evidence, unresolved), +}); + +/** Compare application versions; unmatched or ambiguous entities stay tracked. */ +export const compareApplicationVersionsExecution = ( + rawInput: unknown, + lookup: EvidenceLookup | undefined, + options: Options, +) => + mapResult( + compareApplicationVersionsEvidence(rawInput, lookup, options), + (execution) => + comparisonExecution( + execution, + execution.result.summary.unknown > 0 + ? "application-version-comparison" + : undefined, + ), + ); + +/** Compare export shapes; dynamic, partial or ambiguous pairs stay tracked. */ +export const compareJavaScriptExportShapesExecution = ( + rawInput: unknown, + lookup: EvidenceLookup | undefined, + options: Options, +) => + mapResult( + compareJavaScriptExportShapesEvidence(rawInput, lookup, options), + (execution) => + comparisonExecution( + execution, + execution.result.summary.unknown > 0 || + execution.result.coverage.status !== "complete-within-inputs" + ? "javascript-export-shape" + : undefined, + ), + ); + +/** Compare historical source with a bundle; unmapped files stay tracked. */ +export const sourceToBundleComparisonExecution = async ( + rawInput: unknown, + lookup: EvidenceLookup | undefined, + resources: ArtifactResourceScope, + options: Options, +) => + mapResult( + await executeSourceToBundleComparison(rawInput, lookup, resources, options), + (execution) => + comparisonExecution( + execution, + execution.result.summary.unknown > 0 + ? "source-to-bundle-comparison" + : undefined, + ), + ); + +/** Build the obligation ledger from the bundle the request names, which it retains. */ +export const reconstructionObligationLedgerExecution = ( + rawInput: unknown, +): Result => + mapResult( + resolveReconstructionObligationLedgerRequest(rawInput), + (resolved) => + settledExecution({ + evidence: buildResolvedReconstructionObligationLedgerEvidence(resolved), + sources: resolved.sources.bundle.records, + }), + ); diff --git a/src/server/contractToolBindings.ts b/src/server/contractToolBindings.ts index d666951ddc..17afe82462 100644 --- a/src/server/contractToolBindings.ts +++ b/src/server/contractToolBindings.ts @@ -5,7 +5,11 @@ import type { z } from "zod"; import type { ExecutionOptions } from "../ports/AnalysisProvider.js"; import type { AnalysisViewRetention } from "../application/analysisView/AnalysisViewService.js"; import type { EvidenceLookup } from "../application/EvidenceInputResolver.js"; -import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js"; +import type { + EvidenceUnknownWriter, + EvidenceWriter, +} from "../application/investigation/InvestigationRecordPort.js"; +import type { AnalysisViewRequest } from "../domain/analysisView/analysisViewRequest.js"; import { TOOL_CONTRACTS } from "../contracts/toolContracts.js"; import type { ToolContract } from "../contracts/toolContractTypes.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; @@ -18,6 +22,8 @@ import type { BinarySessionPort } from "../application/binary/BinarySessionPort. import type { InvestigationWorkflowExecution } from "../application/investigation/InvestigationWorkflows.js"; import type { ArtifactResourceScope } from "../resources/index.js"; import { + type ApplicationWorkflowRequest, + createApplicationToolHandler, createDerivedToolHandler, type DerivedAcquisition, type DerivedSources, @@ -73,6 +79,7 @@ type EvidenceBinding = ( readonly value?: never; readonly derive?: never; readonly acquire?: never; + readonly workflow?: never; } | { readonly admission: "application"; @@ -81,6 +88,7 @@ type EvidenceBinding = ( readonly value?: never; readonly derive?: never; readonly acquire?: never; + readonly workflow?: never; } ) & { /** @@ -109,6 +117,7 @@ type ValueBinding = readonly summary?: never; readonly derive?: never; readonly acquire?: never; + readonly workflow?: never; } | { readonly admission: "application"; @@ -117,6 +126,7 @@ type ValueBinding = readonly summary?: never; readonly derive?: never; readonly acquire?: never; + readonly workflow?: never; }; /** @@ -140,6 +150,8 @@ type DerivedBinding = { readonly run?: never; readonly summary?: never; readonly value?: never; + readonly workflow?: never; + readonly view?: never; } & ( | { readonly derive: ( @@ -173,14 +185,45 @@ interface RetainedSummaryBinding { readonly value?: never; readonly derive?: never; readonly acquire?: never; + readonly workflow?: never; + readonly view?: never; } +/** + * Run an application workflow that completes Evidence from session-held + * Evidence or caller-named files, under analysis admission, and deliver it + * with the sources it read and its residual unknown. When the request + * selects a view (or a summary), the view is staged against the completed + * Evidence before anything is recorded, and the call is refused before the + * workflow runs if the complete Evidence cannot be retained. + */ +interface ApplicationWorkflowBinding { + readonly workflow: ( + input: Input, + request: ApplicationWorkflowRequest, + ) => Promise>; + readonly view?: (input: Input) => AnalysisViewRequest | undefined; + readonly run?: never; + readonly summary?: never; + readonly value?: never; + readonly derive?: never; + readonly acquire?: never; +} + +/** An application-admitted workflow validates the raw request itself. */ +type ApplicationBinding = + | (ApplicationWorkflowBinding & { readonly admission: "sdk" }) + | (ApplicationWorkflowBinding & { + readonly admission: "application"; + }); + /** How one named contract runs over MCP; only summary-capable contracts take `summary`. */ export type ContractToolBinding = // The SDK admits the request frame: declared Evidence inputs stay // unchecked until the workflow resolves them. | EvidenceBinding>> | ValueBinding>> + | ApplicationBinding>> | DerivedBinding | (ContractInput extends { readonly detail: "complete" | "summary" } ? RetainedSummaryBinding> @@ -195,6 +238,10 @@ export type ContractToolBindings = { export interface ContractToolDependencies { readonly logger: Logger; readonly recordEvidence?: EvidenceWriter["recordEvidence"] | undefined; + /** Records application Evidence together with its residual unknown. */ + readonly recordEvidenceWithUnknown?: + | EvidenceUnknownWriter["recordEvidenceWithUnknown"] + | undefined; readonly evidenceById?: EvidenceLookup | undefined; readonly withAdmittedAnalysis?: WithAdmittedAnalysis | undefined; } @@ -247,14 +294,20 @@ export const registerContractTools = ( dependencies: ContractToolDependencies, contracts: readonly ToolContract[] = TOOL_CONTRACTS, ): void => { - const { logger, recordEvidence, evidenceById, withAdmittedAnalysis } = - dependencies; + const { + logger, + recordEvidence, + recordEvidenceWithUnknown, + evidenceById, + withAdmittedAnalysis, + } = dependencies; const retention: AnalysisViewRetention = { recordEvidence, evidenceById }; const table: Readonly< Record< string, | EvidenceBinding | ValueBinding + | ApplicationBinding | DerivedBinding | RetainedSummaryBinding>> | undefined @@ -273,30 +326,38 @@ export const registerContractTools = ( const handler = binding.value !== undefined ? createValueToolHandler(server, binding.value, logger)(contract) - : binding.derive !== undefined || binding.acquire !== undefined - ? createDerivedToolHandler( + : binding.workflow !== undefined + ? createApplicationToolHandler( server, - binding.session, - derivedAcquisition(binding), + binding, logger, + { recordEvidence, recordEvidenceWithUnknown, evidenceById }, + withAdmittedAnalysis, )(contract) - : binding.run !== undefined - ? createEvidenceToolHandler( + : binding.derive !== undefined || binding.acquire !== undefined + ? createDerivedToolHandler( server, - binding.run, + binding.session, + derivedAcquisition(binding), logger, - recordEvidence, - withAdmittedAnalysis, - binding.viewSource, )(contract) - : createRetainedSummaryToolHandler( - server, - contract as SummaryContract, - binding.summary, - logger, - retention, - withAdmittedAnalysis, - ); + : binding.run !== undefined + ? createEvidenceToolHandler( + server, + binding.run, + logger, + recordEvidence, + withAdmittedAnalysis, + binding.viewSource, + )(contract) + : createRetainedSummaryToolHandler( + server, + contract as SummaryContract, + binding.summary, + logger, + retention, + withAdmittedAnalysis, + ); server.registerTool(contract.name, registration, handler); } if (unbound.size > 0) diff --git a/src/server/contractToolHandler.ts b/src/server/contractToolHandler.ts index bce4495bc6..11c7a765c1 100644 --- a/src/server/contractToolHandler.ts +++ b/src/server/contractToolHandler.ts @@ -34,6 +34,10 @@ import type { InvestigationWorkflowExecution } from "../application/investigatio import { withAdmittedAnalysis as sessionAdmission } from "./analysisAdmission.js"; import { deliverInvestigationWorkflow } from "./deliverInvestigationWorkflow.js"; import { runDerivedOperation } from "./runDerivedOperation.js"; +import { + deliverApplicationExecution, + type ApplicationExecutionRecords, +} from "./deliverApplicationExecution.js"; /** Application service executing one named contract operation. */ export interface ContractToolService { @@ -279,6 +283,78 @@ export const createDerivedToolHandler = ); }; +/** The request an application workflow runs for. */ +export interface ApplicationWorkflowRequest { + readonly signal: AbortSignal; + readonly progress: ProgressReporter; +} + +/** What an application workflow binding runs and the view it stages. */ +export interface ApplicationWorkflow { + readonly workflow: ( + input: unknown, + request: ApplicationWorkflowRequest, + ) => Promise>; + /** The caller-selected view of the completed Evidence, when the request names one. */ + readonly view?: + | ((input: unknown) => AnalysisViewRequest | undefined) + | undefined; +} + +/** + * Run an application workflow under analysis admission and deliver its + * completed Evidence with its sources and residual unknown. A request for a + * view (or summary) is refused before the workflow runs when the complete + * Evidence cannot be retained; a failure delivers its partial Evidence. + */ +export const createApplicationToolHandler = + ( + server: EvidenceMcpServer, + { workflow, view }: ApplicationWorkflow, + logger: Logger, + records: ApplicationExecutionRecords, + withAdmittedAnalysis?: WithAdmittedAnalysis, + ) => + (contract: ToolContract) => + async (input: unknown, context: ServerContext): Promise => + runAdmittedToolOperation( + server, + withAdmittedAnalysis, + contract.name, + context.mcpReq.signal, + async () => { + const selected = view?.(input); + if (selected !== undefined) { + const retention = requireAnalysisViewRetention(contract.name, { + recordEvidence: records.recordEvidence, + evidenceById: records.evidenceById, + }); + if (!retention.ok) + return server.delivery.toCallToolResult(retention, contract); + } + const result = await logToolExecution(logger, contract.name, () => + workflow(input, { + signal: context.mcpReq.signal, + progress: mcpProgressReporter(context), + }), + ); + if (!result.ok) + return server.delivery.toPartialErrorToolResult( + result.error, + contract.returnsTargetContent, + records.recordEvidence, + ); + return deliverApplicationExecution( + server.delivery, + records, + contract, + result.value, + selected, + context.mcpReq.signal, + ); + }, + ); + /** One owner for optional-provider admission, execution, recording and delivery. */ export const runEvidenceToolOperation = async ( options: { diff --git a/src/server/createServer.ts b/src/server/createServer.ts index c6b85a0036..8e8fd0e855 100644 --- a/src/server/createServer.ts +++ b/src/server/createServer.ts @@ -366,6 +366,7 @@ export const createServer = ( const contractTools = { logger: toolLogger, recordEvidence, + recordEvidenceWithUnknown, withAdmittedAnalysis: analysisAdmission, evidenceById, }; @@ -619,15 +620,13 @@ export const createServer = ( webModuleTrace, webSourceLocation, javascriptRecovery: javascriptRecoveryService, + applicationWorkflows: { resources: artifactResources }, }, contractTools, ); registerApplicationTools(server, { - artifactResources, evidenceById, logger: toolLogger, - recordEvidence, - recordEvidenceWithUnknown, withAdmittedAnalysis: analysisAdmission, }); registerDesktopBuildTools(server, desktopBuildComputers, toolLogger); diff --git a/src/server/deliverApplicationExecution.ts b/src/server/deliverApplicationExecution.ts new file mode 100644 index 0000000000..9f1ec019dc --- /dev/null +++ b/src/server/deliverApplicationExecution.ts @@ -0,0 +1,84 @@ +import { setImmediate } from "node:timers/promises"; +import type { CallToolResult } from "@modelcontextprotocol/server"; +import { inspectAnalysisViewValidated } from "../application/analysisView/AnalysisViewService.js"; +import type { EvidenceLookup } from "../application/EvidenceInputResolver.js"; +import type { + EvidenceUnknownWriter, + EvidenceWriter, +} from "../application/investigation/InvestigationRecordPort.js"; +import type { InvestigationWorkflowExecution } from "../application/investigation/InvestigationWorkflows.js"; +import { recordEvidenceSources } from "../application/investigation/recordEvidenceSources.js"; +import type { ToolContract } from "../contracts/toolContractTypes.js"; +import { cancelledBy } from "../domain/analysisErrorCore.js"; +import type { AnalysisViewRequest } from "../domain/analysisView/analysisViewRequest.js"; +import { jsonValueSchema } from "../domain/jsonValue.js"; +import { ok } from "../domain/result.js"; +import type { ToolResultDelivery } from "./ToolResultDelivery.js"; + +/** The session records an application workflow's delivery reads and writes. */ +export interface ApplicationExecutionRecords { + readonly evidenceById?: EvidenceLookup | undefined; + readonly recordEvidence?: EvidenceWriter["recordEvidence"] | undefined; + readonly recordEvidenceWithUnknown?: + | EvidenceUnknownWriter["recordEvidenceWithUnknown"] + | undefined; +} + +/** + * Stage an optional caller-selected view against the completed parent, then + * commit its sources and the parent (with its residual unknown) and deliver. + * A request cancelled before commit leaves the session unchanged; a delivered + * view that does not fit names the retained parent and a smaller page + * instead of its own record. + */ +export const deliverApplicationExecution = async ( + delivery: ToolResultDelivery, + records: ApplicationExecutionRecords, + contract: ToolContract, + execution: InvestigationWorkflowExecution, + view: AnalysisViewRequest | undefined, + signal: AbortSignal, +): Promise => { + const parent = execution.evidence; + const selected = + view === undefined + ? ok(parent) + : inspectAnalysisViewValidated( + { + source: { + kind: "retained-evidence", + evidence_id: parent.evidence_id, + }, + view, + }, + (id) => + id === parent.evidence_id ? parent : records.evidenceById?.(id), + ); + await setImmediate(); + if (signal.aborted) + return delivery.toErrorToolResult( + cancelledBy(contract.name, signal), + contract.returnsTargetContent, + ); + if (!selected.ok) return delivery.toCallToolResult(selected, contract); + const sources = recordEvidenceSources( + records.recordEvidence, + execution.sources, + { evidence: selected.value }, + ); + if (!sources.ok) return delivery.toCallToolResult(sources, contract); + const saved = + execution.unknown === undefined + ? records.recordEvidence?.(parent) + : records.recordEvidenceWithUnknown?.(parent, execution.unknown); + if (view === undefined) + return delivery.toEvidenceToolResult(parent, contract, saved); + if (saved !== undefined && !saved.ok) + return delivery.toCallToolResult(saved, contract); + return delivery.toSelectedViewToolResult( + selected.value, + { parent, request: jsonValueSchema.parse(view) }, + contract, + records.recordEvidence?.(selected.value), + ); +}; diff --git a/src/server/registerApplicationTools.ts b/src/server/registerApplicationTools.ts index 0425f44e2a..916c8c68ac 100644 --- a/src/server/registerApplicationTools.ts +++ b/src/server/registerApplicationTools.ts @@ -1,38 +1,19 @@ -import { registerPlaywrightTraceTool } from "./registerApplicationTools/playwrightTrace.js"; -import { registerApiContractTool } from "./registerApplicationTools/apiContract.js"; -import { registerNtfsJournalTool } from "./registerApplicationTools/ntfsJournal.js"; import type { EvidenceMcpServer } from "./EvidenceMcpServer.js"; - -import { registerTraceFeatureTool } from "./registerApplicationTools/traceFeature.js"; -import { registerTraceJavaScriptSemanticsTool } from "./registerApplicationTools/traceSemantics.js"; -import { registerCompareApplicationVersionsTool } from "./registerApplicationTools/compareVersions.js"; -import { registerCompareEndpointsTool } from "./registerApplicationTools/compareEndpoints.js"; -import { registerCompareSourceToBundleTool } from "./registerApplicationTools/compareSourceToBundle.js"; -import { registerCompareJavaScriptExportShapesTool } from "./registerApplicationTools/compareExportShapes.js"; import { registerCoverageTools } from "./registerApplicationTools/coverage.js"; import { registerEnvironmentBundleTool } from "./registerApplicationTools/environmentBundle.js"; -import { registerReconstructionObligationLedgerTool } from "./registerApplicationTools/obligationLedger.js"; -import { registerProjectMobileApplicationGraphTools } from "./registerApplicationTools/projectMobileApplicationGraph.js"; import type { ApplicationToolRegistration } from "./registerApplicationTools/types.js"; import { registerGuidedWorkflowTool } from "./registerGuidedWorkflowTool.js"; -/** Register provider-neutral JavaScript application graph workflows. */ +/** + * Register the application tools that deliver plain results. Application + * workflows that complete Evidence are bound through the shared table + * (`applicationWorkflows` in serviceToolBindings.ts). + */ export const registerApplicationTools = ( server: EvidenceMcpServer, options: ApplicationToolRegistration, ): void => { registerGuidedWorkflowTool(server); - registerTraceFeatureTool(server, options); - registerTraceJavaScriptSemanticsTool(server, options); - registerCompareApplicationVersionsTool(server, options); - registerCompareEndpointsTool(server, options); - registerApiContractTool(server, options); - registerNtfsJournalTool(server, options); - registerPlaywrightTraceTool(server, options); - registerCompareSourceToBundleTool(server, options); - registerCompareJavaScriptExportShapesTool(server, options); - registerReconstructionObligationLedgerTool(server, options); registerCoverageTools(server, options); registerEnvironmentBundleTool(server, options); - registerProjectMobileApplicationGraphTools(server, options); }; diff --git a/src/server/registerApplicationTools/apiContract.ts b/src/server/registerApplicationTools/apiContract.ts deleted file mode 100644 index dbbe07245e..0000000000 --- a/src/server/registerApplicationTools/apiContract.ts +++ /dev/null @@ -1,62 +0,0 @@ -import type { EvidenceMcpServer } from "../EvidenceMcpServer.js"; -import { runAdmittedToolOperation } from "../admittedToolOperation.js"; -import { requireAnalysisViewRetention } from "../../application/analysisView/AnalysisViewService.js"; -import { inspectApiContractEvidence } from "../../application/apiContract/ApiContractService.js"; -import { toolContract } from "../../contracts/toolContracts.js"; -import { toolRegistrationOptions } from "../toolRegistrationOptions.js"; -import { logToolExecution } from "../toolLogging.js"; -import { deliverApplicationEvidence } from "./helpers.js"; -import type { ApplicationToolRegistration } from "./types.js"; - -const contract = toolContract("inspect_api_contract"); - -/** Reads use the server's existing artifact resource owner and Evidence session. */ -export const registerApiContractTool = ( - server: EvidenceMcpServer, - options: ApplicationToolRegistration, -): void => { - server.registerTool( - contract.name, - toolRegistrationOptions(contract), - async (input, context) => - runAdmittedToolOperation( - server, - options.withAdmittedAnalysis, - contract.name, - context.mcpReq.signal, - async () => { - if (input.detail === "summary" || input.view !== undefined) { - const retention = requireAnalysisViewRetention( - contract.name, - options, - ); - if (!retention.ok) - return server.delivery.toCallToolResult(retention, contract); - } - const result = await logToolExecution( - options.logger, - contract.name, - () => - inspectApiContractEvidence(input, options.artifactResources, { - signal: context.mcpReq.signal, - }), - ); - if (!result.ok) - return server.delivery.toPartialErrorToolResult( - result.error, - contract.returnsTargetContent, - options.recordEvidence, - ); - return deliverApplicationEvidence( - server, - options, - contract, - { evidence: result.value, sources: [] }, - input.view ?? - (input.detail === "summary" ? { kind: "summary" } : undefined), - context.mcpReq.signal, - ); - }, - ), - ); -}; diff --git a/src/server/registerApplicationTools/compareEndpoints.ts b/src/server/registerApplicationTools/compareEndpoints.ts deleted file mode 100644 index 69b4b156de..0000000000 --- a/src/server/registerApplicationTools/compareEndpoints.ts +++ /dev/null @@ -1,60 +0,0 @@ -import type { EvidenceMcpServer } from "../EvidenceMcpServer.js"; -import { runAdmittedToolOperation } from "../admittedToolOperation.js"; -import { requireAnalysisViewRetention } from "../../application/analysisView/AnalysisViewService.js"; -import { compareStaticAndObservedEndpointsEvidence } from "../../application/javascript/StaticObservedEndpointComparisonService.js"; -import { toolContract } from "../../contracts/toolContracts.js"; -import { toolRegistrationOptions } from "../toolRegistrationOptions.js"; -import { logToolExecution } from "../toolLogging.js"; -import { deliverApplicationEvidence } from "./helpers.js"; -import type { ApplicationToolRegistration } from "./types.js"; - -const contract = toolContract("compare_static_and_observed_endpoints"); - -/** Both adapters execute the same authenticated, provider-free comparison. */ -export const registerCompareEndpointsTool = ( - server: EvidenceMcpServer, - options: ApplicationToolRegistration, -): void => { - server.registerTool( - contract.name, - toolRegistrationOptions(contract), - async (input, context) => - runAdmittedToolOperation( - server, - options.withAdmittedAnalysis, - contract.name, - context.mcpReq.signal, - async () => { - if (input.detail === "summary" || input.view !== undefined) { - const retention = requireAnalysisViewRetention( - contract.name, - options, - ); - if (!retention.ok) - return server.delivery.toCallToolResult(retention, contract); - } - const result = await logToolExecution( - options.logger, - contract.name, - () => - compareStaticAndObservedEndpointsEvidence( - input, - options.evidenceById, - { signal: context.mcpReq.signal }, - ), - ); - if (!result.ok) - return server.delivery.toCallToolResult(result, contract); - return deliverApplicationEvidence( - server, - options, - contract, - result.value, - input.view ?? - (input.detail === "summary" ? { kind: "summary" } : undefined), - context.mcpReq.signal, - ); - }, - ), - ); -}; diff --git a/src/server/registerApplicationTools/compareExportShapes.ts b/src/server/registerApplicationTools/compareExportShapes.ts deleted file mode 100644 index 779c0fdedb..0000000000 --- a/src/server/registerApplicationTools/compareExportShapes.ts +++ /dev/null @@ -1,63 +0,0 @@ -import type { EvidenceMcpServer } from "../EvidenceMcpServer.js"; -import { runAdmittedToolOperation } from "../admittedToolOperation.js"; -import { recordEvidenceSources } from "../../application/investigation/recordEvidenceSources.js"; - -import { compareJavaScriptExportShapesEvidence } from "../../application/javascript/JavaScriptApplicationWorkflowService.js"; -import { toolContract } from "../../contracts/toolContracts.js"; -import { logToolExecution } from "../toolLogging.js"; -import { toolRegistrationOptions } from "../toolRegistrationOptions.js"; -import { recordResult } from "./helpers.js"; -import type { ApplicationToolRegistration } from "./types.js"; - -const contract = toolContract("compare_javascript_export_shapes"); - -/** Register the execution-free exact JavaScript export-shape comparison. */ -export const registerCompareJavaScriptExportShapesTool = ( - server: EvidenceMcpServer, - options: ApplicationToolRegistration, -): void => { - server.registerTool( - contract.name, - toolRegistrationOptions(contract), - async (input, context) => - runAdmittedToolOperation( - server, - options.withAdmittedAnalysis, - contract.name, - context.mcpReq.signal, - async () => { - const result = await logToolExecution( - options.logger, - contract.name, - () => - Promise.resolve( - compareJavaScriptExportShapesEvidence( - input, - options.evidenceById, - { signal: context.mcpReq.signal }, - ), - ), - ); - if (!result.ok) - return server.delivery.toCallToolResult(result, contract); - const recorded = recordEvidenceSources( - options.recordEvidence, - result.value.sources, - { evidence: result.value.evidence }, - ); - if (!recorded.ok) - return server.delivery.toCallToolResult(recorded, contract); - const comparison = result.value.result; - const unknown = - comparison.summary.unknown > 0 || - comparison.coverage.status !== "complete-within-inputs"; - return recordResult( - { ...options, delivery: server.delivery }, - contract, - result.value.evidence, - unknown ? "javascript-export-shape" : undefined, - ); - }, - ), - ); -}; diff --git a/src/server/registerApplicationTools/compareSourceToBundle.ts b/src/server/registerApplicationTools/compareSourceToBundle.ts deleted file mode 100644 index f3f3688675..0000000000 --- a/src/server/registerApplicationTools/compareSourceToBundle.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { requireAnalysisViewRetention } from "../../application/analysisView/AnalysisViewService.js"; -import type { EvidenceMcpServer } from "../EvidenceMcpServer.js"; -import { runAdmittedToolOperation } from "../admittedToolOperation.js"; - -import { executeSourceToBundleComparison } from "../../application/javascript/JavaScriptApplicationWorkflowService.js"; -import { toolContract } from "../../contracts/toolContracts.js"; -import { logToolExecution } from "../toolLogging.js"; -import { toolRegistrationOptions } from "../toolRegistrationOptions.js"; -import { deliverApplicationEvidence } from "./helpers.js"; -import type { ApplicationToolRegistration } from "./types.js"; - -const contract = toolContract("compare_source_to_bundle"); - -/** Register conservative historical-source to bundle comparison. */ -export const registerCompareSourceToBundleTool = ( - server: EvidenceMcpServer, - options: ApplicationToolRegistration, -): void => { - server.registerTool( - contract.name, - toolRegistrationOptions(contract), - async (input, context) => - runAdmittedToolOperation( - server, - options.withAdmittedAnalysis, - contract.name, - context.mcpReq.signal, - async () => { - if (input.view !== undefined) { - const retention = requireAnalysisViewRetention( - contract.name, - options, - ); - if (!retention.ok) - return server.delivery.toCallToolResult(retention, contract); - } - const result = await logToolExecution( - options.logger, - contract.name, - () => - executeSourceToBundleComparison( - input, - options.evidenceById, - options.artifactResources, - { signal: context.mcpReq.signal }, - ), - ); - if (!result.ok) - return server.delivery.toCallToolResult(result, contract); - return deliverApplicationEvidence( - server, - options, - contract, - result.value, - input.view, - context.mcpReq.signal, - result.value.result.summary.unknown > 0 - ? "source-to-bundle-comparison" - : undefined, - ); - }, - ), - ); -}; diff --git a/src/server/registerApplicationTools/compareVersions.ts b/src/server/registerApplicationTools/compareVersions.ts deleted file mode 100644 index 767c8313d0..0000000000 --- a/src/server/registerApplicationTools/compareVersions.ts +++ /dev/null @@ -1,60 +0,0 @@ -import type { EvidenceMcpServer } from "../EvidenceMcpServer.js"; -import { runAdmittedToolOperation } from "../admittedToolOperation.js"; -import { recordEvidenceSources } from "../../application/investigation/recordEvidenceSources.js"; - -import { compareApplicationVersionsEvidence } from "../../application/javascript/JavaScriptApplicationWorkflowService.js"; -import { toolContract } from "../../contracts/toolContracts.js"; -import { logToolExecution } from "../toolLogging.js"; -import { toolRegistrationOptions } from "../toolRegistrationOptions.js"; -import { recordResult } from "./helpers.js"; -import type { ApplicationToolRegistration } from "./types.js"; - -const compareContract = toolContract("compare_application_versions"); - -/** Register the provider-neutral JavaScript version comparison tool. */ -export const registerCompareApplicationVersionsTool = ( - server: EvidenceMcpServer, - options: ApplicationToolRegistration, -): void => { - server.registerTool( - compareContract.name, - toolRegistrationOptions(compareContract), - async (input, context) => - runAdmittedToolOperation( - server, - options.withAdmittedAnalysis, - compareContract.name, - context.mcpReq.signal, - async () => { - const result = await logToolExecution( - options.logger, - compareContract.name, - () => - Promise.resolve( - compareApplicationVersionsEvidence( - input, - options.evidenceById, - { signal: context.mcpReq.signal }, - ), - ), - ); - if (!result.ok) - return server.delivery.toCallToolResult(result, compareContract); - const recorded = recordEvidenceSources( - options.recordEvidence, - result.value.sources, - { evidence: result.value.evidence }, - ); - if (!recorded.ok) - return server.delivery.toCallToolResult(recorded, compareContract); - const unknown = result.value.result.summary.unknown > 0; - return recordResult( - { ...options, delivery: server.delivery }, - compareContract, - result.value.evidence, - unknown ? "application-version-comparison" : undefined, - ); - }, - ), - ); -}; diff --git a/src/server/registerApplicationTools/helpers.ts b/src/server/registerApplicationTools/helpers.ts deleted file mode 100644 index 99361e16b0..0000000000 --- a/src/server/registerApplicationTools/helpers.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { setImmediate } from "node:timers/promises"; -import type { CallToolResult } from "@modelcontextprotocol/server"; -import type { ToolResultDelivery } from "../ToolResultDelivery.js"; -import { APPLICATION_TOOL_CONTRACTS } from "../../contracts/applicationToolContracts.js"; -import { inspectAnalysisViewValidated } from "../../application/analysisView/AnalysisViewService.js"; -import { recordEvidenceSources } from "../../application/investigation/recordEvidenceSources.js"; -import { cancelledBy } from "../../domain/analysisErrorCore.js"; -import type { AnalysisViewRequest } from "../../domain/analysisView/analysisViewRequest.js"; -import type { Evidence } from "../../domain/evidence.js"; -import { jsonValueSchema } from "../../domain/jsonValue.js"; -import { ok } from "../../domain/result.js"; -import type { ApplicationToolRegistration } from "./types.js"; - -type UnknownKind = - | "application-version-comparison" - | "javascript-export-shape" - | "source-to-bundle-comparison"; - -export const recordResult = ( - options: ApplicationToolRegistration & { - readonly delivery: ToolResultDelivery; - }, - contract: (typeof APPLICATION_TOOL_CONTRACTS)[number], - evidence: Evidence, - unknownKind?: UnknownKind, -) => { - const recorded = recordApplicationResult(options, evidence, unknownKind); - return options.delivery.toEvidenceToolResult(evidence, contract, recorded); -}; - -/** - * Stage an optional caller-selected view against the completed parent, then - * commit its sources and the parent and deliver. A request cancelled before - * commit leaves the session unchanged; a delivered view that does not fit - * names the retained parent and a smaller page instead of its own record. - */ -export const deliverApplicationEvidence = async ( - server: { readonly delivery: ToolResultDelivery }, - options: ApplicationToolRegistration, - contract: (typeof APPLICATION_TOOL_CONTRACTS)[number], - execution: { - readonly evidence: Evidence; - readonly sources: readonly Evidence[]; - }, - view: AnalysisViewRequest | undefined, - signal: AbortSignal, - unknownKind?: UnknownKind, -): Promise => { - const { delivery } = server; - const parent = execution.evidence; - const selected = - view === undefined - ? ok(parent) - : inspectAnalysisViewValidated( - { - source: { - kind: "retained-evidence", - evidence_id: parent.evidence_id, - }, - view, - }, - (id) => - id === parent.evidence_id ? parent : options.evidenceById?.(id), - ); - await setImmediate(); - if (signal.aborted) - return delivery.toErrorToolResult( - cancelledBy(contract.name, signal), - contract.returnsTargetContent, - ); - if (!selected.ok) return delivery.toCallToolResult(selected, contract); - const sources = recordEvidenceSources( - options.recordEvidence, - execution.sources, - { evidence: selected.value }, - ); - if (!sources.ok) return delivery.toCallToolResult(sources, contract); - const saved = recordApplicationResult(options, parent, unknownKind); - if (view === undefined) - return delivery.toEvidenceToolResult(parent, contract, saved); - if (saved !== undefined && !saved.ok) - return delivery.toCallToolResult(saved, contract); - return delivery.toSelectedViewToolResult( - selected.value, - { parent, request: jsonValueSchema.parse(view) }, - contract, - options.recordEvidence?.(selected.value), - ); -}; - -/** Record the complete parent before choosing a delivery projection. */ -export const recordApplicationResult = ( - options: ApplicationToolRegistration, - evidence: Evidence, - unknownKind?: UnknownKind, -) => - unknownKind === undefined - ? options.recordEvidence?.(evidence) - : options.recordEvidenceWithUnknown?.( - evidence, - unknownRegistration(evidence, unknownKind), - ); - -const unknownRegistration = (evidence: Evidence, kind: UnknownKind) => ({ - // Scope unknown identity to the comparison while keeping exact replays stable. - question: `${ - kind === "application-version-comparison" - ? "Which application entities remain unmatched or ambiguous across these versions?" - : kind === "source-to-bundle-comparison" - ? "Which historical source files remain unmatched or ambiguously mapped to the shipped bundle?" - : "Which selected JavaScript export return shapes remain dynamic, incomplete, or ambiguously paired?" - } (comparison ${evidence.evidence_id})`, - severity: "medium" as const, - domain: kind, - supporting_evidence_ids: [evidence.evidence_id], - contradicting_evidence_ids: [], - required_authority: "shipped-artifact" as const, - required_confidence: "observed" as const, - required_environment: null, - recommended_probes: [ - { - operation: "analyze_javascript_application", - rationale: - "Repeat static reconstruction with complete artifacts and source maps when available.", - }, - ...(kind === "application-version-comparison" - ? [ - { - operation: "reconcile_javascript_runtime", - rationale: - "Add passive runtime Evidence without promoting it to static fact.", - }, - ] - : []), - ], - relationships: [], -}); diff --git a/src/server/registerApplicationTools/ntfsJournal.ts b/src/server/registerApplicationTools/ntfsJournal.ts deleted file mode 100644 index db62156a96..0000000000 --- a/src/server/registerApplicationTools/ntfsJournal.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { inspectNtfsJournalEvidence } from "../../application/ntfs/NtfsJournalService.js"; -import { toolContract } from "../../contracts/toolContracts.js"; -import type { EvidenceMcpServer } from "../EvidenceMcpServer.js"; -import { runAdmittedToolOperation } from "../admittedToolOperation.js"; -import { toolRegistrationOptions } from "../toolRegistrationOptions.js"; -import { logToolExecution } from "../toolLogging.js"; -import { deliverApplicationEvidence } from "./helpers.js"; -import type { ApplicationToolRegistration } from "./types.js"; - -const contract = toolContract("inspect_ntfs_journal"); - -export const registerNtfsJournalTool = ( - server: EvidenceMcpServer, - options: ApplicationToolRegistration, -): void => { - server.registerTool( - contract.name, - toolRegistrationOptions(contract), - async (input, context) => - runAdmittedToolOperation( - server, - options.withAdmittedAnalysis, - contract.name, - context.mcpReq.signal, - async () => { - const signal = context.mcpReq.signal; - const result = await logToolExecution( - options.logger, - contract.name, - () => - inspectNtfsJournalEvidence( - input, - options.artifactResources, - signal, - ), - ); - if (!result.ok) - return server.delivery.toPartialErrorToolResult( - result.error, - contract.returnsTargetContent, - options.recordEvidence, - ); - return deliverApplicationEvidence( - server, - options, - contract, - { evidence: result.value, sources: [] }, - undefined, - signal, - ); - }, - ), - ); -}; diff --git a/src/server/registerApplicationTools/obligationLedger.ts b/src/server/registerApplicationTools/obligationLedger.ts deleted file mode 100644 index 873664d582..0000000000 --- a/src/server/registerApplicationTools/obligationLedger.ts +++ /dev/null @@ -1,63 +0,0 @@ -import type { EvidenceMcpServer } from "../EvidenceMcpServer.js"; -import { runAdmittedToolOperation } from "../admittedToolOperation.js"; -import { recordEvidenceSources } from "../../application/investigation/recordEvidenceSources.js"; - -import { buildResolvedReconstructionObligationLedgerEvidence } from "../../application/ReconstructionObligationLedgerService.js"; -import { resolveReconstructionObligationLedgerRequest } from "../../application/ReconstructionObligationLedgerRequest.js"; -import { ok } from "../../domain/result.js"; -import { toolContract } from "../../contracts/toolContracts.js"; -import { logToolExecution } from "../toolLogging.js"; -import { applicationToolRegistrationOptions } from "../toolRegistrationOptions.js"; -import { recordResult } from "./helpers.js"; -import type { ApplicationToolRegistration } from "./types.js"; - -const contract = toolContract("build_reconstruction_obligation_ledger"); - -/** Register conservative reconstruction-obligation generation and closure. */ -export const registerReconstructionObligationLedgerTool = ( - server: EvidenceMcpServer, - options: ApplicationToolRegistration, -): void => { - server.registerTool( - contract.name, - applicationToolRegistrationOptions(contract), - async (input, context) => - runAdmittedToolOperation( - server, - options.withAdmittedAnalysis, - contract.name, - context.mcpReq.signal, - async () => { - const resolved = resolveReconstructionObligationLedgerRequest(input); - if (!resolved.ok) - return server.delivery.toCallToolResult(resolved, contract); - const result = await logToolExecution( - options.logger, - contract.name, - () => - Promise.resolve( - ok( - buildResolvedReconstructionObligationLedgerEvidence( - resolved.value, - ), - ), - ), - ); - if (!result.ok) - return server.delivery.toCallToolResult(result, contract); - const recorded = recordEvidenceSources( - options.recordEvidence, - resolved.value.sources.bundle.records, - { evidence: result.value }, - ); - if (!recorded.ok) - return server.delivery.toCallToolResult(recorded, contract); - return recordResult( - { ...options, delivery: server.delivery }, - contract, - result.value, - ); - }, - ), - ); -}; diff --git a/src/server/registerApplicationTools/playwrightTrace.ts b/src/server/registerApplicationTools/playwrightTrace.ts deleted file mode 100644 index 7732cdb895..0000000000 --- a/src/server/registerApplicationTools/playwrightTrace.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { PlaywrightTraceDecoder } from "../../browser/history/playwrightTrace/PlaywrightTraceDecoder.js"; -import type { EvidenceMcpServer } from "../EvidenceMcpServer.js"; -import { runAdmittedToolOperation } from "../admittedToolOperation.js"; -import { requireAnalysisViewRetention } from "../../application/analysisView/AnalysisViewService.js"; -import { PlaywrightTraceService } from "../../application/playwrightTrace/PlaywrightTraceService.js"; -import { toolContract } from "../../contracts/toolContracts.js"; -import { toolRegistrationOptions } from "../toolRegistrationOptions.js"; -import { logToolExecution } from "../toolLogging.js"; -import { deliverApplicationEvidence } from "./helpers.js"; -import type { ApplicationToolRegistration } from "./types.js"; - -const contract = toolContract("inspect_playwright_trace"); - -/** Reads use the server's existing artifact resource owner and Evidence session. */ -export const registerPlaywrightTraceTool = ( - server: EvidenceMcpServer, - options: ApplicationToolRegistration, -): void => { - const service = new PlaywrightTraceService( - new PlaywrightTraceDecoder(options.artifactResources), - ); - server.registerTool( - contract.name, - toolRegistrationOptions(contract), - async (input, context) => - runAdmittedToolOperation( - server, - options.withAdmittedAnalysis, - contract.name, - context.mcpReq.signal, - async () => { - if (input.detail === "summary" || input.view !== undefined) { - const retention = requireAnalysisViewRetention( - contract.name, - options, - ); - if (!retention.ok) - return server.delivery.toCallToolResult(retention, contract); - } - const result = await logToolExecution( - options.logger, - contract.name, - () => service.inspect(input, context.mcpReq.signal), - ); - // A failed import can carry partial Evidence; retain it for views. - if (!result.ok) - return server.delivery.toPartialErrorToolResult( - result.error, - contract.returnsTargetContent, - options.recordEvidence, - ); - return deliverApplicationEvidence( - server, - options, - contract, - { evidence: result.value, sources: [] }, - input.view ?? - (input.detail === "summary" ? { kind: "summary" } : undefined), - context.mcpReq.signal, - ); - }, - ), - ); -}; diff --git a/src/server/registerApplicationTools/projectMobileApplicationGraph.ts b/src/server/registerApplicationTools/projectMobileApplicationGraph.ts deleted file mode 100644 index 701d4bb756..0000000000 --- a/src/server/registerApplicationTools/projectMobileApplicationGraph.ts +++ /dev/null @@ -1,94 +0,0 @@ -import type { EvidenceLookup } from "../../application/EvidenceInputResolver.js"; -import type { ExecutionOptions } from "../../ports/AnalysisProvider.js"; -import type { EvidenceMcpServer } from "../EvidenceMcpServer.js"; -import type { ServerContext } from "@modelcontextprotocol/server"; -import { runAdmittedToolOperation } from "../admittedToolOperation.js"; - -import { projectAndroidApplicationEvidence } from "../../application/android/AndroidApplicationService.js"; -import { projectAppleApplicationEvidence } from "../../application/apple/AppleApplicationService.js"; -import { projectHarmonyApplicationEvidence } from "../../application/harmony/HarmonyApplicationService.js"; -import { APPLICATION_TOOL_CONTRACTS } from "../../contracts/applicationToolContracts.js"; -import { toolContract } from "../../contracts/toolContracts.js"; -import type { AnalysisError } from "../../domain/analysisErrorBase.js"; -import type { Result } from "../../domain/result.js"; -import type { InventoryProjectionEvidenceResult } from "../../application/InventoryProjectionEvidence.js"; -import { recordEvidenceSources } from "../../application/investigation/recordEvidenceSources.js"; -import { logToolExecution } from "../toolLogging.js"; -import { toolRegistrationOptions } from "../toolRegistrationOptions.js"; -import { recordResult } from "./helpers.js"; -import type { ApplicationToolRegistration } from "./types.js"; - -/** Register execution-free mobile application inventory projection tools. */ -export const registerProjectMobileApplicationGraphTools = ( - server: EvidenceMcpServer, - options: ApplicationToolRegistration, -): void => { - registerProjection({ - server, - options, - contract: toolContract("project_android_application_graph"), - project: projectAndroidApplicationEvidence, - }); - registerProjection({ - server, - options, - contract: toolContract("project_apple_application_graph"), - project: projectAppleApplicationEvidence, - }); - registerProjection({ - server, - options, - contract: toolContract("project_harmony_application_graph"), - project: projectHarmonyApplicationEvidence, - }); -}; - -const registerProjection = (context: { - readonly server: EvidenceMcpServer; - readonly options: ApplicationToolRegistration; - readonly contract: (typeof APPLICATION_TOOL_CONTRACTS)[number]; - readonly project: ( - input: unknown, - lookup?: EvidenceLookup, - options?: Pick, - ) => Result; -}): void => { - const { server, options, contract, project } = context; - server.registerTool( - contract.name, - toolRegistrationOptions(contract), - async (input: unknown, request: ServerContext) => - runAdmittedToolOperation( - server, - options.withAdmittedAnalysis, - contract.name, - request.mcpReq.signal, - async () => { - const result = await logToolExecution( - options.logger, - contract.name, - () => - Promise.resolve( - project(input, options.evidenceById, { - signal: request.mcpReq.signal, - }), - ), - ); - if (!result.ok) - return server.delivery.toCallToolResult(result, contract); - const recordedSources = recordEvidenceSources( - options.recordEvidence, - result.value.sources, - { evidence: result.value.evidence }, - ); - if (!recordedSources.ok) - return server.delivery.toCallToolResult(recordedSources, contract); - return recordResult( - { ...options, delivery: server.delivery }, - contract, - result.value.evidence, - ); - }, - ), - ); -}; diff --git a/src/server/registerApplicationTools/traceFeature.ts b/src/server/registerApplicationTools/traceFeature.ts deleted file mode 100644 index b66c937f3f..0000000000 --- a/src/server/registerApplicationTools/traceFeature.ts +++ /dev/null @@ -1,61 +0,0 @@ -import type { EvidenceMcpServer } from "../EvidenceMcpServer.js"; -import { runAdmittedToolOperation } from "../admittedToolOperation.js"; -import { requireAnalysisViewRetention } from "../../application/analysisView/AnalysisViewService.js"; - -import { traceApplicationFeatureEvidence } from "../../application/javascript/JavaScriptApplicationWorkflowService.js"; -import { toolContract } from "../../contracts/toolContracts.js"; -import { logToolExecution } from "../toolLogging.js"; -import { toolRegistrationOptions } from "../toolRegistrationOptions.js"; -import { deliverApplicationEvidence } from "./helpers.js"; -import type { ApplicationToolRegistration } from "./types.js"; - -const traceContract = toolContract("trace_application_feature"); - -/** Register the provider-neutral JavaScript feature trace tool. */ -export const registerTraceFeatureTool = ( - server: EvidenceMcpServer, - options: ApplicationToolRegistration, -): void => { - server.registerTool( - traceContract.name, - toolRegistrationOptions(traceContract), - async ({ view, ...input }, context) => - runAdmittedToolOperation( - server, - options.withAdmittedAnalysis, - traceContract.name, - context.mcpReq.signal, - async () => { - // A selected view is meaningful only when the complete trace can be retained. - if (view !== undefined) { - const retention = requireAnalysisViewRetention( - traceContract.name, - options, - ); - if (!retention.ok) - return server.delivery.toCallToolResult(retention, traceContract); - } - const result = await logToolExecution( - options.logger, - traceContract.name, - () => - Promise.resolve( - traceApplicationFeatureEvidence(input, options.evidenceById, { - signal: context.mcpReq.signal, - }), - ), - ); - if (!result.ok) - return server.delivery.toCallToolResult(result, traceContract); - return deliverApplicationEvidence( - server, - options, - traceContract, - result.value, - view, - context.mcpReq.signal, - ); - }, - ), - ); -}; diff --git a/src/server/registerApplicationTools/traceSemantics.ts b/src/server/registerApplicationTools/traceSemantics.ts deleted file mode 100644 index b51992b1c9..0000000000 --- a/src/server/registerApplicationTools/traceSemantics.ts +++ /dev/null @@ -1,56 +0,0 @@ -import type { EvidenceMcpServer } from "../EvidenceMcpServer.js"; -import { runAdmittedToolOperation } from "../admittedToolOperation.js"; -import { recordEvidenceSources } from "../../application/investigation/recordEvidenceSources.js"; - -import { traceJavaScriptSemanticsEvidence } from "../../application/javascript/JavaScriptSemanticTraceService.js"; -import { toolContract } from "../../contracts/toolContracts.js"; -import { logToolExecution } from "../toolLogging.js"; -import { toolRegistrationOptions } from "../toolRegistrationOptions.js"; -import { recordResult } from "./helpers.js"; -import type { ApplicationToolRegistration } from "./types.js"; - -const contract = toolContract("trace_javascript_semantics"); - -/** Register the bounded JavaScript semantic relation trace tool. */ -export const registerTraceJavaScriptSemanticsTool = ( - server: EvidenceMcpServer, - options: ApplicationToolRegistration, -): void => { - server.registerTool( - contract.name, - toolRegistrationOptions(contract), - async (input, context) => - runAdmittedToolOperation( - server, - options.withAdmittedAnalysis, - contract.name, - context.mcpReq.signal, - async () => { - const result = await logToolExecution( - options.logger, - contract.name, - () => - Promise.resolve( - traceJavaScriptSemanticsEvidence(input, options.evidenceById, { - signal: context.mcpReq.signal, - }), - ), - ); - if (!result.ok) - return server.delivery.toCallToolResult(result, contract); - const recorded = recordEvidenceSources( - options.recordEvidence, - result.value.sources, - { evidence: result.value.evidence }, - ); - if (!recorded.ok) - return server.delivery.toCallToolResult(recorded, contract); - return recordResult( - { ...options, delivery: server.delivery }, - contract, - result.value.evidence, - ); - }, - ), - ); -}; diff --git a/src/server/registerApplicationTools/types.ts b/src/server/registerApplicationTools/types.ts index 42e4d01772..c59d12cf9c 100644 --- a/src/server/registerApplicationTools/types.ts +++ b/src/server/registerApplicationTools/types.ts @@ -1,20 +1,10 @@ -import type { ArtifactResourceScope } from "../../resources/index.js"; -import type { - EvidenceWriter, - EvidenceReader, - EvidenceUnknownWriter, -} from "../../application/investigation/InvestigationRecordPort.js"; +import type { EvidenceReader } from "../../application/investigation/InvestigationRecordPort.js"; import type { Logger } from "pino"; import type { WithAdmittedAnalysis } from "../analysisAdmission.js"; -/** Shared services for registering JavaScript application graph workflows. */ +/** Shared services for the application tools that deliver plain results. */ export interface ApplicationToolRegistration { - readonly artifactResources: ArtifactResourceScope; readonly withAdmittedAnalysis?: WithAdmittedAnalysis; readonly logger: Logger; readonly evidenceById: EvidenceReader["evidenceById"] | undefined; - readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined; - readonly recordEvidenceWithUnknown: - | EvidenceUnknownWriter["recordEvidenceWithUnknown"] - | undefined; } diff --git a/src/server/serviceToolBindings.ts b/src/server/serviceToolBindings.ts index 2c21a069f8..ccae34e312 100644 --- a/src/server/serviceToolBindings.ts +++ b/src/server/serviceToolBindings.ts @@ -71,6 +71,28 @@ import { readBundleComparisonSources, } from "../application/investigation/BundleComparisonEvidence.js"; import type { WebModuleTraceService } from "../application/WebModuleTraceService.js"; +import { + compareApplicationVersionsExecution, + compareJavaScriptExportShapesExecution, + inspectionExecution, + reconstructionObligationLedgerExecution, + settledExecution, + sourceToBundleComparisonExecution, +} from "../application/ApplicationToolExecutions.js"; +import { projectAndroidApplicationEvidence } from "../application/android/AndroidApplicationService.js"; +import { inspectApiContractEvidence } from "../application/apiContract/ApiContractService.js"; +import { projectAppleApplicationEvidence } from "../application/apple/AppleApplicationService.js"; +import { projectHarmonyApplicationEvidence } from "../application/harmony/HarmonyApplicationService.js"; +import type { EvidenceWorkflowExecution } from "../application/investigation/EvidenceWorkflowExecution.js"; +import type { InvestigationWorkflowExecution } from "../application/investigation/InvestigationWorkflows.js"; +import { traceApplicationFeatureEvidence } from "../application/javascript/JavaScriptApplicationWorkflowService.js"; +import { traceJavaScriptSemanticsEvidence } from "../application/javascript/JavaScriptSemanticTraceService.js"; +import { compareStaticAndObservedEndpointsEvidence } from "../application/javascript/StaticObservedEndpointComparisonService.js"; +import { inspectNtfsJournalEvidence } from "../application/ntfs/NtfsJournalService.js"; +import { PlaywrightTraceService } from "../application/playwrightTrace/PlaywrightTraceService.js"; +import { PlaywrightTraceDecoder } from "../browser/history/playwrightTrace/PlaywrightTraceDecoder.js"; +import type { AnalysisError } from "../domain/analysisErrorBase.js"; +import type { AnalysisViewRequest } from "../domain/analysisView/analysisViewRequest.js"; import type { WebSourceLocationService } from "../application/WebSourceLocationService.js"; import { toolContract } from "../contracts/toolContracts.js"; import { redactExplicitFailure } from "../domain/explicitSensitiveFailure.js"; @@ -115,6 +137,24 @@ export interface SessionDerivedToolOptions { readonly resources: ArtifactResourceScope; } +/** The artifact resource scope application workflows read caller-named files under. */ +export interface ApplicationWorkflowToolOptions { + readonly resources: ArtifactResourceScope; +} + +/** A requested view, or the summary view a `detail: "summary"` request selects. */ +const requestedView = (input: { + readonly detail?: "complete" | "summary"; + readonly view?: AnalysisViewRequest | undefined; +}): AnalysisViewRequest | undefined => + input.view ?? (input.detail === "summary" ? { kind: "summary" } : undefined); + +/** A completed workflow that leaves no residual unknown. */ +const settledResult = ( + result: Result, +): Result => + result.ok ? ok(settledExecution(result.value)) : result; + /** Artifact resources a selected view may read, when the server owns them. */ export interface AnalysisViewToolOptions { readonly resources?: ArtifactResourceScope | undefined; @@ -664,6 +704,110 @@ const SERVICE_TOOL_BINDINGS = { }, }, })) satisfies Bind, + // Application workflows complete Evidence from session-held Evidence or + // caller-named files; a requested view or summary is staged against it. + applicationWorkflows: (({ resources }, { evidenceById }) => { + const playwright = new PlaywrightTraceService( + new PlaywrightTraceDecoder(resources), + ); + return { + trace_application_feature: { + admission: "sdk", + view: ({ view }) => view, + workflow: async ({ view: _selected, ...input }, { signal }) => + settledResult( + traceApplicationFeatureEvidence(input, evidenceById, { signal }), + ), + }, + trace_javascript_semantics: { + admission: "sdk", + workflow: async (input, { signal }) => + settledResult( + traceJavaScriptSemanticsEvidence(input, evidenceById, { signal }), + ), + }, + compare_application_versions: { + admission: "sdk", + workflow: async (input, { signal }) => + compareApplicationVersionsExecution(input, evidenceById, { signal }), + }, + compare_static_and_observed_endpoints: { + admission: "sdk", + view: requestedView, + workflow: async (input, { signal }) => + settledResult( + await compareStaticAndObservedEndpointsEvidence( + input, + evidenceById, + { signal }, + ), + ), + }, + inspect_api_contract: { + admission: "sdk", + view: requestedView, + workflow: async (input, { signal }) => + inspectionExecution( + await inspectApiContractEvidence(input, resources, { signal }), + ), + }, + inspect_ntfs_journal: { + admission: "sdk", + workflow: async (input, { signal }) => + inspectionExecution( + await inspectNtfsJournalEvidence(input, resources, signal), + ), + }, + inspect_playwright_trace: { + admission: "sdk", + view: requestedView, + workflow: async (input, { signal }) => + inspectionExecution(await playwright.inspect(input, signal)), + }, + compare_source_to_bundle: { + admission: "sdk", + view: ({ view }) => view, + workflow: (input, { signal }) => + sourceToBundleComparisonExecution(input, evidenceById, resources, { + signal, + }), + }, + compare_javascript_export_shapes: { + admission: "sdk", + workflow: async (input, { signal }) => + compareJavaScriptExportShapesExecution(input, evidenceById, { + signal, + }), + }, + // The ledger refuses Evidence formats through the format owner. + build_reconstruction_obligation_ledger: { + admission: "application", + workflow: async (input) => + reconstructionObligationLedgerExecution(input), + }, + project_android_application_graph: { + admission: "sdk", + workflow: async (input, { signal }) => + settledResult( + projectAndroidApplicationEvidence(input, evidenceById, { signal }), + ), + }, + project_apple_application_graph: { + admission: "sdk", + workflow: async (input, { signal }) => + settledResult( + projectAppleApplicationEvidence(input, evidenceById, { signal }), + ), + }, + project_harmony_application_graph: { + admission: "sdk", + workflow: async (input, { signal }) => + settledResult( + projectHarmonyApplicationEvidence(input, evidenceById, { signal }), + ), + }, + }; + }) satisfies Bind, sessionStatus: ((options) => ({ binary_session: { admission: "sdk", diff --git a/tests/boundary/mcp/featureTraceViewsMcp.test.ts b/tests/boundary/mcp/featureTraceViewsMcp.test.ts index e8508b3279..e176996729 100644 --- a/tests/boundary/mcp/featureTraceViewsMcp.test.ts +++ b/tests/boundary/mcp/featureTraceViewsMcp.test.ts @@ -12,10 +12,9 @@ import { parseEvidence, type Evidence } from "../../../src/domain/evidence.js"; import { applicationFeatureTraceResultSchema } from "../../../src/domain/javascript/javascriptFeatureTraceSchemas.js"; import { jsonObjectSchema } from "../../../src/domain/jsonValue.js"; import { createServer } from "../../../src/server/createServer.js"; -import { deliverApplicationEvidence } from "../../../src/server/registerApplicationTools/helpers.js"; +import { deliverApplicationExecution } from "../../../src/server/deliverApplicationExecution.js"; +import { settledExecution } from "../../../src/application/ApplicationToolExecutions.js"; import { traceApplicationFeatureEvidence } from "../../../src/application/javascript/JavaScriptApplicationWorkflowService.js"; -import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js"; -import { silentLogger } from "../../../src/logger.js"; import { createToolResultDelivery } from "../../../src/server/toolResult.js"; import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js"; import { createTestBinarySession } from "../../fixtures/binarySession.js"; @@ -513,25 +512,20 @@ it("commits no session facts when cancelled after the trace completes", async () JAVASCRIPT_FEATURE_TRACE_EXAMPLE, ); if (!traceExecution.ok) throw traceExecution.error; - const artifactResources = new ArtifactResourceScope(); - onTestFinished(() => artifactResources.close()); const before = session.exportEvidenceBundle(); for (const view of [undefined, { kind: "summary" } as const]) { const cancelled = new AbortController(); cancelled.abort(new Error("client cancelled")); // Cancellation can only arrive between completion and commit through this // staging step, which the public workflow cannot schedule deterministically. - const delivered = await deliverApplicationEvidence( - { delivery: createToolResultDelivery(undefined) }, + const delivered = await deliverApplicationExecution( + createToolResultDelivery(undefined), { - artifactResources, - logger: silentLogger, evidenceById: (id) => session.evidenceById(id), recordEvidence: (evidence) => session.recordEvidence(evidence), - recordEvidenceWithUnknown: undefined, }, toolContract("trace_application_feature"), - traceExecution.value, + settledExecution(traceExecution.value), view, cancelled.signal, );