diff --git a/src/mcp.ts b/src/mcp.ts index 5fb7812..8b9fa66 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -6,18 +6,23 @@ export interface KnowledgeResult { structuredContent?: Record; isError?: boolean; } + /** Selects one authorized organization for this call only. */ export interface McpTarget { organization_id?: string; } + export interface RepositoryKnowledge extends McpTarget { repository: string; commit?: string; } + const PROTOCOL = "2025-11-25"; + function object(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } + function refused(): ProoflineError { return new ProoflineError( 0, @@ -25,6 +30,130 @@ function refused(): ProoflineError { "Invalid or refused MCP response", ); } + +/** + * Creates an incremental SSE decoder for one expected JSON-RPC response. + * + * It processes complete lines as chunks arrive and stops as soon as the + * expected response ID is received. A pending final event is dispatched at EOF. + */ +function sseDecoder(expectedId: number) { + let buffer = ""; + let data: string[] = []; + let matched: unknown; + + const processLine = (line: string) => { + if (line === "") { + if (data.length > 0) { + const message = data.join("\n"); + + try { + const value: unknown = JSON.parse(message); + + if ( + object(value) && + value.jsonrpc === "2.0" && + value.id === expectedId + ) { + matched = value; + } + } catch { + // Ignore malformed SSE messages and continue looking. + } + } + + data = []; + return; + } + + // Lines beginning with ":" are SSE comments. + if (line.startsWith(":")) return; + + const separator = line.indexOf(":"); + const field = separator === -1 ? line : line.slice(0, separator); + let value = separator === -1 ? "" : line.slice(separator + 1); + + // SSE removes at most one leading space after the colon. + if (value.startsWith(" ")) { + value = value.slice(1); + } + + if (field === "data") { + data.push(value); + } + }; + + return ( + chunk: string, + _headers: Headers, + final: boolean, + ): { done: boolean; value?: unknown } => { + if (matched !== undefined) { + return { done: true, value: matched }; + } + + buffer += chunk; + + for (;;) { + const cr = buffer.indexOf("\r"); + const lf = buffer.indexOf("\n"); + + let separator = -1; + + if (cr === -1) { + separator = lf; + } else if (lf === -1) { + separator = cr; + } else { + separator = Math.min(cr, lf); + } + + if (separator === -1) break; + + // Wait for the next chunk if CR may be followed by LF. + if ( + buffer[separator] === "\r" && + separator === buffer.length - 1 && + !final + ) { + break; + } + + const line = buffer.slice(0, separator); + const isCrLf = + buffer[separator] === "\r" && buffer[separator + 1] === "\n"; + + buffer = buffer.slice(separator + (isCrLf ? 2 : 1)); + + processLine(line); + + if (matched !== undefined) { + return { done: true, value: matched }; + } + } + + // Any remaining unterminated line/event is incomplete. + if (final) { + // EOF terminates a final line even when it has no line ending. + if (buffer.length > 0) { + processLine(buffer); + buffer = ""; + } + + // The SSE specification dispatches pending data at EOF. + if (data.length > 0) { + processLine(""); + } + + if (matched !== undefined) { + return { done: true, value: matched }; + } + } + + return { done: false }; + }; +} + function envelope(value: unknown, id: number): Record { if ( !object(value) || @@ -32,8 +161,10 @@ function envelope(value: unknown, id: number): Record { value.id !== id || "error" in value || !object(value.result) - ) + ) { throw refused(); + } + return value.result; } @@ -44,26 +175,48 @@ export class McpTools { protected async call(name: string, args: object): Promise { // Bind the per-call target before protocol negotiation yields to the caller. const callArguments = { ...args }; + const invoke = ( body: object, phase: "initialize" | "notification" | "call", - ) => - this.transport.request( + ) => { + const expectedId = phase === "initialize" ? 1 : 2; + + return this.transport.request( "POST", "/mcp", {}, undefined, body, - (text) => { + (text, headers) => { if (phase === "notification") { if (text !== "") throw refused(); return undefined; } - return JSON.parse(text) as unknown; + + const contentType = headers + .get("content-type") + ?.split(";")[0] + ?.trim() + .toLowerCase(); + + if (contentType === "application/json") { + return JSON.parse(text) as unknown; + } + + if (contentType !== "text/event-stream") { + throw refused(); + } + + // SSE responses are decoded incrementally by the transport. + throw refused(); }, "application/json, text/event-stream", phase, + phase === "notification" ? undefined : sseDecoder(expectedId), ); + }; + const initialized = envelope( await invoke( { @@ -80,11 +233,16 @@ export class McpTools { ), 1, ); - if (initialized.protocolVersion !== PROTOCOL) throw refused(); + + if (initialized.protocolVersion !== PROTOCOL) { + throw refused(); + } + await invoke( { jsonrpc: "2.0", method: "notifications/initialized" }, "notification", ); + const result = envelope( await invoke( { @@ -97,6 +255,7 @@ export class McpTools { ), 2, ); + if ( !Array.isArray(result.content) || result.content.some( @@ -108,8 +267,10 @@ export class McpTools { (result.isError !== undefined && typeof result.isError !== "boolean") || (result.structuredContent !== undefined && !object(result.structuredContent)) - ) + ) { throw refused(); + } + return result as unknown as KnowledgeResult; } } diff --git a/src/transport.ts b/src/transport.ts index 53c9bd4..85be8e8 100644 --- a/src/transport.ts +++ b/src/transport.ts @@ -143,10 +143,12 @@ function origin(value: string, name: string): URL { `${name} must be an absolute HTTPS URL or loopback HTTP URL`, ); } + const loopback = url.hostname === "localhost" || url.hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(url.hostname); + if ( (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) || url.username || @@ -159,12 +161,15 @@ function origin(value: string, name: string): URL { `${name} must be an HTTPS origin or loopback HTTP origin without credentials`, ); } + return url; } function configuredOrigin(baseUrl: string | undefined): URL { if (baseUrl !== undefined) return origin(baseUrl, "baseUrl"); + const fromEnvironment = environmentBaseUrl(); + return fromEnvironment === undefined ? origin(DEFAULT_BASE_URL, "baseUrl") : origin(fromEnvironment, "PROOFLINE_BASE_URL"); @@ -177,6 +182,13 @@ function positive(value: number, name: string): number { return value; } +/** Returns the normalized media type without optional parameters. */ +function mediaType(headers: Headers): string { + return ( + headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? "" + ); +} + async function decoded( response: Response, deadline: number, @@ -185,39 +197,54 @@ async function decoded( decode: (text: string, headers: Headers) => unknown, ): Promise { const reader = response.body?.getReader(); + if (!reader) { if (!response.ok) return undefined; + throw new ProoflineError( response.status, "urn:proofline:sdk:invalid-response", "the response has no JSON body", ); } + const chunks: Uint8Array[] = []; let size = 0; + try { for (;;) { const { value, done } = await reader.read(); if (done) break; + size += value.byteLength; + if (size > MAX_RESPONSE_BYTES) { await reader.cancel(); + throw new ProoflineError( response.status, "urn:proofline:sdk:invalid-response", "the response exceeds 8 MiB", ); } + chunks.push(value); } + const data = new Uint8Array(size); let offset = 0; + for (const chunk of chunks) { data.set(chunk, offset); offset += chunk.length; } + const decoder = new TextDecoder("utf-8", { fatal: true }); - if (response.ok) return decode(decoder.decode(data), response.headers); + + if (response.ok) { + return decode(decoder.decode(data), response.headers); + } + try { return JSON.parse(decoder.decode(data)) as unknown; } catch { @@ -226,7 +253,8 @@ async function decoded( } } catch (error) { if (error instanceof ProoflineError) throw error; - if (response.ok && (signal.aborted || performance.now() >= deadline)) + + if (response.ok && (signal.aborted || performance.now() >= deadline)) { throw new ProoflineError( 0, waitTimeout @@ -236,6 +264,8 @@ async function decoded( ? "the review wait deadline expired" : "the successful response body did not finish within its timeout", ); + } + throw new ProoflineError( response.status, "urn:proofline:sdk:invalid-response", @@ -246,6 +276,125 @@ async function decoded( } } +type StreamDecodeResult = { + done: boolean; + value?: unknown; +}; + +type StreamDecode = ( + chunk: string, + headers: Headers, + final: boolean, +) => StreamDecodeResult; + +async function decodedStream( + response: Response, + deadline: number, + signal: AbortSignal, + waitTimeout: boolean, + decode: StreamDecode, +): Promise { + const reader = response.body?.getReader(); + + if (!reader) { + throw new ProoflineError( + response.status, + "urn:proofline:sdk:invalid-response", + "the response has no SSE body", + ); + } + + const decoder = new TextDecoder("utf-8", { fatal: true }); + let size = 0; + + try { + for (;;) { + let chunk: ReadableStreamReadResult; + + try { + chunk = await reader.read(); + } catch { + if (signal.aborted || performance.now() >= deadline) { + throw new ProoflineError( + 0, + waitTimeout + ? "urn:proofline:sdk:timeout" + : "urn:proofline:sdk:transport", + waitTimeout + ? "the review wait deadline expired" + : "the successful response body did not finish within its timeout", + ); + } + + throw new ProoflineError( + 0, + "urn:proofline:sdk:transport", + "the response stream could not be read", + ); + } + + if (chunk.done) { + let remaining: string; + + try { + remaining = decoder.decode(); + } catch { + throw new ProoflineError( + response.status, + "urn:proofline:sdk:invalid-response", + "the response is not valid UTF-8", + ); + } + + const result = decode(remaining, response.headers, true); + + if (!result.done) { + throw new ProoflineError( + 0, + "urn:proofline:sdk:mcp", + "the SSE response ended without a matching message", + ); + } + + return result.value; + } + + size += chunk.value.byteLength; + + if (size > MAX_RESPONSE_BYTES) { + void reader.cancel().catch(() => {}); + + throw new ProoflineError( + response.status, + "urn:proofline:sdk:invalid-response", + "the response exceeds 8 MiB", + ); + } + + let text: string; + + try { + text = decoder.decode(chunk.value, { stream: true }); + } catch { + throw new ProoflineError( + response.status, + "urn:proofline:sdk:invalid-response", + "the response is not valid UTF-8", + ); + } + + const result = decode(text, response.headers, false); + + if (result.done) { + void reader.cancel().catch(() => {}); + return result.value; + } + } + } finally { + reader.releaseLock(); + } +} + type Body = Record; function record(value: unknown): value is Body { @@ -253,13 +402,20 @@ function record(value: unknown): value is Body { } function redacted(value: unknown, secret: string): unknown { - if (typeof value === "string") + if (typeof value === "string") { return secret ? value.replaceAll(secret, "[redacted]") : value; - if (Array.isArray(value)) return value.map((item) => redacted(item, secret)); - if (record(value)) + } + + if (Array.isArray(value)) { + return value.map((item) => redacted(item, secret)); + } + + if (record(value)) { return Object.fromEntries( Object.entries(value).map(([key, item]) => [key, redacted(item, secret)]), ); + } + return value; } @@ -276,6 +432,7 @@ type Shape = (view: Body) => boolean; const always: Shape = () => true; const linked: Shape = (view) => environment(view.environment); const explained: Shape = (view) => typeof view.detail === "string"; + // Keyed by every documented reason, so a contract change fails the type check. const refusalShapes = { TRIGGER_DISABLED: always, @@ -300,9 +457,11 @@ const refusalShapes = { function refusal(value: unknown): RunNowRefusal | undefined { if (!record(value) || typeof value.reason !== "string") return undefined; + const shape = Object.hasOwn(refusalShapes, value.reason) ? refusalShapes[value.reason as RunNowRefusal["reason"]] : undefined; + return shape?.(value) ? (value as RunNowRefusal) : undefined; } @@ -311,40 +470,49 @@ function problem( value: unknown, token: SecretToken, ): ProoflineError { - if (!record(value)) + if (!record(value)) { return new ProoflineError( status, "about:blank", "the server refused the request without a problem detail", ); + } + const body = redacted(value, secrets.get(token) ?? "") as Body; const type = typeof body.type === "string" ? body.type : "about:blank"; const title = typeof body.title === "string" ? body.title : undefined; + const detail = typeof body.detail === "string" ? body.detail : title === undefined ? "the server refused the request without a problem detail" - : // Logged internal errors omit detail; the problem itself still arrived. - `the server returned the problem "${title}" without a detail`; + : `the server returned the problem "${title}" without a detail`; + const fields = title === undefined ? {} : { title }; + // The contract types a refusal only as a review request's 400. The 402 a // credit refusal answers is undocumented, so it stays a plain problem. - if (status !== 400 || !("refusal" in body)) + if (status !== 400 || !("refusal" in body)) { return new ProoflineError(status, type, detail, fields); + } + const view = refusal(body.refusal); + if ( view === undefined || typeof body.repository_name !== "string" || typeof body.detail !== "string" || title === undefined - ) + ) { return new ProoflineError( status, "urn:proofline:sdk:invalid-response", detail, fields, ); + } + return new ProoflineError(status, type, detail, { title, refusal: view, @@ -356,10 +524,14 @@ function retryDelay( header: string | null, attempt: number, ): number | undefined { - if (header === null) return Math.min(2 ** attempt, MAX_RETRY_SECONDS) * 1000; + if (header === null) { + return Math.min(2 ** attempt, MAX_RETRY_SECONDS) * 1000; + } + const seconds = /^\d+$/.test(header.trim()) ? Number(header) : Math.max(0, (httpDate(header.trim()) - Date.now()) / 1000); + return Number.isFinite(seconds) && seconds <= MAX_RETRY_SECONDS ? seconds * 1000 : undefined; @@ -367,6 +539,7 @@ function retryDelay( function httpDate(value: string): number { let canonical = value; + if ( !/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/.test( value, @@ -376,25 +549,33 @@ function httpDate(value: string): number { /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}:\d{2}:\d{2}) GMT$/.exec( value, ); + const asctime = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}:\d{2}:\d{2}) (\d{4})$/.exec( value, ); + if (obsolete) { const futureLimit = new Date(); const currentYear = futureLimit.getUTCFullYear(); const year = Math.floor(currentYear / 100) * 100 + Number(obsolete[4]); + canonical = `${obsolete[1]?.slice(0, 3)}, ${obsolete[2]} ${obsolete[3]} ${year} ${obsolete[5]} GMT`; + futureLimit.setUTCFullYear(currentYear + 50); - if (Date.parse(canonical) > futureLimit.getTime()) + + if (Date.parse(canonical) > futureLimit.getTime()) { canonical = `${obsolete[1]?.slice(0, 3)}, ${obsolete[2]} ${obsolete[3]} ${year - 100} ${obsolete[5]} GMT`; + } } else if (asctime) { canonical = `${asctime[1]}, ${asctime[3]?.trim().padStart(2, "0")} ${asctime[2]} ${asctime[5]} ${asctime[4]} GMT`; } else { return Number.NaN; } } + const timestamp = Date.parse(canonical); + return new Date(timestamp).toUTCString() === canonical ? timestamp : Number.NaN; @@ -411,9 +592,12 @@ export class Transport { constructor(options: ClientOptions) { this.#base = configuredOrigin(options.baseUrl); + const token = options.token ?? environmentToken(); + this.#token = token instanceof SecretToken ? token : new SecretToken(token ?? ""); + this.#timeout = positive( options.requestTimeoutMs ?? 30_000, "requestTimeoutMs", @@ -437,50 +621,75 @@ export class Transport { JSON.parse(text), accept = "application/json, application/problem+json", mcpPhase?: "initialize" | "notification" | "call", + decodeStream?: StreamDecode, ): Promise { const path = Object.entries(parameters.path ?? {}).reduce( (value, [key, coordinateValue]) => value.replace(`{${key}}`, coordinate(coordinateValue)), template, ); - if (/[{}]/.test(path)) + + if (/[{}]/.test(path)) { throw new TypeError("a required path coordinate is missing"); + } + const url = new URL(path, this.#base); + for (const [key, value] of Object.entries(parameters.query ?? {})) { - if (value !== null && value !== undefined) + if (value !== null && value !== undefined) { url.searchParams.set(key, String(value)); + } } + const requestBody = body === undefined ? undefined : JSON.stringify(body); - if (mcpPhase && new TextEncoder().encode(requestBody).length > 8192) + + if (mcpPhase && new TextEncoder().encode(requestBody ?? "").length > 8192) { throw new TypeError("MCP request exceeds 8192 bytes"); + } + for (let attempt = 0; ; attempt += 1) { const headers = new Headers({ Accept: accept, "User-Agent": `proofline-typescript/${VERSION}`, }); - if (requestBody !== undefined) + + if (requestBody !== undefined) { headers.set("Content-Type", "application/json"); + } + if (mcpPhase) { headers.set("Origin", this.#base.origin); - if (mcpPhase !== "initialize") + + if (mcpPhase !== "initialize") { headers.set("MCP-Protocol-Version", "2025-11-25"); + } } + this.#token.apply(headers); + const now = performance.now(); + const waitRemaining = deadline === undefined ? this.#timeout : deadline - now; + const remaining = Math.min(this.#timeout, waitRemaining); + const waitTimeout = deadline !== undefined && waitRemaining <= this.#timeout; - if (remaining <= 0) + + if (remaining <= 0) { throw new ProoflineError( 0, "urn:proofline:sdk:timeout", "the request deadline expired", ); + } + const requestDeadline = now + remaining; const signal = AbortSignal.timeout(Math.ceil(remaining)); + let response: Response; + try { response = await fetch(url, { method, @@ -491,53 +700,100 @@ export class Transport { signal, }); } catch { - if (signal.aborted && waitTimeout) + if (signal.aborted && waitTimeout) { throw new ProoflineError( 0, "urn:proofline:sdk:timeout", "the review wait deadline expired", ); + } + throw new ProoflineError( 0, "urn:proofline:sdk:transport", "the request did not receive a response within its timeout", ); } + + // Validate the MCP response status and media type before decoding. if (mcpPhase && response.ok) { const notification = mcpPhase === "notification"; + const contentType = mediaType(response.headers); + + const validContentType = + contentType === "application/json" || + contentType === "text/event-stream"; + if ( response.status !== (notification ? 202 : 200) || response.headers.has("mcp-session-id") || - (!notification && - response.headers.get("content-type")?.split(";")[0]?.trim() !== - "application/json") + (!notification && !validContentType) ) { await response.body?.cancel(); + throw new ProoflineError( 0, "urn:proofline:sdk:mcp", - "Unsupported MCP response", + `Unsupported MCP response (status ${response.status}, content type ${contentType || "missing"})`, ); } - if (notification && !response.body) return undefined as T; + + if (notification && !response.body) { + return undefined as T; + } } - const value = await decoded( - response, - requestDeadline, - signal, - waitTimeout, - decode, - ); - if (response.ok) return value as T; + + let value: unknown; + + if ( + mcpPhase && + response.ok && + mediaType(response.headers) === "text/event-stream" + ) { + if (!decodeStream) { + await response.body?.cancel().catch(() => {}); + + throw new ProoflineError( + 0, + "urn:proofline:sdk:mcp", + "An SSE response requires a streaming decoder", + ); + } + + value = await decodedStream( + response, + requestDeadline, + signal, + waitTimeout, + decodeStream, + ); + } else { + value = await decoded( + response, + requestDeadline, + signal, + waitTimeout, + decode, + ); + } + + if (response.ok) { + return value as T; + } + const error = problem(response.status, value, this.#token); + const delay = retryDelay(response.headers.get("Retry-After"), attempt); + if ( method !== "GET" || ![429, 503].includes(response.status) || attempt >= MAX_RETRIES || delay === undefined - ) + ) { throw error; + } + if (deadline !== undefined && performance.now() + delay >= deadline) { throw new ProoflineError( 0, @@ -545,6 +801,7 @@ export class Transport { "the review timeout expires before the server permits a retry", ); } + await sleep(delay); } } @@ -561,5 +818,6 @@ function coordinate(value: unknown): string { "path coordinates must be nonempty strings or numbers without traversal segments", ); } + return encodeURIComponent(String(value)); } diff --git a/tests/http.test.mjs b/tests/http.test.mjs index c1263ee..649c3d2 100644 --- a/tests/http.test.mjs +++ b/tests/http.test.mjs @@ -310,6 +310,266 @@ test("generated methods use the authenticated token surface and preserve server assert.equal(fixture.calls.at(-1).body, '{"mode":"FULL"}'); }); +test("knowledge accepts an MCP SSE response terminated by EOF", async (t) => { + const { baseUrl } = await server(t, (_request, response, seen) => { + const body = JSON.parse(seen.at(-1).body); + + if (body.method === "initialize") { + response.writeHead(200, { + "Content-Type": "application/json", + }); + response.end( + JSON.stringify({ + jsonrpc: "2.0", + id: 1, + result: { protocolVersion: "2025-11-25" }, + }), + ); + return; + } + + if (body.method === "notifications/initialized") { + response.writeHead(202); + response.end(); + return; + } + + response.writeHead(200, { + "Content-Type": "text/event-stream", + }); + + response.end( + `event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + id: 2, + result: { + isError: false, + content: [{ type: "text", text: "EOF response received" }], + }, + })}`, + ); + }); + + const client = new ProoflineClient({ baseUrl, token }); + + const result = await client.knowledge.getWikiPage({ + repository: "owner/name", + page_key: "index", + }); + + assert.equal(result.isError, false); + assert.equal(result.content[0].text, "EOF response received"); +}); + +test("knowledge accepts an MCP SSE response and cancels the completed stream", async (t) => { + let resolveStreamClosed; + const streamClosed = new Promise((resolve) => { + resolveStreamClosed = resolve; + }); + + const { baseUrl } = await server(t, (_request, response, seen) => { + const body = JSON.parse(seen.at(-1).body); + + if (body.method === "initialize") { + response.writeHead(200, { + "Content-Type": "text/event-stream", + }); + response.end( + `event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + id: 1, + result: { protocolVersion: "2025-11-25" }, + })}\n\n`, + ); + return; + } + + if (body.method === "notifications/initialized") { + response.writeHead(202); + response.end(); + return; + } + + response.writeHead(200, { + "Content-Type": "text/event-stream", + }); + + response.once("close", resolveStreamClosed); + + response.write( + `event: message\r\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + id: 2, + result: { + isError: false, + content: [{ type: "text", text: "SSE response received" }], + }, + })}\r`, + ); + + response.write("\n\r\n"); + + // Keep the response open. The SDK should cancel it after + // receiving the matching JSON-RPC response. + }); + + const client = new ProoflineClient({ baseUrl, token }); + + const result = await client.knowledge.getWikiPage({ + repository: "owner/name", + page_key: "index", + }); + + assert.equal(result.isError, false); + assert.equal(result.content[0].text, "SSE response received"); + + let timeout; + try { + await Promise.race([ + streamClosed, + new Promise((_, reject) => { + timeout = setTimeout( + () => reject(new Error("The SSE stream was not cancelled")), + 2000, + ); + }), + ]); + } finally { + clearTimeout(timeout); + } +}); + +test("knowledge handles an MCP SSE response split across chunks", async (t) => { + const { baseUrl } = await server(t, (_request, response, seen) => { + const body = JSON.parse(seen.at(-1).body); + + if (body.method === "initialize") { + return json(response, 200, { + jsonrpc: "2.0", + id: 1, + result: { protocolVersion: "2025-11-25" }, + }); + } + + if (body.method === "notifications/initialized") { + response.writeHead(202); + return response.end(); + } + + response.writeHead(200, { + "Content-Type": "text/event-stream", + }); + + const message = JSON.stringify({ + jsonrpc: "2.0", + id: 2, + result: { + isError: false, + content: [{ type: "text", text: "Fragmented response received" }], + }, + }); + + // Deliberately divide one SSE event into separate network writes. + const chunks = [ + "event: message\r\n", + `data: ${message.slice(0, 15)}`, + message.slice(15, 40), + message.slice(40), + "\r", + "\n", + "\r", + "\n", + ]; + + let index = 0; + + const sendNextChunk = () => { + if (index >= chunks.length) return; + + response.write(chunks[index]); + index += 1; + + setTimeout(sendNextChunk, 10); + }; + + sendNextChunk(); + }); + + const client = new ProoflineClient({ baseUrl, token }); + + const result = await client.knowledge.getWikiPage({ + repository: "owner/name", + page_key: "index", + }); + + assert.equal(result.isError, false); + assert.equal(result.content[0].text, "Fragmented response received"); +}); + +test("knowledge times out and closes an MCP SSE stream without the expected response", async (t) => { + let resolveStreamClosed; + const streamClosed = new Promise((resolve) => { + resolveStreamClosed = resolve; + }); + + const { baseUrl } = await server(t, (_request, response, seen) => { + const body = JSON.parse(seen.at(-1).body); + + if (body.method === "initialize") { + return json(response, 200, { + jsonrpc: "2.0", + id: 1, + result: { protocolVersion: "2025-11-25" }, + }); + } + + if (body.method === "notifications/initialized") { + response.writeHead(202); + return response.end(); + } + + response.writeHead(200, { + "Content-Type": "text/event-stream", + }); + response.once("close", resolveStreamClosed); + + // Keep the SSE response open without sending the expected JSON-RPC ID 2. + response.write(": waiting for the MCP response\n\n"); + }); + + const client = new ProoflineClient({ + baseUrl, + token, + requestTimeoutMs: 100, + }); + + await assert.rejects( + client.knowledge.getWikiPage({ + repository: "owner/name", + page_key: "index", + }), + (error) => + error instanceof ProoflineError && + error.status === 0 && + error.type === "urn:proofline:sdk:transport", + ); + + let timeout; + try { + await Promise.race([ + streamClosed, + new Promise((_, reject) => { + timeout = setTimeout( + () => reject(new Error("The timed-out SSE stream was not closed")), + 2000, + ); + }), + ]); + } finally { + clearTimeout(timeout); + } +}); + test("coverage uploads preserve the tested commit, report text and server refusals", async (t) => { const body = { tested_sha: "c".repeat(40),