feat(mcp): add opt-in streamable HTTP transport (#4955)

Add an explicit Streamable HTTP entry for environment/gateway hosts while keeping stdio registrations and default behavior. Preserve the shared provider/session owner across DELETE and replacement; fence and drain tool/completion work before handover or teardown.

Bound HTTP input and plain-response admission, cancel refused bodies, join whole exchanges and asynchronous response cleanup before provider hooks, gate startup readiness, and reject queued HTTP/1.1 pipelining while retaining sequential keep-alive.

Validation: 8 static/build tasks, 83 adapter tests and registry metadata pass. A real installed gh binary produces seven equivalent CLI/stdio/HTTP reports with DELETE/replacement and clean signal shutdown. Broader local native-provider/ownership failures reproduce on clean main and are documented with limitations in the PR.

Co-authored-by: Edgar Arakelyan <[email protected]>
Co-authored-by: gensokyo-dev <[email protected]>
This commit is contained in:
Edgar Arakelyanandgensokyo-dev authored and GitHub committed 2026-10-19 23:58:51 +08:00
1 parent 255d906e15
commit 60bd646478
36 files changed
+5211 -57

No files matched your search

+2 -2
View File
@@ -1,7 +1,6 @@
import { AsyncLocalStorage } from "node:async_hooks";
import {
McpServer,
isCallToolResult,
isJSONRPCRequest,
isJSONRPCNotification,
@@ -40,6 +39,7 @@ import {
measureMcpResultWithinBudget,
TARGET_CONTENT_RESULT_META,
} from "./toolResultEncoding.js";
import { RequestTrackingMcpServer } from "./RequestTrackingMcpServer.js";
export type { CompactInputSchemaPresentation } from "../contracts/compactInputSchema.js";
@@ -104,7 +104,7 @@ export const forgetPendingMcpRequest = (
};
/** Bind oversized MCP error recovery to this server's Evidence ledger. */
export class EvidenceMcpServer extends McpServer {
export class EvidenceMcpServer extends RequestTrackingMcpServer {
readonly catalogIdentity: ReturnType<typeof createCatalogIdentity>;
private readonly compactPresentation:
| CompactInputSchemaPresentation
@@ -0,0 +1,88 @@
import { Client } from "@modelcontextprotocol/client";
import { InMemoryTransport } from "@modelcontextprotocol/server";
import { expect, it } from "vitest";
import { z } from "zod";
import { RequestTrackingMcpServer } from "./RequestTrackingMcpServer.js";
it.each([false, true])(
"preserves context-only callbacks with HTTP tracking enabled=%s",
async (tracking) => {
const server = new RequestTrackingMcpServer({
name: "context-only",
version: "1",
});
if (tracking) server.enableRequestTracking();
server.registerTool("context", {}, (context) => ({
content: [{ type: "text", text: String(context.mcpReq.signal.aborted) }],
}));
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const client = new Client({ name: "context-client", version: "1" });
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
expect((await client.callTool({ name: "context" })).content).toEqual([
{ type: "text", text: "false" },
]);
expect(await server.drainRequests(0)).toBe(true);
} finally {
await client.close();
await server.close();
}
},
);
it("never starts a tool whose asynchronous input validation finishes after transport cancellation", async () => {
let release!: () => void;
let entered!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const validating = new Promise<void>((resolve) => {
entered = resolve;
});
let calls = 0;
const server = new RequestTrackingMcpServer({
name: "validation-race",
version: "1",
});
server.enableRequestTracking();
server.registerTool(
"slow_validation",
{
inputSchema: z.object({
value: z.string().refine(async () => {
entered();
await gate;
return true;
}),
}),
},
() => {
calls += 1;
return { content: [] };
},
);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const client = new Client({ name: "validation-client", version: "1" });
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
void client
.callTool({ name: "slow_validation", arguments: { value: "x" } })
.catch(() => undefined);
await validating;
await server.close();
expect(await server.drainRequests(0)).toBe(true);
release();
await new Promise<void>((resolve) => setImmediate(resolve));
expect(calls).toBe(0);
expect(await server.drainRequests(0)).toBe(true);
} finally {
release();
await client.close();
await server.close();
}
});
+92
View File
@@ -0,0 +1,92 @@
import {
McpServer,
type Icon,
type RegisteredTool,
type ServerContext,
type ScopeChallengeHandler,
type StandardSchemaWithJSON,
type ToolAnnotations,
type ToolCallback,
} from "@modelcontextprotocol/server";
/** Tracks tools automatically; other resource-using MCP callbacks use runRequest. */
export class RequestTrackingMcpServer extends McpServer {
readonly #calls = new Set<Promise<unknown>>();
#tracking = false;
/** HTTP sessions share resources across transports; stdio keeps the SDK's original behavior. */
enableRequestTracking(): void {
this.#tracking = true;
}
override registerTool<
OutputArgs extends StandardSchemaWithJSON,
InputArgs extends StandardSchemaWithJSON | undefined = undefined,
>(
name: string,
config: {
title?: string;
description?: string;
inputSchema?: InputArgs;
outputSchema?: OutputArgs;
annotations?: ToolAnnotations;
icons?: Icon[];
scopeChallenge?: ScopeChallengeHandler;
_meta?: Record<string, unknown>;
},
callback: ToolCallback<InputArgs>,
): RegisteredTool {
// The SDK calls a schema-less callback with context alone, and a schema'd
// callback with (validated input, context). Narrow its conditional type at
// the same inputSchema discriminant used by the SDK.
const tracked =
config.inputSchema === undefined
? (context: ServerContext) =>
this.runRequest(context.mcpReq.signal, () =>
(callback as ToolCallback<undefined>)(context),
)
: (args: unknown, context: ServerContext) =>
this.runRequest(context.mcpReq.signal, () =>
(callback as ToolCallback<StandardSchemaWithJSON>)(args, context),
);
return super.registerTool<OutputArgs, InputArgs>(
name,
config,
tracked as ToolCallback<InputArgs>,
);
}
/** Retain HTTP dispatch, tool and completion work under the HTTP owner's shared drain. */
runRequest<T>(
signal: AbortSignal | undefined,
callback: () => T | Promise<T>,
): T | Promise<T> {
if (!this.#tracking) return callback();
// SDK validation can finish after its transport closed. Such a callback
// must never start work against the next session's shared resources.
const call = Promise.resolve().then(() => {
signal?.throwIfAborted();
return callback();
});
this.#calls.add(call);
return call.finally(() => this.#calls.delete(call));
}
/** Wait for running handlers, including their finally blocks; a timeout retains ownership. */
async drainRequests(timeoutMs?: number): Promise<boolean> {
if (this.#calls.size === 0) return true;
const settled = Promise.allSettled(this.#calls).then(() => true);
if (timeoutMs === undefined) return settled;
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
settled,
new Promise<false>((resolve) => {
timer = setTimeout(() => resolve(false), timeoutMs);
}),
]);
} finally {
clearTimeout(timer);
}
}
}
+180
View File
@@ -0,0 +1,180 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { writeWebResponse } from "./nodeHttpBridge.js";
import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
export type HttpAdmissionLifetime = "dispatch" | "response";
export interface NodeHttpExchangeContext {
readonly onDispatchSettled: (state: {
readonly hasUnreadBody: boolean;
readonly admissionLifetime: HttpAdmissionLifetime;
}) => void;
readonly onBodyCleanup: (cleanup: Promise<void>) => void;
}
interface NodeHttpRequestTarget {
readonly serve: (
request: IncomingMessage,
response: ServerResponse,
context: NodeHttpExchangeContext,
) => Promise<void>;
readonly refuse: (reason: "capacity" | "cleanup") => Response;
}
/** Own admitted exchanges and separately joinable response-source cleanup. */
export class NodeHttpRequestOwner {
#active = 0;
readonly #exchanges = new Set<Promise<void>>();
readonly #bodyCleanups = new Set<Promise<void>>();
readonly #cleanupFailures: unknown[] = [];
constructor(
private readonly capacity: number,
private readonly target: NodeHttpRequestTarget,
) {
if (!Number.isSafeInteger(capacity) || capacity < 1)
throw new RangeError(
"maxConcurrentDispatches must be a positive safe integer",
);
}
handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
// Node queues a pipelined response without assigning a socket until its
// predecessor finishes. Never start work or queue a refusal behind it.
if (request.socket.destroyed || response.socket === null) {
request.socket.destroy();
return Promise.resolve();
}
const refusal =
this.#cleanupFailures.length > 0
? "cleanup"
: this.#active >= this.capacity
? "capacity"
: undefined;
if (refusal !== undefined) {
return this.#trackExchange(async () => {
try {
await writeWebResponse(this.target.refuse(refusal), response, {
closeConnection: true,
onBodyCleanup: this.#trackBodyCleanup,
});
} catch {
response.destroy();
}
});
}
this.#active += 1;
let reserved = true;
let dispatched = false;
let inputDone = false;
let responseDone = false;
let holdResponse = true;
let pendingCleanups = 0;
let cleanupFailed = false;
const release = (): void => {
if (!reserved) return;
reserved = false;
this.#active -= 1;
request.off("end", inputEnded);
request.off("close", inputEnded);
response.off("close", inputEnded);
};
const releaseIfReady = (): void => {
if (
dispatched &&
inputDone &&
(!holdResponse ||
(responseDone && pendingCleanups === 0 && !cleanupFailed))
)
release();
};
const inputEnded = (): void => {
inputDone = true;
releaseIfReady();
};
return this.#trackExchange(async () => {
if (request.socket.destroyed || response.destroyed) {
release();
return;
}
try {
await this.target.serve(request, response, {
onBodyCleanup: (cleanup) => {
pendingCleanups += 1;
this.#trackBodyCleanup(cleanup, (succeeded) => {
pendingCleanups -= 1;
cleanupFailed ||= !succeeded;
releaseIfReady();
});
},
onDispatchSettled: ({ hasUnreadBody, admissionLifetime }) => {
dispatched = true;
holdResponse = admissionLifetime === "response";
if (!hasUnreadBody || request.destroyed || response.destroyed) {
inputEnded();
return;
}
request.once("end", inputEnded);
request.once("close", inputEnded);
response.once("close", inputEnded);
},
});
} catch (cause: unknown) {
response.destroy();
release();
throw cause;
} finally {
responseDone = true;
releaseIfReady();
}
});
}
#trackExchange(serve: () => Promise<void>): Promise<void> {
const exchange = Promise.resolve().then(serve);
this.#exchanges.add(exchange);
return exchange.finally(() => this.#exchanges.delete(exchange));
}
readonly #trackBodyCleanup = (
cleanup: Promise<void>,
settled?: (succeeded: boolean) => void,
): void => {
this.#bodyCleanups.add(cleanup);
void cleanup.then(
() => {
this.#bodyCleanups.delete(cleanup);
settled?.(true);
},
(cause: unknown) => {
this.#cleanupFailures.push(cause);
this.#bodyCleanups.delete(cleanup);
settled?.(false);
},
);
};
async drain(): Promise<void> {
// An exchange can register cancellation after its route has returned,
// including when a late Response finds that its client already left.
while (this.#exchanges.size > 0)
await Promise.allSettled([...this.#exchanges]);
while (this.#bodyCleanups.size > 0)
await Promise.allSettled([...this.#bodyCleanups]);
if (this.#cleanupFailures.length > 0)
throw new AnalysisResourceConstraintError(
"mcp_http_response_cleanup",
"transport",
"HTTP response cleanup could not be confirmed; provider shutdown remains blocked",
{ failed_cleanup_count: this.#cleanupFailures.length },
{
cause: new AggregateError(
this.#cleanupFailures,
"Response cleanup failed",
),
retryable: false,
},
);
}
}
+283
View File
@@ -0,0 +1,283 @@
import { once } from "node:events";
import { createServer, type Server } from "node:http";
import { connect } from "node:net";
import type { AddressInfo } from "node:net";
import { afterEach, expect, it, vi } from "vitest";
import { toWebRequest, writeWebResponse } from "./nodeHttpBridge.js";
const servers: Server[] = [];
const encoder = new TextEncoder();
const decoder = new TextDecoder();
afterEach(async () => {
for (const server of servers.splice(0)) {
server.closeAllConnections();
await new Promise((resolve) => server.close(() => resolve(undefined)));
}
});
/** Serve a web handler through the bridge on an ephemeral loopback port. */
const serve = async (
handle: (request: Request) => Response | Promise<Response>,
): Promise<string> => {
const server = createServer();
servers.push(server);
server.listen(0, "127.0.0.1");
await once(server, "listening");
const origin = `http://127.0.0.1:${String((server.address() as AddressInfo).port)}`;
server.on("request", (request, response) => {
void (async () => {
try {
const webRequest = toWebRequest(request, response, origin);
await writeWebResponse(await handle(webRequest), response);
} catch {
response.destroy();
}
})();
});
return origin;
};
it("ends a HEAD reply after the headers and cancels a body the handler attached", async () => {
let pulls = 0;
let cancelled = false;
const origin = await serve(
() =>
new Response(
new ReadableStream<Uint8Array>({
pull: async () => {
pulls += 1;
// Never produces a chunk, like an idle event stream.
await new Promise(() => undefined);
},
cancel: () => {
cancelled = true;
},
}),
{ headers: { "content-type": "text/event-stream" } },
),
);
const response = await fetch(`${origin}/events`, { method: "HEAD" });
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("text/event-stream");
await vi.waitFor(() => {
expect(cancelled).toBe(true);
});
expect(pulls).toBeLessThanOrEqual(1);
});
it("finishes a HEAD reply without waiting on a teed body whose sibling stays live", async () => {
const cached = new Response(
new ReadableStream<Uint8Array>({
pull: () => new Promise(() => undefined),
}),
{ headers: { "content-type": "text/event-stream" } },
);
let finished = false;
const server = createServer((_request, response) => {
void writeWebResponse(cached.clone(), response).then(() => {
finished = true;
});
});
servers.push(server);
server.listen(0, "127.0.0.1");
await once(server, "listening");
const { port } = server.address() as AddressInfo;
const response = await fetch(`http://127.0.0.1:${String(port)}/events`, {
method: "HEAD",
});
expect(response.status).toBe(200);
await vi.waitFor(() => {
expect(finished).toBe(true);
});
});
it("cancels the body when an asynchronous route resolves after its client left", async () => {
let cancelled = false;
let settled = false;
let received = false;
const server = createServer((_request, response) => {
received = true;
response.once("close", () => {
const idle = new Response(
new ReadableStream<Uint8Array>({
pull: () => new Promise(() => undefined),
cancel: () => {
cancelled = true;
},
}),
);
const settle = (): void => {
settled = true;
};
void writeWebResponse(idle, response).then(settle, settle);
});
});
servers.push(server);
server.listen(0, "127.0.0.1");
await once(server, "listening");
const { port } = server.address() as AddressInfo;
const socket = connect(port, "127.0.0.1");
await once(socket, "connect");
socket.write("GET /late HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n");
await vi.waitFor(() => {
expect(received).toBe(true);
});
socket.destroy();
await vi.waitFor(() => {
expect(settled).toBe(true);
expect(cancelled).toBe(true);
});
});
it("returns when a client leaves a teed streaming body whose sibling stays live", async () => {
const cached = new Response(
new ReadableStream<Uint8Array>({
start: (controller) => {
controller.enqueue(encoder.encode("data: first\n\n"));
},
pull: () => new Promise(() => undefined),
}),
{ headers: { "content-type": "text/event-stream" } },
);
let settled = false;
const server = createServer((_request, response) => {
const settle = (): void => {
settled = true;
};
void writeWebResponse(cached.clone(), response).then(settle, settle);
});
servers.push(server);
server.listen(0, "127.0.0.1");
await once(server, "listening");
const { port } = server.address() as AddressInfo;
const leave = new AbortController();
const response = await fetch(`http://127.0.0.1:${String(port)}/events`, {
signal: leave.signal,
});
if (response.body === null) throw new Error("Expected a streamed body");
const first = await response.body.getReader().read();
expect(decoder.decode(first.value)).toBe("data: first\n\n");
leave.abort();
await vi.waitFor(() => {
expect(settled).toBe(true);
});
});
it("forwards method, URL, headers and the request body as a web Request", async () => {
const seen: Request[] = [];
const origin = await serve(async (request) => {
seen.push(request);
return Response.json(
{ body: await request.text() },
{ headers: { "x-reply": "bridged" } },
);
});
const response = await fetch(`${origin}/mcp?page=2`, {
method: "POST",
headers: { "content-type": "application/json", "x-probe": "yes" },
body: '{"hello":1}',
});
expect(response.status).toBe(200);
expect(response.headers.get("x-reply")).toBe("bridged");
await expect(response.json()).resolves.toEqual({ body: '{"hello":1}' });
const request = seen[0];
if (request === undefined) throw new Error("Request not bridged");
const url = new URL(request.url);
expect(request.method).toBe("POST");
expect(`${url.pathname}${url.search}`).toBe("/mcp?page=2");
expect(request.headers.get("x-probe")).toBe("yes");
expect(request.headers.get("host")).toBe(new URL(origin).host);
});
it("forwards GET requests without a body", async () => {
const origin = await serve((request) =>
Response.json({ bodyless: request.body === null }),
);
const response = await fetch(`${origin}/mcp`);
await expect(response.json()).resolves.toEqual({ bodyless: true });
});
it("streams response chunks as the handler produces them", async () => {
let release: () => void = () => undefined;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const origin = await serve(
() =>
new Response(
new ReadableStream({
async start(controller) {
controller.enqueue(encoder.encode("event: message\ndata: 1\n\n"));
await gate;
controller.enqueue(encoder.encode("event: message\ndata: 2\n\n"));
controller.close();
},
}),
{ headers: { "content-type": "text/event-stream" } },
),
);
const response = await fetch(`${origin}/stream`);
expect(response.headers.get("content-type")).toBe("text/event-stream");
const reader = response.body?.getReader();
if (reader === undefined) throw new Error("Response body missing");
const first = await reader.read();
expect(decoder.decode(first.value)).toContain("data: 1");
release();
let rest = "";
for (;;) {
const { done, value } = await reader.read();
if (done) break;
rest += decoder.decode(value);
}
expect(rest).toContain("data: 2");
});
it("aborts the web Request and cancels its response body when the client leaves", async () => {
let aborted = false;
let cancelled = false;
const origin = await serve((request) => {
request.signal.addEventListener("abort", () => {
aborted = true;
});
return new Response(
new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode(": open\n\n"));
},
cancel() {
cancelled = true;
},
}),
{ headers: { "content-type": "text/event-stream" } },
);
});
const controller = new AbortController();
const response = await fetch(`${origin}/stream`, {
signal: controller.signal,
});
const reader = response.body?.getReader();
if (reader === undefined) throw new Error("Response body missing");
await reader.read();
controller.abort();
await vi.waitFor(() => {
expect(aborted).toBe(true);
expect(cancelled).toBe(true);
});
});
it("preserves every Set-Cookie header of a composed route", async () => {
const origin = await serve(() => {
const headers = new Headers({ "x-one": "1" });
headers.append("set-cookie", "session=a; Path=/; HttpOnly");
headers.append("set-cookie", "csrf=b; Path=/");
return new Response("ok", { headers });
});
const response = await fetch(`${origin}/cookies`);
expect(response.headers.get("x-one")).toBe("1");
expect(response.headers.getSetCookie()).toEqual([
"session=a; Path=/; HttpOnly",
"csrf=b; Path=/",
]);
});
+228
View File
@@ -0,0 +1,228 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { finished } from "node:stream";
/** Fetch rejects a body on these methods, so their request streams are not forwarded. */
const BODYLESS_METHODS: ReadonlySet<string> = new Set(["GET", "HEAD"]);
/** The request target was not an origin-form path; the bridge serves an origin server only. */
export class UnsupportedRequestTargetError extends Error {
override readonly name = "UnsupportedRequestTargetError";
constructor(target: string) {
super(`Unsupported request target ${target}`);
}
}
/** Join an origin-form target onto the listener's origin verbatim, so `//host/path` stays a path and a path that URL parsing would rewrite (dot segments) is refused rather than routed elsewhere. */
const requestUrl = (target: string, origin: string): URL => {
if (!target.startsWith("/") || target.includes("#"))
throw new UnsupportedRequestTargetError(target);
const url = new URL(`${origin}${target}`);
const rawPath = target.split("?")[0] ?? "";
if (url.pathname !== rawPath) throw new UnsupportedRequestTargetError(target);
return url;
};
const toHeaders = (incoming: IncomingMessage["headers"]): Headers => {
const headers = new Headers();
for (const [name, value] of Object.entries(incoming)) {
if (value === undefined) continue;
if (Array.isArray(value))
for (const entry of value) headers.append(name, entry);
else headers.set(name, value);
}
return headers;
};
/** Cancelling a body stops reads; the response owner closes an unread upload after replying. */
const requestBody = (request: IncomingMessage): ReadableStream<Uint8Array> => {
let ended = false;
let controller: ReadableStreamDefaultController<Uint8Array>;
let cleanup = (): void => undefined;
const onData = (chunk: unknown): void => {
if (ended) return;
if (!Buffer.isBuffer(chunk)) {
ended = true;
request.pause();
request.off("data", onData);
controller.error(new TypeError("HTTP request body must be bytes"));
return;
}
controller.enqueue(new Uint8Array(chunk));
if ((controller.desiredSize ?? 0) <= 0) request.pause();
};
return new ReadableStream<Uint8Array>(
{
start(target) {
controller = target;
request.pause();
cleanup = finished(
request,
{ readable: true, writable: false },
(cause) => {
request.off("data", onData);
cleanup();
if (ended) return;
ended = true;
if (cause) controller.error(cause);
else controller.close();
},
);
request.on("data", onData);
},
pull() {
if (!ended) request.resume();
},
cancel() {
ended = true;
request.pause();
request.off("data", onData);
// Keep finished's error/close ownership until the raw request settles.
},
},
new ByteLengthQueuingStrategy({
highWaterMark: request.readableHighWaterMark,
}),
);
};
/** Translate a node:http request into a web Request whose signal aborts when the client leaves. */
export const toWebRequest = (
request: IncomingMessage,
response: ServerResponse,
origin: string,
): Request => {
const controller = new AbortController();
response.once("close", () => {
if (!response.writableFinished) controller.abort();
});
const method = request.method ?? "GET";
return new Request(requestUrl(request.url ?? "/", origin), {
method,
headers: toHeaders(request.headers),
signal: controller.signal,
...(BODYLESS_METHODS.has(method)
? {}
: { body: requestBody(request), duplex: "half" }),
});
};
/** Header fields for writeHead; repeated Set-Cookie values survive as one array. */
const responseHeaders = (
headers: Headers,
closeConnection: boolean,
): Record<string, string | string[]> => {
const fields: Record<string, string | string[]> = {};
for (const [name, value] of headers)
if (name !== "set-cookie") fields[name] = value;
const cookies = headers.getSetCookie();
if (cookies.length > 0) fields["set-cookie"] = cookies;
if (closeConnection) fields.connection = "close";
return fields;
};
/** Resolve on the next `drain` or `close`, removing both listeners, so a long stream does not accumulate waiters. */
const drainOrClose = (target: ServerResponse): Promise<void> =>
new Promise((resolve) => {
if (target.destroyed) {
resolve();
return;
}
const settle = (): void => {
target.off("drain", settle);
target.off("close", settle);
resolve();
};
target.once("drain", settle);
target.once("close", settle);
});
export interface WebResponseOptions {
readonly closeConnection?: boolean;
/** Retain cleanup independently of request completion, including pending tee cancellation. */
readonly onBodyCleanup?: (cleanup: Promise<void>) => void;
}
const retainCleanup = (
cleanup: Promise<void>,
options: WebResponseOptions,
): void => {
options.onBodyCleanup?.(cleanup);
// The owner receives the original outcome; standalone writers stay nonblocking.
void cleanup.catch(() => undefined);
};
/** Copy with backpressure; request completion does not wait on source cancellation. */
const pumpBody = async (
reader: ReadableStreamDefaultReader<Uint8Array>,
target: ServerResponse,
cancel: () => void,
): Promise<void> => {
let left = false;
const leave = (): void => {
if (left) return;
left = true;
cancel();
};
target.once("close", leave);
try {
if (target.destroyed) {
leave();
return;
}
for (
let next = await reader.read();
!next.done && !left;
next = await reader.read()
)
if (!target.write(next.value) && !left) await drainOrClose(target);
} finally {
target.off("close", leave);
}
if (!left) target.end();
};
/** Stream a web Response into node:http, flushing headers and each chunk as it arrives; `closeConnection` ends the socket after this reply. A HEAD reply ends after the headers and cancels any body the route attached. */
export const writeWebResponse = async (
response: Response,
target: ServerResponse,
options: WebResponseOptions = {},
): Promise<void> => {
// One owner spans headers, pumping and completion. The pump borrows its reader,
// so every output failure cancels the same source exactly once before release.
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
try {
reader = response.body?.getReader();
} catch (cause: unknown) {
retainCleanup(Promise.reject(cause), options);
throw cause;
}
let cancelled = false;
const cancel = (): void => {
if (cancelled || reader === undefined) return;
cancelled = true;
retainCleanup(reader.cancel(), options);
};
try {
if (target.destroyed) {
cancel();
return;
}
target.writeHead(
response.status,
responseHeaders(response.headers, options.closeConnection ?? false),
);
target.flushHeaders();
if (reader === undefined || target.req.method === "HEAD") {
target.end();
// A tee's sibling may remain caller-owned; delivery does not wait for its cleanup.
cancel();
return;
}
await pumpBody(reader, target, cancel);
} catch (cause: unknown) {
cancel();
throw cause;
} finally {
reader?.releaseLock();
}
};
File diff suppressed because it is too large. Load diff
+697
View File
@@ -0,0 +1,697 @@
import {
hostHeaderValidationResponse,
isInitializeRequest,
isJsonContentType,
localhostAllowedHostnames,
originValidationResponse,
readRequestBody,
WebStandardStreamableHTTPServerTransport,
type McpServer,
type McpRequestContext,
type Server,
} from "@modelcontextprotocol/server";
import { randomUUID } from "node:crypto";
import { once } from "node:events";
import {
createServer as createHttpServer,
type IncomingMessage,
type ServerResponse,
} from "node:http";
import { isIPv4, isIPv6, type AddressInfo } from "node:net";
import type { Logger } from "pino";
import {
toWebRequest,
UnsupportedRequestTargetError,
writeWebResponse,
} from "./nodeHttpBridge.js";
import { StreamableHttpListenError } from "./streamableHttpListenError.js";
import {
NodeHttpRequestOwner,
type HttpAdmissionLifetime,
type NodeHttpExchangeContext,
} from "./NodeHttpRequestOwner.js";
import { RequestTrackingMcpServer } from "../RequestTrackingMcpServer.js";
import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
/** MCP endpoint path shared by `rea mcp --http` and agent environment servers. */
export const MCP_HTTP_PATH = "/mcp";
/** One plain HTTP route served beside the MCP endpoint as web Request to Response. */
export interface StreamableHttpRoute {
readonly method: string;
readonly path: string;
readonly handle: (request: Request) => Response | Promise<Response>;
}
export interface ServeStreamableHttpOptions {
readonly host: string;
readonly port: number;
/** Called once; the instance serves every session in turn on a fresh transport. */
readonly createMcpServer: (
context: McpRequestContext,
) => RequestTrackingMcpServer | Promise<RequestTrackingMcpServer>;
/** Maximum time a client session handover waits for cancelled tool/completion handlers. */
readonly sessionDrainTimeoutMs?: number;
/** Concurrent HTTP input/route work (default 8); unread uploads retain their permit. */
readonly maxConcurrentDispatches?: number;
readonly routes?: readonly StreamableHttpRoute[];
readonly logger?: Logger;
/** Reports listener failures after binding; request failures are logged instead. */
readonly onerror?: (error: Error) => void;
/** Close the server instance as the last stage of `close`; false when the factory's owner closes it. */
readonly closeInstance?: boolean;
}
export interface StreamableHttpServer {
/** The bound MCP endpoint URL. */
readonly url: string;
/** Stop incoming dispatch and drain handlers before shared provider owners close. */
readonly prepareShutdown: () => Promise<void>;
readonly close: () => Promise<void>;
}
/** The bind host as the SDK compares Host headers: lowercase, IPv6 bracketed and canonical. */
const normalizedHostname = (host: string): string | undefined => {
try {
return new URL(`http://${isIPv6(host) ? `[${host}]` : host}`).hostname;
} catch {
return undefined;
}
};
const isLoopbackIpv4 = (address: string): boolean =>
isIPv4(address) && address.startsWith("127.");
/** Classify the native bound IP; configured DNS names are not binding evidence. */
const isLoopbackAddress = (hostname: string): boolean => {
if (isLoopbackIpv4(hostname)) return true;
if (!hostname.startsWith("[") || !hostname.endsWith("]")) return false;
const inner = hostname.slice(1, -1);
if (inner === "::1") return true;
if (!inner.startsWith("::ffff:")) return false;
const mapped = inner.slice("::ffff:".length);
if (isLoopbackIpv4(mapped)) return true;
const hex = /^([0-9a-f]{1,4}):[0-9a-f]{1,4}$/u.exec(mapped);
return hex !== null && Number.parseInt(hex[1] ?? "0", 16) >> 8 === 0x7f;
};
/** Classify the bound address first, then allow its address and configured name. */
export const hostHeaderAllowlist = (
host: string,
boundAddress: string,
): string[] | undefined => {
const bound = normalizedHostname(boundAddress);
if (bound === undefined || !isLoopbackAddress(bound)) return undefined;
const names = [normalizedHostname(host), bound];
const known = names.filter((name): name is string => name !== undefined);
return [...new Set([...localhostAllowedHostnames(), ...known])];
};
const jsonError = (status: number, code: number, message: string): Response =>
Response.json(
{ jsonrpc: "2.0", error: { code, message }, id: null },
{ status },
);
const protocolOf = (instance: McpServer | Server): Server =>
"server" in instance ? instance.server : instance;
const describe = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
const NO_SHUTDOWN_HOOK = (): void => undefined;
const SHUTTING_DOWN = (): Response =>
jsonError(503, -32000, "Server shutting down");
const SESSION_NOT_FOUND = (): Response =>
jsonError(404, -32001, "Session not found");
const DEFAULT_SESSION_DRAIN_TIMEOUT_MS = 10_000;
const DEFAULT_MAX_CONCURRENT_DISPATCHES = 8;
class SessionDrainTimeoutError extends AnalysisResourceConstraintError {
constructor(timeoutMs: number) {
super(
"mcp_http_session",
"transport",
"Previous MCP session still has running requests; retry after they finish",
{ drain_timeout_ms: timeoutMs },
);
}
}
/** Split a header field on `separator` outside quoted strings, honouring backslash escapes (RFC 9110). */
const splitUnquoted = (value: string, separator: string): string[] => {
const parts: string[] = [];
let current = "";
let quoted = false;
let escaped = false;
for (const char of value) {
if (escaped) escaped = false;
else if (quoted && char === "\\") escaped = true;
else if (char === '"') quoted = !quoted;
else if (char === separator && !quoted) {
parts.push(current);
current = "";
continue;
}
current += char;
}
parts.push(current);
return parts;
};
/** The media type proper of one header value or Accept range: no parameters, lowercase. */
const mediaType = (value: string): string =>
(splitUnquoted(value, ";")[0] ?? "").trim().toLowerCase();
/** An Accept range's quality weight; a missing or unreadable `q` counts as 1, as in RFC 9110. */
const quality = (range: string): number => {
const q = splitUnquoted(range, ";")
.slice(1)
.map((parameter) => parameter.split("="))
.find(([name]) => name?.trim().toLowerCase() === "q")?.[1];
const value = q === undefined ? 1 : Number(q.trim());
return Number.isFinite(value) ? value : 1;
};
/** The headers the SDK requires of a streamable POST; a request without them is left to the transport's refusal. */
const hasStreamablePostHeaders = (request: Request): boolean => {
const accept = request.headers.get("accept") ?? "";
// Exact media ranges with a positive weight: `application/json-patch+json`, `text/event-streaming`
// and `application/json;q=0` do not count.
const accepted = new Set(
splitUnquoted(accept, ",")
.filter((range) => quality(range) > 0)
.map(mediaType),
);
// The SDK's own checks too: its Accept test is a case-sensitive substring match, so a header it
// would refuse with 406 (such as `Application/JSON`) must not close the live session first.
return (
accepted.has("application/json") &&
accepted.has("text/event-stream") &&
accept.includes("application/json") &&
accept.includes("text/event-stream") &&
isJsonContentType(request.headers.get("content-type"))
);
};
/** Only a new client's initialize travels without a session id; peek within the SDK body bound. */
const isInitializePost = async (request: Request): Promise<boolean> => {
if (
request.method !== "POST" ||
request.headers.has("mcp-session-id") ||
!hasStreamablePostHeaders(request)
)
return false;
const probe = request.clone();
try {
const read = await readRequestBody(probe);
if (read.tooLarge) return false;
const body: unknown = JSON.parse(read.text);
// The transport accepts only a lone initialize, so only that may evict a session.
return Array.isArray(body)
? body.length === 1 && isInitializeRequest(body[0])
: isInitializeRequest(body);
} catch {
return false;
} finally {
// The clone is one branch of a tee; awaiting its cancel would wait for the original to drain.
void probe.body?.cancel().catch(() => undefined);
}
};
/** Owns parsing and dispatch as well as the connected transport of one session. */
class LiveSession {
#closed = false;
readonly #bodyAbort = new AbortController();
readonly #shutdown: () => Promise<void>;
constructor(
readonly transport: WebStandardStreamableHTTPServerTransport,
private readonly instance: RequestTrackingMcpServer,
) {
this.#shutdown = transport.close.bind(transport);
}
/** Install after connect, so the SDK and Evidence adapter have bound their callbacks. */
fenceDispatch(): void {
const dispatch = this.transport.onmessage;
this.transport.onmessage = (...args) => {
if (!this.#closed) dispatch?.(...args);
};
}
handle(request: Request): Promise<Response> {
if (this.#closed) return Promise.resolve(SESSION_NOT_FOUND());
// DELETE awaits this session's close; including it in its own drain would deadlock.
if (request.method === "DELETE")
return this.transport.handleRequest(request);
return Promise.resolve(
this.instance.runRequest(undefined, async () => {
if (this.#closed) return SESSION_NOT_FOUND();
const bodyAbort = new AbortController();
try {
const guarded =
request.body === null
? request
: new Request(request, {
body: request.body.pipeThrough(
new TransformStream<Uint8Array, Uint8Array>(),
{
signal: AbortSignal.any([
this.#bodyAbort.signal,
bodyAbort.signal,
]),
},
),
duplex: "half",
} as RequestInit);
const response = await this.transport.handleRequest(guarded);
if (!this.#closed) return response;
// The SDK may have crossed an await before close and created its SSE
// response afterwards. Cancel that stream before releasing its owner.
await response.body?.cancel();
return SESSION_NOT_FOUND();
} finally {
// Header/size refusals can leave the SDK body unread. Its forwarding
// stream belongs to this dispatch, not the remaining session lifetime.
bodyAbort.abort();
}
}),
);
}
shutdown(): Promise<void> {
this.#closed = true;
this.#bodyAbort.abort();
return this.#shutdown();
}
}
/** Owns the single connected server and the transport of its current session. */
export class McpSessionSlot {
#live: LiveSession | undefined;
#arming: Promise<LiveSession> | undefined;
#closed = false;
#hookRan = false;
#draining = false;
#ending: Promise<void> | undefined;
/** The instance's own close hook, captured once; it runs exactly once, when the listener closes. */
readonly #shutdownHook: () => void;
constructor(
private readonly instance: RequestTrackingMcpServer,
private readonly logger: Logger | undefined,
private readonly drainTimeoutMs = DEFAULT_SESSION_DRAIN_TIMEOUT_MS,
) {
instance.enableRequestTracking();
const protocol = protocolOf(instance);
const captured = protocol.onclose ?? NO_SHUTDOWN_HOOK;
let running = false;
// Completion is recorded only after the hook returns, so a hook that threw stays eligible for a retry.
this.#shutdownHook = () => {
if (this.#hookRan || running) return;
running = true;
try {
captured();
this.#hookRan = true;
} finally {
running = false;
}
};
protocol.onclose = this.#shutdownHook;
}
/** Route one MCP request; a new client's initialize replaces a session its predecessor left open. */
async handle(request: Request): Promise<Response> {
try {
return await this.#handle(request);
} catch (cause: unknown) {
if (!(cause instanceof SessionDrainTimeoutError)) throw cause;
return jsonError(503, -32000, cause.message);
}
}
async #handle(request: Request): Promise<Response> {
if (this.#closed) return SHUTTING_DOWN();
if (this.#draining) await this.#live?.transport.close();
if (this.#closed) return SHUTTING_DOWN();
const open = this.#live;
if (
open?.transport.sessionId !== undefined &&
(await isInitializePost(request)) &&
// A client that left while its initialize was probed would evict the session for nobody.
!request.signal.aborted
) {
if (this.#closed) return SHUTTING_DOWN();
this.logger?.info("MCP HTTP session replaced by a new client");
await open.transport.close();
}
if (this.#closed) return SHUTTING_DOWN();
const session = await this.#current();
// Shutdown may have closed the slot while this request was arming it.
if (this.#closed) return SHUTTING_DOWN();
return session.handle(request);
}
/** Cancel and drain MCP work before any shared provider shutdown hook can run. */
async prepareShutdown(): Promise<void> {
this.#closed = true;
await this.#arming?.catch(() => undefined);
const open = this.#live;
// The session stays owned until its shutdown succeeds, so a retry can finish it.
try {
await open?.transport.close();
} catch (cause: unknown) {
// Shutdown may have joined a handover that already started its bounded
// drain. Retry that timeout with shutdown's completion-based wait.
if (!(cause instanceof SessionDrainTimeoutError)) throw cause;
await open?.transport.close();
}
if (this.#live === open) this.#live = undefined;
}
/** Finish shutdown once every consumer of the shared providers has settled. */
async close(): Promise<void> {
await this.prepareShutdown();
// Without a live transport nothing fires the instance's hook; run it here, once.
this.#shutdownHook();
}
#current(): Promise<LiveSession> {
if (this.#closed)
return Promise.reject(new Error("MCP HTTP session slot is closed"));
if (this.#live !== undefined) return Promise.resolve(this.#live);
this.#arming ??= this.#arm().finally(() => {
this.#arming = undefined;
});
return this.#arming;
}
async #arm(): Promise<LiveSession> {
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
onsessioninitialized: () => this.logger?.info("MCP HTTP session opened"),
onsessionclosed: () =>
this.logger?.info("MCP HTTP session closed by the client"),
});
const session = new LiveSession(transport, this.instance);
// The SDK closes the transport on DELETE; that ends the session, not the server.
transport.close = () => this.#endSession(session);
await this.instance.connect(transport);
session.fenceDispatch();
this.#live = session;
return session;
}
/** Close one session's transport while the instance's onclose hooks wait for close(). */
async #endSession(session: LiveSession): Promise<void> {
if (this.#live !== session) return;
if (this.#ending !== undefined) return this.#ending;
this.#draining = true;
const ending = this.#finishSession(session).finally(() => {
if (this.#ending === ending) this.#ending = undefined;
});
this.#ending = ending;
return ending;
}
async #finishSession(session: LiveSession): Promise<void> {
const protocol = protocolOf(this.instance);
protocol.onclose = NO_SHUTDOWN_HOOK;
try {
await session.shutdown();
if (
!(await this.instance.drainRequests(
this.#closed ? undefined : this.drainTimeoutMs,
))
)
throw new SessionDrainTimeoutError(this.drainTimeoutMs);
// A timed-out handler remains owned and blocks reuse until a later drain succeeds.
if (this.#live === session) this.#live = undefined;
this.#draining = false;
} finally {
protocol.onclose = this.#shutdownHook;
}
}
}
const endpointUrl = (address: AddressInfo): string => {
const host =
address.family === "IPv6" ? `[${address.address}]` : address.address;
return `http://${host}:${String(address.port)}${MCP_HTTP_PATH}`;
};
interface NodeRequestTarget {
readonly route: (request: Request) => Promise<{
readonly response: Response;
readonly admissionLifetime: HttpAdmissionLifetime;
}>;
readonly origin: () => string;
readonly logger: Logger | undefined;
}
/** Serve one MCP server, plus plain routes, over streamable HTTP until closed. */
export const serveStreamableHttp = async (
options: ServeStreamableHttpOptions,
): Promise<StreamableHttpServer> => {
const { host, port, logger, routes = [], closeInstance = true } = options;
// Scoped IPv6 literals bind but cannot be named in a URL; refuse them before anything exists.
if (host.includes("%"))
throw new StreamableHttpListenError(
new Error(`scoped IPv6 bind address ${host} is not supported`),
);
// Loopback is classified from the address the listener binds, after it binds; the instance
// is created after that, so a bind failure leaves nothing to clean up.
let allowedHosts: string[] | undefined;
let slot: McpSessionSlot | undefined;
let origin = "";
let stopped = false;
const route: NodeRequestTarget["route"] = async (request) => {
const local = (response: Response) => ({
response,
admissionLifetime: "response" as const,
});
if (stopped) return local(jsonError(503, -32000, "Server shutting down"));
// One loopback allowlist gates Host (DNS rebinding) and Origin (browser pages); a missing Origin passes.
const refused =
allowedHosts === undefined
? undefined
: (hostHeaderValidationResponse(request, allowedHosts) ??
originValidationResponse(request, allowedHosts));
if (refused !== undefined) return local(refused);
if (slot === undefined)
return local(jsonError(503, -32000, "Server starting"));
const { pathname } = new URL(request.url);
if (pathname === MCP_HTTP_PATH)
return {
response: await slot.handle(request),
admissionLifetime: "dispatch",
};
const match = routes.find(
(candidate) =>
candidate.path === pathname && candidate.method === request.method,
);
return local(
match === undefined
? jsonError(404, -32601, `No route for ${request.method} ${pathname}`)
: await match.handle(request),
);
};
const httpServer = createHttpServer();
const target: NodeRequestTarget = { route, origin: () => origin, logger };
const requests = new NodeHttpRequestOwner(
options.maxConcurrentDispatches ?? DEFAULT_MAX_CONCURRENT_DISPATCHES,
{
serve: (request, response, context) =>
serveNodeRequest(target, request, response, context),
refuse: (reason) =>
jsonError(
503,
-32000,
reason === "capacity"
? "HTTP request capacity is full; retry after pending dispatches finish"
: "HTTP response cleanup failed; this server is not accepting new requests",
),
},
);
const prepareTransportShutdown = stagedClose([
async () => {
stopped = true;
await closeHttpServer(httpServer);
},
() => slot?.prepareShutdown() ?? Promise.resolve(),
() => requests.drain(),
]);
try {
httpServer.listen(port, host);
await once(httpServer, "listening");
} catch (cause: unknown) {
throw new StreamableHttpListenError(cause);
}
const bound = httpServer.address();
let url: string;
try {
if (bound === null || typeof bound === "string")
throw new TypeError("MCP HTTP listener has no TCP address");
url = endpointUrl(bound);
origin = new URL(url).origin;
allowedHosts = hostHeaderAllowlist(host, bound.address);
} catch (cause: unknown) {
await prepareTransportShutdown().catch(() => undefined);
throw new StreamableHttpListenError(cause);
}
httpServer.on("request", (request, response) => {
void requests.handle(request, response).catch((cause: unknown) => {
logger?.warn(
{ error: describe(cause) },
"MCP HTTP request did not complete",
);
response.destroy();
});
});
// Bind failures already rejected the listening wait above; only later listener errors are reported.
httpServer.on("error", (error) => options.onerror?.(error));
let instance: RequestTrackingMcpServer;
try {
instance = await options.createMcpServer({ era: "legacy" });
} catch (cause: unknown) {
// Starting responses may still be in flight; application routes stay unavailable.
await prepareTransportShutdown().catch(() => undefined);
throw cause;
}
protocolOf(instance).onerror = (error) =>
logger?.warn({ error: error.message }, "MCP HTTP request rejected");
const live = new McpSessionSlot(
instance,
logger,
options.sessionDrainTimeoutMs,
);
slot = live;
if (allowedHosts === undefined)
logger?.warn(
{ host },
"MCP HTTP Host header validation relaxed for a non-loopback bind",
);
// The URL is the only way to reach an ephemeral port, so the announcement ignores the log threshold.
logger
?.child({}, { level: "info" })
.info({ transport: "streamable-http", url }, "MCP transport listening");
const prepareShutdown = stagedClose([
prepareTransportShutdown,
() => live.close(),
]);
const close = stagedClose([
prepareShutdown,
...(closeInstance ? [() => instance.close()] : []),
]);
return { url, prepareShutdown, close };
};
/** Stop accepting, drop open connections and release the port. */
const closeHttpServer = (
httpServer: ReturnType<typeof createHttpServer>,
): Promise<void> => {
// close() first, as Node documents: a connection accepted before it would otherwise miss the forced-close pass.
const closed = new Promise<void>((resolve, reject) => {
httpServer.close((error) =>
error === undefined ? resolve() : reject(error),
);
});
httpServer.closeAllConnections();
return closed;
};
/** Translate one node:http exchange through `route`, logging a failure and answering it when headers are still open. */
const serveNodeRequest = async (
target: NodeRequestTarget,
request: IncomingMessage,
response: ServerResponse,
context: NodeHttpExchangeContext,
): Promise<void> => {
const { route, origin, logger } = target;
// A reply sent before an incoming body was fully consumed leaves the rest on the socket, which
// the bridged stream keeps paused; closing the connection after the reply releases it. The
// incoming message decides (end of stream, not "body disturbed"), so a partially read upload
// and a GET or HEAD that carried a body close too.
const declaresBody =
request.headers["content-length"] !== undefined ||
request.headers["transfer-encoding"] !== undefined;
let webRequest: Request | undefined;
const unreadBody = (): boolean => declaresBody && !request.readableEnded;
let reported = false;
let admissionLifetime: HttpAdmissionLifetime = "response";
const settled = (): void => {
if (reported) return;
reported = true;
context.onDispatchSettled({
hasUnreadBody: unreadBody(),
admissionLifetime,
});
};
try {
try {
webRequest = toWebRequest(request, response, origin());
} catch (cause: unknown) {
// Fetch refuses methods such as TRACE that node:http accepts, and the bridge refuses
// targets that are not origin-form paths; both are answered instead of thrown.
const target = cause instanceof UnsupportedRequestTargetError;
await writeWebResponse(
jsonError(
target ? 400 : 405,
-32600,
target
? "Unsupported request target"
: `Unsupported method ${request.method ?? ""}`,
),
response,
{ closeConnection: true, onBodyCleanup: context.onBodyCleanup },
);
return;
}
let webResponse: Response;
try {
const routed = await route(webRequest);
webResponse = routed.response;
admissionLifetime = routed.admissionLifetime;
} finally {
settled();
}
await writeWebResponse(webResponse, response, {
closeConnection: unreadBody(),
onBodyCleanup: context.onBodyCleanup,
});
} catch (cause: unknown) {
// A client that left mid-stream is routine; a failure before headers is not.
logger?.[response.headersSent ? "debug" : "warn"](
{ error: describe(cause) },
"MCP HTTP request did not complete",
);
if (response.headersSent) response.destroy();
else
await writeWebResponse(
jsonError(500, -32603, "Internal server error"),
response,
{ closeConnection: unreadBody(), onBodyCleanup: context.onBodyCleanup },
).catch(() => undefined);
} finally {
settled();
}
};
/** Run close stages in order once each; a failed stage is retried by the next call instead of replaying its rejection. */
const stagedClose = (
stages: readonly (() => Promise<void>)[],
): (() => Promise<void>) => {
const done = stages.map(() => false);
let closing: Promise<void> | undefined;
return () => {
if (closing !== undefined) return closing;
const attempt = (async () => {
for (const [index, stage] of stages.entries()) {
if (done[index]) continue;
await stage();
done[index] = true;
}
})();
closing = attempt;
void attempt.catch(() => {
if (closing === attempt) closing = undefined;
});
return attempt;
};
};
@@ -0,0 +1,10 @@
/** The listener could not bind before any client connected; the message names the system cause. */
export class StreamableHttpListenError extends Error {
override readonly name = "StreamableHttpListenError";
constructor(cause: unknown) {
super(
`MCP HTTP listener could not bind: ${cause instanceof Error ? cause.message : String(cause)}`,
{ cause },
);
}
}
+14 -2
View File
@@ -1,4 +1,7 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import {
currentMcpRequestSignal,
type EvidenceMcpServer,
} from "./EvidenceMcpServer.js";
import {
completable,
type RegisteredPrompt,
@@ -31,7 +34,16 @@ export const registerGuidedPrompts = (
analysis: AnalysisOperationPort,
session?: BinarySessionPort,
): GuidedPromptRegistry => {
const completion = createPromptCompletionSource(analysis, session);
const source = createPromptCompletionSource(analysis, session);
const completion: PromptCompletionSource = {
async complete(kind, value, context) {
// Completions can query the same providers as tools. Cancellation alone
// does not mean their provider cleanup has finished.
return server.runRequest(currentMcpRequestSignal(), () =>
source.complete(kind, value, context),
);
},
};
const prompts = new Map<string, RegisteredPrompt>();
for (const contract of PROMPT_CONTRACTS)
prompts.set(contract.name, registerPrompt(server, contract, completion));
+130 -5
View File
@@ -3,11 +3,57 @@ import { expect, it } from "vitest";
import pino from "pino";
import { createShutdown } from "../main/shutdown.js";
import { registerProcessShutdown } from "../main/processShutdown.js";
import type { RuntimeDependencies } from "../main/types.js";
import type { StdioServerHandle } from "@modelcontextprotocol/server/stdio";
import {
createExitStatus,
latchSignalShutdown,
registerProcessShutdown,
registerSignalShutdown,
} from "../main/processShutdown.js";
import type { McpServerHandle, RuntimeDependencies } from "../main/types.js";
import { createManagedBinarySession } from "../composition/binary.js";
it("registers only signals for a listener and reports the signal exit status", () => {
const signals = new EventEmitter();
const statuses: number[] = [];
const unregister = registerSignalShutdown(
(status) => statuses.push(status),
signals,
);
signals.emit("SIGTERM");
signals.emit("SIGINT");
expect(statuses).toEqual([143, 130]);
unregister();
signals.emit("SIGTERM");
expect(statuses).toEqual([143, 130]);
expect(signals.listenerCount("SIGTERM")).toBe(0);
});
it("names the signal that fired, passes none for stdin, and ignores stdin when the events omit it", () => {
const signals = new EventEmitter();
const input = new EventEmitter();
const triggers: (string | undefined)[] = [];
const withInput = registerProcessShutdown((signal) => triggers.push(signal), {
signals,
stdin: input,
});
signals.emit("SIGINT");
input.emit("end");
expect(triggers).toEqual(["SIGINT", undefined]);
withInput();
const signalsOnly = registerProcessShutdown(
(signal) => triggers.push(signal),
{ signals },
);
signals.emit("SIGTERM");
input.emit("end");
input.emit("close");
expect(triggers).toEqual(["SIGINT", undefined, "SIGTERM"]);
signalsOnly();
signals.emit("SIGINT");
expect(triggers).toEqual(["SIGINT", undefined, "SIGTERM"]);
expect(input.listenerCount("end")).toBe(0);
});
const shutdownEvents = ["SIGINT", "SIGTERM", "end", "close"] as const;
const flush = async (): Promise<void> => {
@@ -51,7 +97,7 @@ it.each(shutdownEvents)(
};
},
};
const handle: StdioServerHandle = {
const handle: McpServerHandle = {
close: async () => {
transportCloseCalls += 1;
if (transportCloseCalls === 1)
@@ -110,6 +156,55 @@ it.each(shutdownEvents)(
},
);
it("keeps shared provider owners open when the transport preparation barrier fails", async () => {
const events: string[] = [];
let attempts = 0;
const session = createManagedBinarySession();
const closeSession = session.close.bind(session);
session.close = async (...args) => {
events.push("session");
return closeSession(...args);
};
const lifecycle = createShutdown({
handle: {
prepareShutdown: async () => {
events.push("prepare");
attempts += 1;
if (attempts === 1) throw new Error("tool cleanup is still running");
},
close: async () => {
events.push("transport");
},
},
closeOptionalProviders: async () => {
events.push("provider");
},
session,
dependencies: {
env: {},
serve: () => {
throw new Error("unused transport");
},
writeStderr: () => undefined,
setExitCode: () => undefined,
registerShutdown: () => () => undefined,
},
serverLogger: pino({ enabled: false }),
});
await expect(lifecycle.shutdown()).rejects.toThrow(
"tool cleanup is still running",
);
expect(events).toEqual(["prepare"]);
await lifecycle.shutdown();
expect(events).toEqual([
"prepare",
"prepare",
"transport",
"provider",
"session",
]);
});
it("joins concurrent shutdown events and retries only failed owners", async () => {
const signals = new EventEmitter();
const input = new EventEmitter();
@@ -134,7 +229,7 @@ it("joins concurrent shutdown events and retries only failed owners", async () =
registerShutdown: (handler) =>
registerProcessShutdown(handler, { signals, stdin: input }),
};
const handle: StdioServerHandle = {
const handle: McpServerHandle = {
close: async () => {
transportCloseCalls += 1;
if (transportCloseCalls === 1)
@@ -176,3 +271,33 @@ it("joins concurrent shutdown events and retries only failed owners", async () =
expect(input.listenerCount("end")).toBe(0);
expect(input.listenerCount("close")).toBe(0);
});
it("latches the first startup signal, exits at once on a second, and hands the status over on release", () => {
const signals = new EventEmitter();
const exits: number[] = [];
const latch = latchSignalShutdown(signals, (status) => exits.push(status));
expect(signals.listenerCount("SIGINT")).toBe(1);
signals.emit("SIGTERM");
expect(exits).toEqual([]);
signals.emit("SIGINT");
expect(exits).toEqual([143]);
expect(latch.release()).toBe(143);
expect(signals.listenerCount("SIGINT")).toBe(0);
expect(signals.listenerCount("SIGTERM")).toBe(0);
const quiet = latchSignalShutdown(signals, (status) => exits.push(status));
expect(quiet.release()).toBeUndefined();
});
it("keeps a signal's exit status through the entry's normal return and yields to a real failure", () => {
const codes: number[] = [];
const exit = createExitStatus((code) => codes.push(code));
exit.set(0);
exit.signal(143);
exit.set(0);
expect(codes).toEqual([0, 143, 143]);
exit.set(1);
expect(codes.at(-1)).toBe(1);
const plain = createExitStatus((code) => codes.push(code));
plain.set(0);
expect(codes.at(-1)).toBe(0);
});