fix(mcp): keep prompt completion within ready provider sessions
Avoid lazy provider startup for document and procedure completion. Propagate MCP cancellation through completers, cancel lookups during session transitions, and share provider result projection with ordinary operations. Cover cold, starting, warm, queued, cancelled, and closed sessions through MCP composition and provider boundaries.
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
|
||||
import {
|
||||
McpServer,
|
||||
isCallToolResult,
|
||||
@@ -34,6 +36,12 @@ 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;
|
||||
@@ -124,6 +132,7 @@ class ErrorEvidenceTransport implements Transport {
|
||||
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,
|
||||
@@ -141,6 +150,8 @@ class ErrorEvidenceTransport implements Transport {
|
||||
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 (
|
||||
@@ -148,14 +159,28 @@ class ErrorEvidenceTransport implements Transport {
|
||||
message.method === "notifications/cancelled"
|
||||
) {
|
||||
const id = message.params?.["requestId"];
|
||||
if (typeof id === "string" || typeof id === "number")
|
||||
if (typeof id === "string" || typeof id === "number") {
|
||||
this.pendingTools.delete(id);
|
||||
this.pendingCompletions.get(id)?.abort();
|
||||
this.pendingCompletions.delete(id);
|
||||
}
|
||||
}
|
||||
this.onmessage?.(message, extra);
|
||||
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?.();
|
||||
};
|
||||
}
|
||||
@@ -176,6 +201,9 @@ class ErrorEvidenceTransport implements Transport {
|
||||
await this.transport.close();
|
||||
} finally {
|
||||
this.pendingTools.clear();
|
||||
for (const completion of this.pendingCompletions.values())
|
||||
completion.abort();
|
||||
this.pendingCompletions.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,8 +239,10 @@ class ErrorEvidenceTransport implements Transport {
|
||||
await this.transport.send({ ...recovered, result }, options);
|
||||
} else await this.transport.send(recovered, options);
|
||||
} finally {
|
||||
if (!isJSONRPCRequest(message) && id !== undefined)
|
||||
if (!isJSONRPCRequest(message) && id !== undefined) {
|
||||
this.pendingTools.delete(id);
|
||||
this.pendingCompletions.delete(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,11 @@ import type { EvidenceReader } from "../application/investigation/InvestigationR
|
||||
import { z } from "zod";
|
||||
|
||||
import { uniqueSorted } from "../domain/canonicalOrdering.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
|
||||
import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js";
|
||||
import type { PromptCompletionKind } from "../contracts/promptContracts.js";
|
||||
import { currentMcpRequestSignal } from "./EvidenceMcpServer.js";
|
||||
import { artifactInventoryResultSchema } from "../domain/artifactGraph.js";
|
||||
import { artifactInspectionResultSchema } from "../domain/artifactInspection.js";
|
||||
import { parseProcessCapture } from "../domain/process/processCaptureParsing.js";
|
||||
@@ -57,9 +59,13 @@ const completionCandidates = async (
|
||||
): Promise<readonly string[]> => {
|
||||
switch (kind) {
|
||||
case "document":
|
||||
return documentCandidates(analysis);
|
||||
return documentCandidates(analysis, session);
|
||||
case "procedure":
|
||||
return procedureCandidates(analysis, context?.arguments?.document);
|
||||
return procedureCandidates(
|
||||
analysis,
|
||||
session,
|
||||
context?.arguments?.document,
|
||||
);
|
||||
case "provider":
|
||||
return providerCandidates(session);
|
||||
case "evidence":
|
||||
@@ -74,8 +80,15 @@ const completionCandidates = async (
|
||||
|
||||
const documentCandidates = async (
|
||||
analysis: AnalysisOperationPort,
|
||||
session: BinarySessionPort | undefined,
|
||||
): Promise<readonly string[]> => {
|
||||
const result = await analysis.execute("list_documents", {});
|
||||
const result = await completionInventoryLookup(
|
||||
analysis,
|
||||
session,
|
||||
"list_documents",
|
||||
{},
|
||||
);
|
||||
if (result === undefined) return [];
|
||||
if (!result.ok) return [];
|
||||
const parsed = documentListSchema.safeParse(result.value.result);
|
||||
return parsed.success ? parsed.data : [];
|
||||
@@ -83,12 +96,19 @@ const documentCandidates = async (
|
||||
|
||||
const procedureCandidates = async (
|
||||
analysis: AnalysisOperationPort,
|
||||
session: BinarySessionPort | undefined,
|
||||
document: string | undefined,
|
||||
): Promise<readonly string[]> => {
|
||||
const byAddress = new Map<string, string>();
|
||||
const input =
|
||||
document === undefined || document.length === 0 ? {} : { document };
|
||||
const result = await analysis.execute("list_procedures", input);
|
||||
const result = await completionInventoryLookup(
|
||||
analysis,
|
||||
session,
|
||||
"list_procedures",
|
||||
input,
|
||||
);
|
||||
if (result === undefined) return [];
|
||||
if (result.ok) {
|
||||
const parsed = z
|
||||
.array(z.object({ address: z.string(), value: z.string() }))
|
||||
@@ -111,6 +131,21 @@ const procedureCandidates = async (
|
||||
return candidates;
|
||||
};
|
||||
|
||||
const completionInventoryLookup = async (
|
||||
analysis: AnalysisOperationPort,
|
||||
session: BinarySessionPort | undefined,
|
||||
operation: "list_documents" | "list_procedures",
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
) => {
|
||||
const signal = currentMcpRequestSignal();
|
||||
const options = signal === undefined ? {} : { signal };
|
||||
const result =
|
||||
session === undefined
|
||||
? await analysis.execute(operation, parameters, options)
|
||||
: await session.executeIfProviderReady(operation, parameters, options);
|
||||
return signal?.aborted === true ? undefined : result;
|
||||
};
|
||||
|
||||
const providerCandidates = (
|
||||
session: BinarySessionPort | undefined,
|
||||
): readonly string[] => {
|
||||
|
||||
Reference in New Issue
Block a user