1
import type { AuthProvider, McpFetch } from "../auth-provider.ts";2
import {3
isJsonRpcRequest,4
isJsonRpcResponse,5
JSON_RPC_ERROR_CODES,6
type JsonRpcId,7
type JsonRpcMessage,8
McpAbortError,9
McpConnectionClosedError,10
parseJsonRpcMessage,11
toError,12
} from "../protocol/jsonrpc.ts";13
import {14
DEFAULT_MAX_MESSAGE_BYTES,15
type McpTransport,16
type McpTransportSendOptions,17
TransportEvents,18
} from "./transport.ts";20
const MAX_ERROR_BODY_BYTES = 8 * 1024;21
const ERROR_MESSAGE_BODY_CHARS = 500;22
const DEFAULT_RECONNECT_INITIAL_DELAY_MS = 1_000;23
const DEFAULT_RECONNECT_MAX_DELAY_MS = 30_000;24
const DEFAULT_RECONNECT_MAX_RETRIES = 5;26
export interface SseEvent {27
event?: string;28
data: string;29
id?: string;30
}32
export interface ConsumeSseOptions {33
maxEventBytes?: number;34
onEvent(event: SseEvent): void;35
/** Called for every `id` field, including events without data (for example resumption priming events). */36
onId?(id: string): void;37
/** Called for every valid `retry` field, in milliseconds. */38
onRetry?(delayMs: number): void;39
}41
export async function consumeSseStream(stream: ReadableStream<Uint8Array>, options: ConsumeSseOptions): Promise<void> {42
const reader = stream.getReader();43
const decoder = new TextDecoder();44
let buffered = "";45
let eventName: string | undefined;46
let eventId: string | undefined;47
let dataLines: string[] = [];48
// Bytes of the pending event's data, including the "\n" joins, so events streamed as many49
// short `data:` lines without a terminating blank line cannot grow without bound.50
let dataBytes = 0;51
const maxEventBytes = options.maxEventBytes ?? DEFAULT_MAX_MESSAGE_BYTES;53
const dispatch = () => {54
if (dataLines.length === 0) {55
eventName = undefined;56
eventId = undefined;57
return;58
}59
const data = dataLines.join("\n");60
options.onEvent({ ...(eventName ? { event: eventName } : {}), data, ...(eventId ? { id: eventId } : {}) });61
eventName = undefined;62
eventId = undefined;63
dataLines = [];64
dataBytes = 0;65
};67
const processLine = (rawLine: string) => {68
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;69
if (line === "") {70
dispatch();71
return;72
}73
if (line.startsWith(":")) return;74
const colon = line.indexOf(":");75
const field = colon < 0 ? line : line.slice(0, colon);76
let value = colon < 0 ? "" : line.slice(colon + 1);77
if (value.startsWith(" ")) value = value.slice(1);78
if (field === "data") {79
dataBytes += Buffer.byteLength(value) + (dataLines.length > 0 ? 1 : 0);80
if (dataBytes > maxEventBytes) throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);81
dataLines.push(value);82
} else if (field === "event") eventName = value;83
else if (field === "id" && !value.includes("\0")) {84
eventId = value;85
options.onId?.(value);86
} else if (field === "retry" && /^\d+$/.test(value)) options.onRetry?.(Number(value));87
};89
try {90
while (true) {91
const { done, value } = await reader.read();92
if (done) break;93
buffered += decoder.decode(value, { stream: true });94
let newline = buffered.indexOf("\n");95
while (newline >= 0) {96
processLine(buffered.slice(0, newline));97
buffered = buffered.slice(newline + 1);98
newline = buffered.indexOf("\n");99
}100
if (Buffer.byteLength(buffered) > maxEventBytes)101
throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);102
}103
buffered += decoder.decode();104
if (buffered) processLine(buffered);105
dispatch();106
} finally {107
reader.releaseLock();108
}109
}111
export interface StreamableHttpReconnectOptions {112
/** Delay before the first reconnection attempt, unless the server sent a `retry` field. Default: 1000. */113
initialDelayMs?: number;114
/** Upper bound for the exponential backoff. Default: 30000. */115
maxDelayMs?: number;116
/** Consecutive failed attempts before giving up on a stream. Default: 5. */117
maxRetries?: number;118
}120
export interface StreamableHttpTransportOptions {121
url: string | URL;122
headers?: Record<string, string>;123
fetch?: McpFetch;124
/** Open the server-to-client GET stream after initialization. Default: true. */125
openGetStream?: boolean;126
maxMessageBytes?: number;127
authProvider?: AuthProvider;128
/** Reconnection of dropped SSE streams (the GET stream, and response streams that carry event IDs). */129
reconnect?: StreamableHttpReconnectOptions;130
}132
export class McpHttpError extends Error {133
readonly status: number;134
readonly body: string;136
constructor(status: number, message: string, body = "") {137
super(message);138
this.name = "McpHttpError";139
this.status = status;140
this.body = body;141
}142
}144
export class McpAuthRequiredError extends McpHttpError {145
readonly wwwAuthenticate: string | null;147
constructor(response: Response, body = "") {148
super(401, "MCP server requires authentication", body);149
this.name = "McpAuthRequiredError";150
this.wwwAuthenticate = response.headers.get("www-authenticate");151
}152
}154
export class McpSessionExpiredError extends McpHttpError {155
constructor(body = "") {156
super(404, "MCP session expired", body);157
this.name = "McpSessionExpiredError";158
}159
}161
function contentType(response: Response): string | undefined {162
return response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();163
}165
/** 401, or 403 with an `insufficient_scope` bearer challenge (step-up authorization). */166
function needsAuthorization(response: Response): boolean {167
if (response.status === 401) return true;168
if (response.status !== 403) return false;169
return /(?:^|[\s,])error="?insufficient_scope"?/i.test(response.headers.get("www-authenticate") ?? "");170
}172
/** Statuses worth retrying when a stream fails to (re)open. */173
function isTransientStatus(status: number): boolean {174
return status === 408 || status === 429 || status >= 500;175
}177
function discard(response: Response): Promise<void> {178
return response.body?.cancel().catch(() => {}) ?? Promise.resolve();179
}181
function describeHttpFailure(status: number, body: string): string {182
const text = body.trim();183
const snippet = text.length > ERROR_MESSAGE_BODY_CHARS ? `${text.slice(0, ERROR_MESSAGE_BODY_CHARS - 3)}...` : text;184
return `MCP HTTP request failed with status ${status}${snippet ? `: ${snippet}` : ""}`;185
}187
interface StreamCursor {188
lastEventId: string | undefined;189
retryMs: number | undefined;190
/** Whether the stream delivered any event since it was (re)opened. */191
received: boolean;192
}194
export class StreamableHttpTransport extends TransportEvents implements McpTransport {195
readonly url: URL;196
readonly options: Readonly<StreamableHttpTransportOptions>;197
private fetch: McpFetch;198
private controller = new AbortController();199
private started = false;200
private closed = false;201
private sessionIdValue: string | undefined;202
private protocolVersion: string | undefined;203
private getStreamStarted = false;204
/** Access token of the latest request, which `close()` reuses instead of asking the auth provider. */205
private lastToken: string | undefined;207
constructor(options: StreamableHttpTransportOptions) {208
super();209
this.options = Object.freeze({ ...options, headers: options.headers ? { ...options.headers } : undefined });210
this.url = new URL(options.url);211
const fetch = options.fetch ?? globalThis.fetch;212
// Call fetch without a receiver. `this.fetch(...)` and `context.fetch(...)` would pass the transport or213
// the auth context as `this`, which Cloudflare Workers reject for the platform fetch ("Illegal invocation").214
this.fetch = (input, init) => fetch(input, init);215
}217
get sessionId(): string | undefined {218
return this.sessionIdValue;219
}221
async start(): Promise<void> {222
if (this.started) throw new Error("MCP Streamable HTTP transport already started");223
if (this.closed) throw new McpConnectionClosedError();224
this.started = true;225
}227
setProtocolVersion(version: string): void {228
this.protocolVersion = version;229
}231
async send(message: JsonRpcMessage, { signal }: McpTransportSendOptions = {}): Promise<void> {232
if (!this.started || this.closed) throw new McpConnectionClosedError();233
const response = await this.authorizedFetch(234
"POST",235
{236
headers: { accept: "application/json, text/event-stream", "content-type": "application/json" },237
body: JSON.stringify(message),238
},239
signal,240
);241
await this.checkResponse(response);242
this.captureSession(response);244
if (!isJsonRpcRequest(message)) {245
// Notifications and responses are acknowledged with 202 and carry no reply; ignore any body.246
await discard(response);247
// The server-to-client stream may only open once the session is initialized.248
if ("method" in message && message.method === "notifications/initialized") this.startGetStream();249
return;250
}251
if (response.status === 202 || response.status === 204) {252
throw new McpHttpError(response.status, `MCP server accepted request ${message.method} without a response`);253
}254
const type = contentType(response);255
if (type === "application/json") {256
const body: unknown = await response.json();257
for (const item of Array.isArray(body) ? body : [body]) this.emitMessage(parseJsonRpcMessage(item));258
return;259
}260
if (type === "text/event-stream" && response.body) {261
void this.consumeResponseStream(response.body, message.id);262
return;263
}264
await discard(response);265
throw new McpHttpError(response.status, `Unsupported MCP response content type: ${type ?? "missing"}`);266
}268
async close(): Promise<void> {269
if (this.closed) return;270
this.closed = true;271
this.controller.abort();272
if (this.started && this.sessionIdValue) {273
// Best effort: the session expires on the server anyway. The auth provider may refresh tokens274
// over the network, so it is not asked here and closing never waits for a refresh.275
try {276
const response = await this.fetch(this.url, {277
method: "DELETE",278
headers: this.buildHeaders({}, this.lastToken),279
signal: AbortSignal.timeout(1_000),280
});281
await discard(response);282
} catch {}283
}284
this.emitClose();285
}287
/**288
* Fetch with auth headers. A 401 (or a 403 asking for more scope) is handed to the auth provider289
* once, and the request is retried with whatever credentials it left behind.290
*291
* `signal` only stops dispatch: getting a token or the authorization recovery can take a while, and a292
* request its sender gave up on in the meantime must not reach the server. It does not abort the shared293
* recovery, which other requests may wait for.294
*/295
private async authorizedFetch(296
method: "GET" | "POST",297
init: { headers: Record<string, string>; body?: string },298
signal?: AbortSignal,299
): Promise<Response> {300
const onUnauthorized = this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);301
for (let attempt = 0; ; attempt++) {302
const { headers, token } = await this.headers(init.headers);303
if (signal?.aborted) throw new McpAbortError();304
const response = await this.fetch(this.url, {305
method,306
headers,307
body: init.body,308
signal: this.controller.signal,309
});310
if (attempt > 0 || !onUnauthorized || !needsAuthorization(response)) return response;311
try {312
await onUnauthorized({ response, serverUrl: this.url, fetch: this.fetch, token });313
} finally {314
await discard(response);315
}316
}317
}319
private async headers(extra: Record<string, string> = {}): Promise<{ headers: Headers; token?: string }> {320
const token = await this.options.authProvider?.token();321
this.lastToken = token;322
return { headers: this.buildHeaders(extra, token), ...(token ? { token } : {}) };323
}325
private buildHeaders(extra: Record<string, string>, token: string | undefined): Headers {326
const headers = new Headers(this.options.headers);327
for (const [name, value] of Object.entries(extra)) headers.set(name, value);328
if (this.sessionIdValue) headers.set("Mcp-Session-Id", this.sessionIdValue);329
if (this.protocolVersion) headers.set("MCP-Protocol-Version", this.protocolVersion);330
if (token) headers.set("Authorization", `Bearer ${token}`);331
return headers;332
}334
private captureSession(response: Response): void {335
const sessionId = response.headers.get("mcp-session-id");336
if (sessionId) this.sessionIdValue = sessionId;337
}339
private async checkResponse(response: Response): Promise<void> {340
if (response.ok) return;341
const body = (await response.text().catch(() => "")).slice(0, MAX_ERROR_BODY_BYTES);342
if (response.status === 401) throw new McpAuthRequiredError(response, body);343
if (response.status === 404 && this.sessionIdValue) throw new McpSessionExpiredError(body);344
throw new McpHttpError(response.status, describeHttpFailure(response.status, body), body);345
}347
private async consumeSse(348
stream: ReadableStream<Uint8Array>,349
cursor: StreamCursor,350
onMessage?: (message: JsonRpcMessage) => void,351
): Promise<void> {352
await consumeSseStream(stream, {353
maxEventBytes: this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES,354
onId: (id) => {355
cursor.lastEventId = id;356
},357
onRetry: (delayMs) => {358
cursor.retryMs = delayMs;359
},360
onEvent: (event) => {361
cursor.received = true;362
// Events without data prime resumption; other event types are not JSON-RPC.363
if (!event.data.trim() || (event.event !== undefined && event.event !== "message")) return;364
let message: JsonRpcMessage;365
try {366
message = parseJsonRpcMessage(JSON.parse(event.data));367
} catch (error) {368
this.emitError(error);369
return;370
}371
onMessage?.(message);372
this.emitMessage(message);373
},374
});375
}377
/**378
* Read the SSE stream answering one request. When the stream ends or breaks before the response379
* arrives and the server assigned event IDs, resume it with GET and `Last-Event-ID`, as the380
* server may close response streams at will. Otherwise only this request fails.381
*/382
private async consumeResponseStream(body: ReadableStream<Uint8Array>, requestId: JsonRpcId): Promise<void> {383
const cursor: StreamCursor = { lastEventId: undefined, retryMs: undefined, received: false };384
let answered = false;385
const onMessage = (message: JsonRpcMessage) => {386
if (isJsonRpcResponse(message) && message.id === requestId) answered = true;387
};388
let stream: ReadableStream<Uint8Array> | undefined = body;389
let failure: unknown;390
for (let attempt = 0; ; ) {391
if (stream) {392
try {393
await this.consumeSse(stream, cursor, onMessage);394
failure = undefined;395
} catch (error) {396
failure = error;397
}398
}399
if (answered || this.closed) return;400
if (failure !== undefined && !this.isRetryable(failure)) break;401
if (cursor.lastEventId === undefined || attempt >= this.maxRetries()) break;402
if (cursor.received) attempt = 0;403
cursor.received = false;404
if (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))) return;405
try {406
stream = await this.openSseStream(cursor.lastEventId);407
} catch (error) {408
failure = error;409
if (!this.isRetryable(error)) break;410
stream = undefined;411
}412
}413
if (this.closed) return;414
const reason = failure === undefined ? "stream ended without a response" : toError(failure).message;415
this.emitMessage({416
jsonrpc: "2.0",417
id: requestId,418
error: { code: JSON_RPC_ERROR_CODES.internalError, message: `MCP response stream failed: ${reason}` },419
});420
}422
private startGetStream(): void {423
if (this.options.openGetStream === false || this.getStreamStarted || this.closed) return;424
this.getStreamStarted = true;425
void this.runGetStream();426
}428
/** Keep the server-to-client stream open, reconnecting with backoff when it drops. */429
private async runGetStream(): Promise<void> {430
const cursor: StreamCursor = { lastEventId: undefined, retryMs: undefined, received: false };431
for (let attempt = 0; !this.closed; ) {432
try {433
const stream = await this.openSseStream(cursor.lastEventId);434
// The server does not offer a GET stream.435
if (!stream) return;436
const openedAt = Date.now();437
await this.consumeSse(stream, cursor);438
// A stream that stayed up for a while counts as healthy, even if it was idle.439
if (cursor.received || Date.now() - openedAt > this.maxDelay()) attempt = 0;440
} catch (error) {441
if (this.closed) return;442
if (!this.isRetryable(error)) {443
this.emitError(error);444
return;445
}446
}447
cursor.received = false;448
if (attempt >= this.maxRetries()) {449
this.emitError(new Error("MCP server-to-client stream dropped and could not be reopened"));450
return;451
}452
if (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))) return;453
}454
}456
/** Open a GET SSE stream. Resolves to undefined when the server answers 405 (no GET stream). */457
private async openSseStream(lastEventId: string | undefined): Promise<ReadableStream<Uint8Array> | undefined> {458
const response = await this.authorizedFetch("GET", {459
headers: {460
accept: "text/event-stream",461
...(lastEventId === undefined ? {} : { "last-event-id": lastEventId }),462
},463
});464
if (response.status === 405) {465
await discard(response);466
return undefined;467
}468
await this.checkResponse(response);469
this.captureSession(response);470
const type = contentType(response);471
if (type !== "text/event-stream" || !response.body) {472
await discard(response);473
throw new McpHttpError(response.status, `Unsupported MCP GET response content type: ${type ?? "missing"}`);474
}475
return response.body;476
}478
/**479
* Network failures and transient statuses are retried; auth, session, and protocol errors are not.480
* `fetch` reports network failures, including a connection dropped mid-body, as `TypeError`.481
*/482
private isRetryable(error: unknown): boolean {483
if (error instanceof McpHttpError) return isTransientStatus(error.status);484
if (error instanceof TypeError) return true;485
const code = (error as { code?: unknown } | undefined)?.code;486
return typeof code === "string" && (code.startsWith("E") || code.startsWith("UND_ERR"));487
}489
private reconnectDelay(attempt: number, serverDelayMs: number | undefined): number {490
if (serverDelayMs !== undefined) return serverDelayMs;491
const initial = this.options.reconnect?.initialDelayMs ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS;492
return Math.min(initial * 2 ** attempt, this.maxDelay());493
}495
private maxDelay(): number {496
return this.options.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS;497
}499
private maxRetries(): number {500
return this.options.reconnect?.maxRetries ?? DEFAULT_RECONNECT_MAX_RETRIES;501
}503
/** Resolves false when the transport closed while waiting. */504
private sleep(ms: number): Promise<boolean> {505
const signal = this.controller.signal;506
if (signal.aborted) return Promise.resolve(false);507
return new Promise((resolve) => {508
const onAbort = () => {509
clearTimeout(timer);510
resolve(false);511
};512
const timer = setTimeout(() => {513
signal.removeEventListener("abort", onAbort);514
resolve(true);515
}, ms);516
// A reconnect wait alone does not keep the process alive.517
timer.unref?.();518
signal.addEventListener("abort", onAbort, { once: true });519
});520
}521
}