@dev-crowagent/pigeon-mcp 0.0.0-stage → 1.7.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/CHANGELOG.md +143 -0
- package/README.md +256 -2
- package/THIRD_PARTY_NOTICES/modelcontextprotocol-typescript-sdk.txt +21 -0
- 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 +193 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +747 -0
- package/dist/client.js.map +1 -0
- package/dist/config-schema.d.ts +105 -0
- package/dist/config-schema.d.ts.map +1 -0
- package/dist/config-schema.js +101 -0
- package/dist/config-schema.js.map +1 -0
- package/dist/config.d.ts +57 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +160 -0
- package/dist/config.js.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/input-schema.d.ts +7 -0
- package/dist/input-schema.d.ts.map +1 -0
- package/dist/input-schema.js +13 -0
- package/dist/input-schema.js.map +1 -0
- package/dist/model-content.d.ts +19 -0
- package/dist/model-content.d.ts.map +1 -0
- package/dist/model-content.js +67 -0
- package/dist/model-content.js.map +1 -0
- package/dist/naming.d.ts +23 -0
- package/dist/naming.d.ts.map +1 -0
- package/dist/naming.js +37 -0
- package/dist/naming.js.map +1 -0
- package/dist/oauth/auth-provider.d.ts +52 -0
- package/dist/oauth/auth-provider.d.ts.map +1 -0
- package/dist/oauth/auth-provider.js +97 -0
- package/dist/oauth/auth-provider.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 +121 -0
- package/dist/oauth/callback.js.map +1 -0
- package/dist/oauth/client-settings.d.ts +107 -0
- package/dist/oauth/client-settings.d.ts.map +1 -0
- package/dist/oauth/client-settings.js +114 -0
- package/dist/oauth/client-settings.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 +32 -0
- package/dist/oauth/errors.d.ts.map +1 -0
- package/dist/oauth/errors.js +58 -0
- package/dist/oauth/errors.js.map +1 -0
- package/dist/oauth/flow.d.ts +112 -0
- package/dist/oauth/flow.d.ts.map +1 -0
- package/dist/oauth/flow.js +360 -0
- package/dist/oauth/flow.js.map +1 -0
- package/dist/oauth/index.d.ts +11 -0
- package/dist/oauth/index.d.ts.map +1 -0
- package/dist/oauth/index.js +9 -0
- package/dist/oauth/index.js.map +1 -0
- package/dist/oauth/loopback.d.ts +51 -0
- package/dist/oauth/loopback.d.ts.map +1 -0
- package/dist/oauth/loopback.js +98 -0
- package/dist/oauth/loopback.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/sign-in.d.ts +73 -0
- package/dist/oauth/sign-in.d.ts.map +1 -0
- package/dist/oauth/sign-in.js +182 -0
- package/dist/oauth/sign-in.js.map +1 -0
- package/dist/oauth/types.d.ts +83 -0
- package/dist/oauth/types.d.ts.map +1 -0
- package/dist/oauth/types.js +113 -0
- package/dist/oauth/types.js.map +1 -0
- package/dist/output-limit.d.ts +24 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +58 -0
- package/dist/output-limit.js.map +1 -0
- package/dist/protocol/content.d.ts +83 -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/http-headers.d.ts +31 -0
- package/dist/protocol/http-headers.d.ts.map +1 -0
- package/dist/protocol/http-headers.js +129 -0
- package/dist/protocol/http-headers.js.map +1 -0
- package/dist/protocol/jsonrpc.d.ts +64 -0
- package/dist/protocol/jsonrpc.d.ts.map +1 -0
- package/dist/protocol/jsonrpc.js +74 -0
- package/dist/protocol/jsonrpc.js.map +1 -0
- package/dist/protocol/stateless.d.ts +47 -0
- package/dist/protocol/stateless.d.ts.map +1 -0
- package/dist/protocol/stateless.js +102 -0
- package/dist/protocol/stateless.js.map +1 -0
- package/dist/protocol/types.d.ts +156 -0
- package/dist/protocol/types.d.ts.map +1 -0
- package/dist/protocol/types.js +12 -0
- package/dist/protocol/types.js.map +1 -0
- package/dist/result-schema.d.ts +10 -0
- package/dist/result-schema.d.ts.map +1 -0
- package/dist/result-schema.js +78 -0
- package/dist/result-schema.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/lines.d.ts +34 -0
- package/dist/transports/lines.d.ts.map +1 -0
- package/dist/transports/lines.js +85 -0
- package/dist/transports/lines.js.map +1 -0
- package/dist/transports/pipe.d.ts +49 -0
- package/dist/transports/pipe.d.ts.map +1 -0
- package/dist/transports/pipe.js +96 -0
- package/dist/transports/pipe.js.map +1 -0
- package/dist/transports/stdio.d.ts +29 -0
- package/dist/transports/stdio.d.ts.map +1 -0
- package/dist/transports/stdio.js +170 -0
- package/dist/transports/stdio.js.map +1 -0
- package/dist/transports/streamable-http.d.ts +113 -0
- package/dist/transports/streamable-http.d.ts.map +1 -0
- package/dist/transports/streamable-http.js +586 -0
- package/dist/transports/streamable-http.js.map +1 -0
- package/dist/transports/transport.d.ts +48 -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 +65 -5
|
@@ -0,0 +1,586 @@
|
|
|
1
|
+
import { standardRequestHeaders } from "../protocol/http-headers.js";
|
|
2
|
+
import { isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse, isObject, JSON_RPC_ERROR_CODES, McpAbortError, McpConnectionClosedError, normalizeOwnRequestId, parseJsonRpcMessage, toError, } from "../protocol/jsonrpc.js";
|
|
3
|
+
import { STATELESS_PROTOCOL_VERSION } from "../protocol/types.js";
|
|
4
|
+
import { DEFAULT_MAX_MESSAGE_BYTES, TransportEvents, } from "./transport.js";
|
|
5
|
+
const MAX_ERROR_BODY_BYTES = 8 * 1024;
|
|
6
|
+
const ERROR_MESSAGE_BODY_CHARS = 500;
|
|
7
|
+
const DEFAULT_RECONNECT_INITIAL_DELAY_MS = 1_000;
|
|
8
|
+
const DEFAULT_RECONNECT_MAX_DELAY_MS = 30_000;
|
|
9
|
+
const DEFAULT_RECONNECT_MAX_RETRIES = 5;
|
|
10
|
+
export async function consumeSseStream(stream, options) {
|
|
11
|
+
const reader = stream.getReader();
|
|
12
|
+
const decoder = new TextDecoder();
|
|
13
|
+
// The incomplete last line. Only new text is scanned and the line is read once when it ends, so a large
|
|
14
|
+
// line arriving in many chunks costs time linear in its size.
|
|
15
|
+
let pendingLine = "";
|
|
16
|
+
let pendingLineBytes = 0;
|
|
17
|
+
let eventName;
|
|
18
|
+
let eventId;
|
|
19
|
+
let dataLines = [];
|
|
20
|
+
// Bytes of the pending event's data, including the "\n" joins, so events streamed as many
|
|
21
|
+
// short `data:` lines without a terminating blank line cannot grow without bound.
|
|
22
|
+
let dataBytes = 0;
|
|
23
|
+
const maxEventBytes = options.maxEventBytes ?? DEFAULT_MAX_MESSAGE_BYTES;
|
|
24
|
+
const dispatch = () => {
|
|
25
|
+
if (dataLines.length === 0) {
|
|
26
|
+
eventName = undefined;
|
|
27
|
+
eventId = undefined;
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const data = dataLines.join("\n");
|
|
31
|
+
options.onEvent({ ...(eventName ? { event: eventName } : {}), data, ...(eventId ? { id: eventId } : {}) });
|
|
32
|
+
eventName = undefined;
|
|
33
|
+
eventId = undefined;
|
|
34
|
+
dataLines = [];
|
|
35
|
+
dataBytes = 0;
|
|
36
|
+
};
|
|
37
|
+
const processLine = (line) => {
|
|
38
|
+
if (line === "") {
|
|
39
|
+
dispatch();
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (line.startsWith(":"))
|
|
43
|
+
return;
|
|
44
|
+
const colon = line.indexOf(":");
|
|
45
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
46
|
+
let value = colon < 0 ? "" : line.slice(colon + 1);
|
|
47
|
+
if (value.startsWith(" "))
|
|
48
|
+
value = value.slice(1);
|
|
49
|
+
if (field === "data") {
|
|
50
|
+
dataBytes += Buffer.byteLength(value) + (dataLines.length > 0 ? 1 : 0);
|
|
51
|
+
if (dataBytes > maxEventBytes)
|
|
52
|
+
throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);
|
|
53
|
+
dataLines.push(value);
|
|
54
|
+
}
|
|
55
|
+
else if (field === "event")
|
|
56
|
+
eventName = value;
|
|
57
|
+
else if (field === "id" && !value.includes("\0")) {
|
|
58
|
+
eventId = value;
|
|
59
|
+
options.onId?.(value);
|
|
60
|
+
}
|
|
61
|
+
else if (field === "retry" && /^\d+$/.test(value))
|
|
62
|
+
options.onRetry?.(Number(value));
|
|
63
|
+
};
|
|
64
|
+
// SSE lines end with CRLF, LF, or a lone CR.
|
|
65
|
+
let skipLeadingLf = false;
|
|
66
|
+
const consumeLines = (text) => {
|
|
67
|
+
let start = 0;
|
|
68
|
+
for (let i = 0; i < text.length; i++) {
|
|
69
|
+
const char = text[i];
|
|
70
|
+
if (char !== "\r" && char !== "\n")
|
|
71
|
+
continue;
|
|
72
|
+
processLine(pendingLine + text.slice(start, i));
|
|
73
|
+
pendingLine = "";
|
|
74
|
+
pendingLineBytes = 0;
|
|
75
|
+
if (char === "\r") {
|
|
76
|
+
if (i + 1 < text.length) {
|
|
77
|
+
if (text[i + 1] === "\n")
|
|
78
|
+
i++;
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
skipLeadingLf = true;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
start = i + 1;
|
|
85
|
+
}
|
|
86
|
+
const rest = text.slice(start);
|
|
87
|
+
pendingLine += rest;
|
|
88
|
+
pendingLineBytes += Buffer.byteLength(rest);
|
|
89
|
+
};
|
|
90
|
+
try {
|
|
91
|
+
while (true) {
|
|
92
|
+
const { done, value } = await reader.read();
|
|
93
|
+
if (done)
|
|
94
|
+
break;
|
|
95
|
+
let text = decoder.decode(value, { stream: true });
|
|
96
|
+
// A CRLF split across chunks: the CR already ended the line, so drop the LF.
|
|
97
|
+
if (skipLeadingLf && text.length > 0) {
|
|
98
|
+
if (text.startsWith("\n"))
|
|
99
|
+
text = text.slice(1);
|
|
100
|
+
skipLeadingLf = false;
|
|
101
|
+
}
|
|
102
|
+
consumeLines(text);
|
|
103
|
+
if (pendingLineBytes > maxEventBytes)
|
|
104
|
+
throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);
|
|
105
|
+
}
|
|
106
|
+
let tail = decoder.decode();
|
|
107
|
+
if (skipLeadingLf && tail.startsWith("\n"))
|
|
108
|
+
tail = tail.slice(1);
|
|
109
|
+
consumeLines(tail);
|
|
110
|
+
if (pendingLine)
|
|
111
|
+
processLine(pendingLine);
|
|
112
|
+
dispatch();
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
// Releasing the lock alone leaves the response open; the original error wins over a failed cancel.
|
|
116
|
+
await reader.cancel().catch(() => { });
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
reader.releaseLock();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
export class McpHttpError extends Error {
|
|
124
|
+
status;
|
|
125
|
+
body;
|
|
126
|
+
constructor(status, message, body = "") {
|
|
127
|
+
super(message);
|
|
128
|
+
this.name = "McpHttpError";
|
|
129
|
+
this.status = status;
|
|
130
|
+
this.body = body;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
export class McpAuthRequiredError extends McpHttpError {
|
|
134
|
+
wwwAuthenticate;
|
|
135
|
+
constructor(response, body = "") {
|
|
136
|
+
super(401, "MCP server requires authentication", body);
|
|
137
|
+
this.name = "McpAuthRequiredError";
|
|
138
|
+
this.wwwAuthenticate = response.headers.get("www-authenticate");
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
export class McpSessionExpiredError extends McpHttpError {
|
|
142
|
+
constructor(body = "") {
|
|
143
|
+
super(404, "MCP session expired", body);
|
|
144
|
+
this.name = "McpSessionExpiredError";
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function contentType(response) {
|
|
148
|
+
return response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
149
|
+
}
|
|
150
|
+
/** 401, or 403 with an `insufficient_scope` bearer challenge (step-up authorization). */
|
|
151
|
+
function needsAuthorization(response) {
|
|
152
|
+
if (response.status === 401)
|
|
153
|
+
return true;
|
|
154
|
+
if (response.status !== 403)
|
|
155
|
+
return false;
|
|
156
|
+
return /(?:^|[\s,])error="?insufficient_scope"?/i.test(response.headers.get("www-authenticate") ?? "");
|
|
157
|
+
}
|
|
158
|
+
/** Statuses worth retrying when a stream fails to (re)open. */
|
|
159
|
+
function isTransientStatus(status) {
|
|
160
|
+
return status === 408 || status === 429 || status >= 500;
|
|
161
|
+
}
|
|
162
|
+
function discard(response) {
|
|
163
|
+
return response.body?.cancel().catch(() => { }) ?? Promise.resolve();
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Reads a response body as text, decoding chunks as they arrive. Once the body exceeds `maxBytes`, the rest is
|
|
167
|
+
* cancelled and the text holds only the first `maxBytes` bytes.
|
|
168
|
+
*/
|
|
169
|
+
async function readBodyText(response, maxBytes) {
|
|
170
|
+
if (!response.body)
|
|
171
|
+
return { text: "", truncated: false };
|
|
172
|
+
const reader = response.body.getReader();
|
|
173
|
+
const decoder = new TextDecoder();
|
|
174
|
+
let text = "";
|
|
175
|
+
let remaining = maxBytes;
|
|
176
|
+
try {
|
|
177
|
+
while (true) {
|
|
178
|
+
const { done, value } = await reader.read();
|
|
179
|
+
if (done)
|
|
180
|
+
return { text: text + decoder.decode(), truncated: false };
|
|
181
|
+
if (value.byteLength > remaining) {
|
|
182
|
+
await reader.cancel().catch(() => { });
|
|
183
|
+
// Decoding a subarray copies only the kept bytes, so the result never references the dropped rest.
|
|
184
|
+
return { text: text + decoder.decode(value.subarray(0, remaining), { stream: true }), truncated: true };
|
|
185
|
+
}
|
|
186
|
+
remaining -= value.byteLength;
|
|
187
|
+
text += decoder.decode(value, { stream: true });
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
reader.releaseLock();
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function describeHttpFailure(status, body) {
|
|
195
|
+
const text = body.trim();
|
|
196
|
+
const snippet = text.length > ERROR_MESSAGE_BODY_CHARS ? `${text.slice(0, ERROR_MESSAGE_BODY_CHARS - 3)}...` : text;
|
|
197
|
+
return `MCP HTTP request failed with status ${status}${snippet ? `: ${snippet}` : ""}`;
|
|
198
|
+
}
|
|
199
|
+
/** The JSON-RPC error in an HTTP error body, which servers on the stateless revision send with 4xx statuses. */
|
|
200
|
+
export function jsonRpcErrorIn(body) {
|
|
201
|
+
let parsed;
|
|
202
|
+
try {
|
|
203
|
+
parsed = JSON.parse(body);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
return undefined;
|
|
207
|
+
}
|
|
208
|
+
if (!isObject(parsed) || parsed.jsonrpc !== "2.0" || !isObject(parsed.error))
|
|
209
|
+
return undefined;
|
|
210
|
+
const { code, message, data } = parsed.error;
|
|
211
|
+
if (typeof code !== "number" || typeof message !== "string")
|
|
212
|
+
return undefined;
|
|
213
|
+
return { code, message, ...(data === undefined ? {} : { data }) };
|
|
214
|
+
}
|
|
215
|
+
export class StreamableHttpTransport extends TransportEvents {
|
|
216
|
+
sendsHeaders = true;
|
|
217
|
+
url;
|
|
218
|
+
options;
|
|
219
|
+
fetch;
|
|
220
|
+
controller = new AbortController();
|
|
221
|
+
started = false;
|
|
222
|
+
closed = false;
|
|
223
|
+
sessionIdValue;
|
|
224
|
+
protocolVersion;
|
|
225
|
+
/**
|
|
226
|
+
* MCP 2026-07-28: no session, `Mcp-Method` and `Mcp-Name` headers, response streams that cannot be
|
|
227
|
+
* resumed, and closing a request's response stream cancels it.
|
|
228
|
+
*/
|
|
229
|
+
stateless = false;
|
|
230
|
+
getStreamStarted = false;
|
|
231
|
+
/** Access token of the latest request, which `close()` reuses instead of asking the auth provider. */
|
|
232
|
+
lastToken;
|
|
233
|
+
constructor(options) {
|
|
234
|
+
super();
|
|
235
|
+
this.options = Object.freeze({ ...options, headers: options.headers ? { ...options.headers } : undefined });
|
|
236
|
+
this.url = new URL(options.url);
|
|
237
|
+
const fetch = options.fetch ?? globalThis.fetch;
|
|
238
|
+
// Call fetch without a receiver. `this.fetch(...)` and `context.fetch(...)` would pass the transport or
|
|
239
|
+
// the auth context as `this`, which Cloudflare Workers reject for the platform fetch ("Illegal invocation").
|
|
240
|
+
this.fetch = (input, init) => fetch(input, init);
|
|
241
|
+
}
|
|
242
|
+
get sessionId() {
|
|
243
|
+
return this.sessionIdValue;
|
|
244
|
+
}
|
|
245
|
+
async start() {
|
|
246
|
+
if (this.started)
|
|
247
|
+
throw new Error("MCP Streamable HTTP transport already started");
|
|
248
|
+
if (this.closed)
|
|
249
|
+
throw new McpConnectionClosedError();
|
|
250
|
+
this.started = true;
|
|
251
|
+
}
|
|
252
|
+
setProtocolVersion(version) {
|
|
253
|
+
this.protocolVersion = version;
|
|
254
|
+
this.stateless = version === STATELESS_PROTOCOL_VERSION;
|
|
255
|
+
// A server that answered `initialize` with the stateless revision may have started a session.
|
|
256
|
+
if (this.stateless)
|
|
257
|
+
this.sessionIdValue = undefined;
|
|
258
|
+
}
|
|
259
|
+
async send(message, { signal, headers } = {}) {
|
|
260
|
+
if (!this.started || this.closed)
|
|
261
|
+
throw new McpConnectionClosedError();
|
|
262
|
+
const statelessRequest = this.stateless && isJsonRpcRequest(message);
|
|
263
|
+
// Aborting the request's response stream already cancelled it.
|
|
264
|
+
if (this.stateless && isJsonRpcNotification(message) && message.method === "notifications/cancelled")
|
|
265
|
+
return;
|
|
266
|
+
const response = await this.authorizedFetch("POST", {
|
|
267
|
+
headers: {
|
|
268
|
+
accept: "application/json, text/event-stream",
|
|
269
|
+
"content-type": "application/json",
|
|
270
|
+
...(statelessRequest ? { ...headers, ...standardRequestHeaders(message.method, message.params) } : {}),
|
|
271
|
+
},
|
|
272
|
+
body: JSON.stringify(message),
|
|
273
|
+
// Closing the connection cancels a stateless request, also before its response arrives.
|
|
274
|
+
...(statelessRequest && signal ? { signal } : {}),
|
|
275
|
+
}, signal);
|
|
276
|
+
if (statelessRequest && response.status >= 400 && response.status < 500 && response.status !== 401) {
|
|
277
|
+
const body = (await readBodyText(response, MAX_ERROR_BODY_BYTES).catch(() => ({ text: "" }))).text;
|
|
278
|
+
const error = jsonRpcErrorIn(body);
|
|
279
|
+
if (!error)
|
|
280
|
+
throw new McpHttpError(response.status, describeHttpFailure(response.status, body), body);
|
|
281
|
+
this.emitMessage({ jsonrpc: "2.0", id: message.id, error });
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
await this.checkResponse(response);
|
|
285
|
+
this.captureSession(response);
|
|
286
|
+
if (!isJsonRpcRequest(message)) {
|
|
287
|
+
// Notifications and responses are acknowledged with 202 and carry no reply; ignore any body.
|
|
288
|
+
await discard(response);
|
|
289
|
+
// The server-to-client stream may only open once the session is initialized.
|
|
290
|
+
if ("method" in message && message.method === "notifications/initialized")
|
|
291
|
+
this.startGetStream();
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if (response.status === 202 || response.status === 204) {
|
|
295
|
+
throw new McpHttpError(response.status, `MCP server accepted request ${message.method} without a response`);
|
|
296
|
+
}
|
|
297
|
+
const type = contentType(response);
|
|
298
|
+
if (type === "application/json") {
|
|
299
|
+
const maxBytes = this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;
|
|
300
|
+
const { text, truncated } = await readBodyText(response, maxBytes);
|
|
301
|
+
if (truncated)
|
|
302
|
+
throw new Error(`MCP JSON response exceeds ${maxBytes} bytes`);
|
|
303
|
+
const body = JSON.parse(text);
|
|
304
|
+
for (const item of Array.isArray(body) ? body : [body])
|
|
305
|
+
this.emitMessage(parseJsonRpcMessage(item));
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
if (type === "text/event-stream" && response.body) {
|
|
309
|
+
void this.consumeResponseStream(response.body, message.id, signal);
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
await discard(response);
|
|
313
|
+
throw new McpHttpError(response.status, `Unsupported MCP response content type: ${type ?? "missing"}`);
|
|
314
|
+
}
|
|
315
|
+
async close() {
|
|
316
|
+
if (this.closed)
|
|
317
|
+
return;
|
|
318
|
+
this.closed = true;
|
|
319
|
+
this.controller.abort();
|
|
320
|
+
if (this.started && this.sessionIdValue) {
|
|
321
|
+
// Best effort: the session expires on the server anyway. The auth provider may refresh tokens
|
|
322
|
+
// over the network, so it is not asked here and closing never waits for a refresh.
|
|
323
|
+
try {
|
|
324
|
+
const response = await this.fetch(this.url, {
|
|
325
|
+
method: "DELETE",
|
|
326
|
+
headers: this.buildHeaders({}, this.lastToken),
|
|
327
|
+
signal: AbortSignal.timeout(1_000),
|
|
328
|
+
});
|
|
329
|
+
await discard(response);
|
|
330
|
+
}
|
|
331
|
+
catch { }
|
|
332
|
+
}
|
|
333
|
+
this.emitClose();
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Fetch with auth headers. A 401 (or a 403 asking for more scope) is handed to the auth provider
|
|
337
|
+
* once, and the request is retried with whatever credentials it left behind. `init.signal` aborts
|
|
338
|
+
* the fetch itself.
|
|
339
|
+
*
|
|
340
|
+
* `signal` only stops dispatch: getting a token or the authorization recovery can take a while, and a
|
|
341
|
+
* request its sender gave up on in the meantime must not reach the server. It does not abort the shared
|
|
342
|
+
* recovery, which other requests may wait for.
|
|
343
|
+
*/
|
|
344
|
+
async authorizedFetch(method, init, signal) {
|
|
345
|
+
const onUnauthorized = this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);
|
|
346
|
+
const fetchSignal = init.signal ? AbortSignal.any([this.controller.signal, init.signal]) : this.controller.signal;
|
|
347
|
+
for (let attempt = 0;; attempt++) {
|
|
348
|
+
const { headers, token } = await this.headers(init.headers);
|
|
349
|
+
if (signal?.aborted)
|
|
350
|
+
throw new McpAbortError();
|
|
351
|
+
const response = await this.fetch(this.url, {
|
|
352
|
+
method,
|
|
353
|
+
headers,
|
|
354
|
+
body: init.body,
|
|
355
|
+
signal: fetchSignal,
|
|
356
|
+
});
|
|
357
|
+
if (attempt > 0 || !onUnauthorized || !needsAuthorization(response))
|
|
358
|
+
return response;
|
|
359
|
+
try {
|
|
360
|
+
await onUnauthorized({ response, serverUrl: this.url, fetch: this.fetch, token });
|
|
361
|
+
}
|
|
362
|
+
finally {
|
|
363
|
+
await discard(response);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
async headers(extra = {}) {
|
|
368
|
+
const token = await this.options.authProvider?.token();
|
|
369
|
+
this.lastToken = token;
|
|
370
|
+
return { headers: this.buildHeaders(extra, token), ...(token ? { token } : {}) };
|
|
371
|
+
}
|
|
372
|
+
buildHeaders(extra, token) {
|
|
373
|
+
const headers = new Headers(this.options.headers);
|
|
374
|
+
for (const [name, value] of Object.entries(extra))
|
|
375
|
+
headers.set(name, value);
|
|
376
|
+
if (this.sessionIdValue)
|
|
377
|
+
headers.set("Mcp-Session-Id", this.sessionIdValue);
|
|
378
|
+
if (this.protocolVersion)
|
|
379
|
+
headers.set("MCP-Protocol-Version", this.protocolVersion);
|
|
380
|
+
if (token)
|
|
381
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
382
|
+
return headers;
|
|
383
|
+
}
|
|
384
|
+
captureSession(response) {
|
|
385
|
+
const sessionId = response.headers.get("mcp-session-id");
|
|
386
|
+
if (sessionId && !this.stateless)
|
|
387
|
+
this.sessionIdValue = sessionId;
|
|
388
|
+
}
|
|
389
|
+
async checkResponse(response) {
|
|
390
|
+
if (response.ok)
|
|
391
|
+
return;
|
|
392
|
+
// Reads only the excerpt the error keeps and cancels the rest, so a huge error body is never buffered.
|
|
393
|
+
const body = (await readBodyText(response, MAX_ERROR_BODY_BYTES).catch(() => ({ text: "" }))).text;
|
|
394
|
+
if (response.status === 401)
|
|
395
|
+
throw new McpAuthRequiredError(response, body);
|
|
396
|
+
if (response.status === 404 && this.sessionIdValue)
|
|
397
|
+
throw new McpSessionExpiredError(body);
|
|
398
|
+
throw new McpHttpError(response.status, describeHttpFailure(response.status, body), body);
|
|
399
|
+
}
|
|
400
|
+
async consumeSse(stream, cursor, onMessage) {
|
|
401
|
+
await consumeSseStream(stream, {
|
|
402
|
+
maxEventBytes: this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES,
|
|
403
|
+
onId: (id) => {
|
|
404
|
+
cursor.lastEventId = id;
|
|
405
|
+
},
|
|
406
|
+
onRetry: (delayMs) => {
|
|
407
|
+
cursor.retryMs = delayMs;
|
|
408
|
+
},
|
|
409
|
+
onEvent: (event) => {
|
|
410
|
+
cursor.received = true;
|
|
411
|
+
// Events without data prime resumption; other event types are not JSON-RPC.
|
|
412
|
+
if (!event.data.trim() || (event.event !== undefined && event.event !== "message"))
|
|
413
|
+
return;
|
|
414
|
+
let message;
|
|
415
|
+
try {
|
|
416
|
+
message = parseJsonRpcMessage(JSON.parse(event.data));
|
|
417
|
+
}
|
|
418
|
+
catch (error) {
|
|
419
|
+
this.emitError(error);
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
onMessage?.(message);
|
|
423
|
+
this.emitMessage(message);
|
|
424
|
+
},
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Read the SSE stream answering one request. When the stream ends or breaks before the response
|
|
429
|
+
* arrives and the server assigned event IDs, resume it with GET and `Last-Event-ID`, as the
|
|
430
|
+
* server may close response streams at will. Otherwise, and always on the stateless revision,
|
|
431
|
+
* only this request fails.
|
|
432
|
+
*/
|
|
433
|
+
async consumeResponseStream(body, requestId, signal) {
|
|
434
|
+
const cursor = { lastEventId: undefined, retryMs: undefined, received: false };
|
|
435
|
+
let answered = false;
|
|
436
|
+
const onMessage = (message) => {
|
|
437
|
+
if (isJsonRpcResponse(message) && normalizeOwnRequestId(message.id) === requestId)
|
|
438
|
+
answered = true;
|
|
439
|
+
};
|
|
440
|
+
let stream = body;
|
|
441
|
+
let failure;
|
|
442
|
+
for (let attempt = 0;;) {
|
|
443
|
+
if (stream) {
|
|
444
|
+
try {
|
|
445
|
+
await this.consumeSse(stream, cursor, onMessage);
|
|
446
|
+
failure = undefined;
|
|
447
|
+
}
|
|
448
|
+
catch (error) {
|
|
449
|
+
failure = error;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
// An aborted `signal`: the request settled without this stream (timed out, cancelled).
|
|
453
|
+
if (answered || this.closed || signal?.aborted)
|
|
454
|
+
return;
|
|
455
|
+
if (failure !== undefined && !this.isRetryable(failure))
|
|
456
|
+
break;
|
|
457
|
+
if (this.stateless || cursor.lastEventId === undefined || attempt >= this.maxRetries())
|
|
458
|
+
break;
|
|
459
|
+
if (cursor.received)
|
|
460
|
+
attempt = 0;
|
|
461
|
+
cursor.received = false;
|
|
462
|
+
if (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs))))
|
|
463
|
+
return;
|
|
464
|
+
try {
|
|
465
|
+
stream = await this.openSseStream(cursor.lastEventId);
|
|
466
|
+
}
|
|
467
|
+
catch (error) {
|
|
468
|
+
failure = error;
|
|
469
|
+
if (!this.isRetryable(error))
|
|
470
|
+
break;
|
|
471
|
+
stream = undefined;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
if (this.closed)
|
|
475
|
+
return;
|
|
476
|
+
const reason = failure === undefined ? "stream ended without a response" : toError(failure).message;
|
|
477
|
+
this.emitMessage({
|
|
478
|
+
jsonrpc: "2.0",
|
|
479
|
+
id: requestId,
|
|
480
|
+
error: { code: JSON_RPC_ERROR_CODES.internalError, message: `MCP response stream failed: ${reason}` },
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
startGetStream() {
|
|
484
|
+
if (this.options.openGetStream === false || this.getStreamStarted || this.closed)
|
|
485
|
+
return;
|
|
486
|
+
this.getStreamStarted = true;
|
|
487
|
+
void this.runGetStream();
|
|
488
|
+
}
|
|
489
|
+
/** Keep the server-to-client stream open, reconnecting with backoff when it drops. */
|
|
490
|
+
async runGetStream() {
|
|
491
|
+
const cursor = { lastEventId: undefined, retryMs: undefined, received: false };
|
|
492
|
+
for (let attempt = 0; !this.closed;) {
|
|
493
|
+
try {
|
|
494
|
+
const stream = await this.openSseStream(cursor.lastEventId);
|
|
495
|
+
// The server does not offer a GET stream.
|
|
496
|
+
if (!stream)
|
|
497
|
+
return;
|
|
498
|
+
const openedAt = Date.now();
|
|
499
|
+
await this.consumeSse(stream, cursor);
|
|
500
|
+
// A stream that stayed up for a while counts as healthy, even if it was idle.
|
|
501
|
+
if (cursor.received || Date.now() - openedAt > this.maxDelay())
|
|
502
|
+
attempt = 0;
|
|
503
|
+
}
|
|
504
|
+
catch (error) {
|
|
505
|
+
if (this.closed)
|
|
506
|
+
return;
|
|
507
|
+
if (!this.isRetryable(error)) {
|
|
508
|
+
this.emitError(error);
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
cursor.received = false;
|
|
513
|
+
if (attempt >= this.maxRetries()) {
|
|
514
|
+
this.emitError(new Error("MCP server-to-client stream dropped and could not be reopened"));
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
if (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs))))
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
/** Open a GET SSE stream. Resolves to undefined when the server answers 405 (no GET stream). */
|
|
522
|
+
async openSseStream(lastEventId) {
|
|
523
|
+
const response = await this.authorizedFetch("GET", {
|
|
524
|
+
headers: {
|
|
525
|
+
accept: "text/event-stream",
|
|
526
|
+
...(lastEventId === undefined ? {} : { "last-event-id": lastEventId }),
|
|
527
|
+
},
|
|
528
|
+
});
|
|
529
|
+
if (response.status === 405) {
|
|
530
|
+
await discard(response);
|
|
531
|
+
return undefined;
|
|
532
|
+
}
|
|
533
|
+
await this.checkResponse(response);
|
|
534
|
+
this.captureSession(response);
|
|
535
|
+
const type = contentType(response);
|
|
536
|
+
if (type !== "text/event-stream" || !response.body) {
|
|
537
|
+
await discard(response);
|
|
538
|
+
throw new McpHttpError(response.status, `Unsupported MCP GET response content type: ${type ?? "missing"}`);
|
|
539
|
+
}
|
|
540
|
+
return response.body;
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Network failures and transient statuses are retried; auth, session, and protocol errors are not.
|
|
544
|
+
* `fetch` reports network failures, including a connection dropped mid-body, as `TypeError`.
|
|
545
|
+
*/
|
|
546
|
+
isRetryable(error) {
|
|
547
|
+
if (error instanceof McpHttpError)
|
|
548
|
+
return isTransientStatus(error.status);
|
|
549
|
+
if (error instanceof TypeError)
|
|
550
|
+
return true;
|
|
551
|
+
const code = error?.code;
|
|
552
|
+
return typeof code === "string" && (code.startsWith("E") || code.startsWith("UND_ERR"));
|
|
553
|
+
}
|
|
554
|
+
reconnectDelay(attempt, serverDelayMs) {
|
|
555
|
+
if (serverDelayMs !== undefined)
|
|
556
|
+
return serverDelayMs;
|
|
557
|
+
const initial = this.options.reconnect?.initialDelayMs ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS;
|
|
558
|
+
return Math.min(initial * 2 ** attempt, this.maxDelay());
|
|
559
|
+
}
|
|
560
|
+
maxDelay() {
|
|
561
|
+
return this.options.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS;
|
|
562
|
+
}
|
|
563
|
+
maxRetries() {
|
|
564
|
+
return this.options.reconnect?.maxRetries ?? DEFAULT_RECONNECT_MAX_RETRIES;
|
|
565
|
+
}
|
|
566
|
+
/** Resolves false when the transport closed while waiting. */
|
|
567
|
+
sleep(ms) {
|
|
568
|
+
const signal = this.controller.signal;
|
|
569
|
+
if (signal.aborted)
|
|
570
|
+
return Promise.resolve(false);
|
|
571
|
+
return new Promise((resolve) => {
|
|
572
|
+
const onAbort = () => {
|
|
573
|
+
clearTimeout(timer);
|
|
574
|
+
resolve(false);
|
|
575
|
+
};
|
|
576
|
+
const timer = setTimeout(() => {
|
|
577
|
+
signal.removeEventListener("abort", onAbort);
|
|
578
|
+
resolve(true);
|
|
579
|
+
}, ms);
|
|
580
|
+
// A reconnect wait alone does not keep the process alive.
|
|
581
|
+
timer.unref?.();
|
|
582
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
//# sourceMappingURL=streamable-http.js.map
|