@studiometa/productive-mcp 0.10.9 → 0.10.11

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.
Files changed (77) hide show
  1. package/README.md +129 -7
  2. package/dist/api-reference/generated.d.ts +3 -0
  3. package/dist/api-reference/generated.d.ts.map +1 -0
  4. package/dist/api-reference/types.d.ts +31 -0
  5. package/dist/api-reference/types.d.ts.map +1 -0
  6. package/dist/auth.js +2 -0
  7. package/dist/auth.js.map +1 -1
  8. package/dist/crypto.js +2 -0
  9. package/dist/crypto.js.map +1 -1
  10. package/dist/handlers/activities.d.ts +1 -0
  11. package/dist/handlers/activities.d.ts.map +1 -1
  12. package/dist/handlers/api-read.d.ts +14 -0
  13. package/dist/handlers/api-read.d.ts.map +1 -0
  14. package/dist/handlers/api-utils.d.ts +27 -0
  15. package/dist/handlers/api-utils.d.ts.map +1 -0
  16. package/dist/handlers/api-write.d.ts +10 -0
  17. package/dist/handlers/api-write.d.ts.map +1 -0
  18. package/dist/handlers/attachments.d.ts +1 -0
  19. package/dist/handlers/attachments.d.ts.map +1 -1
  20. package/dist/handlers/bookings.d.ts +1 -0
  21. package/dist/handlers/bookings.d.ts.map +1 -1
  22. package/dist/handlers/comments.d.ts +1 -0
  23. package/dist/handlers/comments.d.ts.map +1 -1
  24. package/dist/handlers/companies.d.ts +1 -0
  25. package/dist/handlers/companies.d.ts.map +1 -1
  26. package/dist/handlers/custom-fields.d.ts +1 -0
  27. package/dist/handlers/custom-fields.d.ts.map +1 -1
  28. package/dist/handlers/deals.d.ts +1 -0
  29. package/dist/handlers/deals.d.ts.map +1 -1
  30. package/dist/handlers/discussions.d.ts +1 -0
  31. package/dist/handlers/discussions.d.ts.map +1 -1
  32. package/dist/handlers/help.d.ts.map +1 -1
  33. package/dist/handlers/index.d.ts.map +1 -1
  34. package/dist/handlers/pages.d.ts +1 -0
  35. package/dist/handlers/pages.d.ts.map +1 -1
  36. package/dist/handlers/projects.d.ts +1 -0
  37. package/dist/handlers/projects.d.ts.map +1 -1
  38. package/dist/handlers/schema.d.ts.map +1 -1
  39. package/dist/handlers/services.d.ts +1 -0
  40. package/dist/handlers/services.d.ts.map +1 -1
  41. package/dist/handlers/tasks.d.ts +1 -0
  42. package/dist/handlers/tasks.d.ts.map +1 -1
  43. package/dist/handlers/time.d.ts +1 -0
  44. package/dist/handlers/time.d.ts.map +1 -1
  45. package/dist/handlers/timers.d.ts +1 -0
  46. package/dist/handlers/timers.d.ts.map +1 -1
  47. package/dist/handlers/types.d.ts +1 -0
  48. package/dist/handlers/types.d.ts.map +1 -1
  49. package/dist/handlers-B9FASjNJ.js +41290 -0
  50. package/dist/handlers-B9FASjNJ.js.map +1 -0
  51. package/dist/handlers.js +1 -1
  52. package/dist/http-B3J8ZV4I.js +2534 -0
  53. package/dist/http-B3J8ZV4I.js.map +1 -0
  54. package/dist/http.d.ts +5 -0
  55. package/dist/http.d.ts.map +1 -1
  56. package/dist/http.js +2 -170
  57. package/dist/index.js +4 -3
  58. package/dist/oauth.d.ts +1 -1
  59. package/dist/oauth.d.ts.map +1 -1
  60. package/dist/oauth.js +8 -116
  61. package/dist/oauth.js.map +1 -1
  62. package/dist/schema.d.ts +32 -1
  63. package/dist/schema.d.ts.map +1 -1
  64. package/dist/server.js +4 -3
  65. package/dist/{stdio-Bi1Lvp8O.js → stdio-BpKd5pcS.js} +9 -3
  66. package/dist/{stdio-Bi1Lvp8O.js.map → stdio-BpKd5pcS.js.map} +1 -1
  67. package/dist/stdio.js +1 -2
  68. package/dist/tools.d.ts.map +1 -1
  69. package/dist/tools.js +196 -120
  70. package/dist/tools.js.map +1 -1
  71. package/dist/{version-BFw4junA.js → version-Dm6m3p60.js} +13 -7
  72. package/dist/{version-BFw4junA.js.map → version-Dm6m3p60.js.map} +1 -1
  73. package/package.json +3 -3
  74. package/skills/SKILL.md +113 -1
  75. package/dist/handlers-t95fhdps.js +0 -4225
  76. package/dist/handlers-t95fhdps.js.map +0 -1
  77. package/dist/http.js.map +0 -1
