@vite-hub/source 0.1.0 → 0.3.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/README.md +83 -49
- package/dist/client.d.ts +1 -1
- package/dist/client.js +30 -4
- package/dist/{collection-B_4w_J8h.d.ts → collection-B8sgxw5-.d.ts} +52 -19
- package/dist/collection-C0Rvrx3p.js +297 -0
- package/dist/drizzle.d.ts +11 -4
- package/dist/drizzle.js +6 -8
- package/dist/error-diagnostics-ClQKdi7c.js +194 -0
- package/dist/github-D5S0dEZe.js +1312 -0
- package/dist/{glob-BmFqTvJY.js → glob-DmdMVqjx.js} +1 -2
- package/dist/index.d.ts +186 -55
- package/dist/index.js +152 -207
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +25 -140
- package/dist/object-CtSHeGQO.js +17 -0
- package/dist/{path-BS8rYm0n.js → path-DFlSryRA.js} +32 -2
- package/dist/root-DJNmqCEW.js +11 -0
- package/dist/server.d.ts +7 -244
- package/dist/server.js +38 -45
- package/dist/{types-BigOktIj.d.ts → types-Ln-FxVFn.d.ts} +6 -1
- package/dist/vite.d.ts +77 -10
- package/dist/vite.js +619 -713
- package/package.json +25 -47
- package/dist/auth-B-tX_rp0.js +0 -1426
- package/dist/client-BwstxtdY.js +0 -8280
- package/dist/collection-cursor-WzV1Jd6v.js +0 -124
- package/dist/error-diagnostics-X0kuFjBT.js +0 -51
- package/dist/file-BX0FSvgE.js +0 -60
- package/dist/file-DadN9dbN.d.ts +0 -19
- package/dist/file.d.ts +0 -2
- package/dist/file.js +0 -2
- package/dist/files.d.ts +0 -15
- package/dist/files.js +0 -38
- package/dist/github.d.ts +0 -20
- package/dist/github.js +0 -1332
- package/dist/glob.d.ts +0 -23
- package/dist/glob.js +0 -2
- package/dist/markdown.d.ts +0 -5
- package/dist/markdown.js +0 -10
- package/dist/mrmime-40h5OOIp.js +0 -448
- package/dist/path-DOBpV8ol.js +0 -32
- package/dist/sse-D9gqqNPj.js +0 -448
- package/dist/streamableHttp-BL-E7pl5.js +0 -509
- package/dist/types-CoWcW8oz.js +0 -7590
- package/tsconfig.vite.json +0 -6
- package/types/source/fallback.d.ts +0 -1
- package/types/source/index.d.ts +0 -1
|
@@ -1,509 +0,0 @@
|
|
|
1
|
-
import { a as __toESM, i as __commonJSMin } from "./path-BS8rYm0n.js";
|
|
2
|
-
import { G as isJSONRPCResultResponse, V as isInitializedNotification, W as isJSONRPCRequest, x as JSONRPCMessageSchema } from "./types-CoWcW8oz.js";
|
|
3
|
-
import { a as fetchLeavingRedirects, c as normalizeHeaders, i as createFetchWithInit, l as unfollowedRedirect, n as auth, o as fetchWithinOrigin, r as extractWWWAuthenticateParams, s as followWithinOrigin, t as UnauthorizedError, u as createParser } from "./auth-B-tX_rp0.js";
|
|
4
|
-
/*!
|
|
5
|
-
* content-type
|
|
6
|
-
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
7
|
-
* MIT Licensed
|
|
8
|
-
*/
|
|
9
|
-
//#endregion
|
|
10
|
-
//#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js
|
|
11
|
-
var import_content_type = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
|
|
12
|
-
/**
|
|
13
|
-
* RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
|
|
14
|
-
*
|
|
15
|
-
* parameter = token "=" ( token / quoted-string )
|
|
16
|
-
* token = 1*tchar
|
|
17
|
-
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
|
|
18
|
-
* / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
|
|
19
|
-
* / DIGIT / ALPHA
|
|
20
|
-
* ; any VCHAR, except delimiters
|
|
21
|
-
* quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
|
|
22
|
-
* qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
|
|
23
|
-
* obs-text = %x80-FF
|
|
24
|
-
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
|
|
25
|
-
*/
|
|
26
|
-
var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
|
|
27
|
-
/**
|
|
28
|
-
* RegExp to match quoted-pair in RFC 7230 sec 3.2.6
|
|
29
|
-
*
|
|
30
|
-
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
|
|
31
|
-
* obs-text = %x80-FF
|
|
32
|
-
*/
|
|
33
|
-
var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
|
|
34
|
-
/**
|
|
35
|
-
* RegExp to match type in RFC 7231 sec 3.1.1.1
|
|
36
|
-
*
|
|
37
|
-
* media-type = type "/" subtype
|
|
38
|
-
* type = token
|
|
39
|
-
* subtype = token
|
|
40
|
-
*/
|
|
41
|
-
var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
42
|
-
exports.parse = parse;
|
|
43
|
-
/**
|
|
44
|
-
* Parse media type to object.
|
|
45
|
-
*
|
|
46
|
-
* @param {string|object} string
|
|
47
|
-
* @return {Object}
|
|
48
|
-
* @public
|
|
49
|
-
*/
|
|
50
|
-
function parse(string) {
|
|
51
|
-
if (!string) throw new TypeError("argument string is required");
|
|
52
|
-
var header = typeof string === "object" ? getcontenttype(string) : string;
|
|
53
|
-
if (typeof header !== "string") throw new TypeError("argument string is required to be a string");
|
|
54
|
-
var index = header.indexOf(";");
|
|
55
|
-
var type = index !== -1 ? header.slice(0, index).trim() : header.trim();
|
|
56
|
-
if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type");
|
|
57
|
-
var obj = new ContentType(type.toLowerCase());
|
|
58
|
-
if (index !== -1) {
|
|
59
|
-
var key;
|
|
60
|
-
var match;
|
|
61
|
-
var value;
|
|
62
|
-
PARAM_REGEXP.lastIndex = index;
|
|
63
|
-
while (match = PARAM_REGEXP.exec(header)) {
|
|
64
|
-
if (match.index !== index) throw new TypeError("invalid parameter format");
|
|
65
|
-
index += match[0].length;
|
|
66
|
-
key = match[1].toLowerCase();
|
|
67
|
-
value = match[2];
|
|
68
|
-
if (value.charCodeAt(0) === 34) {
|
|
69
|
-
value = value.slice(1, -1);
|
|
70
|
-
if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1");
|
|
71
|
-
}
|
|
72
|
-
obj.parameters[key] = value;
|
|
73
|
-
}
|
|
74
|
-
if (index !== header.length) throw new TypeError("invalid parameter format");
|
|
75
|
-
}
|
|
76
|
-
return obj;
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* Get content-type from req/res objects.
|
|
80
|
-
*
|
|
81
|
-
* @param {object}
|
|
82
|
-
* @return {Object}
|
|
83
|
-
* @private
|
|
84
|
-
*/
|
|
85
|
-
function getcontenttype(obj) {
|
|
86
|
-
var header;
|
|
87
|
-
if (typeof obj.getHeader === "function") header = obj.getHeader("content-type");
|
|
88
|
-
else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"];
|
|
89
|
-
if (typeof header !== "string") throw new TypeError("content-type header is missing from object");
|
|
90
|
-
return header;
|
|
91
|
-
}
|
|
92
|
-
/**
|
|
93
|
-
* Class to represent a content type.
|
|
94
|
-
* @private
|
|
95
|
-
*/
|
|
96
|
-
function ContentType(type) {
|
|
97
|
-
this.parameters = Object.create(null);
|
|
98
|
-
this.type = type;
|
|
99
|
-
}
|
|
100
|
-
})))(), 1);
|
|
101
|
-
/**
|
|
102
|
-
* Extracts the media type (the lowercased `type/subtype` pair, without
|
|
103
|
-
* parameters) from a raw `Content-Type` header value, or `undefined` when the
|
|
104
|
-
* header is missing or empty.
|
|
105
|
-
*
|
|
106
|
-
* Content-Type comparisons must use the parsed media type, never a substring
|
|
107
|
-
* search of the raw header: a value like `text/plain; a=application/json`
|
|
108
|
-
* contains the substring `application/json` but its media type is
|
|
109
|
-
* `text/plain`, and case variants or parameters make naive string comparison
|
|
110
|
-
* wrong in both directions.
|
|
111
|
-
*
|
|
112
|
-
* "Essence" is the WHATWG MIME Sniffing standard's term for the bare
|
|
113
|
-
* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence);
|
|
114
|
-
* the Fetch standard's request classification is defined against it
|
|
115
|
-
* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header).
|
|
116
|
-
*
|
|
117
|
-
* Parsing is RFC 9110 (`content-type` package) first. When the parameter
|
|
118
|
-
* section is malformed (`application/json;`, `application/json; charset=`),
|
|
119
|
-
* browsers and most HTTP stacks still derive the media type from the segment
|
|
120
|
-
* before the first `;` — the fallback matches that widely-implemented
|
|
121
|
-
* behavior, so a header whose media type is unambiguous is not rejected for
|
|
122
|
-
* a sloppy parameter section.
|
|
123
|
-
*/
|
|
124
|
-
function mediaTypeEssence(header) {
|
|
125
|
-
if (!header) return;
|
|
126
|
-
try {
|
|
127
|
-
return import_content_type.parse(header).type;
|
|
128
|
-
} catch {
|
|
129
|
-
const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase();
|
|
130
|
-
if (essence === "" || header.slice(essence.length).includes(",")) return;
|
|
131
|
-
return essence;
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
//#endregion
|
|
135
|
-
//#region ../../node_modules/.pnpm/eventsource-parser@3.1.1/node_modules/eventsource-parser/dist/stream.js
|
|
136
|
-
var EventSourceParserStream = class extends TransformStream {
|
|
137
|
-
constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
|
|
138
|
-
let parser;
|
|
139
|
-
super({
|
|
140
|
-
start(controller) {
|
|
141
|
-
parser = createParser({
|
|
142
|
-
onEvent: (event) => {
|
|
143
|
-
controller.enqueue(event);
|
|
144
|
-
},
|
|
145
|
-
onError(error) {
|
|
146
|
-
typeof onError == "function" && onError(error), (onError === "terminate" || error.type === "max-buffer-size-exceeded") && controller.error(error);
|
|
147
|
-
},
|
|
148
|
-
onRetry,
|
|
149
|
-
onComment,
|
|
150
|
-
maxBufferSize
|
|
151
|
-
});
|
|
152
|
-
},
|
|
153
|
-
transform(chunk) {
|
|
154
|
-
parser.feed(chunk);
|
|
155
|
-
}
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
};
|
|
159
|
-
//#endregion
|
|
160
|
-
//#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
|
|
161
|
-
const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
|
|
162
|
-
initialReconnectionDelay: 1e3,
|
|
163
|
-
maxReconnectionDelay: 3e4,
|
|
164
|
-
reconnectionDelayGrowFactor: 1.5,
|
|
165
|
-
maxRetries: 2
|
|
166
|
-
};
|
|
167
|
-
var StreamableHTTPError = class extends Error {
|
|
168
|
-
constructor(code, message) {
|
|
169
|
-
super(`Streamable HTTP error: ${message}`);
|
|
170
|
-
this.code = code;
|
|
171
|
-
}
|
|
172
|
-
};
|
|
173
|
-
/**
|
|
174
|
-
* Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.
|
|
175
|
-
* It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events
|
|
176
|
-
* for receiving messages.
|
|
177
|
-
*/
|
|
178
|
-
var StreamableHTTPClientTransport = class {
|
|
179
|
-
constructor(url, opts) {
|
|
180
|
-
this._hasCompletedAuthFlow = false;
|
|
181
|
-
this._url = url;
|
|
182
|
-
this._resourceMetadataUrl = void 0;
|
|
183
|
-
this._scope = void 0;
|
|
184
|
-
this._requestInit = opts?.requestInit;
|
|
185
|
-
this._authProvider = opts?.authProvider;
|
|
186
|
-
this._fetch = opts?.fetch;
|
|
187
|
-
this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
|
|
188
|
-
this._followRedirects = opts?.redirectPolicy === "follow";
|
|
189
|
-
if (this._followRedirects) {
|
|
190
|
-
this._fetch = fetchLeavingRedirects(this._fetch);
|
|
191
|
-
this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);
|
|
192
|
-
}
|
|
193
|
-
this._sessionId = opts?.sessionId;
|
|
194
|
-
this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
|
|
195
|
-
}
|
|
196
|
-
/** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */
|
|
197
|
-
_unfollowedRedirect(response, url) {
|
|
198
|
-
const text = unfollowedRedirect(response, url);
|
|
199
|
-
return text && !this._followRedirects ? `${text} (redirectPolicy: 'same-origin')` : text;
|
|
200
|
-
}
|
|
201
|
-
async _authThenStart() {
|
|
202
|
-
if (!this._authProvider) throw new UnauthorizedError("No auth provider");
|
|
203
|
-
let result;
|
|
204
|
-
try {
|
|
205
|
-
result = await auth(this._authProvider, {
|
|
206
|
-
serverUrl: this._url,
|
|
207
|
-
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
208
|
-
scope: this._scope,
|
|
209
|
-
fetchFn: this._fetchWithInit
|
|
210
|
-
});
|
|
211
|
-
} catch (error) {
|
|
212
|
-
this.onerror?.(error);
|
|
213
|
-
throw error;
|
|
214
|
-
}
|
|
215
|
-
if (result !== "AUTHORIZED") throw new UnauthorizedError();
|
|
216
|
-
return await this._startOrAuthSse({ resumptionToken: void 0 });
|
|
217
|
-
}
|
|
218
|
-
async _commonHeaders() {
|
|
219
|
-
const headers = {};
|
|
220
|
-
if (this._authProvider) {
|
|
221
|
-
const tokens = await this._authProvider.tokens();
|
|
222
|
-
if (tokens) headers["Authorization"] = `Bearer ${tokens.access_token}`;
|
|
223
|
-
}
|
|
224
|
-
if (this._sessionId) headers["mcp-session-id"] = this._sessionId;
|
|
225
|
-
if (this._protocolVersion) headers["mcp-protocol-version"] = this._protocolVersion;
|
|
226
|
-
const extraHeaders = normalizeHeaders(this._requestInit?.headers);
|
|
227
|
-
return new Headers({
|
|
228
|
-
...headers,
|
|
229
|
-
...extraHeaders
|
|
230
|
-
});
|
|
231
|
-
}
|
|
232
|
-
async _startOrAuthSse(options) {
|
|
233
|
-
const { resumptionToken } = options;
|
|
234
|
-
try {
|
|
235
|
-
const headers = await this._commonHeaders();
|
|
236
|
-
headers.set("Accept", "text/event-stream");
|
|
237
|
-
if (resumptionToken) headers.set("last-event-id", resumptionToken);
|
|
238
|
-
const fetchFn = this._fetch ?? fetch;
|
|
239
|
-
const init = {
|
|
240
|
-
method: "GET",
|
|
241
|
-
headers,
|
|
242
|
-
signal: this._abortController?.signal
|
|
243
|
-
};
|
|
244
|
-
let response = await fetchFn(this._url, this._followRedirects ? init : {
|
|
245
|
-
...init,
|
|
246
|
-
redirect: "manual"
|
|
247
|
-
});
|
|
248
|
-
const followed = this._followRedirects ? void 0 : followWithinOrigin(fetchFn, this._url, init, response);
|
|
249
|
-
if (followed) response = await followed;
|
|
250
|
-
if (!response.ok) {
|
|
251
|
-
await response.body?.cancel();
|
|
252
|
-
if (response.status === 401 && this._authProvider) return await this._authThenStart();
|
|
253
|
-
if (response.status === 405) return;
|
|
254
|
-
throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);
|
|
255
|
-
}
|
|
256
|
-
this._handleSseStream(response.body, options, true);
|
|
257
|
-
} catch (error) {
|
|
258
|
-
this.onerror?.(error);
|
|
259
|
-
throw error;
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
/**
|
|
263
|
-
* Calculates the next reconnection delay using backoff algorithm
|
|
264
|
-
*
|
|
265
|
-
* @param attempt Current reconnection attempt count for the specific stream
|
|
266
|
-
* @returns Time to wait in milliseconds before next reconnection attempt
|
|
267
|
-
*/
|
|
268
|
-
_getNextReconnectionDelay(attempt) {
|
|
269
|
-
if (this._serverRetryMs !== void 0) return this._serverRetryMs;
|
|
270
|
-
const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
|
|
271
|
-
const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
|
|
272
|
-
const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
|
|
273
|
-
return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
|
|
274
|
-
}
|
|
275
|
-
/**
|
|
276
|
-
* Schedule a reconnection attempt using server-provided retry interval or backoff
|
|
277
|
-
*
|
|
278
|
-
* @param lastEventId The ID of the last received event for resumability
|
|
279
|
-
* @param attemptCount Current reconnection attempt count for this specific stream
|
|
280
|
-
*/
|
|
281
|
-
_scheduleReconnection(options, attemptCount = 0) {
|
|
282
|
-
const maxRetries = this._reconnectionOptions.maxRetries;
|
|
283
|
-
if (attemptCount >= maxRetries) {
|
|
284
|
-
this.onerror?.(/* @__PURE__ */ new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
|
|
285
|
-
return;
|
|
286
|
-
}
|
|
287
|
-
const delay = this._getNextReconnectionDelay(attemptCount);
|
|
288
|
-
this._reconnectionTimeout = setTimeout(() => {
|
|
289
|
-
this._startOrAuthSse(options).catch((error) => {
|
|
290
|
-
this.onerror?.(/* @__PURE__ */ new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
|
|
291
|
-
this._scheduleReconnection(options, attemptCount + 1);
|
|
292
|
-
});
|
|
293
|
-
}, delay);
|
|
294
|
-
}
|
|
295
|
-
_handleSseStream(stream, options, isReconnectable) {
|
|
296
|
-
if (!stream) return;
|
|
297
|
-
const { onresumptiontoken, replayMessageId } = options;
|
|
298
|
-
let lastEventId;
|
|
299
|
-
let hasPrimingEvent = false;
|
|
300
|
-
let receivedResponse = false;
|
|
301
|
-
const processStream = async () => {
|
|
302
|
-
try {
|
|
303
|
-
const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({ onRetry: (retryMs) => {
|
|
304
|
-
this._serverRetryMs = retryMs;
|
|
305
|
-
} })).getReader();
|
|
306
|
-
while (true) {
|
|
307
|
-
const { value: event, done } = await reader.read();
|
|
308
|
-
if (done) break;
|
|
309
|
-
if (event.id) {
|
|
310
|
-
lastEventId = event.id;
|
|
311
|
-
hasPrimingEvent = true;
|
|
312
|
-
onresumptiontoken?.(event.id);
|
|
313
|
-
}
|
|
314
|
-
if (!event.data) continue;
|
|
315
|
-
if (!event.event || event.event === "message") try {
|
|
316
|
-
const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
|
|
317
|
-
if (isJSONRPCResultResponse(message)) {
|
|
318
|
-
receivedResponse = true;
|
|
319
|
-
if (replayMessageId !== void 0) message.id = replayMessageId;
|
|
320
|
-
}
|
|
321
|
-
this.onmessage?.(message);
|
|
322
|
-
} catch (error) {
|
|
323
|
-
this.onerror?.(error);
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
if ((isReconnectable || hasPrimingEvent) && !receivedResponse && this._abortController && !this._abortController.signal.aborted) this._scheduleReconnection({
|
|
327
|
-
resumptionToken: lastEventId,
|
|
328
|
-
onresumptiontoken,
|
|
329
|
-
replayMessageId
|
|
330
|
-
}, 0);
|
|
331
|
-
} catch (error) {
|
|
332
|
-
this.onerror?.(/* @__PURE__ */ new Error(`SSE stream disconnected: ${error}`));
|
|
333
|
-
if ((isReconnectable || hasPrimingEvent) && !receivedResponse && this._abortController && !this._abortController.signal.aborted) try {
|
|
334
|
-
this._scheduleReconnection({
|
|
335
|
-
resumptionToken: lastEventId,
|
|
336
|
-
onresumptiontoken,
|
|
337
|
-
replayMessageId
|
|
338
|
-
}, 0);
|
|
339
|
-
} catch (error) {
|
|
340
|
-
this.onerror?.(/* @__PURE__ */ new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`));
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
};
|
|
344
|
-
processStream();
|
|
345
|
-
}
|
|
346
|
-
async start() {
|
|
347
|
-
if (this._abortController) throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
|
|
348
|
-
this._abortController = new AbortController();
|
|
349
|
-
}
|
|
350
|
-
/**
|
|
351
|
-
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
|
|
352
|
-
*/
|
|
353
|
-
async finishAuth(authorizationCode) {
|
|
354
|
-
if (!this._authProvider) throw new UnauthorizedError("No auth provider");
|
|
355
|
-
if (await auth(this._authProvider, {
|
|
356
|
-
serverUrl: this._url,
|
|
357
|
-
authorizationCode,
|
|
358
|
-
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
359
|
-
scope: this._scope,
|
|
360
|
-
fetchFn: this._fetchWithInit
|
|
361
|
-
}) !== "AUTHORIZED") throw new UnauthorizedError("Failed to authorize");
|
|
362
|
-
}
|
|
363
|
-
async close() {
|
|
364
|
-
if (this._reconnectionTimeout) {
|
|
365
|
-
clearTimeout(this._reconnectionTimeout);
|
|
366
|
-
this._reconnectionTimeout = void 0;
|
|
367
|
-
}
|
|
368
|
-
this._abortController?.abort();
|
|
369
|
-
this.onclose?.();
|
|
370
|
-
}
|
|
371
|
-
async send(message, options) {
|
|
372
|
-
try {
|
|
373
|
-
const { resumptionToken, onresumptiontoken } = options || {};
|
|
374
|
-
if (resumptionToken) {
|
|
375
|
-
this._startOrAuthSse({
|
|
376
|
-
resumptionToken,
|
|
377
|
-
replayMessageId: isJSONRPCRequest(message) ? message.id : void 0
|
|
378
|
-
}).catch((err) => this.onerror?.(err));
|
|
379
|
-
return;
|
|
380
|
-
}
|
|
381
|
-
const headers = await this._commonHeaders();
|
|
382
|
-
headers.set("content-type", "application/json");
|
|
383
|
-
headers.set("accept", "application/json, text/event-stream");
|
|
384
|
-
const init = {
|
|
385
|
-
...this._requestInit,
|
|
386
|
-
method: "POST",
|
|
387
|
-
headers,
|
|
388
|
-
body: JSON.stringify(message),
|
|
389
|
-
signal: this._abortController?.signal
|
|
390
|
-
};
|
|
391
|
-
const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._url, init);
|
|
392
|
-
const sessionId = response.headers.get("mcp-session-id");
|
|
393
|
-
if (sessionId) this._sessionId = sessionId;
|
|
394
|
-
if (!response.ok) {
|
|
395
|
-
const text = await response.text().catch(() => null);
|
|
396
|
-
if (response.status === 401 && this._authProvider) {
|
|
397
|
-
if (this._hasCompletedAuthFlow) throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
|
|
398
|
-
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
|
|
399
|
-
this._resourceMetadataUrl = resourceMetadataUrl;
|
|
400
|
-
this._scope = scope;
|
|
401
|
-
if (await auth(this._authProvider, {
|
|
402
|
-
serverUrl: this._url,
|
|
403
|
-
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
404
|
-
scope: this._scope,
|
|
405
|
-
fetchFn: this._fetchWithInit
|
|
406
|
-
}) !== "AUTHORIZED") throw new UnauthorizedError();
|
|
407
|
-
this._hasCompletedAuthFlow = true;
|
|
408
|
-
return this.send(message);
|
|
409
|
-
}
|
|
410
|
-
if (response.status === 403 && this._authProvider) {
|
|
411
|
-
const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);
|
|
412
|
-
if (error === "insufficient_scope") {
|
|
413
|
-
const wwwAuthHeader = response.headers.get("WWW-Authenticate");
|
|
414
|
-
if (this._lastUpscopingHeader === wwwAuthHeader) throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
|
|
415
|
-
if (scope) this._scope = scope;
|
|
416
|
-
if (resourceMetadataUrl) this._resourceMetadataUrl = resourceMetadataUrl;
|
|
417
|
-
this._lastUpscopingHeader = wwwAuthHeader ?? void 0;
|
|
418
|
-
if (await auth(this._authProvider, {
|
|
419
|
-
serverUrl: this._url,
|
|
420
|
-
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
421
|
-
scope: this._scope,
|
|
422
|
-
fetchFn: this._fetch
|
|
423
|
-
}) !== "AUTHORIZED") throw new UnauthorizedError();
|
|
424
|
-
return this.send(message);
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${this._unfollowedRedirect(response, this._url) ?? text}`);
|
|
428
|
-
}
|
|
429
|
-
this._hasCompletedAuthFlow = false;
|
|
430
|
-
this._lastUpscopingHeader = void 0;
|
|
431
|
-
if (response.status === 202) {
|
|
432
|
-
await response.body?.cancel();
|
|
433
|
-
if (isInitializedNotification(message)) this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(err));
|
|
434
|
-
return;
|
|
435
|
-
}
|
|
436
|
-
const hasRequests = (Array.isArray(message) ? message : [message]).filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
|
|
437
|
-
const contentType = response.headers.get("content-type");
|
|
438
|
-
const responseMediaType = mediaTypeEssence(contentType);
|
|
439
|
-
if (hasRequests) {
|
|
440
|
-
if (responseMediaType === "text/event-stream") this._handleSseStream(response.body, { onresumptiontoken }, false);
|
|
441
|
-
else if (responseMediaType === "application/json") {
|
|
442
|
-
const data = await response.json();
|
|
443
|
-
const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
|
|
444
|
-
for (const msg of responseMessages) this.onmessage?.(msg);
|
|
445
|
-
} else {
|
|
446
|
-
await response.body?.cancel();
|
|
447
|
-
throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
|
|
448
|
-
}
|
|
449
|
-
} else await response.body?.cancel();
|
|
450
|
-
} catch (error) {
|
|
451
|
-
this.onerror?.(error);
|
|
452
|
-
throw error;
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
get sessionId() {
|
|
456
|
-
return this._sessionId;
|
|
457
|
-
}
|
|
458
|
-
/**
|
|
459
|
-
* Terminates the current session by sending a DELETE request to the server.
|
|
460
|
-
*
|
|
461
|
-
* Clients that no longer need a particular session
|
|
462
|
-
* (e.g., because the user is leaving the client application) SHOULD send an
|
|
463
|
-
* HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
|
|
464
|
-
* terminate the session.
|
|
465
|
-
*
|
|
466
|
-
* The server MAY respond with HTTP 405 Method Not Allowed, indicating that
|
|
467
|
-
* the server does not allow clients to terminate sessions.
|
|
468
|
-
*/
|
|
469
|
-
async terminateSession() {
|
|
470
|
-
if (!this._sessionId) return;
|
|
471
|
-
try {
|
|
472
|
-
const headers = await this._commonHeaders();
|
|
473
|
-
const init = {
|
|
474
|
-
...this._requestInit,
|
|
475
|
-
method: "DELETE",
|
|
476
|
-
headers,
|
|
477
|
-
signal: this._abortController?.signal
|
|
478
|
-
};
|
|
479
|
-
const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._url, init);
|
|
480
|
-
await response.body?.cancel();
|
|
481
|
-
if (!response.ok && response.status !== 405) throw new StreamableHTTPError(response.status, `Failed to terminate session: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);
|
|
482
|
-
this._sessionId = void 0;
|
|
483
|
-
} catch (error) {
|
|
484
|
-
this.onerror?.(error);
|
|
485
|
-
throw error;
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
setProtocolVersion(version) {
|
|
489
|
-
this._protocolVersion = version;
|
|
490
|
-
}
|
|
491
|
-
get protocolVersion() {
|
|
492
|
-
return this._protocolVersion;
|
|
493
|
-
}
|
|
494
|
-
/**
|
|
495
|
-
* Resume an SSE stream from a previous event ID.
|
|
496
|
-
* Opens a GET SSE connection with Last-Event-ID header to replay missed events.
|
|
497
|
-
*
|
|
498
|
-
* @param lastEventId The event ID to resume from
|
|
499
|
-
* @param options Optional callback to receive new resumption tokens
|
|
500
|
-
*/
|
|
501
|
-
async resumeStream(lastEventId, options) {
|
|
502
|
-
await this._startOrAuthSse({
|
|
503
|
-
resumptionToken: lastEventId,
|
|
504
|
-
onresumptiontoken: options?.onresumptiontoken
|
|
505
|
-
});
|
|
506
|
-
}
|
|
507
|
-
};
|
|
508
|
-
//#endregion
|
|
509
|
-
export { StreamableHTTPClientTransport };
|