@ny4n/mcp 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/LICENSES/modelcontextprotocol-typescript-sdk.txt +21 -0
- package/README.md +135 -2
- package/dist/auth-provider.d.ts +19 -0
- package/dist/auth-provider.d.ts.map +1 -0
- package/dist/auth-provider.js +2 -0
- package/dist/auth-provider.js.map +1 -0
- package/dist/client.d.ts +89 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +457 -0
- package/dist/client.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/oauth/callback.d.ts +48 -0
- package/dist/oauth/callback.d.ts.map +1 -0
- package/dist/oauth/callback.js +115 -0
- package/dist/oauth/callback.js.map +1 -0
- package/dist/oauth/discovery.d.ts +30 -0
- package/dist/oauth/discovery.d.ts.map +1 -0
- package/dist/oauth/discovery.js +156 -0
- package/dist/oauth/discovery.js.map +1 -0
- package/dist/oauth/errors.d.ts +25 -0
- package/dist/oauth/errors.d.ts.map +1 -0
- package/dist/oauth/errors.js +48 -0
- package/dist/oauth/errors.js.map +1 -0
- package/dist/oauth/flow.d.ts +102 -0
- package/dist/oauth/flow.d.ts.map +1 -0
- package/dist/oauth/flow.js +334 -0
- package/dist/oauth/flow.js.map +1 -0
- package/dist/oauth/index.d.ts +7 -0
- package/dist/oauth/index.d.ts.map +1 -0
- package/dist/oauth/index.js +6 -0
- package/dist/oauth/index.js.map +1 -0
- package/dist/oauth/provider.d.ts +62 -0
- package/dist/oauth/provider.d.ts.map +1 -0
- package/dist/oauth/provider.js +118 -0
- package/dist/oauth/provider.js.map +1 -0
- package/dist/oauth/types.d.ts +82 -0
- package/dist/oauth/types.d.ts.map +1 -0
- package/dist/oauth/types.js +109 -0
- package/dist/oauth/types.js.map +1 -0
- package/dist/protocol/content.d.ts +82 -0
- package/dist/protocol/content.d.ts.map +1 -0
- package/dist/protocol/content.js +41 -0
- package/dist/protocol/content.js.map +1 -0
- package/dist/protocol/jsonrpc.d.ts +59 -0
- package/dist/protocol/jsonrpc.d.ts.map +1 -0
- package/dist/protocol/jsonrpc.js +67 -0
- package/dist/protocol/jsonrpc.js.map +1 -0
- package/dist/protocol/types.d.ts +123 -0
- package/dist/protocol/types.d.ts.map +1 -0
- package/dist/protocol/types.js +7 -0
- package/dist/protocol/types.js.map +1 -0
- package/dist/testing/index.d.ts +2 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +2 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/transports/in-memory.d.ts +19 -0
- package/dist/transports/in-memory.d.ts.map +1 -0
- package/dist/transports/in-memory.js +50 -0
- package/dist/transports/in-memory.js.map +1 -0
- package/dist/transports/stdio.d.ts +32 -0
- package/dist/transports/stdio.d.ts.map +1 -0
- package/dist/transports/stdio.js +201 -0
- package/dist/transports/stdio.js.map +1 -0
- package/dist/transports/streamable-http.d.ts +99 -0
- package/dist/transports/streamable-http.d.ts.map +1 -0
- package/dist/transports/streamable-http.js +459 -0
- package/dist/transports/streamable-http.js.map +1 -0
- package/dist/transports/transport.d.ts +28 -0
- package/dist/transports/transport.d.ts.map +1 -0
- package/dist/transports/transport.js +38 -0
- package/dist/transports/transport.js.map +1 -0
- package/package.json +59 -5
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import { isJsonRpcRequest, isJsonRpcResponse, JSON_RPC_ERROR_CODES, McpConnectionClosedError, parseJsonRpcMessage, toError, } from "../protocol/jsonrpc.js";
|
|
2
|
+
import { DEFAULT_MAX_MESSAGE_BYTES, TransportEvents } from "./transport.js";
|
|
3
|
+
const MAX_ERROR_BODY_BYTES = 8 * 1024;
|
|
4
|
+
const ERROR_MESSAGE_BODY_CHARS = 500;
|
|
5
|
+
const DEFAULT_RECONNECT_INITIAL_DELAY_MS = 1_000;
|
|
6
|
+
const DEFAULT_RECONNECT_MAX_DELAY_MS = 30_000;
|
|
7
|
+
const DEFAULT_RECONNECT_MAX_RETRIES = 5;
|
|
8
|
+
export async function consumeSseStream(stream, options) {
|
|
9
|
+
const reader = stream.getReader();
|
|
10
|
+
const decoder = new TextDecoder();
|
|
11
|
+
let buffered = "";
|
|
12
|
+
let eventName;
|
|
13
|
+
let eventId;
|
|
14
|
+
let dataLines = [];
|
|
15
|
+
// Bytes of the pending event's data, including the "\n" joins, so events streamed as many
|
|
16
|
+
// short `data:` lines without a terminating blank line cannot grow without bound.
|
|
17
|
+
let dataBytes = 0;
|
|
18
|
+
const maxEventBytes = options.maxEventBytes ?? DEFAULT_MAX_MESSAGE_BYTES;
|
|
19
|
+
const dispatch = () => {
|
|
20
|
+
if (dataLines.length === 0) {
|
|
21
|
+
eventName = undefined;
|
|
22
|
+
eventId = undefined;
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const data = dataLines.join("\n");
|
|
26
|
+
options.onEvent({ ...(eventName ? { event: eventName } : {}), data, ...(eventId ? { id: eventId } : {}) });
|
|
27
|
+
eventName = undefined;
|
|
28
|
+
eventId = undefined;
|
|
29
|
+
dataLines = [];
|
|
30
|
+
dataBytes = 0;
|
|
31
|
+
};
|
|
32
|
+
const processLine = (rawLine) => {
|
|
33
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
34
|
+
if (line === "") {
|
|
35
|
+
dispatch();
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (line.startsWith(":"))
|
|
39
|
+
return;
|
|
40
|
+
const colon = line.indexOf(":");
|
|
41
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
42
|
+
let value = colon < 0 ? "" : line.slice(colon + 1);
|
|
43
|
+
if (value.startsWith(" "))
|
|
44
|
+
value = value.slice(1);
|
|
45
|
+
if (field === "data") {
|
|
46
|
+
dataBytes += Buffer.byteLength(value) + (dataLines.length > 0 ? 1 : 0);
|
|
47
|
+
if (dataBytes > maxEventBytes)
|
|
48
|
+
throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);
|
|
49
|
+
dataLines.push(value);
|
|
50
|
+
}
|
|
51
|
+
else if (field === "event")
|
|
52
|
+
eventName = value;
|
|
53
|
+
else if (field === "id" && !value.includes("\0")) {
|
|
54
|
+
eventId = value;
|
|
55
|
+
options.onId?.(value);
|
|
56
|
+
}
|
|
57
|
+
else if (field === "retry" && /^\d+$/.test(value))
|
|
58
|
+
options.onRetry?.(Number(value));
|
|
59
|
+
};
|
|
60
|
+
try {
|
|
61
|
+
while (true) {
|
|
62
|
+
const { done, value } = await reader.read();
|
|
63
|
+
if (done)
|
|
64
|
+
break;
|
|
65
|
+
buffered += decoder.decode(value, { stream: true });
|
|
66
|
+
let newline = buffered.indexOf("\n");
|
|
67
|
+
while (newline >= 0) {
|
|
68
|
+
processLine(buffered.slice(0, newline));
|
|
69
|
+
buffered = buffered.slice(newline + 1);
|
|
70
|
+
newline = buffered.indexOf("\n");
|
|
71
|
+
}
|
|
72
|
+
if (Buffer.byteLength(buffered) > maxEventBytes)
|
|
73
|
+
throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);
|
|
74
|
+
}
|
|
75
|
+
buffered += decoder.decode();
|
|
76
|
+
if (buffered)
|
|
77
|
+
processLine(buffered);
|
|
78
|
+
dispatch();
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
reader.releaseLock();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export class McpHttpError extends Error {
|
|
85
|
+
status;
|
|
86
|
+
body;
|
|
87
|
+
constructor(status, message, body = "") {
|
|
88
|
+
super(message);
|
|
89
|
+
this.name = "McpHttpError";
|
|
90
|
+
this.status = status;
|
|
91
|
+
this.body = body;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export class McpAuthRequiredError extends McpHttpError {
|
|
95
|
+
wwwAuthenticate;
|
|
96
|
+
constructor(response, body = "") {
|
|
97
|
+
super(401, "MCP server requires authentication", body);
|
|
98
|
+
this.name = "McpAuthRequiredError";
|
|
99
|
+
this.wwwAuthenticate = response.headers.get("www-authenticate");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
export class McpSessionExpiredError extends McpHttpError {
|
|
103
|
+
constructor(body = "") {
|
|
104
|
+
super(404, "MCP session expired", body);
|
|
105
|
+
this.name = "McpSessionExpiredError";
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function contentType(response) {
|
|
109
|
+
return response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
110
|
+
}
|
|
111
|
+
/** 401, or 403 with an `insufficient_scope` bearer challenge (step-up authorization). */
|
|
112
|
+
function needsAuthorization(response) {
|
|
113
|
+
if (response.status === 401)
|
|
114
|
+
return true;
|
|
115
|
+
if (response.status !== 403)
|
|
116
|
+
return false;
|
|
117
|
+
return /(?:^|[\s,])error="?insufficient_scope"?/i.test(response.headers.get("www-authenticate") ?? "");
|
|
118
|
+
}
|
|
119
|
+
/** Statuses worth retrying when a stream fails to (re)open. */
|
|
120
|
+
function isTransientStatus(status) {
|
|
121
|
+
return status === 408 || status === 429 || status >= 500;
|
|
122
|
+
}
|
|
123
|
+
function discard(response) {
|
|
124
|
+
return response.body?.cancel().catch(() => { }) ?? Promise.resolve();
|
|
125
|
+
}
|
|
126
|
+
function describeHttpFailure(status, body) {
|
|
127
|
+
const text = body.trim();
|
|
128
|
+
const snippet = text.length > ERROR_MESSAGE_BODY_CHARS ? `${text.slice(0, ERROR_MESSAGE_BODY_CHARS - 3)}...` : text;
|
|
129
|
+
return `MCP HTTP request failed with status ${status}${snippet ? `: ${snippet}` : ""}`;
|
|
130
|
+
}
|
|
131
|
+
export class StreamableHttpTransport extends TransportEvents {
|
|
132
|
+
url;
|
|
133
|
+
options;
|
|
134
|
+
fetch;
|
|
135
|
+
controller = new AbortController();
|
|
136
|
+
started = false;
|
|
137
|
+
closed = false;
|
|
138
|
+
sessionIdValue;
|
|
139
|
+
protocolVersion;
|
|
140
|
+
getStreamStarted = false;
|
|
141
|
+
/** Access token of the latest request, which `close()` reuses instead of asking the auth provider. */
|
|
142
|
+
lastToken;
|
|
143
|
+
constructor(options) {
|
|
144
|
+
super();
|
|
145
|
+
this.options = Object.freeze({ ...options, headers: options.headers ? { ...options.headers } : undefined });
|
|
146
|
+
this.url = new URL(options.url);
|
|
147
|
+
const fetch = options.fetch ?? globalThis.fetch;
|
|
148
|
+
// Call fetch without a receiver. `this.fetch(...)` and `context.fetch(...)` would pass the transport or
|
|
149
|
+
// the auth context as `this`, which Cloudflare Workers reject for the platform fetch ("Illegal invocation").
|
|
150
|
+
this.fetch = (input, init) => fetch(input, init);
|
|
151
|
+
}
|
|
152
|
+
get sessionId() {
|
|
153
|
+
return this.sessionIdValue;
|
|
154
|
+
}
|
|
155
|
+
async start() {
|
|
156
|
+
if (this.started)
|
|
157
|
+
throw new Error("MCP Streamable HTTP transport already started");
|
|
158
|
+
if (this.closed)
|
|
159
|
+
throw new McpConnectionClosedError();
|
|
160
|
+
this.started = true;
|
|
161
|
+
}
|
|
162
|
+
setProtocolVersion(version) {
|
|
163
|
+
this.protocolVersion = version;
|
|
164
|
+
}
|
|
165
|
+
async send(message) {
|
|
166
|
+
if (!this.started || this.closed)
|
|
167
|
+
throw new McpConnectionClosedError();
|
|
168
|
+
const response = await this.authorizedFetch("POST", {
|
|
169
|
+
headers: { accept: "application/json, text/event-stream", "content-type": "application/json" },
|
|
170
|
+
body: JSON.stringify(message),
|
|
171
|
+
});
|
|
172
|
+
await this.checkResponse(response);
|
|
173
|
+
this.captureSession(response);
|
|
174
|
+
if (!isJsonRpcRequest(message)) {
|
|
175
|
+
// Notifications and responses are acknowledged with 202 and carry no reply; ignore any body.
|
|
176
|
+
await discard(response);
|
|
177
|
+
// The server-to-client stream may only open once the session is initialized.
|
|
178
|
+
if ("method" in message && message.method === "notifications/initialized")
|
|
179
|
+
this.startGetStream();
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (response.status === 202 || response.status === 204) {
|
|
183
|
+
throw new McpHttpError(response.status, `MCP server accepted request ${message.method} without a response`);
|
|
184
|
+
}
|
|
185
|
+
const type = contentType(response);
|
|
186
|
+
if (type === "application/json") {
|
|
187
|
+
const body = await response.json();
|
|
188
|
+
for (const item of Array.isArray(body) ? body : [body])
|
|
189
|
+
this.emitMessage(parseJsonRpcMessage(item));
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (type === "text/event-stream" && response.body) {
|
|
193
|
+
void this.consumeResponseStream(response.body, message.id);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
await discard(response);
|
|
197
|
+
throw new McpHttpError(response.status, `Unsupported MCP response content type: ${type ?? "missing"}`);
|
|
198
|
+
}
|
|
199
|
+
async close() {
|
|
200
|
+
if (this.closed)
|
|
201
|
+
return;
|
|
202
|
+
this.closed = true;
|
|
203
|
+
this.controller.abort();
|
|
204
|
+
if (this.started && this.sessionIdValue) {
|
|
205
|
+
// Best effort: the session expires on the server anyway. The auth provider may refresh tokens
|
|
206
|
+
// over the network, so it is not asked here and closing never waits for a refresh.
|
|
207
|
+
try {
|
|
208
|
+
const response = await this.fetch(this.url, {
|
|
209
|
+
method: "DELETE",
|
|
210
|
+
headers: this.buildHeaders({}, this.lastToken),
|
|
211
|
+
signal: AbortSignal.timeout(1_000),
|
|
212
|
+
});
|
|
213
|
+
await discard(response);
|
|
214
|
+
}
|
|
215
|
+
catch { }
|
|
216
|
+
}
|
|
217
|
+
this.emitClose();
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Fetch with auth headers. A 401 (or a 403 asking for more scope) is handed to the auth provider
|
|
221
|
+
* once, and the request is retried with whatever credentials it left behind.
|
|
222
|
+
*/
|
|
223
|
+
async authorizedFetch(method, init) {
|
|
224
|
+
const onUnauthorized = this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);
|
|
225
|
+
for (let attempt = 0;; attempt++) {
|
|
226
|
+
const { headers, token } = await this.headers(init.headers);
|
|
227
|
+
const response = await this.fetch(this.url, {
|
|
228
|
+
method,
|
|
229
|
+
headers,
|
|
230
|
+
body: init.body,
|
|
231
|
+
signal: this.controller.signal,
|
|
232
|
+
});
|
|
233
|
+
if (attempt > 0 || !onUnauthorized || !needsAuthorization(response))
|
|
234
|
+
return response;
|
|
235
|
+
try {
|
|
236
|
+
await onUnauthorized({ response, serverUrl: this.url, fetch: this.fetch, token });
|
|
237
|
+
}
|
|
238
|
+
finally {
|
|
239
|
+
await discard(response);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
async headers(extra = {}) {
|
|
244
|
+
const token = await this.options.authProvider?.token();
|
|
245
|
+
this.lastToken = token;
|
|
246
|
+
return { headers: this.buildHeaders(extra, token), ...(token ? { token } : {}) };
|
|
247
|
+
}
|
|
248
|
+
buildHeaders(extra, token) {
|
|
249
|
+
const headers = new Headers(this.options.headers);
|
|
250
|
+
for (const [name, value] of Object.entries(extra))
|
|
251
|
+
headers.set(name, value);
|
|
252
|
+
if (this.sessionIdValue)
|
|
253
|
+
headers.set("Mcp-Session-Id", this.sessionIdValue);
|
|
254
|
+
if (this.protocolVersion)
|
|
255
|
+
headers.set("MCP-Protocol-Version", this.protocolVersion);
|
|
256
|
+
if (token)
|
|
257
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
258
|
+
return headers;
|
|
259
|
+
}
|
|
260
|
+
captureSession(response) {
|
|
261
|
+
const sessionId = response.headers.get("mcp-session-id");
|
|
262
|
+
if (sessionId)
|
|
263
|
+
this.sessionIdValue = sessionId;
|
|
264
|
+
}
|
|
265
|
+
async checkResponse(response) {
|
|
266
|
+
if (response.ok)
|
|
267
|
+
return;
|
|
268
|
+
const body = (await response.text().catch(() => "")).slice(0, MAX_ERROR_BODY_BYTES);
|
|
269
|
+
if (response.status === 401)
|
|
270
|
+
throw new McpAuthRequiredError(response, body);
|
|
271
|
+
if (response.status === 404 && this.sessionIdValue)
|
|
272
|
+
throw new McpSessionExpiredError(body);
|
|
273
|
+
throw new McpHttpError(response.status, describeHttpFailure(response.status, body), body);
|
|
274
|
+
}
|
|
275
|
+
async consumeSse(stream, cursor, onMessage) {
|
|
276
|
+
await consumeSseStream(stream, {
|
|
277
|
+
maxEventBytes: this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES,
|
|
278
|
+
onId: (id) => {
|
|
279
|
+
cursor.lastEventId = id;
|
|
280
|
+
},
|
|
281
|
+
onRetry: (delayMs) => {
|
|
282
|
+
cursor.retryMs = delayMs;
|
|
283
|
+
},
|
|
284
|
+
onEvent: (event) => {
|
|
285
|
+
cursor.received = true;
|
|
286
|
+
// Events without data prime resumption; other event types are not JSON-RPC.
|
|
287
|
+
if (!event.data.trim() || (event.event !== undefined && event.event !== "message"))
|
|
288
|
+
return;
|
|
289
|
+
let message;
|
|
290
|
+
try {
|
|
291
|
+
message = parseJsonRpcMessage(JSON.parse(event.data));
|
|
292
|
+
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
this.emitError(error);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
onMessage?.(message);
|
|
298
|
+
this.emitMessage(message);
|
|
299
|
+
},
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Read the SSE stream answering one request. When the stream ends or breaks before the response
|
|
304
|
+
* arrives and the server assigned event IDs, resume it with GET and `Last-Event-ID`, as the
|
|
305
|
+
* server may close response streams at will. Otherwise only this request fails.
|
|
306
|
+
*/
|
|
307
|
+
async consumeResponseStream(body, requestId) {
|
|
308
|
+
const cursor = { lastEventId: undefined, retryMs: undefined, received: false };
|
|
309
|
+
let answered = false;
|
|
310
|
+
const onMessage = (message) => {
|
|
311
|
+
if (isJsonRpcResponse(message) && message.id === requestId)
|
|
312
|
+
answered = true;
|
|
313
|
+
};
|
|
314
|
+
let stream = body;
|
|
315
|
+
let failure;
|
|
316
|
+
for (let attempt = 0;;) {
|
|
317
|
+
if (stream) {
|
|
318
|
+
try {
|
|
319
|
+
await this.consumeSse(stream, cursor, onMessage);
|
|
320
|
+
failure = undefined;
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
failure = error;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (answered || this.closed)
|
|
327
|
+
return;
|
|
328
|
+
if (failure !== undefined && !this.isRetryable(failure))
|
|
329
|
+
break;
|
|
330
|
+
if (cursor.lastEventId === undefined || attempt >= this.maxRetries())
|
|
331
|
+
break;
|
|
332
|
+
if (cursor.received)
|
|
333
|
+
attempt = 0;
|
|
334
|
+
cursor.received = false;
|
|
335
|
+
if (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs))))
|
|
336
|
+
return;
|
|
337
|
+
try {
|
|
338
|
+
stream = await this.openSseStream(cursor.lastEventId);
|
|
339
|
+
}
|
|
340
|
+
catch (error) {
|
|
341
|
+
failure = error;
|
|
342
|
+
if (!this.isRetryable(error))
|
|
343
|
+
break;
|
|
344
|
+
stream = undefined;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (this.closed)
|
|
348
|
+
return;
|
|
349
|
+
const reason = failure === undefined ? "stream ended without a response" : toError(failure).message;
|
|
350
|
+
this.emitMessage({
|
|
351
|
+
jsonrpc: "2.0",
|
|
352
|
+
id: requestId,
|
|
353
|
+
error: { code: JSON_RPC_ERROR_CODES.internalError, message: `MCP response stream failed: ${reason}` },
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
startGetStream() {
|
|
357
|
+
if (this.options.openGetStream === false || this.getStreamStarted || this.closed)
|
|
358
|
+
return;
|
|
359
|
+
this.getStreamStarted = true;
|
|
360
|
+
void this.runGetStream();
|
|
361
|
+
}
|
|
362
|
+
/** Keep the server-to-client stream open, reconnecting with backoff when it drops. */
|
|
363
|
+
async runGetStream() {
|
|
364
|
+
const cursor = { lastEventId: undefined, retryMs: undefined, received: false };
|
|
365
|
+
for (let attempt = 0; !this.closed;) {
|
|
366
|
+
try {
|
|
367
|
+
const stream = await this.openSseStream(cursor.lastEventId);
|
|
368
|
+
// The server does not offer a GET stream.
|
|
369
|
+
if (!stream)
|
|
370
|
+
return;
|
|
371
|
+
const openedAt = Date.now();
|
|
372
|
+
await this.consumeSse(stream, cursor);
|
|
373
|
+
// A stream that stayed up for a while counts as healthy, even if it was idle.
|
|
374
|
+
if (cursor.received || Date.now() - openedAt > this.maxDelay())
|
|
375
|
+
attempt = 0;
|
|
376
|
+
}
|
|
377
|
+
catch (error) {
|
|
378
|
+
if (this.closed)
|
|
379
|
+
return;
|
|
380
|
+
if (!this.isRetryable(error)) {
|
|
381
|
+
this.emitError(error);
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
cursor.received = false;
|
|
386
|
+
if (attempt >= this.maxRetries()) {
|
|
387
|
+
this.emitError(new Error("MCP server-to-client stream dropped and could not be reopened"));
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
if (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs))))
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
/** Open a GET SSE stream. Resolves to undefined when the server answers 405 (no GET stream). */
|
|
395
|
+
async openSseStream(lastEventId) {
|
|
396
|
+
const response = await this.authorizedFetch("GET", {
|
|
397
|
+
headers: {
|
|
398
|
+
accept: "text/event-stream",
|
|
399
|
+
...(lastEventId === undefined ? {} : { "last-event-id": lastEventId }),
|
|
400
|
+
},
|
|
401
|
+
});
|
|
402
|
+
if (response.status === 405) {
|
|
403
|
+
await discard(response);
|
|
404
|
+
return undefined;
|
|
405
|
+
}
|
|
406
|
+
await this.checkResponse(response);
|
|
407
|
+
this.captureSession(response);
|
|
408
|
+
const type = contentType(response);
|
|
409
|
+
if (type !== "text/event-stream" || !response.body) {
|
|
410
|
+
await discard(response);
|
|
411
|
+
throw new McpHttpError(response.status, `Unsupported MCP GET response content type: ${type ?? "missing"}`);
|
|
412
|
+
}
|
|
413
|
+
return response.body;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Network failures and transient statuses are retried; auth, session, and protocol errors are not.
|
|
417
|
+
* `fetch` reports network failures, including a connection dropped mid-body, as `TypeError`.
|
|
418
|
+
*/
|
|
419
|
+
isRetryable(error) {
|
|
420
|
+
if (error instanceof McpHttpError)
|
|
421
|
+
return isTransientStatus(error.status);
|
|
422
|
+
if (error instanceof TypeError)
|
|
423
|
+
return true;
|
|
424
|
+
const code = error?.code;
|
|
425
|
+
return typeof code === "string" && (code.startsWith("E") || code.startsWith("UND_ERR"));
|
|
426
|
+
}
|
|
427
|
+
reconnectDelay(attempt, serverDelayMs) {
|
|
428
|
+
if (serverDelayMs !== undefined)
|
|
429
|
+
return serverDelayMs;
|
|
430
|
+
const initial = this.options.reconnect?.initialDelayMs ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS;
|
|
431
|
+
return Math.min(initial * 2 ** attempt, this.maxDelay());
|
|
432
|
+
}
|
|
433
|
+
maxDelay() {
|
|
434
|
+
return this.options.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS;
|
|
435
|
+
}
|
|
436
|
+
maxRetries() {
|
|
437
|
+
return this.options.reconnect?.maxRetries ?? DEFAULT_RECONNECT_MAX_RETRIES;
|
|
438
|
+
}
|
|
439
|
+
/** Resolves false when the transport closed while waiting. */
|
|
440
|
+
sleep(ms) {
|
|
441
|
+
const signal = this.controller.signal;
|
|
442
|
+
if (signal.aborted)
|
|
443
|
+
return Promise.resolve(false);
|
|
444
|
+
return new Promise((resolve) => {
|
|
445
|
+
const onAbort = () => {
|
|
446
|
+
clearTimeout(timer);
|
|
447
|
+
resolve(false);
|
|
448
|
+
};
|
|
449
|
+
const timer = setTimeout(() => {
|
|
450
|
+
signal.removeEventListener("abort", onAbort);
|
|
451
|
+
resolve(true);
|
|
452
|
+
}, ms);
|
|
453
|
+
// A reconnect wait alone does not keep the process alive.
|
|
454
|
+
timer.unref?.();
|
|
455
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
//# sourceMappingURL=streamable-http.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"streamable-http.js","sourceRoot":"","sources":["../../src/transports/streamable-http.ts"],"names":[],"mappings":"AACA,OAAO,EACN,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,EAGpB,wBAAwB,EACxB,mBAAmB,EACnB,OAAO,GACP,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,yBAAyB,EAAqB,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAE/F,MAAM,oBAAoB,GAAG,CAAC,GAAG,IAAI,CAAC;AACtC,MAAM,wBAAwB,GAAG,GAAG,CAAC;AACrC,MAAM,kCAAkC,GAAG,KAAK,CAAC;AACjD,MAAM,8BAA8B,GAAG,MAAM,CAAC;AAC9C,MAAM,6BAA6B,GAAG,CAAC,CAAC;AAiBxC,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,MAAkC,EAAE,OAA0B;IACpG,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;IAClC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,QAAQ,GAAG,EAAE,CAAC;IAClB,IAAI,SAA6B,CAAC;IAClC,IAAI,OAA2B,CAAC;IAChC,IAAI,SAAS,GAAa,EAAE,CAAC;IAC7B,0FAA0F;IAC1F,kFAAkF;IAClF,IAAI,SAAS,GAAG,CAAC,CAAC;IAClB,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa,IAAI,yBAAyB,CAAC;IAEzE,MAAM,QAAQ,GAAG,GAAG,EAAE;QACrB,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC5B,SAAS,GAAG,SAAS,CAAC;YACtB,OAAO,GAAG,SAAS,CAAC;YACpB,OAAO;QACR,C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,GAAG,CAAC,OAAO,GAAG,CAAC,IAAI,OAAO,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC1D,CAAC;IAEO,QAAQ;QACf,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,UAAU,IAAI,8BAA8B,CAAC;IAC7E,CAAC;IAEO,UAAU;QACjB,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,UAAU,IAAI,6BAA6B,CAAC;IAC5E,CAAC;IAED,8DAA8D;IACtD,KAAK,CAAC,EAAU;QACvB,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC;QACtC,IAAI,MAAM,CAAC,OAAO;YAAE,OAAO,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAClD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC9B,MAAM,OAAO,GAAG,GAAG,EAAE;gBACpB,YAAY,CAAC,KAAK,CAAC,CAAC;gBACpB,OAAO,CAAC,KAAK,CAAC,CAAC;YAChB,CAAC,CAAC;YACF,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;gBAC7B,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;gBAC7C,OAAO,CAAC,IAAI,CAAC,CAAC;YACf,CAAC,EAAE,EAAE,CAAC,CAAC;YACP,0DAA0D;YAC1D,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC;YAChB,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3D,CAAC,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import type { AuthProvider, McpFetch } from \"../auth-provider.ts\";\nimport {\n\tisJsonRpcRequest,\n\tisJsonRpcResponse,\n\tJSON_RPC_ERROR_CODES,\n\ttype JsonRpcId,\n\ttype JsonRpcMessage,\n\tMcpConnectionClosedError,\n\tparseJsonRpcMessage,\n\ttoError,\n} from \"../protocol/jsonrpc.ts\";\nimport { DEFAULT_MAX_MESSAGE_BYTES, type McpTransport, TransportEvents } from \"./transport.ts\";\n\nconst MAX_ERROR_BODY_BYTES = 8 * 1024;\nconst ERROR_MESSAGE_BODY_CHARS = 500;\nconst DEFAULT_RECONNECT_INITIAL_DELAY_MS = 1_000;\nconst DEFAULT_RECONNECT_MAX_DELAY_MS = 30_000;\nconst DEFAULT_RECONNECT_MAX_RETRIES = 5;\n\nexport interface SseEvent {\n\tevent?: string;\n\tdata: string;\n\tid?: string;\n}\n\nexport interface ConsumeSseOptions {\n\tmaxEventBytes?: number;\n\tonEvent(event: SseEvent): void;\n\t/** Called for every `id` field, including events without data (for example resumption priming events). */\n\tonId?(id: string): void;\n\t/** Called for every valid `retry` field, in milliseconds. */\n\tonRetry?(delayMs: number): void;\n}\n\nexport async function consumeSseStream(stream: ReadableStream<Uint8Array>, options: ConsumeSseOptions): Promise<void> {\n\tconst reader = stream.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffered = \"\";\n\tlet eventName: string | undefined;\n\tlet eventId: string | undefined;\n\tlet dataLines: string[] = [];\n\t// Bytes of the pending event's data, including the \"\\n\" joins, so events streamed as many\n\t// short `data:` lines without a terminating blank line cannot grow without bound.\n\tlet dataBytes = 0;\n\tconst maxEventBytes = options.maxEventBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n\n\tconst dispatch = () => {\n\t\tif (dataLines.length === 0) {\n\t\t\teventName = undefined;\n\t\t\teventId = undefined;\n\t\t\treturn;\n\t\t}\n\t\tconst data = dataLines.join(\"\\n\");\n\t\toptions.onEvent({ ...(eventName ? { event: eventName } : {}), data, ...(eventId ? { id: eventId } : {}) });\n\t\teventName = undefined;\n\t\teventId = undefined;\n\t\tdataLines = [];\n\t\tdataBytes = 0;\n\t};\n\n\tconst processLine = (rawLine: string) => {\n\t\tconst line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n\t\tif (line === \"\") {\n\t\t\tdispatch();\n\t\t\treturn;\n\t\t}\n\t\tif (line.startsWith(\":\")) return;\n\t\tconst colon = line.indexOf(\":\");\n\t\tconst field = colon < 0 ? line : line.slice(0, colon);\n\t\tlet value = colon < 0 ? \"\" : line.slice(colon + 1);\n\t\tif (value.startsWith(\" \")) value = value.slice(1);\n\t\tif (field === \"data\") {\n\t\t\tdataBytes += Buffer.byteLength(value) + (dataLines.length > 0 ? 1 : 0);\n\t\t\tif (dataBytes > maxEventBytes) throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);\n\t\t\tdataLines.push(value);\n\t\t} else if (field === \"event\") eventName = value;\n\t\telse if (field === \"id\" && !value.includes(\"\\0\")) {\n\t\t\teventId = value;\n\t\t\toptions.onId?.(value);\n\t\t} else if (field === \"retry\" && /^\\d+$/.test(value)) options.onRetry?.(Number(value));\n\t};\n\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tbuffered += decoder.decode(value, { stream: true });\n\t\t\tlet newline = buffered.indexOf(\"\\n\");\n\t\t\twhile (newline >= 0) {\n\t\t\t\tprocessLine(buffered.slice(0, newline));\n\t\t\t\tbuffered = buffered.slice(newline + 1);\n\t\t\t\tnewline = buffered.indexOf(\"\\n\");\n\t\t\t}\n\t\t\tif (Buffer.byteLength(buffered) > maxEventBytes)\n\t\t\t\tthrow new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);\n\t\t}\n\t\tbuffered += decoder.decode();\n\t\tif (buffered) processLine(buffered);\n\t\tdispatch();\n\t} finally {\n\t\treader.releaseLock();\n\t}\n}\n\nexport interface StreamableHttpReconnectOptions {\n\t/** Delay before the first reconnection attempt, unless the server sent a `retry` field. Default: 1000. */\n\tinitialDelayMs?: number;\n\t/** Upper bound for the exponential backoff. Default: 30000. */\n\tmaxDelayMs?: number;\n\t/** Consecutive failed attempts before giving up on a stream. Default: 5. */\n\tmaxRetries?: number;\n}\n\nexport interface StreamableHttpTransportOptions {\n\turl: string | URL;\n\theaders?: Record<string, string>;\n\tfetch?: McpFetch;\n\t/** Open the server-to-client GET stream after initialization. Default: true. */\n\topenGetStream?: boolean;\n\tmaxMessageBytes?: number;\n\tauthProvider?: AuthProvider;\n\t/** Reconnection of dropped SSE streams (the GET stream, and response streams that carry event IDs). */\n\treconnect?: StreamableHttpReconnectOptions;\n}\n\nexport class McpHttpError extends Error {\n\treadonly status: number;\n\treadonly body: string;\n\n\tconstructor(status: number, message: string, body = \"\") {\n\t\tsuper(message);\n\t\tthis.name = \"McpHttpError\";\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t}\n}\n\nexport class McpAuthRequiredError extends McpHttpError {\n\treadonly wwwAuthenticate: string | null;\n\n\tconstructor(response: Response, body = \"\") {\n\t\tsuper(401, \"MCP server requires authentication\", body);\n\t\tthis.name = \"McpAuthRequiredError\";\n\t\tthis.wwwAuthenticate = response.headers.get(\"www-authenticate\");\n\t}\n}\n\nexport class McpSessionExpiredError extends McpHttpError {\n\tconstructor(body = \"\") {\n\t\tsuper(404, \"MCP session expired\", body);\n\t\tthis.name = \"McpSessionExpiredError\";\n\t}\n}\n\nfunction contentType(response: Response): string | undefined {\n\treturn response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n}\n\n/** 401, or 403 with an `insufficient_scope` bearer challenge (step-up authorization). */\nfunction needsAuthorization(response: Response): boolean {\n\tif (response.status === 401) return true;\n\tif (response.status !== 403) return false;\n\treturn /(?:^|[\\s,])error=\"?insufficient_scope\"?/i.test(response.headers.get(\"www-authenticate\") ?? \"\");\n}\n\n/** Statuses worth retrying when a stream fails to (re)open. */\nfunction isTransientStatus(status: number): boolean {\n\treturn status === 408 || status === 429 || status >= 500;\n}\n\nfunction discard(response: Response): Promise<void> {\n\treturn response.body?.cancel().catch(() => {}) ?? Promise.resolve();\n}\n\nfunction describeHttpFailure(status: number, body: string): string {\n\tconst text = body.trim();\n\tconst snippet = text.length > ERROR_MESSAGE_BODY_CHARS ? `${text.slice(0, ERROR_MESSAGE_BODY_CHARS - 3)}...` : text;\n\treturn `MCP HTTP request failed with status ${status}${snippet ? `: ${snippet}` : \"\"}`;\n}\n\ninterface StreamCursor {\n\tlastEventId: string | undefined;\n\tretryMs: number | undefined;\n\t/** Whether the stream delivered any event since it was (re)opened. */\n\treceived: boolean;\n}\n\nexport class StreamableHttpTransport extends TransportEvents implements McpTransport {\n\treadonly url: URL;\n\treadonly options: Readonly<StreamableHttpTransportOptions>;\n\tprivate fetch: McpFetch;\n\tprivate controller = new AbortController();\n\tprivate started = false;\n\tprivate closed = false;\n\tprivate sessionIdValue: string | undefined;\n\tprivate protocolVersion: string | undefined;\n\tprivate getStreamStarted = false;\n\t/** Access token of the latest request, which `close()` reuses instead of asking the auth provider. */\n\tprivate lastToken: string | undefined;\n\n\tconstructor(options: StreamableHttpTransportOptions) {\n\t\tsuper();\n\t\tthis.options = Object.freeze({ ...options, headers: options.headers ? { ...options.headers } : undefined });\n\t\tthis.url = new URL(options.url);\n\t\tconst fetch = options.fetch ?? globalThis.fetch;\n\t\t// Call fetch without a receiver. `this.fetch(...)` and `context.fetch(...)` would pass the transport or\n\t\t// the auth context as `this`, which Cloudflare Workers reject for the platform fetch (\"Illegal invocation\").\n\t\tthis.fetch = (input, init) => fetch(input, init);\n\t}\n\n\tget sessionId(): string | undefined {\n\t\treturn this.sessionIdValue;\n\t}\n\n\tasync start(): Promise<void> {\n\t\tif (this.started) throw new Error(\"MCP Streamable HTTP transport already started\");\n\t\tif (this.closed) throw new McpConnectionClosedError();\n\t\tthis.started = true;\n\t}\n\n\tsetProtocolVersion(version: string): void {\n\t\tthis.protocolVersion = version;\n\t}\n\n\tasync send(message: JsonRpcMessage): Promise<void> {\n\t\tif (!this.started || this.closed) throw new McpConnectionClosedError();\n\t\tconst response = await this.authorizedFetch(\"POST\", {\n\t\t\theaders: { accept: \"application/json, text/event-stream\", \"content-type\": \"application/json\" },\n\t\t\tbody: JSON.stringify(message),\n\t\t});\n\t\tawait this.checkResponse(response);\n\t\tthis.captureSession(response);\n\n\t\tif (!isJsonRpcRequest(message)) {\n\t\t\t// Notifications and responses are acknowledged with 202 and carry no reply; ignore any body.\n\t\t\tawait discard(response);\n\t\t\t// The server-to-client stream may only open once the session is initialized.\n\t\t\tif (\"method\" in message && message.method === \"notifications/initialized\") this.startGetStream();\n\t\t\treturn;\n\t\t}\n\t\tif (response.status === 202 || response.status === 204) {\n\t\t\tthrow new McpHttpError(response.status, `MCP server accepted request ${message.method} without a response`);\n\t\t}\n\t\tconst type = contentType(response);\n\t\tif (type === \"application/json\") {\n\t\t\tconst body: unknown = await response.json();\n\t\t\tfor (const item of Array.isArray(body) ? body : [body]) this.emitMessage(parseJsonRpcMessage(item));\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"text/event-stream\" && response.body) {\n\t\t\tvoid this.consumeResponseStream(response.body, message.id);\n\t\t\treturn;\n\t\t}\n\t\tawait discard(response);\n\t\tthrow new McpHttpError(response.status, `Unsupported MCP response content type: ${type ?? \"missing\"}`);\n\t}\n\n\tasync close(): Promise<void> {\n\t\tif (this.closed) return;\n\t\tthis.closed = true;\n\t\tthis.controller.abort();\n\t\tif (this.started && this.sessionIdValue) {\n\t\t\t// Best effort: the session expires on the server anyway. The auth provider may refresh tokens\n\t\t\t// over the network, so it is not asked here and closing never waits for a refresh.\n\t\t\ttry {\n\t\t\t\tconst response = await this.fetch(this.url, {\n\t\t\t\t\tmethod: \"DELETE\",\n\t\t\t\t\theaders: this.buildHeaders({}, this.lastToken),\n\t\t\t\t\tsignal: AbortSignal.timeout(1_000),\n\t\t\t\t});\n\t\t\t\tawait discard(response);\n\t\t\t} catch {}\n\t\t}\n\t\tthis.emitClose();\n\t}\n\n\t/**\n\t * Fetch with auth headers. A 401 (or a 403 asking for more scope) is handed to the auth provider\n\t * once, and the request is retried with whatever credentials it left behind.\n\t */\n\tprivate async authorizedFetch(\n\t\tmethod: \"GET\" | \"POST\",\n\t\tinit: { headers: Record<string, string>; body?: string },\n\t): Promise<Response> {\n\t\tconst onUnauthorized = this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);\n\t\tfor (let attempt = 0; ; attempt++) {\n\t\t\tconst { headers, token } = await this.headers(init.headers);\n\t\t\tconst response = await this.fetch(this.url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: init.body,\n\t\t\t\tsignal: this.controller.signal,\n\t\t\t});\n\t\t\tif (attempt > 0 || !onUnauthorized || !needsAuthorization(response)) return response;\n\t\t\ttry {\n\t\t\t\tawait onUnauthorized({ response, serverUrl: this.url, fetch: this.fetch, token });\n\t\t\t} finally {\n\t\t\t\tawait discard(response);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async headers(extra: Record<string, string> = {}): Promise<{ headers: Headers; token?: string }> {\n\t\tconst token = await this.options.authProvider?.token();\n\t\tthis.lastToken = token;\n\t\treturn { headers: this.buildHeaders(extra, token), ...(token ? { token } : {}) };\n\t}\n\n\tprivate buildHeaders(extra: Record<string, string>, token: string | undefined): Headers {\n\t\tconst headers = new Headers(this.options.headers);\n\t\tfor (const [name, value] of Object.entries(extra)) headers.set(name, value);\n\t\tif (this.sessionIdValue) headers.set(\"Mcp-Session-Id\", this.sessionIdValue);\n\t\tif (this.protocolVersion) headers.set(\"MCP-Protocol-Version\", this.protocolVersion);\n\t\tif (token) headers.set(\"Authorization\", `Bearer ${token}`);\n\t\treturn headers;\n\t}\n\n\tprivate captureSession(response: Response): void {\n\t\tconst sessionId = response.headers.get(\"mcp-session-id\");\n\t\tif (sessionId) this.sessionIdValue = sessionId;\n\t}\n\n\tprivate async checkResponse(response: Response): Promise<void> {\n\t\tif (response.ok) return;\n\t\tconst body = (await response.text().catch(() => \"\")).slice(0, MAX_ERROR_BODY_BYTES);\n\t\tif (response.status === 401) throw new McpAuthRequiredError(response, body);\n\t\tif (response.status === 404 && this.sessionIdValue) throw new McpSessionExpiredError(body);\n\t\tthrow new McpHttpError(response.status, describeHttpFailure(response.status, body), body);\n\t}\n\n\tprivate async consumeSse(\n\t\tstream: ReadableStream<Uint8Array>,\n\t\tcursor: StreamCursor,\n\t\tonMessage?: (message: JsonRpcMessage) => void,\n\t): Promise<void> {\n\t\tawait consumeSseStream(stream, {\n\t\t\tmaxEventBytes: this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES,\n\t\t\tonId: (id) => {\n\t\t\t\tcursor.lastEventId = id;\n\t\t\t},\n\t\t\tonRetry: (delayMs) => {\n\t\t\t\tcursor.retryMs = delayMs;\n\t\t\t},\n\t\t\tonEvent: (event) => {\n\t\t\t\tcursor.received = true;\n\t\t\t\t// Events without data prime resumption; other event types are not JSON-RPC.\n\t\t\t\tif (!event.data.trim() || (event.event !== undefined && event.event !== \"message\")) return;\n\t\t\t\tlet message: JsonRpcMessage;\n\t\t\t\ttry {\n\t\t\t\t\tmessage = parseJsonRpcMessage(JSON.parse(event.data));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.emitError(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tonMessage?.(message);\n\t\t\t\tthis.emitMessage(message);\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Read the SSE stream answering one request. When the stream ends or breaks before the response\n\t * arrives and the server assigned event IDs, resume it with GET and `Last-Event-ID`, as the\n\t * server may close response streams at will. Otherwise only this request fails.\n\t */\n\tprivate async consumeResponseStream(body: ReadableStream<Uint8Array>, requestId: JsonRpcId): Promise<void> {\n\t\tconst cursor: StreamCursor = { lastEventId: undefined, retryMs: undefined, received: false };\n\t\tlet answered = false;\n\t\tconst onMessage = (message: JsonRpcMessage) => {\n\t\t\tif (isJsonRpcResponse(message) && message.id === requestId) answered = true;\n\t\t};\n\t\tlet stream: ReadableStream<Uint8Array> | undefined = body;\n\t\tlet failure: unknown;\n\t\tfor (let attempt = 0; ; ) {\n\t\t\tif (stream) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.consumeSse(stream, cursor, onMessage);\n\t\t\t\t\tfailure = undefined;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfailure = error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (answered || this.closed) return;\n\t\t\tif (failure !== undefined && !this.isRetryable(failure)) break;\n\t\t\tif (cursor.lastEventId === undefined || attempt >= this.maxRetries()) break;\n\t\t\tif (cursor.received) attempt = 0;\n\t\t\tcursor.received = false;\n\t\t\tif (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))) return;\n\t\t\ttry {\n\t\t\t\tstream = await this.openSseStream(cursor.lastEventId);\n\t\t\t} catch (error) {\n\t\t\t\tfailure = error;\n\t\t\t\tif (!this.isRetryable(error)) break;\n\t\t\t\tstream = undefined;\n\t\t\t}\n\t\t}\n\t\tif (this.closed) return;\n\t\tconst reason = failure === undefined ? \"stream ended without a response\" : toError(failure).message;\n\t\tthis.emitMessage({\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid: requestId,\n\t\t\terror: { code: JSON_RPC_ERROR_CODES.internalError, message: `MCP response stream failed: ${reason}` },\n\t\t});\n\t}\n\n\tprivate startGetStream(): void {\n\t\tif (this.options.openGetStream === false || this.getStreamStarted || this.closed) return;\n\t\tthis.getStreamStarted = true;\n\t\tvoid this.runGetStream();\n\t}\n\n\t/** Keep the server-to-client stream open, reconnecting with backoff when it drops. */\n\tprivate async runGetStream(): Promise<void> {\n\t\tconst cursor: StreamCursor = { lastEventId: undefined, retryMs: undefined, received: false };\n\t\tfor (let attempt = 0; !this.closed; ) {\n\t\t\ttry {\n\t\t\t\tconst stream = await this.openSseStream(cursor.lastEventId);\n\t\t\t\t// The server does not offer a GET stream.\n\t\t\t\tif (!stream) return;\n\t\t\t\tconst openedAt = Date.now();\n\t\t\t\tawait this.consumeSse(stream, cursor);\n\t\t\t\t// A stream that stayed up for a while counts as healthy, even if it was idle.\n\t\t\t\tif (cursor.received || Date.now() - openedAt > this.maxDelay()) attempt = 0;\n\t\t\t} catch (error) {\n\t\t\t\tif (this.closed) return;\n\t\t\t\tif (!this.isRetryable(error)) {\n\t\t\t\t\tthis.emitError(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcursor.received = false;\n\t\t\tif (attempt >= this.maxRetries()) {\n\t\t\t\tthis.emitError(new Error(\"MCP server-to-client stream dropped and could not be reopened\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))) return;\n\t\t}\n\t}\n\n\t/** Open a GET SSE stream. Resolves to undefined when the server answers 405 (no GET stream). */\n\tprivate async openSseStream(lastEventId: string | undefined): Promise<ReadableStream<Uint8Array> | undefined> {\n\t\tconst response = await this.authorizedFetch(\"GET\", {\n\t\t\theaders: {\n\t\t\t\taccept: \"text/event-stream\",\n\t\t\t\t...(lastEventId === undefined ? {} : { \"last-event-id\": lastEventId }),\n\t\t\t},\n\t\t});\n\t\tif (response.status === 405) {\n\t\t\tawait discard(response);\n\t\t\treturn undefined;\n\t\t}\n\t\tawait this.checkResponse(response);\n\t\tthis.captureSession(response);\n\t\tconst type = contentType(response);\n\t\tif (type !== \"text/event-stream\" || !response.body) {\n\t\t\tawait discard(response);\n\t\t\tthrow new McpHttpError(response.status, `Unsupported MCP GET response content type: ${type ?? \"missing\"}`);\n\t\t}\n\t\treturn response.body;\n\t}\n\n\t/**\n\t * Network failures and transient statuses are retried; auth, session, and protocol errors are not.\n\t * `fetch` reports network failures, including a connection dropped mid-body, as `TypeError`.\n\t */\n\tprivate isRetryable(error: unknown): boolean {\n\t\tif (error instanceof McpHttpError) return isTransientStatus(error.status);\n\t\tif (error instanceof TypeError) return true;\n\t\tconst code = (error as { code?: unknown } | undefined)?.code;\n\t\treturn typeof code === \"string\" && (code.startsWith(\"E\") || code.startsWith(\"UND_ERR\"));\n\t}\n\n\tprivate reconnectDelay(attempt: number, serverDelayMs: number | undefined): number {\n\t\tif (serverDelayMs !== undefined) return serverDelayMs;\n\t\tconst initial = this.options.reconnect?.initialDelayMs ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS;\n\t\treturn Math.min(initial * 2 ** attempt, this.maxDelay());\n\t}\n\n\tprivate maxDelay(): number {\n\t\treturn this.options.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS;\n\t}\n\n\tprivate maxRetries(): number {\n\t\treturn this.options.reconnect?.maxRetries ?? DEFAULT_RECONNECT_MAX_RETRIES;\n\t}\n\n\t/** Resolves false when the transport closed while waiting. */\n\tprivate sleep(ms: number): Promise<boolean> {\n\t\tconst signal = this.controller.signal;\n\t\tif (signal.aborted) return Promise.resolve(false);\n\t\treturn new Promise((resolve) => {\n\t\t\tconst onAbort = () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(false);\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(true);\n\t\t\t}, ms);\n\t\t\t// A reconnect wait alone does not keep the process alive.\n\t\t\ttimer.unref?.();\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t});\n\t}\n}\n"]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type JsonRpcMessage } from "../protocol/jsonrpc.ts";
|
|
2
|
+
export declare const DEFAULT_MAX_MESSAGE_BYTES: number;
|
|
3
|
+
export type McpTransportMessageListener = (message: JsonRpcMessage) => void;
|
|
4
|
+
export type McpTransportErrorListener = (error: Error) => void;
|
|
5
|
+
export type McpTransportCloseListener = () => void;
|
|
6
|
+
export interface McpTransport {
|
|
7
|
+
start(): Promise<void>;
|
|
8
|
+
send(message: JsonRpcMessage): Promise<void>;
|
|
9
|
+
close(): Promise<void>;
|
|
10
|
+
onMessage(listener: McpTransportMessageListener): () => void;
|
|
11
|
+
onError(listener: McpTransportErrorListener): () => void;
|
|
12
|
+
onClose(listener: McpTransportCloseListener): () => void;
|
|
13
|
+
setProtocolVersion?(version: string): void;
|
|
14
|
+
}
|
|
15
|
+
/** Listener bookkeeping shared by transports. `emitClose` fires at most once per transport. */
|
|
16
|
+
export declare abstract class TransportEvents {
|
|
17
|
+
private messageListeners;
|
|
18
|
+
private errorListeners;
|
|
19
|
+
private closeListeners;
|
|
20
|
+
private closeEmitted;
|
|
21
|
+
onMessage(listener: McpTransportMessageListener): () => void;
|
|
22
|
+
onError(listener: McpTransportErrorListener): () => void;
|
|
23
|
+
onClose(listener: McpTransportCloseListener): () => void;
|
|
24
|
+
protected emitMessage(message: JsonRpcMessage): void;
|
|
25
|
+
protected emitError(error: unknown): void;
|
|
26
|
+
protected emitClose(): void;
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=transport.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/transports/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAW,MAAM,wBAAwB,CAAC;AAEtE,eAAO,MAAM,yBAAyB,QAAmB,CAAC;AAE1D,MAAM,MAAM,2BAA2B,GAAG,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;AAC5E,MAAM,MAAM,yBAAyB,GAAG,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;AAC/D,MAAM,MAAM,yBAAyB,GAAG,MAAM,IAAI,CAAC;AAEnD,MAAM,WAAW,YAAY;IAC5B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7C,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,SAAS,CAAC,QAAQ,EAAE,2BAA2B,GAAG,MAAM,IAAI,CAAC;IAC7D,OAAO,CAAC,QAAQ,EAAE,yBAAyB,GAAG,MAAM,IAAI,CAAC;IACzD,OAAO,CAAC,QAAQ,EAAE,yBAAyB,GAAG,MAAM,IAAI,CAAC;IACzD,kBAAkB,CAAC,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3C;AAED,+FAA+F;AAC/F,8BAAsB,eAAe;IACpC,OAAO,CAAC,gBAAgB,CAA0C;IAClE,OAAO,CAAC,cAAc,CAAwC;IAC9D,OAAO,CAAC,cAAc,CAAwC;IAC9D,OAAO,CAAC,YAAY,CAAS;IAE7B,SAAS,CAAC,QAAQ,EAAE,2BAA2B,GAAG,MAAM,IAAI,CAG3D;IAED,OAAO,CAAC,QAAQ,EAAE,yBAAyB,GAAG,MAAM,IAAI,CAGvD;IAED,OAAO,CAAC,QAAQ,EAAE,yBAAyB,GAAG,MAAM,IAAI,CAGvD;IAED,SAAS,CAAC,WAAW,CAAC,OAAO,EAAE,cAAc,GAAG,IAAI,CAEnD;IAED,SAAS,CAAC,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAGxC;IAED,SAAS,CAAC,SAAS,IAAI,IAAI,CAI1B;CACD"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { toError } from "../protocol/jsonrpc.js";
|
|
2
|
+
export const DEFAULT_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
|
|
3
|
+
/** Listener bookkeeping shared by transports. `emitClose` fires at most once per transport. */
|
|
4
|
+
export class TransportEvents {
|
|
5
|
+
messageListeners = new Set();
|
|
6
|
+
errorListeners = new Set();
|
|
7
|
+
closeListeners = new Set();
|
|
8
|
+
closeEmitted = false;
|
|
9
|
+
onMessage(listener) {
|
|
10
|
+
this.messageListeners.add(listener);
|
|
11
|
+
return () => this.messageListeners.delete(listener);
|
|
12
|
+
}
|
|
13
|
+
onError(listener) {
|
|
14
|
+
this.errorListeners.add(listener);
|
|
15
|
+
return () => this.errorListeners.delete(listener);
|
|
16
|
+
}
|
|
17
|
+
onClose(listener) {
|
|
18
|
+
this.closeListeners.add(listener);
|
|
19
|
+
return () => this.closeListeners.delete(listener);
|
|
20
|
+
}
|
|
21
|
+
emitMessage(message) {
|
|
22
|
+
for (const listener of this.messageListeners)
|
|
23
|
+
listener(message);
|
|
24
|
+
}
|
|
25
|
+
emitError(error) {
|
|
26
|
+
const normalized = toError(error);
|
|
27
|
+
for (const listener of this.errorListeners)
|
|
28
|
+
listener(normalized);
|
|
29
|
+
}
|
|
30
|
+
emitClose() {
|
|
31
|
+
if (this.closeEmitted)
|
|
32
|
+
return;
|
|
33
|
+
this.closeEmitted = true;
|
|
34
|
+
for (const listener of this.closeListeners)
|
|
35
|
+
listener();
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=transport.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../src/transports/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAgB1D,+FAA+F;AAC/F,MAAM,OAAgB,eAAe;IAC5B,gBAAgB,GAAG,IAAI,GAAG,EAA+B,CAAC;IAC1D,cAAc,GAAG,IAAI,GAAG,EAA6B,CAAC;IACtD,cAAc,GAAG,IAAI,GAAG,EAA6B,CAAC;IACtD,YAAY,GAAG,KAAK,CAAC;IAE7B,SAAS,CAAC,QAAqC;QAC9C,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACpC,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACrD,CAAC;IAED,OAAO,CAAC,QAAmC;QAC1C,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAClC,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACnD,CAAC;IAED,OAAO,CAAC,QAAmC;QAC1C,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAClC,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACnD,CAAC;IAES,WAAW,CAAC,OAAuB;QAC5C,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,gBAAgB;YAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;IACjE,CAAC;IAES,SAAS,CAAC,KAAc;QACjC,MAAM,UAAU,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;QAClC,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,cAAc;YAAE,QAAQ,CAAC,UAAU,CAAC,CAAC;IAClE,CAAC;IAES,SAAS;QAClB,IAAI,IAAI,CAAC,YAAY;YAAE,OAAO;QAC9B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QACzB,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,cAAc;YAAE,QAAQ,EAAE,CAAC;IACxD,CAAC;CACD","sourcesContent":["import { type JsonRpcMessage, toError } from \"../protocol/jsonrpc.ts\";\n\nexport const DEFAULT_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;\n\nexport type McpTransportMessageListener = (message: JsonRpcMessage) => void;\nexport type McpTransportErrorListener = (error: Error) => void;\nexport type McpTransportCloseListener = () => void;\n\nexport interface McpTransport {\n\tstart(): Promise<void>;\n\tsend(message: JsonRpcMessage): Promise<void>;\n\tclose(): Promise<void>;\n\tonMessage(listener: McpTransportMessageListener): () => void;\n\tonError(listener: McpTransportErrorListener): () => void;\n\tonClose(listener: McpTransportCloseListener): () => void;\n\tsetProtocolVersion?(version: string): void;\n}\n\n/** Listener bookkeeping shared by transports. `emitClose` fires at most once per transport. */\nexport abstract class TransportEvents {\n\tprivate messageListeners = new Set<McpTransportMessageListener>();\n\tprivate errorListeners = new Set<McpTransportErrorListener>();\n\tprivate closeListeners = new Set<McpTransportCloseListener>();\n\tprivate closeEmitted = false;\n\n\tonMessage(listener: McpTransportMessageListener): () => void {\n\t\tthis.messageListeners.add(listener);\n\t\treturn () => this.messageListeners.delete(listener);\n\t}\n\n\tonError(listener: McpTransportErrorListener): () => void {\n\t\tthis.errorListeners.add(listener);\n\t\treturn () => this.errorListeners.delete(listener);\n\t}\n\n\tonClose(listener: McpTransportCloseListener): () => void {\n\t\tthis.closeListeners.add(listener);\n\t\treturn () => this.closeListeners.delete(listener);\n\t}\n\n\tprotected emitMessage(message: JsonRpcMessage): void {\n\t\tfor (const listener of this.messageListeners) listener(message);\n\t}\n\n\tprotected emitError(error: unknown): void {\n\t\tconst normalized = toError(error);\n\t\tfor (const listener of this.errorListeners) listener(normalized);\n\t}\n\n\tprotected emitClose(): void {\n\t\tif (this.closeEmitted) return;\n\t\tthis.closeEmitted = true;\n\t\tfor (const listener of this.closeListeners) listener();\n\t}\n}\n"]}
|