@@ -0,0 +1,2534 @@
1
+ import { a as INSTRUCTIONS, i as readResource, n as listResourceTemplates, r as listResources, t as VERSION } from "./version-Dm6m3p60.js";
2
+ import { _ as union, a as boolean, c as intersection, d as number, f as object, g as string, h as record, i as array, l as literal, m as preprocess, n as _enum, o as custom, p as optional, r as _null, s as discriminatedUnion, t as executeToolWithCredentials, u as looseObject, v as unknown, y as datetime } from "./handlers-B9FASjNJ.js";
3
+ import { a as handlePrompt, t as getAvailablePrompts } from "./stdio-BpKd5pcS.js";
4
+ import { TOOLS } from "./tools.js";
5
+ import { parseAuthHeader } from "./auth.js";
6
+ import { authorizeGetHandler, authorizePostHandler, oauthMetadataHandler, registerHandler, tokenHandler } from "./oauth.js";
7
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
8
+ import { CallToolRequestSchema, ErrorCode, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourceTemplatesRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema } from "@modelcontextprotocol/sdk/types.js";
9
+ import { H3, defineHandler } from "h3";
10
+ import "http";
11
+ import { Http2ServerRequest, constants } from "http2";
12
+ import { Readable } from "stream";
13
+ import crypto$1 from "crypto";
14
+ //#region ../../node_modules/@hono/node-server/dist/index.mjs
15
+ var RequestError = class extends Error {
16
+ constructor(message, options) {
17
+ super(message, options);
18
+ this.name = "RequestError";
19
+ }
20
+ };
21
+ var toRequestError = (e) => {
22
+ if (e instanceof RequestError) return e;
23
+ return new RequestError(e.message, { cause: e });
24
+ };
25
+ var GlobalRequest = global.Request;
26
+ var Request = class extends GlobalRequest {
27
+ constructor(input, options) {
28
+ if (typeof input === "object" && getRequestCache in input) input = input[getRequestCache]();
29
+ if (typeof options?.body?.getReader !== "undefined") options.duplex ??= "half";
30
+ super(input, options);
31
+ }
32
+ };
33
+ var newHeadersFromIncoming = (incoming) => {
34
+ const headerRecord = [];
35
+ const rawHeaders = incoming.rawHeaders;
36
+ for (let i = 0; i < rawHeaders.length; i += 2) {
37
+ const { [i]: key, [i + 1]: value } = rawHeaders;
38
+ if (key.charCodeAt(0) !== 58) headerRecord.push([key, value]);
39
+ }
40
+ return new Headers(headerRecord);
41
+ };
42
+ var wrapBodyStream = Symbol("wrapBodyStream");
43
+ var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
44
+ const init = {
45
+ method,
46
+ headers,
47
+ signal: abortController.signal
48
+ };
49
+ if (method === "TRACE") {
50
+ init.method = "GET";
51
+ const req = new Request(url, init);
52
+ Object.defineProperty(req, "method", { get() {
53
+ return "TRACE";
54
+ } });
55
+ return req;
56
+ }
57
+ if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
58
+ controller.enqueue(incoming.rawBody);
59
+ controller.close();
60
+ } });
61
+ else if (incoming[wrapBodyStream]) {
62
+ let reader;
63
+ init.body = new ReadableStream({ async pull(controller) {
64
+ try {
65
+ reader ||= Readable.toWeb(incoming).getReader();
66
+ const { done, value } = await reader.read();
67
+ if (done) controller.close();
68
+ else controller.enqueue(value);
69
+ } catch (error) {
70
+ controller.error(error);
71
+ }
72
+ } });
73
+ } else init.body = Readable.toWeb(incoming);
74
+ return new Request(url, init);
75
+ };
76
+ var getRequestCache = Symbol("getRequestCache");
77
+ var requestCache = Symbol("requestCache");
78
+ var incomingKey = Symbol("incomingKey");
79
+ var urlKey = Symbol("urlKey");
80
+ var headersKey = Symbol("headersKey");
81
+ var abortControllerKey = Symbol("abortControllerKey");
82
+ var requestPrototype = {
83
+ get method() {
84
+ return this[incomingKey].method || "GET";
85
+ },
86
+ get url() {
87
+ return this[urlKey];
88
+ },
89
+ get headers() {
90
+ return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
91
+ },
92
+ [Symbol("getAbortController")]() {
93
+ this[getRequestCache]();
94
+ return this[abortControllerKey];
95
+ },
96
+ [getRequestCache]() {
97
+ this[abortControllerKey] ||= new AbortController();
98
+ return this[requestCache] ||= newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey]);
99
+ }
100
+ };
101
+ [
102
+ "body",
103
+ "bodyUsed",
104
+ "cache",
105
+ "credentials",
106
+ "destination",
107
+ "integrity",
108
+ "mode",
109
+ "redirect",
110
+ "referrer",
111
+ "referrerPolicy",
112
+ "signal",
113
+ "keepalive"
114
+ ].forEach((k) => {
115
+ Object.defineProperty(requestPrototype, k, { get() {
116
+ return this[getRequestCache]()[k];
117
+ } });
118
+ });
119
+ [
120
+ "arrayBuffer",
121
+ "blob",
122
+ "clone",
123
+ "formData",
124
+ "json",
125
+ "text"
126
+ ].forEach((k) => {
127
+ Object.defineProperty(requestPrototype, k, { value: function() {
128
+ return this[getRequestCache]()[k]();
129
+ } });
130
+ });
131
+ Object.setPrototypeOf(requestPrototype, Request.prototype);
132
+ var newRequest = (incoming, defaultHostname) => {
133
+ const req = Object.create(requestPrototype);
134
+ req[incomingKey] = incoming;
135
+ const incomingUrl = incoming.url || "";
136
+ if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
137
+ if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
138
+ try {
139
+ req[urlKey] = new URL(incomingUrl).href;
140
+ } catch (e) {
141
+ throw new RequestError("Invalid absolute URL", { cause: e });
142
+ }
143
+ return req;
144
+ }
145
+ const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
146
+ if (!host) throw new RequestError("Missing host header");
147
+ let scheme;
148
+ if (incoming instanceof Http2ServerRequest) {
149
+ scheme = incoming.scheme;
150
+ if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
151
+ } else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
152
+ const url = new URL(`${scheme}://${host}${incomingUrl}`);
153
+ if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) throw new RequestError("Invalid host header");
154
+ req[urlKey] = url.href;
155
+ return req;
156
+ };
157
+ var responseCache = Symbol("responseCache");
158
+ var getResponseCache = Symbol("getResponseCache");
159
+ var cacheKey = Symbol("cache");
160
+ var GlobalResponse = global.Response;
161
+ var Response2 = class _Response {
162
+ #body;
163
+ #init;
164
+ [getResponseCache]() {
165
+ delete this[cacheKey];
166
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
167
+ }
168
+ constructor(body, init) {
169
+ let headers;
170
+ this.#body = body;
171
+ if (init instanceof _Response) {
172
+ const cachedGlobalResponse = init[responseCache];
173
+ if (cachedGlobalResponse) {
174
+ this.#init = cachedGlobalResponse;
175
+ this[getResponseCache]();
176
+ return;
177
+ } else {
178
+ this.#init = init.#init;
179
+ headers = new Headers(init.#init.headers);
180
+ }
181
+ } else this.#init = init;
182
+ if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
183
+ init?.status || 200,
184
+ body,
185
+ headers || init?.headers
186
+ ];
187
+ }
188
+ get headers() {
189
+ const cache = this[cacheKey];
190
+ if (cache) {
191
+ if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || { "content-type": "text/plain; charset=UTF-8" });
192
+ return cache[2];
193
+ }
194
+ return this[getResponseCache]().headers;
195
+ }
196
+ get status() {
197
+ return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
198
+ }
199
+ get ok() {
200
+ const status = this.status;
201
+ return status >= 200 && status < 300;
202
+ }
203
+ };
204
+ [
205
+ "body",
206
+ "bodyUsed",
207
+ "redirected",
208
+ "statusText",
209
+ "trailers",
210
+ "type",
211
+ "url"
212
+ ].forEach((k) => {
213
+ Object.defineProperty(Response2.prototype, k, { get() {
214
+ return this[getResponseCache]()[k];
215
+ } });
216
+ });
217
+ [
218
+ "arrayBuffer",
219
+ "blob",
220
+ "clone",
221
+ "formData",
222
+ "json",
223
+ "text"
224
+ ].forEach((k) => {
225
+ Object.defineProperty(Response2.prototype, k, { value: function() {
226
+ return this[getResponseCache]()[k]();
227
+ } });
228
+ });
229
+ Object.setPrototypeOf(Response2, GlobalResponse);
230
+ Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
231
+ async function readWithoutBlocking(readPromise) {
232
+ return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
233
+ }
234
+ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
235
+ const cancel = (error) => {
236
+ reader.cancel(error).catch(() => {});
237
+ };
238
+ writable.on("close", cancel);
239
+ writable.on("error", cancel);
240
+ (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
241
+ return reader.closed.finally(() => {
242
+ writable.off("close", cancel);
243
+ writable.off("error", cancel);
244
+ });
245
+ function handleStreamError(error) {
246
+ if (error) writable.destroy(error);
247
+ }
248
+ function onDrain() {
249
+ reader.read().then(flow, handleStreamError);
250
+ }
251
+ function flow({ done, value }) {
252
+ try {
253
+ if (done) writable.end();
254
+ else if (!writable.write(value)) writable.once("drain", onDrain);
255
+ else return reader.read().then(flow, handleStreamError);
256
+ } catch (e) {
257
+ handleStreamError(e);
258
+ }
259
+ }
260
+ }
261
+ function writeFromReadableStream(stream, writable) {
262
+ if (stream.locked) throw new TypeError("ReadableStream is locked.");
263
+ else if (writable.destroyed) return;
264
+ return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
265
+ }
266
+ var buildOutgoingHttpHeaders = (headers) => {
267
+ const res = {};
268
+ if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
269
+ const cookies = [];
270
+ for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
271
+ else res[k] = v;
272
+ if (cookies.length > 0) res["set-cookie"] = cookies;
273
+ res["content-type"] ??= "text/plain; charset=UTF-8";
274
+ return res;
275
+ };
276
+ var X_ALREADY_SENT = "x-hono-already-sent";
277
+ if (typeof global.crypto === "undefined") global.crypto = crypto$1;
278
+ var outgoingEnded = Symbol("outgoingEnded");
279
+ var incomingDraining = Symbol("incomingDraining");
280
+ var DRAIN_TIMEOUT_MS = 500;
281
+ var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
282
+ var drainIncoming = (incoming) => {
283
+ const incomingWithDrainState = incoming;
284
+ if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
285
+ incomingWithDrainState[incomingDraining] = true;
286
+ if (incoming instanceof Http2ServerRequest) {
287
+ try {
288
+ incoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);
289
+ } catch {}
290
+ return;
291
+ }
292
+ let bytesRead = 0;
293
+ const cleanup = () => {
294
+ clearTimeout(timer);
295
+ incoming.off("data", onData);
296
+ incoming.off("end", cleanup);
297
+ incoming.off("error", cleanup);
298
+ };
299
+ const forceClose = () => {
300
+ cleanup();
301
+ const socket = incoming.socket;
302
+ if (socket && !socket.destroyed) socket.destroySoon();
303
+ };
304
+ const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
305
+ timer.unref?.();
306
+ const onData = (chunk) => {
307
+ bytesRead += chunk.length;
308
+ if (bytesRead > MAX_DRAIN_BYTES) forceClose();
309
+ };
310
+ incoming.on("data", onData);
311
+ incoming.on("end", cleanup);
312
+ incoming.on("error", cleanup);
313
+ incoming.resume();
314
+ };
315
+ var handleRequestError = () => new Response(null, { status: 400 });
316
+ var handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
317
+ var handleResponseError = (e, outgoing) => {
318
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
319
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
320
+ else {
321
+ console.error(e);
322
+ if (!outgoing.headersSent) outgoing.writeHead(500, { "Content-Type": "text/plain" });
323
+ outgoing.end(`Error: ${err.message}`);
324
+ outgoing.destroy(err);
325
+ }
326
+ };
327
+ var flushHeaders = (outgoing) => {
328
+ if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
329
+ };
330
+ var responseViaCache = async (res, outgoing) => {
331
+ let [status, body, header] = res[cacheKey];
332
+ let hasContentLength = false;
333
+ if (!header) header = { "content-type": "text/plain; charset=UTF-8" };
334
+ else if (header instanceof Headers) {
335
+ hasContentLength = header.has("content-length");
336
+ header = buildOutgoingHttpHeaders(header);
337
+ } else if (Array.isArray(header)) {
338
+ const headerObj = new Headers(header);
339
+ hasContentLength = headerObj.has("content-length");
340
+ header = buildOutgoingHttpHeaders(headerObj);
341
+ } else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
342
+ hasContentLength = true;
343
+ break;
344
+ }
345
+ if (!hasContentLength) {
346
+ if (typeof body === "string") header["Content-Length"] = Buffer.byteLength(body);
347
+ else if (body instanceof Uint8Array) header["Content-Length"] = body.byteLength;
348
+ else if (body instanceof Blob) header["Content-Length"] = body.size;
349
+ }
350
+ outgoing.writeHead(status, header);
351
+ if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
352
+ else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
353
+ else {
354
+ flushHeaders(outgoing);
355
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
356
+ }
357
+ outgoing[outgoingEnded]?.();
358
+ };
359
+ var isPromise = (res) => typeof res.then === "function";
360
+ var responseViaResponseObject = async (res, outgoing, options = {}) => {
361
+ if (isPromise(res)) if (options.errorHandler) try {
362
+ res = await res;
363
+ } catch (err) {
364
+ const errRes = await options.errorHandler(err);
365
+ if (!errRes) return;
366
+ res = errRes;
367
+ }
368
+ else res = await res.catch(handleFetchError);
369
+ if (cacheKey in res) return responseViaCache(res, outgoing);
370
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
371
+ if (res.body) {
372
+ const reader = res.body.getReader();
373
+ const values = [];
374
+ let done = false;
375
+ let currentReadPromise = void 0;
376
+ if (resHeaderRecord["transfer-encoding"] !== "chunked") {
377
+ let maxReadCount = 2;
378
+ for (let i = 0; i < maxReadCount; i++) {
379
+ currentReadPromise ||= reader.read();
380
+ const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
381
+ console.error(e);
382
+ done = true;
383
+ });
384
+ if (!chunk) {
385
+ if (i === 1) {
386
+ await new Promise((resolve) => setTimeout(resolve));
387
+ maxReadCount = 3;
388
+ continue;
389
+ }
390
+ break;
391
+ }
392
+ currentReadPromise = void 0;
393
+ if (chunk.value) values.push(chunk.value);
394
+ if (chunk.done) {
395
+ done = true;
396
+ break;
397
+ }
398
+ }
399
+ if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
400
+ }
401
+ outgoing.writeHead(res.status, resHeaderRecord);
402
+ values.forEach((value) => {
403
+ outgoing.write(value);
404
+ });
405
+ if (done) outgoing.end();
406
+ else {
407
+ if (values.length === 0) flushHeaders(outgoing);
408
+ await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
409
+ }
410
+ } else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
411
+ outgoing.writeHead(res.status, resHeaderRecord);
412
+ outgoing.end();
413
+ }
414
+ outgoing[outgoingEnded]?.();
415
+ };
416
+ var getRequestListener = (fetchCallback, options = {}) => {
417
+ const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
418
+ if (options.overrideGlobalObjects !== false && global.Request !== Request) {
419
+ Object.defineProperty(global, "Request", { value: Request });
420
+ Object.defineProperty(global, "Response", { value: Response2 });
421
+ }
422
+ return async (incoming, outgoing) => {
423
+ let res, req;
424
+ try {
425
+ req = newRequest(incoming, options.hostname);
426
+ let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
427
+ if (!incomingEnded) {
428
+ incoming[wrapBodyStream] = true;
429
+ incoming.on("end", () => {
430
+ incomingEnded = true;
431
+ });
432
+ if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
433
+ if (!incomingEnded) setTimeout(() => {
434
+ if (!incomingEnded) setTimeout(() => {
435
+ drainIncoming(incoming);
436
+ });
437
+ });
438
+ };
439
+ outgoing.on("finish", () => {
440
+ if (!incomingEnded) drainIncoming(incoming);
441
+ });
442
+ }
443
+ outgoing.on("close", () => {
444
+ if (req[abortControllerKey]) {
445
+ if (incoming.errored) req[abortControllerKey].abort(incoming.errored.toString());
446
+ else if (!outgoing.writableFinished) req[abortControllerKey].abort("Client connection prematurely closed.");
447
+ }
448
+ if (!incomingEnded) setTimeout(() => {
449
+ if (!incomingEnded) setTimeout(() => {
450
+ drainIncoming(incoming);
451
+ });
452
+ });
453
+ });
454
+ res = fetchCallback(req, {
455
+ incoming,
456
+ outgoing
457
+ });
458
+ if (cacheKey in res) return responseViaCache(res, outgoing);
459
+ } catch (e) {
460
+ if (!res) if (options.errorHandler) {
461
+ res = await options.errorHandler(req ? e : toRequestError(e));
462
+ if (!res) return;
463
+ } else if (!req) res = handleRequestError();
464
+ else res = handleFetchError(e);
465
+ else return handleResponseError(e, outgoing);
466
+ }
467
+ try {
468
+ return await responseViaResponseObject(res, outgoing, options);
469
+ } catch (e) {
470
+ return handleResponseError(e, outgoing);
471
+ }
472
+ };
473
+ };
474
+ var SUPPORTED_PROTOCOL_VERSIONS = [
475
+ "2025-11-25",
476
+ "2025-06-18",
477
+ "2025-03-26",
478
+ "2024-11-05",
479
+ "2024-10-07"
480
+ ];
481
+ var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
482
+ /**
483
+ * Assert 'object' type schema.
484
+ *
485
+ * @internal
486
+ */
487
+ var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function"));
488
+ /**
489
+ * A progress token, used to associate progress notifications with the original request.
490
+ */
491
+ var ProgressTokenSchema = union([string(), number().int()]);
492
+ /**
493
+ * An opaque token used to represent a cursor for pagination.
494
+ */
495
+ var CursorSchema = string();
496
+ looseObject({
497
+ ttl: number().optional(),
498
+ pollInterval: number().optional()
499
+ });
500
+ var TaskMetadataSchema = object({ ttl: number().optional() });
501
+ /**
502
+ * Metadata for associating messages with a task.
503
+ * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.
504
+ */
505
+ var RelatedTaskMetadataSchema = object({ taskId: string() });
506
+ var RequestMetaSchema = looseObject({
507
+ progressToken: ProgressTokenSchema.optional(),
508
+ [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
509
+ });
510
+ /**
511
+ * Common params for any request.
512
+ */
513
+ var BaseRequestParamsSchema = object({ _meta: RequestMetaSchema.optional() });
514
+ /**
515
+ * Common params for any task-augmented request.
516
+ */
517
+ var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() });
518
+ var RequestSchema = object({
519
+ method: string(),
520
+ params: BaseRequestParamsSchema.loose().optional()
521
+ });
522
+ var NotificationsParamsSchema = object({ _meta: RequestMetaSchema.optional() });
523
+ var NotificationSchema = object({
524
+ method: string(),
525
+ params: NotificationsParamsSchema.loose().optional()
526
+ });
527
+ var ResultSchema = looseObject({ _meta: RequestMetaSchema.optional() });
528
+ /**
529
+ * A uniquely identifying ID for a request in JSON-RPC.
530
+ */
531
+ var RequestIdSchema = union([string(), number().int()]);
532
+ /**
533
+ * A request that expects a response.
534
+ */
535
+ var JSONRPCRequestSchema = object({
536
+ jsonrpc: literal("2.0"),
537
+ id: RequestIdSchema,
538
+ ...RequestSchema.shape
539
+ }).strict();
540
+ var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
541
+ /**
542
+ * A notification which does not expect a response.
543
+ */
544
+ var JSONRPCNotificationSchema = object({
545
+ jsonrpc: literal("2.0"),
546
+ ...NotificationSchema.shape
547
+ }).strict();
548
+ /**
549
+ * A successful (non-error) response to a request.
550
+ */
551
+ var JSONRPCResultResponseSchema = object({
552
+ jsonrpc: literal("2.0"),
553
+ id: RequestIdSchema,
554
+ result: ResultSchema
555
+ }).strict();
556
+ /**
557
+ * Checks if a value is a valid JSONRPCResultResponse.
558
+ * @param value - The value to check.
559
+ *
560
+ * @returns True if the value is a valid JSONRPCResultResponse, false otherwise.
561
+ */
562
+ var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
563
+ /**
564
+ * Error codes defined by the JSON-RPC specification.
565
+ */
566
+ var ErrorCode$1;
567
+ (function(ErrorCode) {
568
+ ErrorCode[ErrorCode["ConnectionClosed"] = -32e3] = "ConnectionClosed";
569
+ ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout";
570
+ ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError";
571
+ ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest";
572
+ ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound";
573
+ ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams";
574
+ ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError";
575
+ ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
576
+ })(ErrorCode$1 || (ErrorCode$1 = {}));
577
+ /**
578
+ * A response to a request that indicates an error occurred.
579
+ */
580
+ var JSONRPCErrorResponseSchema = object({
581
+ jsonrpc: literal("2.0"),
582
+ id: RequestIdSchema.optional(),
583
+ error: object({
584
+ code: number().int(),
585
+ message: string(),
586
+ data: unknown().optional()
587
+ })
588
+ }).strict();
589
+ /**
590
+ * Checks if a value is a valid JSONRPCErrorResponse.
591
+ * @param value - The value to check.
592
+ *
593
+ * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise.
594
+ */
595
+ var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
596
+ var JSONRPCMessageSchema = union([
597
+ JSONRPCRequestSchema,
598
+ JSONRPCNotificationSchema,
599
+ JSONRPCResultResponseSchema,
600
+ JSONRPCErrorResponseSchema
601
+ ]);
602
+ union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
603
+ /**
604
+ * A response that indicates success but carries no data.
605
+ */
606
+ var EmptyResultSchema = ResultSchema.strict();
607
+ var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
608
+ requestId: RequestIdSchema.optional(),
609
+ reason: string().optional()
610
+ });
611
+ /**
612
+ * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.
613
+ *
614
+ * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.
615
+ *
616
+ * This notification indicates that the result will be unused, so any associated processing SHOULD cease.
617
+ *
618
+ * A client MUST NOT attempt to cancel its `initialize` request.
619
+ */
620
+ var CancelledNotificationSchema = NotificationSchema.extend({
621
+ method: literal("notifications/cancelled"),
622
+ params: CancelledNotificationParamsSchema
623
+ });
624
+ /**
625
+ * Base schema to add `icons` property.
626
+ *
627
+ */
628
+ var IconsSchema = object({ icons: array(object({
629
+ src: string(),
630
+ mimeType: string().optional(),
631
+ sizes: array(string()).optional(),
632
+ theme: _enum(["light", "dark"]).optional()
633
+ })).optional() });
634
+ /**
635
+ * Base metadata interface for common properties across resources, tools, prompts, and implementations.
636
+ */
637
+ var BaseMetadataSchema = object({
638
+ name: string(),
639
+ title: string().optional()
640
+ });
641
+ /**
642
+ * Describes the name and version of an MCP implementation.
643
+ */
644
+ var ImplementationSchema = BaseMetadataSchema.extend({
645
+ ...BaseMetadataSchema.shape,
646
+ ...IconsSchema.shape,
647
+ version: string(),
648
+ websiteUrl: string().optional(),
649
+ description: string().optional()
650
+ });
651
+ var ElicitationCapabilitySchema = preprocess((value) => {
652
+ if (value && typeof value === "object" && !Array.isArray(value)) {
653
+ if (Object.keys(value).length === 0) return { form: {} };
654
+ }
655
+ return value;
656
+ }, intersection(object({
657
+ form: intersection(object({ applyDefaults: boolean().optional() }), record(string(), unknown())).optional(),
658
+ url: AssertObjectSchema.optional()
659
+ }), record(string(), unknown()).optional()));
660
+ /**
661
+ * Task capabilities for clients, indicating which request types support task creation.
662
+ */
663
+ var ClientTasksCapabilitySchema = looseObject({
664
+ list: AssertObjectSchema.optional(),
665
+ cancel: AssertObjectSchema.optional(),
666
+ requests: looseObject({
667
+ sampling: looseObject({ createMessage: AssertObjectSchema.optional() }).optional(),
668
+ elicitation: looseObject({ create: AssertObjectSchema.optional() }).optional()
669
+ }).optional()
670
+ });
671
+ /**
672
+ * Task capabilities for servers, indicating which request types support task creation.
673
+ */
674
+ var ServerTasksCapabilitySchema = looseObject({
675
+ list: AssertObjectSchema.optional(),
676
+ cancel: AssertObjectSchema.optional(),
677
+ requests: looseObject({ tools: looseObject({ call: AssertObjectSchema.optional() }).optional() }).optional()
678
+ });
679
+ /**
680
+ * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.
681
+ */
682
+ var ClientCapabilitiesSchema = object({
683
+ experimental: record(string(), AssertObjectSchema).optional(),
684
+ sampling: object({
685
+ context: AssertObjectSchema.optional(),
686
+ tools: AssertObjectSchema.optional()
687
+ }).optional(),
688
+ elicitation: ElicitationCapabilitySchema.optional(),
689
+ roots: object({ listChanged: boolean().optional() }).optional(),
690
+ tasks: ClientTasksCapabilitySchema.optional(),
691
+ extensions: record(string(), AssertObjectSchema).optional()
692
+ });
693
+ var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
694
+ protocolVersion: string(),
695
+ capabilities: ClientCapabilitiesSchema,
696
+ clientInfo: ImplementationSchema
697
+ });
698
+ /**
699
+ * This request is sent from the client to the server when it first connects, asking it to begin initialization.
700
+ */
701
+ var InitializeRequestSchema = RequestSchema.extend({
702
+ method: literal("initialize"),
703
+ params: InitializeRequestParamsSchema
704
+ });
705
+ var isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;
706
+ /**
707
+ * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.
708
+ */
709
+ var ServerCapabilitiesSchema = object({
710
+ experimental: record(string(), AssertObjectSchema).optional(),
711
+ logging: AssertObjectSchema.optional(),
712
+ completions: AssertObjectSchema.optional(),
713
+ prompts: object({ listChanged: boolean().optional() }).optional(),
714
+ resources: object({
715
+ subscribe: boolean().optional(),
716
+ listChanged: boolean().optional()
717
+ }).optional(),
718
+ tools: object({ listChanged: boolean().optional() }).optional(),
719
+ tasks: ServerTasksCapabilitySchema.optional(),
720
+ extensions: record(string(), AssertObjectSchema).optional()
721
+ });
722
+ /**
723
+ * After receiving an initialize request from the client, the server sends this response.
724
+ */
725
+ var InitializeResultSchema = ResultSchema.extend({
726
+ protocolVersion: string(),
727
+ capabilities: ServerCapabilitiesSchema,
728
+ serverInfo: ImplementationSchema,
729
+ instructions: string().optional()
730
+ });
731
+ /**
732
+ * This notification is sent from the client to the server after initialization has finished.
733
+ */
734
+ var InitializedNotificationSchema = NotificationSchema.extend({
735
+ method: literal("notifications/initialized"),
736
+ params: NotificationsParamsSchema.optional()
737
+ });
738
+ /**
739
+ * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.
740
+ */
741
+ var PingRequestSchema = RequestSchema.extend({
742
+ method: literal("ping"),
743
+ params: BaseRequestParamsSchema.optional()
744
+ });
745
+ var ProgressSchema = object({
746
+ progress: number(),
747
+ total: optional(number()),
748
+ message: optional(string())
749
+ });
750
+ var ProgressNotificationParamsSchema = object({
751
+ ...NotificationsParamsSchema.shape,
752
+ ...ProgressSchema.shape,
753
+ progressToken: ProgressTokenSchema
754
+ });
755
+ /**
756
+ * An out-of-band notification used to inform the receiver of a progress update for a long-running request.
757
+ *
758
+ * @category notifications/progress
759
+ */
760
+ var ProgressNotificationSchema = NotificationSchema.extend({
761
+ method: literal("notifications/progress"),
762
+ params: ProgressNotificationParamsSchema
763
+ });
764
+ var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() });
765
+ var PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() });
766
+ var PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() });
767
+ /**
768
+ * The status of a task.
769
+ * */
770
+ var TaskStatusSchema = _enum([
771
+ "working",
772
+ "input_required",
773
+ "completed",
774
+ "failed",
775
+ "cancelled"
776
+ ]);
777
+ /**
778
+ * A pollable state object associated with a request.
779
+ */
780
+ var TaskSchema = object({
781
+ taskId: string(),
782
+ status: TaskStatusSchema,
783
+ ttl: union([number(), _null()]),
784
+ createdAt: string(),
785
+ lastUpdatedAt: string(),
786
+ pollInterval: optional(number()),
787
+ statusMessage: optional(string())
788
+ });
789
+ /**
790
+ * Result returned when a task is created, containing the task data wrapped in a task field.
791
+ */
792
+ var CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema });
793
+ /**
794
+ * Parameters for task status notification.
795
+ */
796
+ var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
797
+ /**
798
+ * A notification sent when a task's status changes.
799
+ */
800
+ var TaskStatusNotificationSchema = NotificationSchema.extend({
801
+ method: literal("notifications/tasks/status"),
802
+ params: TaskStatusNotificationParamsSchema
803
+ });
804
+ /**
805
+ * A request to get the state of a specific task.
806
+ */
807
+ var GetTaskRequestSchema = RequestSchema.extend({
808
+ method: literal("tasks/get"),
809
+ params: BaseRequestParamsSchema.extend({ taskId: string() })
810
+ });
811
+ /**
812
+ * The response to a tasks/get request.
813
+ */
814
+ var GetTaskResultSchema = ResultSchema.merge(TaskSchema);
815
+ /**
816
+ * A request to get the result of a specific task.
817
+ */
818
+ var GetTaskPayloadRequestSchema = RequestSchema.extend({
819
+ method: literal("tasks/result"),
820
+ params: BaseRequestParamsSchema.extend({ taskId: string() })
821
+ });
822
+ ResultSchema.loose();
823
+ /**
824
+ * A request to list tasks.
825
+ */
826
+ var ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") });
827
+ /**
828
+ * The response to a tasks/list request.
829
+ */
830
+ var ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: array(TaskSchema) });
831
+ /**
832
+ * A request to cancel a specific task.
833
+ */
834
+ var CancelTaskRequestSchema = RequestSchema.extend({
835
+ method: literal("tasks/cancel"),
836
+ params: BaseRequestParamsSchema.extend({ taskId: string() })
837
+ });
838
+ ResultSchema.merge(TaskSchema);
839
+ /**
840
+ * The contents of a specific resource or sub-resource.
841
+ */
842
+ var ResourceContentsSchema = object({
843
+ uri: string(),
844
+ mimeType: optional(string()),
845
+ _meta: record(string(), unknown()).optional()
846
+ });
847
+ var TextResourceContentsSchema = ResourceContentsSchema.extend({ text: string() });
848
+ /**
849
+ * A Zod schema for validating Base64 strings that is more performant and
850
+ * robust for very large inputs than the default regex-based check. It avoids
851
+ * stack overflows by using the native `atob` function for validation.
852
+ */
853
+ var Base64Schema = string().refine((val) => {
854
+ try {
855
+ atob(val);
856
+ return true;
857
+ } catch {
858
+ return false;
859
+ }
860
+ }, { message: "Invalid Base64 string" });
861
+ var BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: Base64Schema });
862
+ /**
863
+ * The sender or recipient of messages and data in a conversation.
864
+ */
865
+ var RoleSchema = _enum(["user", "assistant"]);
866
+ /**
867
+ * Optional annotations providing clients additional context about a resource.
868
+ */
869
+ var AnnotationsSchema = object({
870
+ audience: array(RoleSchema).optional(),
871
+ priority: number().min(0).max(1).optional(),
872
+ lastModified: datetime({ offset: true }).optional()
873
+ });
874
+ /**
875
+ * A known resource that the server is capable of reading.
876
+ */
877
+ var ResourceSchema = object({
878
+ ...BaseMetadataSchema.shape,
879
+ ...IconsSchema.shape,
880
+ uri: string(),
881
+ description: optional(string()),
882
+ mimeType: optional(string()),
883
+ size: optional(number()),
884
+ annotations: AnnotationsSchema.optional(),
885
+ _meta: optional(looseObject({}))
886
+ });
887
+ /**
888
+ * A template description for resources available on the server.
889
+ */
890
+ var ResourceTemplateSchema = object({
891
+ ...BaseMetadataSchema.shape,
892
+ ...IconsSchema.shape,
893
+ uriTemplate: string(),
894
+ description: optional(string()),
895
+ mimeType: optional(string()),
896
+ annotations: AnnotationsSchema.optional(),
897
+ _meta: optional(looseObject({}))
898
+ });
899
+ /**
900
+ * Sent from the client to request a list of resources the server has.
901
+ */
902
+ var ListResourcesRequestSchema$1 = PaginatedRequestSchema.extend({ method: literal("resources/list") });
903
+ /**
904
+ * The server's response to a resources/list request from the client.
905
+ */
906
+ var ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: array(ResourceSchema) });
907
+ /**
908
+ * Sent from the client to request a list of resource templates the server has.
909
+ */
910
+ var ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") });
911
+ /**
912
+ * The server's response to a resources/templates/list request from the client.
913
+ */
914
+ var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: array(ResourceTemplateSchema) });
915
+ var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: string() });
916
+ /**
917
+ * Parameters for a `resources/read` request.
918
+ */
919
+ var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
920
+ /**
921
+ * Sent from the client to the server, to read a specific resource URI.
922
+ */
923
+ var ReadResourceRequestSchema$1 = RequestSchema.extend({
924
+ method: literal("resources/read"),
925
+ params: ReadResourceRequestParamsSchema
926
+ });
927
+ /**
928
+ * The server's response to a resources/read request from the client.
929
+ */
930
+ var ReadResourceResultSchema = ResultSchema.extend({ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) });
931
+ /**
932
+ * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.
933
+ */
934
+ var ResourceListChangedNotificationSchema = NotificationSchema.extend({
935
+ method: literal("notifications/resources/list_changed"),
936
+ params: NotificationsParamsSchema.optional()
937
+ });
938
+ var SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
939
+ /**
940
+ * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.
941
+ */
942
+ var SubscribeRequestSchema = RequestSchema.extend({
943
+ method: literal("resources/subscribe"),
944
+ params: SubscribeRequestParamsSchema
945
+ });
946
+ var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
947
+ /**
948
+ * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.
949
+ */
950
+ var UnsubscribeRequestSchema = RequestSchema.extend({
951
+ method: literal("resources/unsubscribe"),
952
+ params: UnsubscribeRequestParamsSchema
953
+ });
954
+ /**
955
+ * Parameters for a `notifications/resources/updated` notification.
956
+ */
957
+ var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: string() });
958
+ /**
959
+ * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.
960
+ */
961
+ var ResourceUpdatedNotificationSchema = NotificationSchema.extend({
962
+ method: literal("notifications/resources/updated"),
963
+ params: ResourceUpdatedNotificationParamsSchema
964
+ });
965
+ /**
966
+ * Describes an argument that a prompt can accept.
967
+ */
968
+ var PromptArgumentSchema = object({
969
+ name: string(),
970
+ description: optional(string()),
971
+ required: optional(boolean())
972
+ });
973
+ /**
974
+ * A prompt or prompt template that the server offers.
975
+ */
976
+ var PromptSchema = object({
977
+ ...BaseMetadataSchema.shape,
978
+ ...IconsSchema.shape,
979
+ description: optional(string()),
980
+ arguments: optional(array(PromptArgumentSchema)),
981
+ _meta: optional(looseObject({}))
982
+ });
983
+ /**
984
+ * Sent from the client to request a list of prompts and prompt templates the server has.
985
+ */
986
+ var ListPromptsRequestSchema$1 = PaginatedRequestSchema.extend({ method: literal("prompts/list") });
987
+ /**
988
+ * The server's response to a prompts/list request from the client.
989
+ */
990
+ var ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema) });
991
+ /**
992
+ * Parameters for a `prompts/get` request.
993
+ */
994
+ var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
995
+ name: string(),
996
+ arguments: record(string(), string()).optional()
997
+ });
998
+ /**
999
+ * Used by the client to get a prompt provided by the server.
1000
+ */
1001
+ var GetPromptRequestSchema$1 = RequestSchema.extend({
1002
+ method: literal("prompts/get"),
1003
+ params: GetPromptRequestParamsSchema
1004
+ });
1005
+ /**
1006
+ * Text provided to or from an LLM.
1007
+ */
1008
+ var TextContentSchema = object({
1009
+ type: literal("text"),
1010
+ text: string(),
1011
+ annotations: AnnotationsSchema.optional(),
1012
+ _meta: record(string(), unknown()).optional()
1013
+ });
1014
+ /**
1015
+ * An image provided to or from an LLM.
1016
+ */
1017
+ var ImageContentSchema = object({
1018
+ type: literal("image"),
1019
+ data: Base64Schema,
1020
+ mimeType: string(),
1021
+ annotations: AnnotationsSchema.optional(),
1022
+ _meta: record(string(), unknown()).optional()
1023
+ });
1024
+ /**
1025
+ * An Audio provided to or from an LLM.
1026
+ */
1027
+ var AudioContentSchema = object({
1028
+ type: literal("audio"),
1029
+ data: Base64Schema,
1030
+ mimeType: string(),
1031
+ annotations: AnnotationsSchema.optional(),
1032
+ _meta: record(string(), unknown()).optional()
1033
+ });
1034
+ /**
1035
+ * A tool call request from an assistant (LLM).
1036
+ * Represents the assistant's request to use a tool.
1037
+ */
1038
+ var ToolUseContentSchema = object({
1039
+ type: literal("tool_use"),
1040
+ name: string(),
1041
+ id: string(),
1042
+ input: record(string(), unknown()),
1043
+ _meta: record(string(), unknown()).optional()
1044
+ });
1045
+ /**
1046
+ * The contents of a resource, embedded into a prompt or tool call result.
1047
+ */
1048
+ var EmbeddedResourceSchema = object({
1049
+ type: literal("resource"),
1050
+ resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
1051
+ annotations: AnnotationsSchema.optional(),
1052
+ _meta: record(string(), unknown()).optional()
1053
+ });
1054
+ /**
1055
+ * A content block that can be used in prompts and tool results.
1056
+ */
1057
+ var ContentBlockSchema = union([
1058
+ TextContentSchema,
1059
+ ImageContentSchema,
1060
+ AudioContentSchema,
1061
+ ResourceSchema.extend({ type: literal("resource_link") }),
1062
+ EmbeddedResourceSchema
1063
+ ]);
1064
+ /**
1065
+ * Describes a message returned as part of a prompt.
1066
+ */
1067
+ var PromptMessageSchema = object({
1068
+ role: RoleSchema,
1069
+ content: ContentBlockSchema
1070
+ });
1071
+ /**
1072
+ * The server's response to a prompts/get request from the client.
1073
+ */
1074
+ var GetPromptResultSchema = ResultSchema.extend({
1075
+ description: string().optional(),
1076
+ messages: array(PromptMessageSchema)
1077
+ });
1078
+ /**
1079
+ * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.
1080
+ */
1081
+ var PromptListChangedNotificationSchema = NotificationSchema.extend({
1082
+ method: literal("notifications/prompts/list_changed"),
1083
+ params: NotificationsParamsSchema.optional()
1084
+ });
1085
+ /**
1086
+ * Additional properties describing a Tool to clients.
1087
+ *
1088
+ * NOTE: all properties in ToolAnnotations are **hints**.
1089
+ * They are not guaranteed to provide a faithful description of
1090
+ * tool behavior (including descriptive properties like `title`).
1091
+ *
1092
+ * Clients should never make tool use decisions based on ToolAnnotations
1093
+ * received from untrusted servers.
1094
+ */
1095
+ var ToolAnnotationsSchema = object({
1096
+ title: string().optional(),
1097
+ readOnlyHint: boolean().optional(),
1098
+ destructiveHint: boolean().optional(),
1099
+ idempotentHint: boolean().optional(),
1100
+ openWorldHint: boolean().optional()
1101
+ });
1102
+ /**
1103
+ * Execution-related properties for a tool.
1104
+ */
1105
+ var ToolExecutionSchema = object({ taskSupport: _enum([
1106
+ "required",
1107
+ "optional",
1108
+ "forbidden"
1109
+ ]).optional() });
1110
+ /**
1111
+ * Definition for a tool the client can call.
1112
+ */
1113
+ var ToolSchema = object({
1114
+ ...BaseMetadataSchema.shape,
1115
+ ...IconsSchema.shape,
1116
+ description: string().optional(),
1117
+ inputSchema: object({
1118
+ type: literal("object"),
1119
+ properties: record(string(), AssertObjectSchema).optional(),
1120
+ required: array(string()).optional()
1121
+ }).catchall(unknown()),
1122
+ outputSchema: object({
1123
+ type: literal("object"),
1124
+ properties: record(string(), AssertObjectSchema).optional(),
1125
+ required: array(string()).optional()
1126
+ }).catchall(unknown()).optional(),
1127
+ annotations: ToolAnnotationsSchema.optional(),
1128
+ execution: ToolExecutionSchema.optional(),
1129
+ _meta: record(string(), unknown()).optional()
1130
+ });
1131
+ /**
1132
+ * Sent from the client to request a list of tools the server has.
1133
+ */
1134
+ var ListToolsRequestSchema$1 = PaginatedRequestSchema.extend({ method: literal("tools/list") });
1135
+ /**
1136
+ * The server's response to a tools/list request from the client.
1137
+ */
1138
+ var ListToolsResultSchema = PaginatedResultSchema.extend({ tools: array(ToolSchema) });
1139
+ /**
1140
+ * The server's response to a tool call.
1141
+ */
1142
+ var CallToolResultSchema = ResultSchema.extend({
1143
+ content: array(ContentBlockSchema).default([]),
1144
+ structuredContent: record(string(), unknown()).optional(),
1145
+ isError: boolean().optional()
1146
+ });
1147
+ CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() }));
1148
+ /**
1149
+ * Parameters for a `tools/call` request.
1150
+ */
1151
+ var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
1152
+ name: string(),
1153
+ arguments: record(string(), unknown()).optional()
1154
+ });
1155
+ /**
1156
+ * Used by the client to invoke a tool provided by the server.
1157
+ */
1158
+ var CallToolRequestSchema$1 = RequestSchema.extend({
1159
+ method: literal("tools/call"),
1160
+ params: CallToolRequestParamsSchema
1161
+ });
1162
+ /**
1163
+ * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.
1164
+ */
1165
+ var ToolListChangedNotificationSchema = NotificationSchema.extend({
1166
+ method: literal("notifications/tools/list_changed"),
1167
+ params: NotificationsParamsSchema.optional()
1168
+ });
1169
+ object({
1170
+ autoRefresh: boolean().default(true),
1171
+ debounceMs: number().int().nonnegative().default(300)
1172
+ });
1173
+ /**
1174
+ * The severity of a log message.
1175
+ */
1176
+ var LoggingLevelSchema = _enum([
1177
+ "debug",
1178
+ "info",
1179
+ "notice",
1180
+ "warning",
1181
+ "error",
1182
+ "critical",
1183
+ "alert",
1184
+ "emergency"
1185
+ ]);
1186
+ /**
1187
+ * Parameters for a `logging/setLevel` request.
1188
+ */
1189
+ var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema });
1190
+ /**
1191
+ * A request from the client to the server, to enable or adjust logging.
1192
+ */
1193
+ var SetLevelRequestSchema = RequestSchema.extend({
1194
+ method: literal("logging/setLevel"),
1195
+ params: SetLevelRequestParamsSchema
1196
+ });
1197
+ /**
1198
+ * Parameters for a `notifications/message` notification.
1199
+ */
1200
+ var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
1201
+ level: LoggingLevelSchema,
1202
+ logger: string().optional(),
1203
+ data: unknown()
1204
+ });
1205
+ /**
1206
+ * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.
1207
+ */
1208
+ var LoggingMessageNotificationSchema = NotificationSchema.extend({
1209
+ method: literal("notifications/message"),
1210
+ params: LoggingMessageNotificationParamsSchema
1211
+ });
1212
+ /**
1213
+ * The server's preferences for model selection, requested of the client during sampling.
1214
+ */
1215
+ var ModelPreferencesSchema = object({
1216
+ hints: array(object({ name: string().optional() })).optional(),
1217
+ costPriority: number().min(0).max(1).optional(),
1218
+ speedPriority: number().min(0).max(1).optional(),
1219
+ intelligencePriority: number().min(0).max(1).optional()
1220
+ });
1221
+ /**
1222
+ * Controls tool usage behavior in sampling requests.
1223
+ */
1224
+ var ToolChoiceSchema = object({ mode: _enum([
1225
+ "auto",
1226
+ "required",
1227
+ "none"
1228
+ ]).optional() });
1229
+ /**
1230
+ * The result of a tool execution, provided by the user (server).
1231
+ * Represents the outcome of invoking a tool requested via ToolUseContent.
1232
+ */
1233
+ var ToolResultContentSchema = object({
1234
+ type: literal("tool_result"),
1235
+ toolUseId: string().describe("The unique identifier for the corresponding tool call."),
1236
+ content: array(ContentBlockSchema).default([]),
1237
+ structuredContent: object({}).loose().optional(),
1238
+ isError: boolean().optional(),
1239
+ _meta: record(string(), unknown()).optional()
1240
+ });
1241
+ /**
1242
+ * Basic content types for sampling responses (without tool use).
1243
+ * Used for backwards-compatible CreateMessageResult when tools are not used.
1244
+ */
1245
+ var SamplingContentSchema = discriminatedUnion("type", [
1246
+ TextContentSchema,
1247
+ ImageContentSchema,
1248
+ AudioContentSchema
1249
+ ]);
1250
+ /**
1251
+ * Content block types allowed in sampling messages.
1252
+ * This includes text, image, audio, tool use requests, and tool results.
1253
+ */
1254
+ var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
1255
+ TextContentSchema,
1256
+ ImageContentSchema,
1257
+ AudioContentSchema,
1258
+ ToolUseContentSchema,
1259
+ ToolResultContentSchema
1260
+ ]);
1261
+ /**
1262
+ * Describes a message issued to or received from an LLM API.
1263
+ */
1264
+ var SamplingMessageSchema = object({
1265
+ role: RoleSchema,
1266
+ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
1267
+ _meta: record(string(), unknown()).optional()
1268
+ });
1269
+ /**
1270
+ * Parameters for a `sampling/createMessage` request.
1271
+ */
1272
+ var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
1273
+ messages: array(SamplingMessageSchema),
1274
+ modelPreferences: ModelPreferencesSchema.optional(),
1275
+ systemPrompt: string().optional(),
1276
+ includeContext: _enum([
1277
+ "none",
1278
+ "thisServer",
1279
+ "allServers"
1280
+ ]).optional(),
1281
+ temperature: number().optional(),
1282
+ maxTokens: number().int(),
1283
+ stopSequences: array(string()).optional(),
1284
+ metadata: AssertObjectSchema.optional(),
1285
+ tools: array(ToolSchema).optional(),
1286
+ toolChoice: ToolChoiceSchema.optional()
1287
+ });
1288
+ /**
1289
+ * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.
1290
+ */
1291
+ var CreateMessageRequestSchema = RequestSchema.extend({
1292
+ method: literal("sampling/createMessage"),
1293
+ params: CreateMessageRequestParamsSchema
1294
+ });
1295
+ /**
1296
+ * The client's response to a sampling/create_message request from the server.
1297
+ * This is the backwards-compatible version that returns single content (no arrays).
1298
+ * Used when the request does not include tools.
1299
+ */
1300
+ var CreateMessageResultSchema = ResultSchema.extend({
1301
+ model: string(),
1302
+ stopReason: optional(_enum([
1303
+ "endTurn",
1304
+ "stopSequence",
1305
+ "maxTokens"
1306
+ ]).or(string())),
1307
+ role: RoleSchema,
1308
+ content: SamplingContentSchema
1309
+ });
1310
+ /**
1311
+ * The client's response to a sampling/create_message request when tools were provided.
1312
+ * This version supports array content for tool use flows.
1313
+ */
1314
+ var CreateMessageResultWithToolsSchema = ResultSchema.extend({
1315
+ model: string(),
1316
+ stopReason: optional(_enum([
1317
+ "endTurn",
1318
+ "stopSequence",
1319
+ "maxTokens",
1320
+ "toolUse"
1321
+ ]).or(string())),
1322
+ role: RoleSchema,
1323
+ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
1324
+ });
1325
+ /**
1326
+ * Primitive schema definition for boolean fields.
1327
+ */
1328
+ var BooleanSchemaSchema = object({
1329
+ type: literal("boolean"),
1330
+ title: string().optional(),
1331
+ description: string().optional(),
1332
+ default: boolean().optional()
1333
+ });
1334
+ /**
1335
+ * Primitive schema definition for string fields.
1336
+ */
1337
+ var StringSchemaSchema = object({
1338
+ type: literal("string"),
1339
+ title: string().optional(),
1340
+ description: string().optional(),
1341
+ minLength: number().optional(),
1342
+ maxLength: number().optional(),
1343
+ format: _enum([
1344
+ "email",
1345
+ "uri",
1346
+ "date",
1347
+ "date-time"
1348
+ ]).optional(),
1349
+ default: string().optional()
1350
+ });
1351
+ /**
1352
+ * Primitive schema definition for number fields.
1353
+ */
1354
+ var NumberSchemaSchema = object({
1355
+ type: _enum(["number", "integer"]),
1356
+ title: string().optional(),
1357
+ description: string().optional(),
1358
+ minimum: number().optional(),
1359
+ maximum: number().optional(),
1360
+ default: number().optional()
1361
+ });
1362
+ /**
1363
+ * Schema for single-selection enumeration without display titles for options.
1364
+ */
1365
+ var UntitledSingleSelectEnumSchemaSchema = object({
1366
+ type: literal("string"),
1367
+ title: string().optional(),
1368
+ description: string().optional(),
1369
+ enum: array(string()),
1370
+ default: string().optional()
1371
+ });
1372
+ /**
1373
+ * Schema for single-selection enumeration with display titles for each option.
1374
+ */
1375
+ var TitledSingleSelectEnumSchemaSchema = object({
1376
+ type: literal("string"),
1377
+ title: string().optional(),
1378
+ description: string().optional(),
1379
+ oneOf: array(object({
1380
+ const: string(),
1381
+ title: string()
1382
+ })),
1383
+ default: string().optional()
1384
+ });
1385
+ /**
1386
+ * Union of all primitive schema definitions.
1387
+ */
1388
+ var PrimitiveSchemaDefinitionSchema = union([
1389
+ union([
1390
+ object({
1391
+ type: literal("string"),
1392
+ title: string().optional(),
1393
+ description: string().optional(),
1394
+ enum: array(string()),
1395
+ enumNames: array(string()).optional(),
1396
+ default: string().optional()
1397
+ }),
1398
+ union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]),
1399
+ union([object({
1400
+ type: literal("array"),
1401
+ title: string().optional(),
1402
+ description: string().optional(),
1403
+ minItems: number().optional(),
1404
+ maxItems: number().optional(),
1405
+ items: object({
1406
+ type: literal("string"),
1407
+ enum: array(string())
1408
+ }),
1409
+ default: array(string()).optional()
1410
+ }), object({
1411
+ type: literal("array"),
1412
+ title: string().optional(),
1413
+ description: string().optional(),
1414
+ minItems: number().optional(),
1415
+ maxItems: number().optional(),
1416
+ items: object({ anyOf: array(object({
1417
+ const: string(),
1418
+ title: string()
1419
+ })) }),
1420
+ default: array(string()).optional()
1421
+ })])
1422
+ ]),
1423
+ BooleanSchemaSchema,
1424
+ StringSchemaSchema,
1425
+ NumberSchemaSchema
1426
+ ]);
1427
+ /**
1428
+ * The parameters for a request to elicit additional information from the user via the client.
1429
+ */
1430
+ var ElicitRequestParamsSchema = union([TaskAugmentedRequestParamsSchema.extend({
1431
+ mode: literal("form").optional(),
1432
+ message: string(),
1433
+ requestedSchema: object({
1434
+ type: literal("object"),
1435
+ properties: record(string(), PrimitiveSchemaDefinitionSchema),
1436
+ required: array(string()).optional()
1437
+ })
1438
+ }), TaskAugmentedRequestParamsSchema.extend({
1439
+ mode: literal("url"),
1440
+ message: string(),
1441
+ elicitationId: string(),
1442
+ url: string().url()
1443
+ })]);
1444
+ /**
1445
+ * A request from the server to elicit user input via the client.
1446
+ * The client should present the message and form fields to the user (form mode)
1447
+ * or navigate to a URL (URL mode).
1448
+ */
1449
+ var ElicitRequestSchema = RequestSchema.extend({
1450
+ method: literal("elicitation/create"),
1451
+ params: ElicitRequestParamsSchema
1452
+ });
1453
+ /**
1454
+ * Parameters for a `notifications/elicitation/complete` notification.
1455
+ *
1456
+ * @category notifications/elicitation/complete
1457
+ */
1458
+ var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: string() });
1459
+ /**
1460
+ * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.
1461
+ *
1462
+ * @category notifications/elicitation/complete
1463
+ */
1464
+ var ElicitationCompleteNotificationSchema = NotificationSchema.extend({
1465
+ method: literal("notifications/elicitation/complete"),
1466
+ params: ElicitationCompleteNotificationParamsSchema
1467
+ });
1468
+ /**
1469
+ * The client's response to an elicitation/create request from the server.
1470
+ */
1471
+ var ElicitResultSchema = ResultSchema.extend({
1472
+ action: _enum([
1473
+ "accept",
1474
+ "decline",
1475
+ "cancel"
1476
+ ]),
1477
+ content: preprocess((val) => val === null ? void 0 : val, record(string(), union([
1478
+ string(),
1479
+ number(),
1480
+ boolean(),
1481
+ array(string())
1482
+ ])).optional())
1483
+ });
1484
+ /**
1485
+ * A reference to a resource or resource template definition.
1486
+ */
1487
+ var ResourceTemplateReferenceSchema = object({
1488
+ type: literal("ref/resource"),
1489
+ uri: string()
1490
+ });
1491
+ /**
1492
+ * Identifies a prompt.
1493
+ */
1494
+ var PromptReferenceSchema = object({
1495
+ type: literal("ref/prompt"),
1496
+ name: string()
1497
+ });
1498
+ /**
1499
+ * Parameters for a `completion/complete` request.
1500
+ */
1501
+ var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
1502
+ ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
1503
+ argument: object({
1504
+ name: string(),
1505
+ value: string()
1506
+ }),
1507
+ context: object({ arguments: record(string(), string()).optional() }).optional()
1508
+ });
1509
+ /**
1510
+ * A request from the client to the server, to ask for completion options.
1511
+ */
1512
+ var CompleteRequestSchema = RequestSchema.extend({
1513
+ method: literal("completion/complete"),
1514
+ params: CompleteRequestParamsSchema
1515
+ });
1516
+ /**
1517
+ * The server's response to a completion/complete request
1518
+ */
1519
+ var CompleteResultSchema = ResultSchema.extend({ completion: looseObject({
1520
+ values: array(string()).max(100),
1521
+ total: optional(number().int()),
1522
+ hasMore: optional(boolean())
1523
+ }) });
1524
+ /**
1525
+ * Represents a root directory or file that the server can operate on.
1526
+ */
1527
+ var RootSchema = object({
1528
+ uri: string().startsWith("file://"),
1529
+ name: string().optional(),
1530
+ _meta: record(string(), unknown()).optional()
1531
+ });
1532
+ /**
1533
+ * Sent from the server to request a list of root URIs from the client.
1534
+ */
1535
+ var ListRootsRequestSchema = RequestSchema.extend({
1536
+ method: literal("roots/list"),
1537
+ params: BaseRequestParamsSchema.optional()
1538
+ });
1539
+ /**
1540
+ * The client's response to a roots/list request from the server.
1541
+ */
1542
+ var ListRootsResultSchema = ResultSchema.extend({ roots: array(RootSchema) });
1543
+ /**
1544
+ * A notification from the client to the server, informing it that the list of roots has changed.
1545
+ */
1546
+ var RootsListChangedNotificationSchema = NotificationSchema.extend({
1547
+ method: literal("notifications/roots/list_changed"),
1548
+ params: NotificationsParamsSchema.optional()
1549
+ });
1550
+ union([
1551
+ PingRequestSchema,
1552
+ InitializeRequestSchema,
1553
+ CompleteRequestSchema,
1554
+ SetLevelRequestSchema,
1555
+ GetPromptRequestSchema$1,
1556
+ ListPromptsRequestSchema$1,
1557
+ ListResourcesRequestSchema$1,
1558
+ ListResourceTemplatesRequestSchema$1,
1559
+ ReadResourceRequestSchema$1,
1560
+ SubscribeRequestSchema,
1561
+ UnsubscribeRequestSchema,
1562
+ CallToolRequestSchema$1,
1563
+ ListToolsRequestSchema$1,
1564
+ GetTaskRequestSchema,
1565
+ GetTaskPayloadRequestSchema,
1566
+ ListTasksRequestSchema,
1567
+ CancelTaskRequestSchema
1568
+ ]);
1569
+ union([
1570
+ CancelledNotificationSchema,
1571
+ ProgressNotificationSchema,
1572
+ InitializedNotificationSchema,
1573
+ RootsListChangedNotificationSchema,
1574
+ TaskStatusNotificationSchema
1575
+ ]);
1576
+ union([
1577
+ EmptyResultSchema,
1578
+ CreateMessageResultSchema,
1579
+ CreateMessageResultWithToolsSchema,
1580
+ ElicitResultSchema,
1581
+ ListRootsResultSchema,
1582
+ GetTaskResultSchema,
1583
+ ListTasksResultSchema,
1584
+ CreateTaskResultSchema
1585
+ ]);
1586
+ union([
1587
+ PingRequestSchema,
1588
+ CreateMessageRequestSchema,
1589
+ ElicitRequestSchema,
1590
+ ListRootsRequestSchema,
1591
+ GetTaskRequestSchema,
1592
+ GetTaskPayloadRequestSchema,
1593
+ ListTasksRequestSchema,
1594
+ CancelTaskRequestSchema
1595
+ ]);
1596
+ union([
1597
+ CancelledNotificationSchema,
1598
+ ProgressNotificationSchema,
1599
+ LoggingMessageNotificationSchema,
1600
+ ResourceUpdatedNotificationSchema,
1601
+ ResourceListChangedNotificationSchema,
1602
+ ToolListChangedNotificationSchema,
1603
+ PromptListChangedNotificationSchema,
1604
+ TaskStatusNotificationSchema,
1605
+ ElicitationCompleteNotificationSchema
1606
+ ]);
1607
+ union([
1608
+ EmptyResultSchema,
1609
+ InitializeResultSchema,
1610
+ CompleteResultSchema,
1611
+ GetPromptResultSchema,
1612
+ ListPromptsResultSchema,
1613
+ ListResourcesResultSchema,
1614
+ ListResourceTemplatesResultSchema,
1615
+ ReadResourceResultSchema,
1616
+ CallToolResultSchema,
1617
+ ListToolsResultSchema,
1618
+ GetTaskResultSchema,
1619
+ ListTasksResultSchema,
1620
+ CreateTaskResultSchema
1621
+ ]);
1622
+ //#endregion
1623
+ //#region ../../node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js
1624
+ /**
1625
+ * Web Standards Streamable HTTP Server Transport
1626
+ *
1627
+ * This is the core transport implementation using Web Standard APIs (Request, Response, ReadableStream).
1628
+ * It can run on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc.
1629
+ *
1630
+ * For Node.js Express/HTTP compatibility, use `StreamableHTTPServerTransport` which wraps this transport.
1631
+ */
1632
+ /**
1633
+ * Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification
1634
+ * using Web Standard APIs (Request, Response, ReadableStream).
1635
+ *
1636
+ * This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc.
1637
+ *
1638
+ * Usage example:
1639
+ *
1640
+ * ```typescript
1641
+ * // Stateful mode - server sets the session ID
1642
+ * const statefulTransport = new WebStandardStreamableHTTPServerTransport({
1643
+ * sessionIdGenerator: () => crypto.randomUUID(),
1644
+ * });
1645
+ *
1646
+ * // Stateless mode - explicitly set session ID to undefined
1647
+ * const statelessTransport = new WebStandardStreamableHTTPServerTransport({
1648
+ * sessionIdGenerator: undefined,
1649
+ * });
1650
+ *
1651
+ * // Hono.js usage
1652
+ * app.all('/mcp', async (c) => {
1653
+ * return transport.handleRequest(c.req.raw);
1654
+ * });
1655
+ *
1656
+ * // Cloudflare Workers usage
1657
+ * export default {
1658
+ * async fetch(request: Request): Promise<Response> {
1659
+ * return transport.handleRequest(request);
1660
+ * }
1661
+ * };
1662
+ * ```
1663
+ *
1664
+ * In stateful mode:
1665
+ * - Session ID is generated and included in response headers
1666
+ * - Session ID is always included in initialization responses
1667
+ * - Requests with invalid session IDs are rejected with 404 Not Found
1668
+ * - Non-initialization requests without a session ID are rejected with 400 Bad Request
1669
+ * - State is maintained in-memory (connections, message history)
1670
+ *
1671
+ * In stateless mode:
1672
+ * - No Session ID is included in any responses
1673
+ * - No session validation is performed
1674
+ */
1675
+ var WebStandardStreamableHTTPServerTransport = class {
1676
+ constructor(options = {}) {
1677
+ this._started = false;
1678
+ this._hasHandledRequest = false;
1679
+ this._streamMapping = /* @__PURE__ */ new Map();
1680
+ this._requestToStreamMapping = /* @__PURE__ */ new Map();
1681
+ this._requestResponseMap = /* @__PURE__ */ new Map();
1682
+ this._initialized = false;
1683
+ this._enableJsonResponse = false;
1684
+ this._standaloneSseStreamId = "_GET_stream";
1685
+ this.sessionIdGenerator = options.sessionIdGenerator;
1686
+ this._enableJsonResponse = options.enableJsonResponse ?? false;
1687
+ this._eventStore = options.eventStore;
1688
+ this._onsessioninitialized = options.onsessioninitialized;
1689
+ this._onsessionclosed = options.onsessionclosed;
1690
+ this._allowedHosts = options.allowedHosts;
1691
+ this._allowedOrigins = options.allowedOrigins;
1692
+ this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false;
1693
+ this._retryInterval = options.retryInterval;
1694
+ }
1695
+ /**
1696
+ * Starts the transport. This is required by the Transport interface but is a no-op
1697
+ * for the Streamable HTTP transport as connections are managed per-request.
1698
+ */
1699
+ async start() {
1700
+ if (this._started) throw new Error("Transport already started");
1701
+ this._started = true;
1702
+ }
1703
+ /**
1704
+ * Helper to create a JSON error response
1705
+ */
1706
+ createJsonErrorResponse(status, code, message, options) {
1707
+ const error = {
1708
+ code,
1709
+ message
1710
+ };
1711
+ if (options?.data !== void 0) error.data = options.data;
1712
+ return new Response(JSON.stringify({
1713
+ jsonrpc: "2.0",
1714
+ error,
1715
+ id: null
1716
+ }), {
1717
+ status,
1718
+ headers: {
1719
+ "Content-Type": "application/json",
1720
+ ...options?.headers
1721
+ }
1722
+ });
1723
+ }
1724
+ /**
1725
+ * Validates request headers for DNS rebinding protection.
1726
+ * @returns Error response if validation fails, undefined if validation passes.
1727
+ */
1728
+ validateRequestHeaders(req) {
1729
+ if (!this._enableDnsRebindingProtection) return;
1730
+ if (this._allowedHosts && this._allowedHosts.length > 0) {
1731
+ const hostHeader = req.headers.get("host");
1732
+ if (!hostHeader || !this._allowedHosts.includes(hostHeader)) {
1733
+ const error = `Invalid Host header: ${hostHeader}`;
1734
+ this.onerror?.(new Error(error));
1735
+ return this.createJsonErrorResponse(403, -32e3, error);
1736
+ }
1737
+ }
1738
+ if (this._allowedOrigins && this._allowedOrigins.length > 0) {
1739
+ const originHeader = req.headers.get("origin");
1740
+ if (originHeader && !this._allowedOrigins.includes(originHeader)) {
1741
+ const error = `Invalid Origin header: ${originHeader}`;
1742
+ this.onerror?.(new Error(error));
1743
+ return this.createJsonErrorResponse(403, -32e3, error);
1744
+ }
1745
+ }
1746
+ }
1747
+ /**
1748
+ * Handles an incoming HTTP request, whether GET, POST, or DELETE
1749
+ * Returns a Response object (Web Standard)
1750
+ */
1751
+ async handleRequest(req, options) {
1752
+ if (!this.sessionIdGenerator && this._hasHandledRequest) throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");
1753
+ this._hasHandledRequest = true;
1754
+ const validationError = this.validateRequestHeaders(req);
1755
+ if (validationError) return validationError;
1756
+ switch (req.method) {
1757
+ case "POST": return this.handlePostRequest(req, options);
1758
+ case "GET": return this.handleGetRequest(req);
1759
+ case "DELETE": return this.handleDeleteRequest(req);
1760
+ default: return this.handleUnsupportedRequest();
1761
+ }
1762
+ }
1763
+ /**
1764
+ * Writes a priming event to establish resumption capability.
1765
+ * Only sends if eventStore is configured (opt-in for resumability) and
1766
+ * the client's protocol version supports empty SSE data (>= 2025-11-25).
1767
+ */
1768
+ async writePrimingEvent(controller, encoder, streamId, protocolVersion) {
1769
+ if (!this._eventStore) return;
1770
+ if (protocolVersion < "2025-11-25") return;
1771
+ const primingEventId = await this._eventStore.storeEvent(streamId, {});
1772
+ let primingEvent = `id: ${primingEventId}\ndata: \n\n`;
1773
+ if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`;
1774
+ controller.enqueue(encoder.encode(primingEvent));
1775
+ }
1776
+ /**
1777
+ * Handles GET requests for SSE stream
1778
+ */
1779
+ async handleGetRequest(req) {
1780
+ if (!req.headers.get("accept")?.includes("text/event-stream")) {
1781
+ this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream"));
1782
+ return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream");
1783
+ }
1784
+ const sessionError = this.validateSession(req);
1785
+ if (sessionError) return sessionError;
1786
+ const protocolError = this.validateProtocolVersion(req);
1787
+ if (protocolError) return protocolError;
1788
+ if (this._eventStore) {
1789
+ const lastEventId = req.headers.get("last-event-id");
1790
+ if (lastEventId) return this.replayEvents(lastEventId);
1791
+ }
1792
+ if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) {
1793
+ this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session"));
1794
+ return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session");
1795
+ }
1796
+ const encoder = new TextEncoder();
1797
+ let streamController;
1798
+ const readable = new ReadableStream({
1799
+ start: (controller) => {
1800
+ streamController = controller;
1801
+ },
1802
+ cancel: () => {
1803
+ this._streamMapping.delete(this._standaloneSseStreamId);
1804
+ }
1805
+ });
1806
+ const headers = {
1807
+ "Content-Type": "text/event-stream",
1808
+ "Cache-Control": "no-cache, no-transform",
1809
+ Connection: "keep-alive"
1810
+ };
1811
+ if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId;
1812
+ this._streamMapping.set(this._standaloneSseStreamId, {
1813
+ controller: streamController,
1814
+ encoder,
1815
+ cleanup: () => {
1816
+ this._streamMapping.delete(this._standaloneSseStreamId);
1817
+ try {
1818
+ streamController.close();
1819
+ } catch {}
1820
+ }
1821
+ });
1822
+ return new Response(readable, { headers });
1823
+ }
1824
+ /**
1825
+ * Replays events that would have been sent after the specified event ID
1826
+ * Only used when resumability is enabled
1827
+ */
1828
+ async replayEvents(lastEventId) {
1829
+ if (!this._eventStore) {
1830
+ this.onerror?.(/* @__PURE__ */ new Error("Event store not configured"));
1831
+ return this.createJsonErrorResponse(400, -32e3, "Event store not configured");
1832
+ }
1833
+ try {
1834
+ let streamId;
1835
+ if (this._eventStore.getStreamIdForEventId) {
1836
+ streamId = await this._eventStore.getStreamIdForEventId(lastEventId);
1837
+ if (!streamId) {
1838
+ this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format"));
1839
+ return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format");
1840
+ }
1841
+ if (this._streamMapping.get(streamId) !== void 0) {
1842
+ this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection"));
1843
+ return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection");
1844
+ }
1845
+ }
1846
+ const headers = {
1847
+ "Content-Type": "text/event-stream",
1848
+ "Cache-Control": "no-cache, no-transform",
1849
+ Connection: "keep-alive"
1850
+ };
1851
+ if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId;
1852
+ const encoder = new TextEncoder();
1853
+ let streamController;
1854
+ const readable = new ReadableStream({
1855
+ start: (controller) => {
1856
+ streamController = controller;
1857
+ },
1858
+ cancel: () => {}
1859
+ });
1860
+ const replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => {
1861
+ if (!this.writeSSEEvent(streamController, encoder, message, eventId)) {
1862
+ this.onerror?.(/* @__PURE__ */ new Error("Failed replay events"));
1863
+ try {
1864
+ streamController.close();
1865
+ } catch {}
1866
+ }
1867
+ } });
1868
+ this._streamMapping.set(replayedStreamId, {
1869
+ controller: streamController,
1870
+ encoder,
1871
+ cleanup: () => {
1872
+ this._streamMapping.delete(replayedStreamId);
1873
+ try {
1874
+ streamController.close();
1875
+ } catch {}
1876
+ }
1877
+ });
1878
+ return new Response(readable, { headers });
1879
+ } catch (error) {
1880
+ this.onerror?.(error);
1881
+ return this.createJsonErrorResponse(500, -32e3, "Error replaying events");
1882
+ }
1883
+ }
1884
+ /**
1885
+ * Writes an event to an SSE stream via controller with proper formatting
1886
+ */
1887
+ writeSSEEvent(controller, encoder, message, eventId) {
1888
+ try {
1889
+ let eventData = `event: message\n`;
1890
+ if (eventId) eventData += `id: ${eventId}\n`;
1891
+ eventData += `data: ${JSON.stringify(message)}\n\n`;
1892
+ controller.enqueue(encoder.encode(eventData));
1893
+ return true;
1894
+ } catch (error) {
1895
+ this.onerror?.(error);
1896
+ return false;
1897
+ }
1898
+ }
1899
+ /**
1900
+ * Handles unsupported requests (PUT, PATCH, etc.)
1901
+ */
1902
+ handleUnsupportedRequest() {
1903
+ this.onerror?.(/* @__PURE__ */ new Error("Method not allowed."));
1904
+ return new Response(JSON.stringify({
1905
+ jsonrpc: "2.0",
1906
+ error: {
1907
+ code: -32e3,
1908
+ message: "Method not allowed."
1909
+ },
1910
+ id: null
1911
+ }), {
1912
+ status: 405,
1913
+ headers: {
1914
+ Allow: "GET, POST, DELETE",
1915
+ "Content-Type": "application/json"
1916
+ }
1917
+ });
1918
+ }
1919
+ /**
1920
+ * Handles POST requests containing JSON-RPC messages
1921
+ */
1922
+ async handlePostRequest(req, options) {
1923
+ try {
1924
+ const acceptHeader = req.headers.get("accept");
1925
+ if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
1926
+ this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream"));
1927
+ return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream");
1928
+ }
1929
+ const ct = req.headers.get("content-type");
1930
+ if (!ct || !ct.includes("application/json")) {
1931
+ this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json"));
1932
+ return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json");
1933
+ }
1934
+ const requestInfo = {
1935
+ headers: Object.fromEntries(req.headers.entries()),
1936
+ url: new URL(req.url)
1937
+ };
1938
+ let rawMessage;
1939
+ if (options?.parsedBody !== void 0) rawMessage = options.parsedBody;
1940
+ else try {
1941
+ rawMessage = await req.json();
1942
+ } catch {
1943
+ this.onerror?.(/* @__PURE__ */ new Error("Parse error: Invalid JSON"));
1944
+ return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON");
1945
+ }
1946
+ let messages;
1947
+ try {
1948
+ if (Array.isArray(rawMessage)) messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
1949
+ else messages = [JSONRPCMessageSchema.parse(rawMessage)];
1950
+ } catch {
1951
+ this.onerror?.(/* @__PURE__ */ new Error("Parse error: Invalid JSON-RPC message"));
1952
+ return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message");
1953
+ }
1954
+ const isInitializationRequest = messages.some(isInitializeRequest);
1955
+ if (isInitializationRequest) {
1956
+ if (this._initialized && this.sessionId !== void 0) {
1957
+ this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized"));
1958
+ return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized");
1959
+ }
1960
+ if (messages.length > 1) {
1961
+ this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed"));
1962
+ return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed");
1963
+ }
1964
+ this.sessionId = this.sessionIdGenerator?.();
1965
+ this._initialized = true;
1966
+ if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId));
1967
+ }
1968
+ if (!isInitializationRequest) {
1969
+ const sessionError = this.validateSession(req);
1970
+ if (sessionError) return sessionError;
1971
+ const protocolError = this.validateProtocolVersion(req);
1972
+ if (protocolError) return protocolError;
1973
+ }
1974
+ if (!messages.some(isJSONRPCRequest)) {
1975
+ for (const message of messages) this.onmessage?.(message, {
1976
+ authInfo: options?.authInfo,
1977
+ requestInfo
1978
+ });
1979
+ return new Response(null, { status: 202 });
1980
+ }
1981
+ const streamId = crypto.randomUUID();
1982
+ const initRequest = messages.find((m) => isInitializeRequest(m));
1983
+ const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? "2025-03-26";
1984
+ if (this._enableJsonResponse) return new Promise((resolve) => {
1985
+ this._streamMapping.set(streamId, {
1986
+ resolveJson: resolve,
1987
+ cleanup: () => {
1988
+ this._streamMapping.delete(streamId);
1989
+ }
1990
+ });
1991
+ for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId);
1992
+ for (const message of messages) this.onmessage?.(message, {
1993
+ authInfo: options?.authInfo,
1994
+ requestInfo
1995
+ });
1996
+ });
1997
+ const encoder = new TextEncoder();
1998
+ let streamController;
1999
+ const readable = new ReadableStream({
2000
+ start: (controller) => {
2001
+ streamController = controller;
2002
+ },
2003
+ cancel: () => {
2004
+ this._streamMapping.delete(streamId);
2005
+ }
2006
+ });
2007
+ const headers = {
2008
+ "Content-Type": "text/event-stream",
2009
+ "Cache-Control": "no-cache",
2010
+ Connection: "keep-alive"
2011
+ };
2012
+ if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId;
2013
+ for (const message of messages) if (isJSONRPCRequest(message)) {
2014
+ this._streamMapping.set(streamId, {
2015
+ controller: streamController,
2016
+ encoder,
2017
+ cleanup: () => {
2018
+ this._streamMapping.delete(streamId);
2019
+ try {
2020
+ streamController.close();
2021
+ } catch {}
2022
+ }
2023
+ });
2024
+ this._requestToStreamMapping.set(message.id, streamId);
2025
+ }
2026
+ await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion);
2027
+ for (const message of messages) {
2028
+ let closeSSEStream;
2029
+ let closeStandaloneSSEStream;
2030
+ if (isJSONRPCRequest(message) && this._eventStore && clientProtocolVersion >= "2025-11-25") {
2031
+ closeSSEStream = () => {
2032
+ this.closeSSEStream(message.id);
2033
+ };
2034
+ closeStandaloneSSEStream = () => {
2035
+ this.closeStandaloneSSEStream();
2036
+ };
2037
+ }
2038
+ this.onmessage?.(message, {
2039
+ authInfo: options?.authInfo,
2040
+ requestInfo,
2041
+ closeSSEStream,
2042
+ closeStandaloneSSEStream
2043
+ });
2044
+ }
2045
+ return new Response(readable, {
2046
+ status: 200,
2047
+ headers
2048
+ });
2049
+ } catch (error) {
2050
+ this.onerror?.(error);
2051
+ return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) });
2052
+ }
2053
+ }
2054
+ /**
2055
+ * Handles DELETE requests to terminate sessions
2056
+ */
2057
+ async handleDeleteRequest(req) {
2058
+ const sessionError = this.validateSession(req);
2059
+ if (sessionError) return sessionError;
2060
+ const protocolError = this.validateProtocolVersion(req);
2061
+ if (protocolError) return protocolError;
2062
+ await Promise.resolve(this._onsessionclosed?.(this.sessionId));
2063
+ await this.close();
2064
+ return new Response(null, { status: 200 });
2065
+ }
2066
+ /**
2067
+ * Validates session ID for non-initialization requests.
2068
+ * Returns Response error if invalid, undefined otherwise
2069
+ */
2070
+ validateSession(req) {
2071
+ if (this.sessionIdGenerator === void 0) return;
2072
+ if (!this._initialized) {
2073
+ this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized"));
2074
+ return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized");
2075
+ }
2076
+ const sessionId = req.headers.get("mcp-session-id");
2077
+ if (!sessionId) {
2078
+ this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required"));
2079
+ return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required");
2080
+ }
2081
+ if (sessionId !== this.sessionId) {
2082
+ this.onerror?.(/* @__PURE__ */ new Error("Session not found"));
2083
+ return this.createJsonErrorResponse(404, -32001, "Session not found");
2084
+ }
2085
+ }
2086
+ /**
2087
+ * Validates the MCP-Protocol-Version header on incoming requests.
2088
+ *
2089
+ * For initialization: Version negotiation handles unknown versions gracefully
2090
+ * (server responds with its supported version).
2091
+ *
2092
+ * For subsequent requests with MCP-Protocol-Version header:
2093
+ * - Accept if in supported list
2094
+ * - 400 if unsupported
2095
+ *
2096
+ * For HTTP requests without the MCP-Protocol-Version header:
2097
+ * - Accept and default to the version negotiated at initialization
2098
+ */
2099
+ validateProtocolVersion(req) {
2100
+ const protocolVersion = req.headers.get("mcp-protocol-version");
2101
+ if (protocolVersion !== null && !SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) {
2102
+ this.onerror?.(/* @__PURE__ */ new Error(`Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`));
2103
+ return this.createJsonErrorResponse(400, -32e3, `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`);
2104
+ }
2105
+ }
2106
+ async close() {
2107
+ this._streamMapping.forEach(({ cleanup }) => {
2108
+ cleanup();
2109
+ });
2110
+ this._streamMapping.clear();
2111
+ this._requestResponseMap.clear();
2112
+ this.onclose?.();
2113
+ }
2114
+ /**
2115
+ * Close an SSE stream for a specific request, triggering client reconnection.
2116
+ * Use this to implement polling behavior during long-running operations -
2117
+ * client will reconnect after the retry interval specified in the priming event.
2118
+ */
2119
+ closeSSEStream(requestId) {
2120
+ const streamId = this._requestToStreamMapping.get(requestId);
2121
+ if (!streamId) return;
2122
+ const stream = this._streamMapping.get(streamId);
2123
+ if (stream) stream.cleanup();
2124
+ }
2125
+ /**
2126
+ * Close the standalone GET SSE stream, triggering client reconnection.
2127
+ * Use this to implement polling behavior for server-initiated notifications.
2128
+ */
2129
+ closeStandaloneSSEStream() {
2130
+ const stream = this._streamMapping.get(this._standaloneSseStreamId);
2131
+ if (stream) stream.cleanup();
2132
+ }
2133
+ async send(message, options) {
2134
+ let requestId = options?.relatedRequestId;
2135
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id;
2136
+ if (requestId === void 0) {
2137
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
2138
+ let eventId;
2139
+ if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message);
2140
+ const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId);
2141
+ if (standaloneSse === void 0) return;
2142
+ if (standaloneSse.controller && standaloneSse.encoder) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId);
2143
+ return;
2144
+ }
2145
+ const streamId = this._requestToStreamMapping.get(requestId);
2146
+ if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`);
2147
+ const stream = this._streamMapping.get(streamId);
2148
+ if (!this._enableJsonResponse && stream?.controller && stream?.encoder) {
2149
+ let eventId;
2150
+ if (this._eventStore) eventId = await this._eventStore.storeEvent(streamId, message);
2151
+ this.writeSSEEvent(stream.controller, stream.encoder, message, eventId);
2152
+ }
2153
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
2154
+ this._requestResponseMap.set(requestId, message);
2155
+ const relatedIds = Array.from(this._requestToStreamMapping.entries()).filter(([_, sid]) => sid === streamId).map(([id]) => id);
2156
+ if (relatedIds.every((id) => this._requestResponseMap.has(id))) {
2157
+ if (!stream) throw new Error(`No connection established for request ID: ${String(requestId)}`);
2158
+ if (this._enableJsonResponse && stream.resolveJson) {
2159
+ const headers = { "Content-Type": "application/json" };
2160
+ if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId;
2161
+ const responses = relatedIds.map((id) => this._requestResponseMap.get(id));
2162
+ if (responses.length === 1) stream.resolveJson(new Response(JSON.stringify(responses[0]), {
2163
+ status: 200,
2164
+ headers
2165
+ }));
2166
+ else stream.resolveJson(new Response(JSON.stringify(responses), {
2167
+ status: 200,
2168
+ headers
2169
+ }));
2170
+ } else stream.cleanup();
2171
+ for (const id of relatedIds) {
2172
+ this._requestResponseMap.delete(id);
2173
+ this._requestToStreamMapping.delete(id);
2174
+ }
2175
+ }
2176
+ }
2177
+ }
2178
+ };
2179
+ //#endregion
2180
+ //#region ../../node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js
2181
+ /**
2182
+ * Node.js HTTP Streamable HTTP Server Transport
2183
+ *
2184
+ * This is a thin wrapper around `WebStandardStreamableHTTPServerTransport` that provides
2185
+ * compatibility with Node.js HTTP server (IncomingMessage/ServerResponse).
2186
+ *
2187
+ * For web-standard environments (Cloudflare Workers, Deno, Bun), use `WebStandardStreamableHTTPServerTransport` directly.
2188
+ */
2189
+ /**
2190
+ * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.
2191
+ * It supports both SSE streaming and direct HTTP responses.
2192
+ *
2193
+ * This is a wrapper around `WebStandardStreamableHTTPServerTransport` that provides Node.js HTTP compatibility.
2194
+ * It uses the `@hono/node-server` library to convert between Node.js HTTP and Web Standard APIs.
2195
+ *
2196
+ * Usage example:
2197
+ *
2198
+ * ```typescript
2199
+ * // Stateful mode - server sets the session ID
2200
+ * const statefulTransport = new StreamableHTTPServerTransport({
2201
+ * sessionIdGenerator: () => randomUUID(),
2202
+ * });
2203
+ *
2204
+ * // Stateless mode - explicitly set session ID to undefined
2205
+ * const statelessTransport = new StreamableHTTPServerTransport({
2206
+ * sessionIdGenerator: undefined,
2207
+ * });
2208
+ *
2209
+ * // Using with pre-parsed request body
2210
+ * app.post('/mcp', (req, res) => {
2211
+ * transport.handleRequest(req, res, req.body);
2212
+ * });
2213
+ * ```
2214
+ *
2215
+ * In stateful mode:
2216
+ * - Session ID is generated and included in response headers
2217
+ * - Session ID is always included in initialization responses
2218
+ * - Requests with invalid session IDs are rejected with 404 Not Found
2219
+ * - Non-initialization requests without a session ID are rejected with 400 Bad Request
2220
+ * - State is maintained in-memory (connections, message history)
2221
+ *
2222
+ * In stateless mode:
2223
+ * - No Session ID is included in any responses
2224
+ * - No session validation is performed
2225
+ */
2226
+ var StreamableHTTPServerTransport = class {
2227
+ constructor(options = {}) {
2228
+ this._requestContext = /* @__PURE__ */ new WeakMap();
2229
+ this._webStandardTransport = new WebStandardStreamableHTTPServerTransport(options);
2230
+ this._requestListener = getRequestListener(async (webRequest) => {
2231
+ const context = this._requestContext.get(webRequest);
2232
+ return this._webStandardTransport.handleRequest(webRequest, {
2233
+ authInfo: context?.authInfo,
2234
+ parsedBody: context?.parsedBody
2235
+ });
2236
+ }, { overrideGlobalObjects: false });
2237
+ }
2238
+ /**
2239
+ * Gets the session ID for this transport instance.
2240
+ */
2241
+ get sessionId() {
2242
+ return this._webStandardTransport.sessionId;
2243
+ }
2244
+ /**
2245
+ * Sets callback for when the transport is closed.
2246
+ */
2247
+ set onclose(handler) {
2248
+ this._webStandardTransport.onclose = handler;
2249
+ }
2250
+ get onclose() {
2251
+ return this._webStandardTransport.onclose;
2252
+ }
2253
+ /**
2254
+ * Sets callback for transport errors.
2255
+ */
2256
+ set onerror(handler) {
2257
+ this._webStandardTransport.onerror = handler;
2258
+ }
2259
+ get onerror() {
2260
+ return this._webStandardTransport.onerror;
2261
+ }
2262
+ /**
2263
+ * Sets callback for incoming messages.
2264
+ */
2265
+ set onmessage(handler) {
2266
+ this._webStandardTransport.onmessage = handler;
2267
+ }
2268
+ get onmessage() {
2269
+ return this._webStandardTransport.onmessage;
2270
+ }
2271
+ /**
2272
+ * Starts the transport. This is required by the Transport interface but is a no-op
2273
+ * for the Streamable HTTP transport as connections are managed per-request.
2274
+ */
2275
+ async start() {
2276
+ return this._webStandardTransport.start();
2277
+ }
2278
+ /**
2279
+ * Closes the transport and all active connections.
2280
+ */
2281
+ async close() {
2282
+ return this._webStandardTransport.close();
2283
+ }
2284
+ /**
2285
+ * Sends a JSON-RPC message through the transport.
2286
+ */
2287
+ async send(message, options) {
2288
+ return this._webStandardTransport.send(message, options);
2289
+ }
2290
+ /**
2291
+ * Handles an incoming HTTP request, whether GET or POST.
2292
+ *
2293
+ * This method converts Node.js HTTP objects to Web Standard Request/Response
2294
+ * and delegates to the underlying WebStandardStreamableHTTPServerTransport.
2295
+ *
2296
+ * @param req - Node.js IncomingMessage, optionally with auth property from middleware
2297
+ * @param res - Node.js ServerResponse
2298
+ * @param parsedBody - Optional pre-parsed body from body-parser middleware
2299
+ */
2300
+ async handleRequest(req, res, parsedBody) {
2301
+ const authInfo = req.auth;
2302
+ await getRequestListener(async (webRequest) => {
2303
+ return this._webStandardTransport.handleRequest(webRequest, {
2304
+ authInfo,
2305
+ parsedBody
2306
+ });
2307
+ }, { overrideGlobalObjects: false })(req, res);
2308
+ }
2309
+ /**
2310
+ * Close an SSE stream for a specific request, triggering client reconnection.
2311
+ * Use this to implement polling behavior during long-running operations -
2312
+ * client will reconnect after the retry interval specified in the priming event.
2313
+ */
2314
+ closeSSEStream(requestId) {
2315
+ this._webStandardTransport.closeSSEStream(requestId);
2316
+ }
2317
+ /**
2318
+ * Close the standalone GET SSE stream, triggering client reconnection.
2319
+ * Use this to implement polling behavior for server-initiated notifications.
2320
+ */
2321
+ closeStandaloneSSEStream() {
2322
+ this._webStandardTransport.closeStandaloneSSEStream();
2323
+ }
2324
+ };
2325
+ //#endregion
2326
+ //#region src/http.ts
2327
+ var OAUTH_PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource/mcp";
2328
+ /**
2329
+ * JSON-RPC error response
2330
+ */
2331
+ function jsonRpcError(code, message, id = null) {
2332
+ return {
2333
+ jsonrpc: "2.0",
2334
+ error: {
2335
+ code,
2336
+ message
2337
+ },
2338
+ id
2339
+ };
2340
+ }
2341
+ /**
2342
+ * JSON-RPC success response
2343
+ */
2344
+ function jsonRpcSuccess(result, id = null) {
2345
+ return {
2346
+ jsonrpc: "2.0",
2347
+ result,
2348
+ id
2349
+ };
2350
+ }
2351
+ /**
2352
+ * Handle the initialize JSON-RPC method
2353
+ */
2354
+ function handleInitialize() {
2355
+ return {
2356
+ protocolVersion: "2024-11-05",
2357
+ serverInfo: {
2358
+ name: "productive-mcp",
2359
+ version: VERSION
2360
+ },
2361
+ capabilities: {
2362
+ tools: {},
2363
+ prompts: {},
2364
+ resources: {}
2365
+ },
2366
+ instructions: INSTRUCTIONS
2367
+ };
2368
+ }
2369
+ /**
2370
+ * Handle the tools/list JSON-RPC method
2371
+ */
2372
+ function handleToolsList() {
2373
+ return { tools: TOOLS };
2374
+ }
2375
+ /**
2376
+ * Get base URL from event headers
2377
+ */
2378
+ function getBaseUrl(event) {
2379
+ const host = event.req.headers.get("host") || "localhost:3000";
2380
+ return `${event.req.headers.get("x-forwarded-proto") || "http"}://${host}`;
2381
+ }
2382
+ function buildProtectedResourceMetadata(event) {
2383
+ const baseUrl = getBaseUrl(event);
2384
+ return {
2385
+ resource: `${baseUrl}/mcp`,
2386
+ authorization_servers: [baseUrl],
2387
+ scopes_supported: ["productive"],
2388
+ bearer_methods_supported: ["header"]
2389
+ };
2390
+ }
2391
+ function createAuthInfo(token, credentials) {
2392
+ return {
2393
+ token,
2394
+ clientId: credentials.userId || credentials.organizationId,
2395
+ scopes: ["productive"],
2396
+ extra: { credentials }
2397
+ };
2398
+ }
2399
+ function getCredentialsFromAuthInfo(authInfo) {
2400
+ const credentials = authInfo?.extra?.credentials;
2401
+ if (!credentials || typeof credentials !== "object" || !("organizationId" in credentials) || !("apiToken" in credentials) || typeof credentials.organizationId !== "string" || typeof credentials.apiToken !== "string") throw new Error("Authentication required. Provide Bearer token with base64(organizationId:apiToken:userId)");
2402
+ const userId = "userId" in credentials && typeof credentials.userId === "string" ? credentials.userId : void 0;
2403
+ return {
2404
+ organizationId: credentials.organizationId,
2405
+ apiToken: credentials.apiToken,
2406
+ userId
2407
+ };
2408
+ }
2409
+ function createHttpMcpServer() {
2410
+ const server = new Server({
2411
+ name: "productive-mcp",
2412
+ version: VERSION
2413
+ }, {
2414
+ capabilities: {
2415
+ tools: {},
2416
+ prompts: {},
2417
+ resources: {}
2418
+ },
2419
+ instructions: INSTRUCTIONS
2420
+ });
2421
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
2422
+ return { tools: TOOLS };
2423
+ });
2424
+ server.setRequestHandler(ListPromptsRequestSchema, async () => {
2425
+ return { prompts: getAvailablePrompts() };
2426
+ });
2427
+ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
2428
+ return handlePrompt(request.params.name, request.params.arguments);
2429
+ });
2430
+ server.setRequestHandler(ListResourcesRequestSchema, async () => {
2431
+ return { resources: listResources() };
2432
+ });
2433
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
2434
+ return { resourceTemplates: listResourceTemplates() };
2435
+ });
2436
+ server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
2437
+ const credentials = getCredentialsFromAuthInfo(extra.authInfo);
2438
+ if (!request.params.uri) throw new McpError(ErrorCode.InvalidParams, "Invalid params: uri is required");
2439
+ return readResource(request.params.uri, credentials);
2440
+ });
2441
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
2442
+ const credentials = getCredentialsFromAuthInfo(extra.authInfo);
2443
+ return executeToolWithCredentials(request.params.name, request.params.arguments || {}, credentials);
2444
+ });
2445
+ return server;
2446
+ }
2447
+ async function createHttpMcpTransport() {
2448
+ const transport = new StreamableHTTPServerTransport({
2449
+ sessionIdGenerator: void 0,
2450
+ enableJsonResponse: true
2451
+ });
2452
+ await createHttpMcpServer().connect(transport);
2453
+ return transport;
2454
+ }
2455
+ function setUnauthorizedResponseHeaders(event) {
2456
+ const baseUrl = getBaseUrl(event);
2457
+ event.res.headers.delete("Set-Cookie");
2458
+ event.res.headers.set("WWW-Authenticate", `Bearer resource_metadata="${baseUrl}${OAUTH_PROTECTED_RESOURCE_PATH}"`);
2459
+ }
2460
+ function authenticateRequest(event) {
2461
+ const authHeader = event.req.headers.get("authorization");
2462
+ const tokenMatch = authHeader?.match(/^Bearer\s+(.+)$/i);
2463
+ const credentials = parseAuthHeader(authHeader);
2464
+ if (!credentials || !tokenMatch?.[1]) return null;
2465
+ return createAuthInfo(tokenMatch[1], credentials);
2466
+ }
2467
+ /**
2468
+ * Create the H3 application with all routes
2469
+ */
2470
+ function createHttpApp() {
2471
+ const app = new H3();
2472
+ app.get("/.well-known/oauth-authorization-server", oauthMetadataHandler);
2473
+ app.post("/register", registerHandler);
2474
+ app.get("/authorize", authorizeGetHandler);
2475
+ app.post("/authorize", authorizePostHandler);
2476
+ app.post("/token", tokenHandler);
2477
+ const protectedResourceMetadataHandler = defineHandler((event) => {
2478
+ event.res.headers.set("Content-Type", "application/json");
2479
+ event.res.headers.set("Cache-Control", "public, max-age=3600");
2480
+ return buildProtectedResourceMetadata(event);
2481
+ });
2482
+ app.get(OAUTH_PROTECTED_RESOURCE_PATH, protectedResourceMetadataHandler);
2483
+ app.get("/", defineHandler(() => {
2484
+ return {
2485
+ status: "ok",
2486
+ service: "productive-mcp",
2487
+ version: VERSION
2488
+ };
2489
+ }));
2490
+ app.get("/health", defineHandler(() => {
2491
+ return { status: "ok" };
2492
+ }));
2493
+ const mcpHandler = defineHandler(async (event) => {
2494
+ const authInfo = authenticateRequest(event);
2495
+ if (!authInfo) {
2496
+ setUnauthorizedResponseHeaders(event);
2497
+ event.res.status = 401;
2498
+ event.res.headers.set("Content-Type", "application/json");
2499
+ return event.req.method === "POST" ? jsonRpcError(-32001, "Authentication required. Provide Bearer token with base64(organizationId:apiToken:userId)") : { error: "Authentication required" };
2500
+ }
2501
+ const nodeReq = event.runtime?.node?.req;
2502
+ const nodeRes = event.runtime?.node?.res;
2503
+ if (!nodeReq || !nodeRes) {
2504
+ event.res.status = 501;
2505
+ return { error: "MCP HTTP transport requires Node.js runtime" };
2506
+ }
2507
+ nodeReq.auth = authInfo;
2508
+ let parsedBody;
2509
+ if (event.req.method === "POST") {
2510
+ try {
2511
+ parsedBody = await event.req.json();
2512
+ } catch {
2513
+ event.res.status = 400;
2514
+ event.res.headers.set("Content-Type", "application/json");
2515
+ return jsonRpcError(-32700, "Parse error: Invalid JSON");
2516
+ }
2517
+ const body = parsedBody;
2518
+ if (body?.method === "resources/read" && !body.params?.uri) {
2519
+ event.res.status = 200;
2520
+ event.res.headers.set("Content-Type", "application/json");
2521
+ return jsonRpcError(-32602, "Invalid params: uri is required", body.id ?? null);
2522
+ }
2523
+ }
2524
+ await (await createHttpMcpTransport()).handleRequest(nodeReq, nodeRes, parsedBody);
2525
+ });
2526
+ app.get("/mcp", mcpHandler);
2527
+ app.post("/mcp", mcpHandler);
2528
+ app.delete("/mcp", mcpHandler);
2529
+ return app;
2530
+ }
2531
+ //#endregion
2532
+ export { handleToolsList as a, handleInitialize as i, createHttpMcpServer as n, jsonRpcError as o, createHttpMcpTransport as r, jsonRpcSuccess as s, createHttpApp as t };
2533
+
2534
+ //# sourceMappingURL=http-B3J8ZV4I.js.map