@qwen-code/qwen-code 0.16.2 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/bundled/qc-helper/docs/configuration/settings.md +5 -1
  2. package/bundled/qc-helper/docs/features/channels/_meta.ts +1 -0
  3. package/bundled/qc-helper/docs/features/channels/feishu.md +170 -0
  4. package/chunks/{agent-RY5EB3XR.js → agent-KVXFGIOU.js} +17 -12
  5. package/chunks/{anthropicContentGenerator-LYI3OHBB.js → anthropicContentGenerator-L4HWAOIV.js} +5 -5
  6. package/chunks/{askUserQuestion-R3MKD2JT.js → askUserQuestion-DC6OWQIL.js} +5 -3
  7. package/chunks/chunk-24YKA2DA.js +233 -0
  8. package/chunks/{chunk-UFC57OYT.js → chunk-33RDTIU6.js} +5 -3
  9. package/chunks/{chunk-C6WMLUNB.js → chunk-3BJBCG2K.js} +1 -1
  10. package/chunks/chunk-3HX5LZ6R.js +1798 -0
  11. package/chunks/{chunk-GQXXO5HJ.js → chunk-4O2TWJK4.js} +25 -5
  12. package/chunks/{chunk-RDYWTWEM.js → chunk-5IFG2VC4.js} +299 -232
  13. package/chunks/chunk-6RQTH7UQ.js +115 -0
  14. package/chunks/{chunk-7HM6OB7M.js → chunk-7EHPK6TK.js} +1336 -5164
  15. package/chunks/{chunk-PJLEMR7N.js → chunk-7NNBQRV7.js} +6 -6
  16. package/chunks/{chunk-K5PGHDBN.js → chunk-AKBFRR6J.js} +112 -132
  17. package/chunks/{chunk-C27V5A2J.js → chunk-EMVEDSVZ.js} +1 -1
  18. package/chunks/{chunk-TXQI3VZ7.js → chunk-GJHMAWS7.js} +1 -1
  19. package/chunks/{chunk-K72FHBFO.js → chunk-HAQCNXSG.js} +1 -0
  20. package/chunks/{chunk-T4VD6OJ4.js → chunk-HCSJIOLR.js} +1 -1
  21. package/chunks/chunk-J37FGIOA.js +1623 -0
  22. package/chunks/chunk-J5VCSWPA.js +1467 -0
  23. package/chunks/{chunk-UE5LPQF7.js → chunk-JI7FDD65.js} +7 -7
  24. package/chunks/{chunk-4YNZFYJY.js → chunk-MEN6IEKX.js} +2533 -3943
  25. package/chunks/{chunk-USE2VQ5P.js → chunk-NP3ICQCN.js} +1 -1
  26. package/chunks/{chunk-66CJCYYZ.js → chunk-QEXSIXLX.js} +1 -1
  27. package/chunks/{chunk-YMDXEEOW.js → chunk-R2B65CAN.js} +1 -82
  28. package/chunks/chunk-SZOEIL6S.js +35 -0
  29. package/chunks/chunk-TI4GXJKO.js +4277 -0
  30. package/chunks/{chunk-E7E2MFYM.js → chunk-U2K6HDUJ.js} +434 -13
  31. package/chunks/{chunk-FO7BIVSR.js → chunk-UQRYJQBE.js} +5 -3
  32. package/chunks/{chunk-VMOWXTRC.js → chunk-V7LMZR76.js} +1 -1
  33. package/chunks/chunk-W57YDFU5.js +41 -0
  34. package/chunks/computer-use-2J5ZXEER.js +768 -0
  35. package/chunks/{contextCommand-DDGVLQSF.js → contextCommand-52NTEMCT.js} +19 -14
  36. package/chunks/{cron-create-BTEOGHPH.js → cron-create-FXRORK2U.js} +5 -3
  37. package/chunks/{cron-delete-56CEWELN.js → cron-delete-D24IN6CA.js} +5 -3
  38. package/chunks/{cron-list-SV6QRZW2.js → cron-list-SMOX26SL.js} +5 -3
  39. package/chunks/{devtools-WN62SQPV.js → devtools-IXE4UP72.js} +31 -3748
  40. package/chunks/{dist-MN2PDDPR.js → dist-6RUZ2JD6.js} +13 -1612
  41. package/chunks/{dist-R2SXPG74.js → dist-AHZNZWRI.js} +5 -4
  42. package/chunks/dist-GRQVFL3G.js +94147 -0
  43. package/chunks/{dist-BXDUQ2QY.js → dist-XTTPOFAH.js} +4 -3
  44. package/chunks/{edit-4LLGNYVZ.js → edit-RLFUTT5F.js} +20 -14
  45. package/chunks/{enter-worktree-E2R5XAFT.js → enter-worktree-CYRAPQKJ.js} +20 -14
  46. package/chunks/{exit-worktree-YVBYYYDD.js → exit-worktree-WQZM72QD.js} +20 -14
  47. package/chunks/{exitPlanMode-WD5IH7NS.js → exitPlanMode-STFEBQZE.js} +20 -14
  48. package/chunks/{geminiContentGenerator-LM65ADWM.js → geminiContentGenerator-DIV32SKO.js} +4 -3
  49. package/chunks/{glob-6X6OCEWE.js → glob-N3XO4RVI.js} +20 -14
  50. package/chunks/{grep-2UUPSSIQ.js → grep-AK5MP7P3.js} +20 -14
  51. package/chunks/{ls-MYXAM7LJ.js → ls-7FYQHPWF.js} +5 -3
  52. package/chunks/{lsp-PFGI35JL.js → lsp-DKG34USR.js} +5 -3
  53. package/chunks/{monitor-VUHPEGUW.js → monitor-IVBWJZEZ.js} +20 -14
  54. package/chunks/{notebook-edit-P4QVLW6I.js → notebook-edit-PM46AXFS.js} +21 -15
  55. package/chunks/{openaiContentGenerator-JH4YNZ3H.js → openaiContentGenerator-4QXCH7L2.js} +13 -10
  56. package/chunks/{qwenContentGenerator-5FE4UYUT.js → qwenContentGenerator-BLXQIIMX.js} +21 -16
  57. package/chunks/{read-file-J7DH4OKV.js → read-file-IEQAS3EZ.js} +10 -6
  58. package/chunks/{ripGrep-33DECY4F.js → ripGrep-HQO7IE4C.js} +17 -12
  59. package/chunks/{send-message-JUFP62VD.js → send-message-ZL7CDM7K.js} +5 -3
  60. package/chunks/{serve-7FX7MREA.js → serve-CYRAK4UM.js} +63 -1837
  61. package/chunks/{shell-ZNTQIRK6.js → shell-UZBGNO2Q.js} +17 -12
  62. package/chunks/{skill-CFCUIY23.js → skill-JVC34QYN.js} +24 -13
  63. package/chunks/{src-AHV2CWEQ.js → src-FOODLH7B.js} +49 -41
  64. package/chunks/{syntheticOutput-AKTXC6FR.js → syntheticOutput-U3YJ3GOO.js} +3 -2
  65. package/chunks/{task-stop-2NYFR2ES.js → task-stop-NPUI3YBA.js} +5 -3
  66. package/chunks/{todoWrite-WHZ2O2XP.js → todoWrite-Y6F7YEIM.js} +6 -4
  67. package/chunks/{tool-search-C2EMLFBJ.js → tool-search-P7PRPOW3.js} +13 -8
  68. package/chunks/{web-fetch-S6MZXPZ5.js → web-fetch-XWEK4TFX.js} +6 -4
  69. package/chunks/{write-file-EEPVRS4Q.js → write-file-SIIEUON5.js} +21 -15
  70. package/cli.js +412 -329
  71. package/package.json +2 -2
  72. package/chunks/chunk-JVD46YJV.js +0 -434
  73. package/chunks/undici-4ARNOH74.js +0 -8
@@ -0,0 +1,4277 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import {
4
+ _enum,
5
+ _null,
6
+ array,
7
+ boolean,
8
+ custom2 as custom,
9
+ discriminatedUnion,
10
+ intersection,
11
+ iso_exports,
12
+ literal,
13
+ looseObject,
14
+ number,
15
+ object,
16
+ optional,
17
+ preprocess,
18
+ record,
19
+ safeParse,
20
+ string,
21
+ union,
22
+ unknown
23
+ } from "./chunk-AKBFRR6J.js";
24
+ import {
25
+ require_ajv,
26
+ require_dist
27
+ } from "./chunk-R2B65CAN.js";
28
+ import {
29
+ init_esbuild_shims
30
+ } from "./chunk-A4BMJM77.js";
31
+ import {
32
+ __commonJS,
33
+ __name,
34
+ __require,
35
+ __toESM
36
+ } from "./chunk-J2S4EL5Y.js";
37
+
38
+ // node_modules/isexe/windows.js
39
+ var require_windows = __commonJS({
40
+ "node_modules/isexe/windows.js"(exports, module) {
41
+ init_esbuild_shims();
42
+ module.exports = isexe;
43
+ isexe.sync = sync;
44
+ var fs = __require("fs");
45
+ function checkPathExt(path, options) {
46
+ var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
47
+ if (!pathext) {
48
+ return true;
49
+ }
50
+ pathext = pathext.split(";");
51
+ if (pathext.indexOf("") !== -1) {
52
+ return true;
53
+ }
54
+ for (var i = 0; i < pathext.length; i++) {
55
+ var p = pathext[i].toLowerCase();
56
+ if (p && path.substr(-p.length).toLowerCase() === p) {
57
+ return true;
58
+ }
59
+ }
60
+ return false;
61
+ }
62
+ __name(checkPathExt, "checkPathExt");
63
+ function checkStat(stat, path, options) {
64
+ if (!stat.isSymbolicLink() && !stat.isFile()) {
65
+ return false;
66
+ }
67
+ return checkPathExt(path, options);
68
+ }
69
+ __name(checkStat, "checkStat");
70
+ function isexe(path, options, cb) {
71
+ fs.stat(path, function(er, stat) {
72
+ cb(er, er ? false : checkStat(stat, path, options));
73
+ });
74
+ }
75
+ __name(isexe, "isexe");
76
+ function sync(path, options) {
77
+ return checkStat(fs.statSync(path), path, options);
78
+ }
79
+ __name(sync, "sync");
80
+ }
81
+ });
82
+
83
+ // node_modules/isexe/mode.js
84
+ var require_mode = __commonJS({
85
+ "node_modules/isexe/mode.js"(exports, module) {
86
+ init_esbuild_shims();
87
+ module.exports = isexe;
88
+ isexe.sync = sync;
89
+ var fs = __require("fs");
90
+ function isexe(path, options, cb) {
91
+ fs.stat(path, function(er, stat) {
92
+ cb(er, er ? false : checkStat(stat, options));
93
+ });
94
+ }
95
+ __name(isexe, "isexe");
96
+ function sync(path, options) {
97
+ return checkStat(fs.statSync(path), options);
98
+ }
99
+ __name(sync, "sync");
100
+ function checkStat(stat, options) {
101
+ return stat.isFile() && checkMode(stat, options);
102
+ }
103
+ __name(checkStat, "checkStat");
104
+ function checkMode(stat, options) {
105
+ var mod = stat.mode;
106
+ var uid = stat.uid;
107
+ var gid = stat.gid;
108
+ var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
109
+ var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
110
+ var u = parseInt("100", 8);
111
+ var g = parseInt("010", 8);
112
+ var o = parseInt("001", 8);
113
+ var ug = u | g;
114
+ var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
115
+ return ret;
116
+ }
117
+ __name(checkMode, "checkMode");
118
+ }
119
+ });
120
+
121
+ // node_modules/isexe/index.js
122
+ var require_isexe = __commonJS({
123
+ "node_modules/isexe/index.js"(exports, module) {
124
+ init_esbuild_shims();
125
+ var fs = __require("fs");
126
+ var core;
127
+ if (process.platform === "win32" || globalThis.TESTING_WINDOWS) {
128
+ core = require_windows();
129
+ } else {
130
+ core = require_mode();
131
+ }
132
+ module.exports = isexe;
133
+ isexe.sync = sync;
134
+ function isexe(path, options, cb) {
135
+ if (typeof options === "function") {
136
+ cb = options;
137
+ options = {};
138
+ }
139
+ if (!cb) {
140
+ if (typeof Promise !== "function") {
141
+ throw new TypeError("callback not provided");
142
+ }
143
+ return new Promise(function(resolve, reject) {
144
+ isexe(path, options || {}, function(er, is) {
145
+ if (er) {
146
+ reject(er);
147
+ } else {
148
+ resolve(is);
149
+ }
150
+ });
151
+ });
152
+ }
153
+ core(path, options || {}, function(er, is) {
154
+ if (er) {
155
+ if (er.code === "EACCES" || options && options.ignoreErrors) {
156
+ er = null;
157
+ is = false;
158
+ }
159
+ }
160
+ cb(er, is);
161
+ });
162
+ }
163
+ __name(isexe, "isexe");
164
+ function sync(path, options) {
165
+ try {
166
+ return core.sync(path, options || {});
167
+ } catch (er) {
168
+ if (options && options.ignoreErrors || er.code === "EACCES") {
169
+ return false;
170
+ } else {
171
+ throw er;
172
+ }
173
+ }
174
+ }
175
+ __name(sync, "sync");
176
+ }
177
+ });
178
+
179
+ // node_modules/which/which.js
180
+ var require_which = __commonJS({
181
+ "node_modules/which/which.js"(exports, module) {
182
+ init_esbuild_shims();
183
+ var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
184
+ var path = __require("path");
185
+ var COLON = isWindows ? ";" : ":";
186
+ var isexe = require_isexe();
187
+ var getNotFoundError = /* @__PURE__ */ __name((cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" }), "getNotFoundError");
188
+ var getPathInfo = /* @__PURE__ */ __name((cmd, opt) => {
189
+ const colon = opt.colon || COLON;
190
+ const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [
191
+ // windows always checks the cwd first
192
+ ...isWindows ? [process.cwd()] : [],
193
+ ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
194
+ "").split(colon)
195
+ ];
196
+ const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
197
+ const pathExt = isWindows ? pathExtExe.split(colon) : [""];
198
+ if (isWindows) {
199
+ if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
200
+ pathExt.unshift("");
201
+ }
202
+ return {
203
+ pathEnv,
204
+ pathExt,
205
+ pathExtExe
206
+ };
207
+ }, "getPathInfo");
208
+ var which = /* @__PURE__ */ __name((cmd, opt, cb) => {
209
+ if (typeof opt === "function") {
210
+ cb = opt;
211
+ opt = {};
212
+ }
213
+ if (!opt)
214
+ opt = {};
215
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
216
+ const found = [];
217
+ const step = /* @__PURE__ */ __name((i) => new Promise((resolve, reject) => {
218
+ if (i === pathEnv.length)
219
+ return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
220
+ const ppRaw = pathEnv[i];
221
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
222
+ const pCmd = path.join(pathPart, cmd);
223
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
224
+ resolve(subStep(p, i, 0));
225
+ }), "step");
226
+ const subStep = /* @__PURE__ */ __name((p, i, ii) => new Promise((resolve, reject) => {
227
+ if (ii === pathExt.length)
228
+ return resolve(step(i + 1));
229
+ const ext = pathExt[ii];
230
+ isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
231
+ if (!er && is) {
232
+ if (opt.all)
233
+ found.push(p + ext);
234
+ else
235
+ return resolve(p + ext);
236
+ }
237
+ return resolve(subStep(p, i, ii + 1));
238
+ });
239
+ }), "subStep");
240
+ return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
241
+ }, "which");
242
+ var whichSync = /* @__PURE__ */ __name((cmd, opt) => {
243
+ opt = opt || {};
244
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
245
+ const found = [];
246
+ for (let i = 0; i < pathEnv.length; i++) {
247
+ const ppRaw = pathEnv[i];
248
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
249
+ const pCmd = path.join(pathPart, cmd);
250
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
251
+ for (let j = 0; j < pathExt.length; j++) {
252
+ const cur = p + pathExt[j];
253
+ try {
254
+ const is = isexe.sync(cur, { pathExt: pathExtExe });
255
+ if (is) {
256
+ if (opt.all)
257
+ found.push(cur);
258
+ else
259
+ return cur;
260
+ }
261
+ } catch (ex) {
262
+ }
263
+ }
264
+ }
265
+ if (opt.all && found.length)
266
+ return found;
267
+ if (opt.nothrow)
268
+ return null;
269
+ throw getNotFoundError(cmd);
270
+ }, "whichSync");
271
+ module.exports = which;
272
+ which.sync = whichSync;
273
+ }
274
+ });
275
+
276
+ // node_modules/path-key/index.js
277
+ var require_path_key = __commonJS({
278
+ "node_modules/path-key/index.js"(exports, module) {
279
+ "use strict";
280
+ init_esbuild_shims();
281
+ var pathKey = /* @__PURE__ */ __name((options = {}) => {
282
+ const environment = options.env || process.env;
283
+ const platform = options.platform || process.platform;
284
+ if (platform !== "win32") {
285
+ return "PATH";
286
+ }
287
+ return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
288
+ }, "pathKey");
289
+ module.exports = pathKey;
290
+ module.exports.default = pathKey;
291
+ }
292
+ });
293
+
294
+ // node_modules/cross-spawn/lib/util/resolveCommand.js
295
+ var require_resolveCommand = __commonJS({
296
+ "node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
297
+ "use strict";
298
+ init_esbuild_shims();
299
+ var path = __require("path");
300
+ var which = require_which();
301
+ var getPathKey = require_path_key();
302
+ function resolveCommandAttempt(parsed, withoutPathExt) {
303
+ const env = parsed.options.env || process.env;
304
+ const cwd = process.cwd();
305
+ const hasCustomCwd = parsed.options.cwd != null;
306
+ const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
307
+ if (shouldSwitchCwd) {
308
+ try {
309
+ process.chdir(parsed.options.cwd);
310
+ } catch (err) {
311
+ }
312
+ }
313
+ let resolved;
314
+ try {
315
+ resolved = which.sync(parsed.command, {
316
+ path: env[getPathKey({ env })],
317
+ pathExt: withoutPathExt ? path.delimiter : void 0
318
+ });
319
+ } catch (e) {
320
+ } finally {
321
+ if (shouldSwitchCwd) {
322
+ process.chdir(cwd);
323
+ }
324
+ }
325
+ if (resolved) {
326
+ resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
327
+ }
328
+ return resolved;
329
+ }
330
+ __name(resolveCommandAttempt, "resolveCommandAttempt");
331
+ function resolveCommand(parsed) {
332
+ return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
333
+ }
334
+ __name(resolveCommand, "resolveCommand");
335
+ module.exports = resolveCommand;
336
+ }
337
+ });
338
+
339
+ // node_modules/cross-spawn/lib/util/escape.js
340
+ var require_escape = __commonJS({
341
+ "node_modules/cross-spawn/lib/util/escape.js"(exports, module) {
342
+ "use strict";
343
+ init_esbuild_shims();
344
+ var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
345
+ function escapeCommand(arg) {
346
+ arg = arg.replace(metaCharsRegExp, "^$1");
347
+ return arg;
348
+ }
349
+ __name(escapeCommand, "escapeCommand");
350
+ function escapeArgument(arg, doubleEscapeMetaChars) {
351
+ arg = `${arg}`;
352
+ arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
353
+ arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
354
+ arg = `"${arg}"`;
355
+ arg = arg.replace(metaCharsRegExp, "^$1");
356
+ if (doubleEscapeMetaChars) {
357
+ arg = arg.replace(metaCharsRegExp, "^$1");
358
+ }
359
+ return arg;
360
+ }
361
+ __name(escapeArgument, "escapeArgument");
362
+ module.exports.command = escapeCommand;
363
+ module.exports.argument = escapeArgument;
364
+ }
365
+ });
366
+
367
+ // node_modules/shebang-regex/index.js
368
+ var require_shebang_regex = __commonJS({
369
+ "node_modules/shebang-regex/index.js"(exports, module) {
370
+ "use strict";
371
+ init_esbuild_shims();
372
+ module.exports = /^#!(.*)/;
373
+ }
374
+ });
375
+
376
+ // node_modules/shebang-command/index.js
377
+ var require_shebang_command = __commonJS({
378
+ "node_modules/shebang-command/index.js"(exports, module) {
379
+ "use strict";
380
+ init_esbuild_shims();
381
+ var shebangRegex = require_shebang_regex();
382
+ module.exports = (string2 = "") => {
383
+ const match = string2.match(shebangRegex);
384
+ if (!match) {
385
+ return null;
386
+ }
387
+ const [path, argument] = match[0].replace(/#! ?/, "").split(" ");
388
+ const binary = path.split("/").pop();
389
+ if (binary === "env") {
390
+ return argument;
391
+ }
392
+ return argument ? `${binary} ${argument}` : binary;
393
+ };
394
+ }
395
+ });
396
+
397
+ // node_modules/cross-spawn/lib/util/readShebang.js
398
+ var require_readShebang = __commonJS({
399
+ "node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
400
+ "use strict";
401
+ init_esbuild_shims();
402
+ var fs = __require("fs");
403
+ var shebangCommand = require_shebang_command();
404
+ function readShebang(command) {
405
+ const size = 150;
406
+ const buffer = Buffer.alloc(size);
407
+ let fd;
408
+ try {
409
+ fd = fs.openSync(command, "r");
410
+ fs.readSync(fd, buffer, 0, size, 0);
411
+ fs.closeSync(fd);
412
+ } catch (e) {
413
+ }
414
+ return shebangCommand(buffer.toString());
415
+ }
416
+ __name(readShebang, "readShebang");
417
+ module.exports = readShebang;
418
+ }
419
+ });
420
+
421
+ // node_modules/cross-spawn/lib/parse.js
422
+ var require_parse = __commonJS({
423
+ "node_modules/cross-spawn/lib/parse.js"(exports, module) {
424
+ "use strict";
425
+ init_esbuild_shims();
426
+ var path = __require("path");
427
+ var resolveCommand = require_resolveCommand();
428
+ var escape = require_escape();
429
+ var readShebang = require_readShebang();
430
+ var isWin = process.platform === "win32";
431
+ var isExecutableRegExp = /\.(?:com|exe)$/i;
432
+ var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
433
+ function detectShebang(parsed) {
434
+ parsed.file = resolveCommand(parsed);
435
+ const shebang = parsed.file && readShebang(parsed.file);
436
+ if (shebang) {
437
+ parsed.args.unshift(parsed.file);
438
+ parsed.command = shebang;
439
+ return resolveCommand(parsed);
440
+ }
441
+ return parsed.file;
442
+ }
443
+ __name(detectShebang, "detectShebang");
444
+ function parseNonShell(parsed) {
445
+ if (!isWin) {
446
+ return parsed;
447
+ }
448
+ const commandFile = detectShebang(parsed);
449
+ const needsShell = !isExecutableRegExp.test(commandFile);
450
+ if (parsed.options.forceShell || needsShell) {
451
+ const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
452
+ parsed.command = path.normalize(parsed.command);
453
+ parsed.command = escape.command(parsed.command);
454
+ parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
455
+ const shellCommand = [parsed.command].concat(parsed.args).join(" ");
456
+ parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
457
+ parsed.command = process.env.comspec || "cmd.exe";
458
+ parsed.options.windowsVerbatimArguments = true;
459
+ }
460
+ return parsed;
461
+ }
462
+ __name(parseNonShell, "parseNonShell");
463
+ function parse2(command, args, options) {
464
+ if (args && !Array.isArray(args)) {
465
+ options = args;
466
+ args = null;
467
+ }
468
+ args = args ? args.slice(0) : [];
469
+ options = Object.assign({}, options);
470
+ const parsed = {
471
+ command,
472
+ args,
473
+ options,
474
+ file: void 0,
475
+ original: {
476
+ command,
477
+ args
478
+ }
479
+ };
480
+ return options.shell ? parsed : parseNonShell(parsed);
481
+ }
482
+ __name(parse2, "parse");
483
+ module.exports = parse2;
484
+ }
485
+ });
486
+
487
+ // node_modules/cross-spawn/lib/enoent.js
488
+ var require_enoent = __commonJS({
489
+ "node_modules/cross-spawn/lib/enoent.js"(exports, module) {
490
+ "use strict";
491
+ init_esbuild_shims();
492
+ var isWin = process.platform === "win32";
493
+ function notFoundError(original, syscall) {
494
+ return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
495
+ code: "ENOENT",
496
+ errno: "ENOENT",
497
+ syscall: `${syscall} ${original.command}`,
498
+ path: original.command,
499
+ spawnargs: original.args
500
+ });
501
+ }
502
+ __name(notFoundError, "notFoundError");
503
+ function hookChildProcess(cp, parsed) {
504
+ if (!isWin) {
505
+ return;
506
+ }
507
+ const originalEmit = cp.emit;
508
+ cp.emit = function(name, arg1) {
509
+ if (name === "exit") {
510
+ const err = verifyENOENT(arg1, parsed);
511
+ if (err) {
512
+ return originalEmit.call(cp, "error", err);
513
+ }
514
+ }
515
+ return originalEmit.apply(cp, arguments);
516
+ };
517
+ }
518
+ __name(hookChildProcess, "hookChildProcess");
519
+ function verifyENOENT(status, parsed) {
520
+ if (isWin && status === 1 && !parsed.file) {
521
+ return notFoundError(parsed.original, "spawn");
522
+ }
523
+ return null;
524
+ }
525
+ __name(verifyENOENT, "verifyENOENT");
526
+ function verifyENOENTSync(status, parsed) {
527
+ if (isWin && status === 1 && !parsed.file) {
528
+ return notFoundError(parsed.original, "spawnSync");
529
+ }
530
+ return null;
531
+ }
532
+ __name(verifyENOENTSync, "verifyENOENTSync");
533
+ module.exports = {
534
+ hookChildProcess,
535
+ verifyENOENT,
536
+ verifyENOENTSync,
537
+ notFoundError
538
+ };
539
+ }
540
+ });
541
+
542
+ // node_modules/cross-spawn/index.js
543
+ var require_cross_spawn = __commonJS({
544
+ "node_modules/cross-spawn/index.js"(exports, module) {
545
+ "use strict";
546
+ init_esbuild_shims();
547
+ var cp = __require("child_process");
548
+ var parse2 = require_parse();
549
+ var enoent = require_enoent();
550
+ function spawn2(command, args, options) {
551
+ const parsed = parse2(command, args, options);
552
+ const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
553
+ enoent.hookChildProcess(spawned, parsed);
554
+ return spawned;
555
+ }
556
+ __name(spawn2, "spawn");
557
+ function spawnSync(command, args, options) {
558
+ const parsed = parse2(command, args, options);
559
+ const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
560
+ result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
561
+ return result;
562
+ }
563
+ __name(spawnSync, "spawnSync");
564
+ module.exports = spawn2;
565
+ module.exports.spawn = spawn2;
566
+ module.exports.sync = spawnSync;
567
+ module.exports._parse = parse2;
568
+ module.exports._enoent = enoent;
569
+ }
570
+ });
571
+
572
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
573
+ init_esbuild_shims();
574
+ var LATEST_PROTOCOL_VERSION = "2025-11-25";
575
+ var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
576
+ var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
577
+ var JSONRPC_VERSION = "2.0";
578
+ var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function"));
579
+ var ProgressTokenSchema = union([string(), number().int()]);
580
+ var CursorSchema = string();
581
+ var TaskCreationParamsSchema = looseObject({
582
+ /**
583
+ * Time in milliseconds to keep task results available after completion.
584
+ * If null, the task has unlimited lifetime until manually cleaned up.
585
+ */
586
+ ttl: union([number(), _null()]).optional(),
587
+ /**
588
+ * Time in milliseconds to wait between task status requests.
589
+ */
590
+ pollInterval: number().optional()
591
+ });
592
+ var TaskMetadataSchema = object({
593
+ ttl: number().optional()
594
+ });
595
+ var RelatedTaskMetadataSchema = object({
596
+ taskId: string()
597
+ });
598
+ var RequestMetaSchema = looseObject({
599
+ /**
600
+ * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
601
+ */
602
+ progressToken: ProgressTokenSchema.optional(),
603
+ /**
604
+ * If specified, this request is related to the provided task.
605
+ */
606
+ [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
607
+ });
608
+ var BaseRequestParamsSchema = object({
609
+ /**
610
+ * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
611
+ */
612
+ _meta: RequestMetaSchema.optional()
613
+ });
614
+ var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
615
+ /**
616
+ * If specified, the caller is requesting task-augmented execution for this request.
617
+ * The request will return a CreateTaskResult immediately, and the actual result can be
618
+ * retrieved later via tasks/result.
619
+ *
620
+ * Task augmentation is subject to capability negotiation - receivers MUST declare support
621
+ * for task augmentation of specific request types in their capabilities.
622
+ */
623
+ task: TaskMetadataSchema.optional()
624
+ });
625
+ var isTaskAugmentedRequestParams = /* @__PURE__ */ __name((value) => TaskAugmentedRequestParamsSchema.safeParse(value).success, "isTaskAugmentedRequestParams");
626
+ var RequestSchema = object({
627
+ method: string(),
628
+ params: BaseRequestParamsSchema.loose().optional()
629
+ });
630
+ var NotificationsParamsSchema = object({
631
+ /**
632
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
633
+ * for notes on _meta usage.
634
+ */
635
+ _meta: RequestMetaSchema.optional()
636
+ });
637
+ var NotificationSchema = object({
638
+ method: string(),
639
+ params: NotificationsParamsSchema.loose().optional()
640
+ });
641
+ var ResultSchema = looseObject({
642
+ /**
643
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
644
+ * for notes on _meta usage.
645
+ */
646
+ _meta: RequestMetaSchema.optional()
647
+ });
648
+ var RequestIdSchema = union([string(), number().int()]);
649
+ var JSONRPCRequestSchema = object({
650
+ jsonrpc: literal(JSONRPC_VERSION),
651
+ id: RequestIdSchema,
652
+ ...RequestSchema.shape
653
+ }).strict();
654
+ var isJSONRPCRequest = /* @__PURE__ */ __name((value) => JSONRPCRequestSchema.safeParse(value).success, "isJSONRPCRequest");
655
+ var JSONRPCNotificationSchema = object({
656
+ jsonrpc: literal(JSONRPC_VERSION),
657
+ ...NotificationSchema.shape
658
+ }).strict();
659
+ var isJSONRPCNotification = /* @__PURE__ */ __name((value) => JSONRPCNotificationSchema.safeParse(value).success, "isJSONRPCNotification");
660
+ var JSONRPCResultResponseSchema = object({
661
+ jsonrpc: literal(JSONRPC_VERSION),
662
+ id: RequestIdSchema,
663
+ result: ResultSchema
664
+ }).strict();
665
+ var isJSONRPCResultResponse = /* @__PURE__ */ __name((value) => JSONRPCResultResponseSchema.safeParse(value).success, "isJSONRPCResultResponse");
666
+ var ErrorCode;
667
+ (function(ErrorCode2) {
668
+ ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed";
669
+ ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout";
670
+ ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError";
671
+ ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest";
672
+ ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";
673
+ ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";
674
+ ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
675
+ ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
676
+ })(ErrorCode || (ErrorCode = {}));
677
+ var JSONRPCErrorResponseSchema = object({
678
+ jsonrpc: literal(JSONRPC_VERSION),
679
+ id: RequestIdSchema.optional(),
680
+ error: object({
681
+ /**
682
+ * The error type that occurred.
683
+ */
684
+ code: number().int(),
685
+ /**
686
+ * A short description of the error. The message SHOULD be limited to a concise single sentence.
687
+ */
688
+ message: string(),
689
+ /**
690
+ * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
691
+ */
692
+ data: unknown().optional()
693
+ })
694
+ }).strict();
695
+ var isJSONRPCErrorResponse = /* @__PURE__ */ __name((value) => JSONRPCErrorResponseSchema.safeParse(value).success, "isJSONRPCErrorResponse");
696
+ var JSONRPCMessageSchema = union([
697
+ JSONRPCRequestSchema,
698
+ JSONRPCNotificationSchema,
699
+ JSONRPCResultResponseSchema,
700
+ JSONRPCErrorResponseSchema
701
+ ]);
702
+ var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
703
+ var EmptyResultSchema = ResultSchema.strict();
704
+ var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
705
+ /**
706
+ * The ID of the request to cancel.
707
+ *
708
+ * This MUST correspond to the ID of a request previously issued in the same direction.
709
+ */
710
+ requestId: RequestIdSchema.optional(),
711
+ /**
712
+ * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
713
+ */
714
+ reason: string().optional()
715
+ });
716
+ var CancelledNotificationSchema = NotificationSchema.extend({
717
+ method: literal("notifications/cancelled"),
718
+ params: CancelledNotificationParamsSchema
719
+ });
720
+ var IconSchema = object({
721
+ /**
722
+ * URL or data URI for the icon.
723
+ */
724
+ src: string(),
725
+ /**
726
+ * Optional MIME type for the icon.
727
+ */
728
+ mimeType: string().optional(),
729
+ /**
730
+ * Optional array of strings that specify sizes at which the icon can be used.
731
+ * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
732
+ *
733
+ * If not provided, the client should assume that the icon can be used at any size.
734
+ */
735
+ sizes: array(string()).optional(),
736
+ /**
737
+ * Optional specifier for the theme this icon is designed for. `light` indicates
738
+ * the icon is designed to be used with a light background, and `dark` indicates
739
+ * the icon is designed to be used with a dark background.
740
+ *
741
+ * If not provided, the client should assume the icon can be used with any theme.
742
+ */
743
+ theme: _enum(["light", "dark"]).optional()
744
+ });
745
+ var IconsSchema = object({
746
+ /**
747
+ * Optional set of sized icons that the client can display in a user interface.
748
+ *
749
+ * Clients that support rendering icons MUST support at least the following MIME types:
750
+ * - `image/png` - PNG images (safe, universal compatibility)
751
+ * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
752
+ *
753
+ * Clients that support rendering icons SHOULD also support:
754
+ * - `image/svg+xml` - SVG images (scalable but requires security precautions)
755
+ * - `image/webp` - WebP images (modern, efficient format)
756
+ */
757
+ icons: array(IconSchema).optional()
758
+ });
759
+ var BaseMetadataSchema = object({
760
+ /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
761
+ name: string(),
762
+ /**
763
+ * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
764
+ * even by those unfamiliar with domain-specific terminology.
765
+ *
766
+ * If not provided, the name should be used for display (except for Tool,
767
+ * where `annotations.title` should be given precedence over using `name`,
768
+ * if present).
769
+ */
770
+ title: string().optional()
771
+ });
772
+ var ImplementationSchema = BaseMetadataSchema.extend({
773
+ ...BaseMetadataSchema.shape,
774
+ ...IconsSchema.shape,
775
+ version: string(),
776
+ /**
777
+ * An optional URL of the website for this implementation.
778
+ */
779
+ websiteUrl: string().optional(),
780
+ /**
781
+ * An optional human-readable description of what this implementation does.
782
+ *
783
+ * This can be used by clients or servers to provide context about their purpose
784
+ * and capabilities. For example, a server might describe the types of resources
785
+ * or tools it provides, while a client might describe its intended use case.
786
+ */
787
+ description: string().optional()
788
+ });
789
+ var FormElicitationCapabilitySchema = intersection(object({
790
+ applyDefaults: boolean().optional()
791
+ }), record(string(), unknown()));
792
+ var ElicitationCapabilitySchema = preprocess((value) => {
793
+ if (value && typeof value === "object" && !Array.isArray(value)) {
794
+ if (Object.keys(value).length === 0) {
795
+ return { form: {} };
796
+ }
797
+ }
798
+ return value;
799
+ }, intersection(object({
800
+ form: FormElicitationCapabilitySchema.optional(),
801
+ url: AssertObjectSchema.optional()
802
+ }), record(string(), unknown()).optional()));
803
+ var ClientTasksCapabilitySchema = looseObject({
804
+ /**
805
+ * Present if the client supports listing tasks.
806
+ */
807
+ list: AssertObjectSchema.optional(),
808
+ /**
809
+ * Present if the client supports cancelling tasks.
810
+ */
811
+ cancel: AssertObjectSchema.optional(),
812
+ /**
813
+ * Capabilities for task creation on specific request types.
814
+ */
815
+ requests: looseObject({
816
+ /**
817
+ * Task support for sampling requests.
818
+ */
819
+ sampling: looseObject({
820
+ createMessage: AssertObjectSchema.optional()
821
+ }).optional(),
822
+ /**
823
+ * Task support for elicitation requests.
824
+ */
825
+ elicitation: looseObject({
826
+ create: AssertObjectSchema.optional()
827
+ }).optional()
828
+ }).optional()
829
+ });
830
+ var ServerTasksCapabilitySchema = looseObject({
831
+ /**
832
+ * Present if the server supports listing tasks.
833
+ */
834
+ list: AssertObjectSchema.optional(),
835
+ /**
836
+ * Present if the server supports cancelling tasks.
837
+ */
838
+ cancel: AssertObjectSchema.optional(),
839
+ /**
840
+ * Capabilities for task creation on specific request types.
841
+ */
842
+ requests: looseObject({
843
+ /**
844
+ * Task support for tool requests.
845
+ */
846
+ tools: looseObject({
847
+ call: AssertObjectSchema.optional()
848
+ }).optional()
849
+ }).optional()
850
+ });
851
+ var ClientCapabilitiesSchema = object({
852
+ /**
853
+ * Experimental, non-standard capabilities that the client supports.
854
+ */
855
+ experimental: record(string(), AssertObjectSchema).optional(),
856
+ /**
857
+ * Present if the client supports sampling from an LLM.
858
+ */
859
+ sampling: object({
860
+ /**
861
+ * Present if the client supports context inclusion via includeContext parameter.
862
+ * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
863
+ */
864
+ context: AssertObjectSchema.optional(),
865
+ /**
866
+ * Present if the client supports tool use via tools and toolChoice parameters.
867
+ */
868
+ tools: AssertObjectSchema.optional()
869
+ }).optional(),
870
+ /**
871
+ * Present if the client supports eliciting user input.
872
+ */
873
+ elicitation: ElicitationCapabilitySchema.optional(),
874
+ /**
875
+ * Present if the client supports listing roots.
876
+ */
877
+ roots: object({
878
+ /**
879
+ * Whether the client supports issuing notifications for changes to the roots list.
880
+ */
881
+ listChanged: boolean().optional()
882
+ }).optional(),
883
+ /**
884
+ * Present if the client supports task creation.
885
+ */
886
+ tasks: ClientTasksCapabilitySchema.optional()
887
+ });
888
+ var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
889
+ /**
890
+ * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
891
+ */
892
+ protocolVersion: string(),
893
+ capabilities: ClientCapabilitiesSchema,
894
+ clientInfo: ImplementationSchema
895
+ });
896
+ var InitializeRequestSchema = RequestSchema.extend({
897
+ method: literal("initialize"),
898
+ params: InitializeRequestParamsSchema
899
+ });
900
+ var ServerCapabilitiesSchema = object({
901
+ /**
902
+ * Experimental, non-standard capabilities that the server supports.
903
+ */
904
+ experimental: record(string(), AssertObjectSchema).optional(),
905
+ /**
906
+ * Present if the server supports sending log messages to the client.
907
+ */
908
+ logging: AssertObjectSchema.optional(),
909
+ /**
910
+ * Present if the server supports sending completions to the client.
911
+ */
912
+ completions: AssertObjectSchema.optional(),
913
+ /**
914
+ * Present if the server offers any prompt templates.
915
+ */
916
+ prompts: object({
917
+ /**
918
+ * Whether this server supports issuing notifications for changes to the prompt list.
919
+ */
920
+ listChanged: boolean().optional()
921
+ }).optional(),
922
+ /**
923
+ * Present if the server offers any resources to read.
924
+ */
925
+ resources: object({
926
+ /**
927
+ * Whether this server supports clients subscribing to resource updates.
928
+ */
929
+ subscribe: boolean().optional(),
930
+ /**
931
+ * Whether this server supports issuing notifications for changes to the resource list.
932
+ */
933
+ listChanged: boolean().optional()
934
+ }).optional(),
935
+ /**
936
+ * Present if the server offers any tools to call.
937
+ */
938
+ tools: object({
939
+ /**
940
+ * Whether this server supports issuing notifications for changes to the tool list.
941
+ */
942
+ listChanged: boolean().optional()
943
+ }).optional(),
944
+ /**
945
+ * Present if the server supports task creation.
946
+ */
947
+ tasks: ServerTasksCapabilitySchema.optional()
948
+ });
949
+ var InitializeResultSchema = ResultSchema.extend({
950
+ /**
951
+ * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
952
+ */
953
+ protocolVersion: string(),
954
+ capabilities: ServerCapabilitiesSchema,
955
+ serverInfo: ImplementationSchema,
956
+ /**
957
+ * Instructions describing how to use the server and its features.
958
+ *
959
+ * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
960
+ */
961
+ instructions: string().optional()
962
+ });
963
+ var InitializedNotificationSchema = NotificationSchema.extend({
964
+ method: literal("notifications/initialized"),
965
+ params: NotificationsParamsSchema.optional()
966
+ });
967
+ var isInitializedNotification = /* @__PURE__ */ __name((value) => InitializedNotificationSchema.safeParse(value).success, "isInitializedNotification");
968
+ var PingRequestSchema = RequestSchema.extend({
969
+ method: literal("ping"),
970
+ params: BaseRequestParamsSchema.optional()
971
+ });
972
+ var ProgressSchema = object({
973
+ /**
974
+ * The progress thus far. This should increase every time progress is made, even if the total is unknown.
975
+ */
976
+ progress: number(),
977
+ /**
978
+ * Total number of items to process (or total progress required), if known.
979
+ */
980
+ total: optional(number()),
981
+ /**
982
+ * An optional message describing the current progress.
983
+ */
984
+ message: optional(string())
985
+ });
986
+ var ProgressNotificationParamsSchema = object({
987
+ ...NotificationsParamsSchema.shape,
988
+ ...ProgressSchema.shape,
989
+ /**
990
+ * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
991
+ */
992
+ progressToken: ProgressTokenSchema
993
+ });
994
+ var ProgressNotificationSchema = NotificationSchema.extend({
995
+ method: literal("notifications/progress"),
996
+ params: ProgressNotificationParamsSchema
997
+ });
998
+ var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
999
+ /**
1000
+ * An opaque token representing the current pagination position.
1001
+ * If provided, the server should return results starting after this cursor.
1002
+ */
1003
+ cursor: CursorSchema.optional()
1004
+ });
1005
+ var PaginatedRequestSchema = RequestSchema.extend({
1006
+ params: PaginatedRequestParamsSchema.optional()
1007
+ });
1008
+ var PaginatedResultSchema = ResultSchema.extend({
1009
+ /**
1010
+ * An opaque token representing the pagination position after the last returned result.
1011
+ * If present, there may be more results available.
1012
+ */
1013
+ nextCursor: CursorSchema.optional()
1014
+ });
1015
+ var TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]);
1016
+ var TaskSchema = object({
1017
+ taskId: string(),
1018
+ status: TaskStatusSchema,
1019
+ /**
1020
+ * Time in milliseconds to keep task results available after completion.
1021
+ * If null, the task has unlimited lifetime until manually cleaned up.
1022
+ */
1023
+ ttl: union([number(), _null()]),
1024
+ /**
1025
+ * ISO 8601 timestamp when the task was created.
1026
+ */
1027
+ createdAt: string(),
1028
+ /**
1029
+ * ISO 8601 timestamp when the task was last updated.
1030
+ */
1031
+ lastUpdatedAt: string(),
1032
+ pollInterval: optional(number()),
1033
+ /**
1034
+ * Optional diagnostic message for failed tasks or other status information.
1035
+ */
1036
+ statusMessage: optional(string())
1037
+ });
1038
+ var CreateTaskResultSchema = ResultSchema.extend({
1039
+ task: TaskSchema
1040
+ });
1041
+ var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
1042
+ var TaskStatusNotificationSchema = NotificationSchema.extend({
1043
+ method: literal("notifications/tasks/status"),
1044
+ params: TaskStatusNotificationParamsSchema
1045
+ });
1046
+ var GetTaskRequestSchema = RequestSchema.extend({
1047
+ method: literal("tasks/get"),
1048
+ params: BaseRequestParamsSchema.extend({
1049
+ taskId: string()
1050
+ })
1051
+ });
1052
+ var GetTaskResultSchema = ResultSchema.merge(TaskSchema);
1053
+ var GetTaskPayloadRequestSchema = RequestSchema.extend({
1054
+ method: literal("tasks/result"),
1055
+ params: BaseRequestParamsSchema.extend({
1056
+ taskId: string()
1057
+ })
1058
+ });
1059
+ var GetTaskPayloadResultSchema = ResultSchema.loose();
1060
+ var ListTasksRequestSchema = PaginatedRequestSchema.extend({
1061
+ method: literal("tasks/list")
1062
+ });
1063
+ var ListTasksResultSchema = PaginatedResultSchema.extend({
1064
+ tasks: array(TaskSchema)
1065
+ });
1066
+ var CancelTaskRequestSchema = RequestSchema.extend({
1067
+ method: literal("tasks/cancel"),
1068
+ params: BaseRequestParamsSchema.extend({
1069
+ taskId: string()
1070
+ })
1071
+ });
1072
+ var CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
1073
+ var ResourceContentsSchema = object({
1074
+ /**
1075
+ * The URI of this resource.
1076
+ */
1077
+ uri: string(),
1078
+ /**
1079
+ * The MIME type of this resource, if known.
1080
+ */
1081
+ mimeType: optional(string()),
1082
+ /**
1083
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1084
+ * for notes on _meta usage.
1085
+ */
1086
+ _meta: record(string(), unknown()).optional()
1087
+ });
1088
+ var TextResourceContentsSchema = ResourceContentsSchema.extend({
1089
+ /**
1090
+ * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
1091
+ */
1092
+ text: string()
1093
+ });
1094
+ var Base64Schema = string().refine((val) => {
1095
+ try {
1096
+ atob(val);
1097
+ return true;
1098
+ } catch {
1099
+ return false;
1100
+ }
1101
+ }, { message: "Invalid Base64 string" });
1102
+ var BlobResourceContentsSchema = ResourceContentsSchema.extend({
1103
+ /**
1104
+ * A base64-encoded string representing the binary data of the item.
1105
+ */
1106
+ blob: Base64Schema
1107
+ });
1108
+ var RoleSchema = _enum(["user", "assistant"]);
1109
+ var AnnotationsSchema = object({
1110
+ /**
1111
+ * Intended audience(s) for the resource.
1112
+ */
1113
+ audience: array(RoleSchema).optional(),
1114
+ /**
1115
+ * Importance hint for the resource, from 0 (least) to 1 (most).
1116
+ */
1117
+ priority: number().min(0).max(1).optional(),
1118
+ /**
1119
+ * ISO 8601 timestamp for the most recent modification.
1120
+ */
1121
+ lastModified: iso_exports.datetime({ offset: true }).optional()
1122
+ });
1123
+ var ResourceSchema = object({
1124
+ ...BaseMetadataSchema.shape,
1125
+ ...IconsSchema.shape,
1126
+ /**
1127
+ * The URI of this resource.
1128
+ */
1129
+ uri: string(),
1130
+ /**
1131
+ * A description of what this resource represents.
1132
+ *
1133
+ * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
1134
+ */
1135
+ description: optional(string()),
1136
+ /**
1137
+ * The MIME type of this resource, if known.
1138
+ */
1139
+ mimeType: optional(string()),
1140
+ /**
1141
+ * Optional annotations for the client.
1142
+ */
1143
+ annotations: AnnotationsSchema.optional(),
1144
+ /**
1145
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1146
+ * for notes on _meta usage.
1147
+ */
1148
+ _meta: optional(looseObject({}))
1149
+ });
1150
+ var ResourceTemplateSchema = object({
1151
+ ...BaseMetadataSchema.shape,
1152
+ ...IconsSchema.shape,
1153
+ /**
1154
+ * A URI template (according to RFC 6570) that can be used to construct resource URIs.
1155
+ */
1156
+ uriTemplate: string(),
1157
+ /**
1158
+ * A description of what this template is for.
1159
+ *
1160
+ * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
1161
+ */
1162
+ description: optional(string()),
1163
+ /**
1164
+ * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
1165
+ */
1166
+ mimeType: optional(string()),
1167
+ /**
1168
+ * Optional annotations for the client.
1169
+ */
1170
+ annotations: AnnotationsSchema.optional(),
1171
+ /**
1172
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1173
+ * for notes on _meta usage.
1174
+ */
1175
+ _meta: optional(looseObject({}))
1176
+ });
1177
+ var ListResourcesRequestSchema = PaginatedRequestSchema.extend({
1178
+ method: literal("resources/list")
1179
+ });
1180
+ var ListResourcesResultSchema = PaginatedResultSchema.extend({
1181
+ resources: array(ResourceSchema)
1182
+ });
1183
+ var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
1184
+ method: literal("resources/templates/list")
1185
+ });
1186
+ var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
1187
+ resourceTemplates: array(ResourceTemplateSchema)
1188
+ });
1189
+ var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
1190
+ /**
1191
+ * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
1192
+ *
1193
+ * @format uri
1194
+ */
1195
+ uri: string()
1196
+ });
1197
+ var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
1198
+ var ReadResourceRequestSchema = RequestSchema.extend({
1199
+ method: literal("resources/read"),
1200
+ params: ReadResourceRequestParamsSchema
1201
+ });
1202
+ var ReadResourceResultSchema = ResultSchema.extend({
1203
+ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))
1204
+ });
1205
+ var ResourceListChangedNotificationSchema = NotificationSchema.extend({
1206
+ method: literal("notifications/resources/list_changed"),
1207
+ params: NotificationsParamsSchema.optional()
1208
+ });
1209
+ var SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
1210
+ var SubscribeRequestSchema = RequestSchema.extend({
1211
+ method: literal("resources/subscribe"),
1212
+ params: SubscribeRequestParamsSchema
1213
+ });
1214
+ var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
1215
+ var UnsubscribeRequestSchema = RequestSchema.extend({
1216
+ method: literal("resources/unsubscribe"),
1217
+ params: UnsubscribeRequestParamsSchema
1218
+ });
1219
+ var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({
1220
+ /**
1221
+ * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
1222
+ */
1223
+ uri: string()
1224
+ });
1225
+ var ResourceUpdatedNotificationSchema = NotificationSchema.extend({
1226
+ method: literal("notifications/resources/updated"),
1227
+ params: ResourceUpdatedNotificationParamsSchema
1228
+ });
1229
+ var PromptArgumentSchema = object({
1230
+ /**
1231
+ * The name of the argument.
1232
+ */
1233
+ name: string(),
1234
+ /**
1235
+ * A human-readable description of the argument.
1236
+ */
1237
+ description: optional(string()),
1238
+ /**
1239
+ * Whether this argument must be provided.
1240
+ */
1241
+ required: optional(boolean())
1242
+ });
1243
+ var PromptSchema = object({
1244
+ ...BaseMetadataSchema.shape,
1245
+ ...IconsSchema.shape,
1246
+ /**
1247
+ * An optional description of what this prompt provides
1248
+ */
1249
+ description: optional(string()),
1250
+ /**
1251
+ * A list of arguments to use for templating the prompt.
1252
+ */
1253
+ arguments: optional(array(PromptArgumentSchema)),
1254
+ /**
1255
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1256
+ * for notes on _meta usage.
1257
+ */
1258
+ _meta: optional(looseObject({}))
1259
+ });
1260
+ var ListPromptsRequestSchema = PaginatedRequestSchema.extend({
1261
+ method: literal("prompts/list")
1262
+ });
1263
+ var ListPromptsResultSchema = PaginatedResultSchema.extend({
1264
+ prompts: array(PromptSchema)
1265
+ });
1266
+ var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
1267
+ /**
1268
+ * The name of the prompt or prompt template.
1269
+ */
1270
+ name: string(),
1271
+ /**
1272
+ * Arguments to use for templating the prompt.
1273
+ */
1274
+ arguments: record(string(), string()).optional()
1275
+ });
1276
+ var GetPromptRequestSchema = RequestSchema.extend({
1277
+ method: literal("prompts/get"),
1278
+ params: GetPromptRequestParamsSchema
1279
+ });
1280
+ var TextContentSchema = object({
1281
+ type: literal("text"),
1282
+ /**
1283
+ * The text content of the message.
1284
+ */
1285
+ text: string(),
1286
+ /**
1287
+ * Optional annotations for the client.
1288
+ */
1289
+ annotations: AnnotationsSchema.optional(),
1290
+ /**
1291
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1292
+ * for notes on _meta usage.
1293
+ */
1294
+ _meta: record(string(), unknown()).optional()
1295
+ });
1296
+ var ImageContentSchema = object({
1297
+ type: literal("image"),
1298
+ /**
1299
+ * The base64-encoded image data.
1300
+ */
1301
+ data: Base64Schema,
1302
+ /**
1303
+ * The MIME type of the image. Different providers may support different image types.
1304
+ */
1305
+ mimeType: string(),
1306
+ /**
1307
+ * Optional annotations for the client.
1308
+ */
1309
+ annotations: AnnotationsSchema.optional(),
1310
+ /**
1311
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1312
+ * for notes on _meta usage.
1313
+ */
1314
+ _meta: record(string(), unknown()).optional()
1315
+ });
1316
+ var AudioContentSchema = object({
1317
+ type: literal("audio"),
1318
+ /**
1319
+ * The base64-encoded audio data.
1320
+ */
1321
+ data: Base64Schema,
1322
+ /**
1323
+ * The MIME type of the audio. Different providers may support different audio types.
1324
+ */
1325
+ mimeType: string(),
1326
+ /**
1327
+ * Optional annotations for the client.
1328
+ */
1329
+ annotations: AnnotationsSchema.optional(),
1330
+ /**
1331
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1332
+ * for notes on _meta usage.
1333
+ */
1334
+ _meta: record(string(), unknown()).optional()
1335
+ });
1336
+ var ToolUseContentSchema = object({
1337
+ type: literal("tool_use"),
1338
+ /**
1339
+ * The name of the tool to invoke.
1340
+ * Must match a tool name from the request's tools array.
1341
+ */
1342
+ name: string(),
1343
+ /**
1344
+ * Unique identifier for this tool call.
1345
+ * Used to correlate with ToolResultContent in subsequent messages.
1346
+ */
1347
+ id: string(),
1348
+ /**
1349
+ * Arguments to pass to the tool.
1350
+ * Must conform to the tool's inputSchema.
1351
+ */
1352
+ input: record(string(), unknown()),
1353
+ /**
1354
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1355
+ * for notes on _meta usage.
1356
+ */
1357
+ _meta: record(string(), unknown()).optional()
1358
+ });
1359
+ var EmbeddedResourceSchema = object({
1360
+ type: literal("resource"),
1361
+ resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
1362
+ /**
1363
+ * Optional annotations for the client.
1364
+ */
1365
+ annotations: AnnotationsSchema.optional(),
1366
+ /**
1367
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1368
+ * for notes on _meta usage.
1369
+ */
1370
+ _meta: record(string(), unknown()).optional()
1371
+ });
1372
+ var ResourceLinkSchema = ResourceSchema.extend({
1373
+ type: literal("resource_link")
1374
+ });
1375
+ var ContentBlockSchema = union([
1376
+ TextContentSchema,
1377
+ ImageContentSchema,
1378
+ AudioContentSchema,
1379
+ ResourceLinkSchema,
1380
+ EmbeddedResourceSchema
1381
+ ]);
1382
+ var PromptMessageSchema = object({
1383
+ role: RoleSchema,
1384
+ content: ContentBlockSchema
1385
+ });
1386
+ var GetPromptResultSchema = ResultSchema.extend({
1387
+ /**
1388
+ * An optional description for the prompt.
1389
+ */
1390
+ description: string().optional(),
1391
+ messages: array(PromptMessageSchema)
1392
+ });
1393
+ var PromptListChangedNotificationSchema = NotificationSchema.extend({
1394
+ method: literal("notifications/prompts/list_changed"),
1395
+ params: NotificationsParamsSchema.optional()
1396
+ });
1397
+ var ToolAnnotationsSchema = object({
1398
+ /**
1399
+ * A human-readable title for the tool.
1400
+ */
1401
+ title: string().optional(),
1402
+ /**
1403
+ * If true, the tool does not modify its environment.
1404
+ *
1405
+ * Default: false
1406
+ */
1407
+ readOnlyHint: boolean().optional(),
1408
+ /**
1409
+ * If true, the tool may perform destructive updates to its environment.
1410
+ * If false, the tool performs only additive updates.
1411
+ *
1412
+ * (This property is meaningful only when `readOnlyHint == false`)
1413
+ *
1414
+ * Default: true
1415
+ */
1416
+ destructiveHint: boolean().optional(),
1417
+ /**
1418
+ * If true, calling the tool repeatedly with the same arguments
1419
+ * will have no additional effect on the its environment.
1420
+ *
1421
+ * (This property is meaningful only when `readOnlyHint == false`)
1422
+ *
1423
+ * Default: false
1424
+ */
1425
+ idempotentHint: boolean().optional(),
1426
+ /**
1427
+ * If true, this tool may interact with an "open world" of external
1428
+ * entities. If false, the tool's domain of interaction is closed.
1429
+ * For example, the world of a web search tool is open, whereas that
1430
+ * of a memory tool is not.
1431
+ *
1432
+ * Default: true
1433
+ */
1434
+ openWorldHint: boolean().optional()
1435
+ });
1436
+ var ToolExecutionSchema = object({
1437
+ /**
1438
+ * Indicates the tool's preference for task-augmented execution.
1439
+ * - "required": Clients MUST invoke the tool as a task
1440
+ * - "optional": Clients MAY invoke the tool as a task or normal request
1441
+ * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task
1442
+ *
1443
+ * If not present, defaults to "forbidden".
1444
+ */
1445
+ taskSupport: _enum(["required", "optional", "forbidden"]).optional()
1446
+ });
1447
+ var ToolSchema = object({
1448
+ ...BaseMetadataSchema.shape,
1449
+ ...IconsSchema.shape,
1450
+ /**
1451
+ * A human-readable description of the tool.
1452
+ */
1453
+ description: string().optional(),
1454
+ /**
1455
+ * A JSON Schema 2020-12 object defining the expected parameters for the tool.
1456
+ * Must have type: 'object' at the root level per MCP spec.
1457
+ */
1458
+ inputSchema: object({
1459
+ type: literal("object"),
1460
+ properties: record(string(), AssertObjectSchema).optional(),
1461
+ required: array(string()).optional()
1462
+ }).catchall(unknown()),
1463
+ /**
1464
+ * An optional JSON Schema 2020-12 object defining the structure of the tool's output
1465
+ * returned in the structuredContent field of a CallToolResult.
1466
+ * Must have type: 'object' at the root level per MCP spec.
1467
+ */
1468
+ outputSchema: object({
1469
+ type: literal("object"),
1470
+ properties: record(string(), AssertObjectSchema).optional(),
1471
+ required: array(string()).optional()
1472
+ }).catchall(unknown()).optional(),
1473
+ /**
1474
+ * Optional additional tool information.
1475
+ */
1476
+ annotations: ToolAnnotationsSchema.optional(),
1477
+ /**
1478
+ * Execution-related properties for this tool.
1479
+ */
1480
+ execution: ToolExecutionSchema.optional(),
1481
+ /**
1482
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1483
+ * for notes on _meta usage.
1484
+ */
1485
+ _meta: record(string(), unknown()).optional()
1486
+ });
1487
+ var ListToolsRequestSchema = PaginatedRequestSchema.extend({
1488
+ method: literal("tools/list")
1489
+ });
1490
+ var ListToolsResultSchema = PaginatedResultSchema.extend({
1491
+ tools: array(ToolSchema)
1492
+ });
1493
+ var CallToolResultSchema = ResultSchema.extend({
1494
+ /**
1495
+ * A list of content objects that represent the result of the tool call.
1496
+ *
1497
+ * If the Tool does not define an outputSchema, this field MUST be present in the result.
1498
+ * For backwards compatibility, this field is always present, but it may be empty.
1499
+ */
1500
+ content: array(ContentBlockSchema).default([]),
1501
+ /**
1502
+ * An object containing structured tool output.
1503
+ *
1504
+ * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
1505
+ */
1506
+ structuredContent: record(string(), unknown()).optional(),
1507
+ /**
1508
+ * Whether the tool call ended in an error.
1509
+ *
1510
+ * If not set, this is assumed to be false (the call was successful).
1511
+ *
1512
+ * Any errors that originate from the tool SHOULD be reported inside the result
1513
+ * object, with `isError` set to true, _not_ as an MCP protocol-level error
1514
+ * response. Otherwise, the LLM would not be able to see that an error occurred
1515
+ * and self-correct.
1516
+ *
1517
+ * However, any errors in _finding_ the tool, an error indicating that the
1518
+ * server does not support tool calls, or any other exceptional conditions,
1519
+ * should be reported as an MCP error response.
1520
+ */
1521
+ isError: boolean().optional()
1522
+ });
1523
+ var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
1524
+ toolResult: unknown()
1525
+ }));
1526
+ var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
1527
+ /**
1528
+ * The name of the tool to call.
1529
+ */
1530
+ name: string(),
1531
+ /**
1532
+ * Arguments to pass to the tool.
1533
+ */
1534
+ arguments: record(string(), unknown()).optional()
1535
+ });
1536
+ var CallToolRequestSchema = RequestSchema.extend({
1537
+ method: literal("tools/call"),
1538
+ params: CallToolRequestParamsSchema
1539
+ });
1540
+ var ToolListChangedNotificationSchema = NotificationSchema.extend({
1541
+ method: literal("notifications/tools/list_changed"),
1542
+ params: NotificationsParamsSchema.optional()
1543
+ });
1544
+ var ListChangedOptionsBaseSchema = object({
1545
+ /**
1546
+ * If true, the list will be refreshed automatically when a list changed notification is received.
1547
+ * The callback will be called with the updated list.
1548
+ *
1549
+ * If false, the callback will be called with null items, allowing manual refresh.
1550
+ *
1551
+ * @default true
1552
+ */
1553
+ autoRefresh: boolean().default(true),
1554
+ /**
1555
+ * Debounce time in milliseconds for list changed notification processing.
1556
+ *
1557
+ * Multiple notifications received within this timeframe will only trigger one refresh.
1558
+ * Set to 0 to disable debouncing.
1559
+ *
1560
+ * @default 300
1561
+ */
1562
+ debounceMs: number().int().nonnegative().default(300)
1563
+ });
1564
+ var LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
1565
+ var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
1566
+ /**
1567
+ * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
1568
+ */
1569
+ level: LoggingLevelSchema
1570
+ });
1571
+ var SetLevelRequestSchema = RequestSchema.extend({
1572
+ method: literal("logging/setLevel"),
1573
+ params: SetLevelRequestParamsSchema
1574
+ });
1575
+ var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
1576
+ /**
1577
+ * The severity of this log message.
1578
+ */
1579
+ level: LoggingLevelSchema,
1580
+ /**
1581
+ * An optional name of the logger issuing this message.
1582
+ */
1583
+ logger: string().optional(),
1584
+ /**
1585
+ * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
1586
+ */
1587
+ data: unknown()
1588
+ });
1589
+ var LoggingMessageNotificationSchema = NotificationSchema.extend({
1590
+ method: literal("notifications/message"),
1591
+ params: LoggingMessageNotificationParamsSchema
1592
+ });
1593
+ var ModelHintSchema = object({
1594
+ /**
1595
+ * A hint for a model name.
1596
+ */
1597
+ name: string().optional()
1598
+ });
1599
+ var ModelPreferencesSchema = object({
1600
+ /**
1601
+ * Optional hints to use for model selection.
1602
+ */
1603
+ hints: array(ModelHintSchema).optional(),
1604
+ /**
1605
+ * How much to prioritize cost when selecting a model.
1606
+ */
1607
+ costPriority: number().min(0).max(1).optional(),
1608
+ /**
1609
+ * How much to prioritize sampling speed (latency) when selecting a model.
1610
+ */
1611
+ speedPriority: number().min(0).max(1).optional(),
1612
+ /**
1613
+ * How much to prioritize intelligence and capabilities when selecting a model.
1614
+ */
1615
+ intelligencePriority: number().min(0).max(1).optional()
1616
+ });
1617
+ var ToolChoiceSchema = object({
1618
+ /**
1619
+ * Controls when tools are used:
1620
+ * - "auto": Model decides whether to use tools (default)
1621
+ * - "required": Model MUST use at least one tool before completing
1622
+ * - "none": Model MUST NOT use any tools
1623
+ */
1624
+ mode: _enum(["auto", "required", "none"]).optional()
1625
+ });
1626
+ var ToolResultContentSchema = object({
1627
+ type: literal("tool_result"),
1628
+ toolUseId: string().describe("The unique identifier for the corresponding tool call."),
1629
+ content: array(ContentBlockSchema).default([]),
1630
+ structuredContent: object({}).loose().optional(),
1631
+ isError: boolean().optional(),
1632
+ /**
1633
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1634
+ * for notes on _meta usage.
1635
+ */
1636
+ _meta: record(string(), unknown()).optional()
1637
+ });
1638
+ var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
1639
+ var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
1640
+ TextContentSchema,
1641
+ ImageContentSchema,
1642
+ AudioContentSchema,
1643
+ ToolUseContentSchema,
1644
+ ToolResultContentSchema
1645
+ ]);
1646
+ var SamplingMessageSchema = object({
1647
+ role: RoleSchema,
1648
+ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
1649
+ /**
1650
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1651
+ * for notes on _meta usage.
1652
+ */
1653
+ _meta: record(string(), unknown()).optional()
1654
+ });
1655
+ var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
1656
+ messages: array(SamplingMessageSchema),
1657
+ /**
1658
+ * The server's preferences for which model to select. The client MAY modify or omit this request.
1659
+ */
1660
+ modelPreferences: ModelPreferencesSchema.optional(),
1661
+ /**
1662
+ * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
1663
+ */
1664
+ systemPrompt: string().optional(),
1665
+ /**
1666
+ * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.
1667
+ * The client MAY ignore this request.
1668
+ *
1669
+ * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client
1670
+ * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
1671
+ */
1672
+ includeContext: _enum(["none", "thisServer", "allServers"]).optional(),
1673
+ temperature: number().optional(),
1674
+ /**
1675
+ * The requested maximum number of tokens to sample (to prevent runaway completions).
1676
+ *
1677
+ * The client MAY choose to sample fewer tokens than the requested maximum.
1678
+ */
1679
+ maxTokens: number().int(),
1680
+ stopSequences: array(string()).optional(),
1681
+ /**
1682
+ * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
1683
+ */
1684
+ metadata: AssertObjectSchema.optional(),
1685
+ /**
1686
+ * Tools that the model may use during generation.
1687
+ * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
1688
+ */
1689
+ tools: array(ToolSchema).optional(),
1690
+ /**
1691
+ * Controls how the model uses tools.
1692
+ * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
1693
+ * Default is `{ mode: "auto" }`.
1694
+ */
1695
+ toolChoice: ToolChoiceSchema.optional()
1696
+ });
1697
+ var CreateMessageRequestSchema = RequestSchema.extend({
1698
+ method: literal("sampling/createMessage"),
1699
+ params: CreateMessageRequestParamsSchema
1700
+ });
1701
+ var CreateMessageResultSchema = ResultSchema.extend({
1702
+ /**
1703
+ * The name of the model that generated the message.
1704
+ */
1705
+ model: string(),
1706
+ /**
1707
+ * The reason why sampling stopped, if known.
1708
+ *
1709
+ * Standard values:
1710
+ * - "endTurn": Natural end of the assistant's turn
1711
+ * - "stopSequence": A stop sequence was encountered
1712
+ * - "maxTokens": Maximum token limit was reached
1713
+ *
1714
+ * This field is an open string to allow for provider-specific stop reasons.
1715
+ */
1716
+ stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string())),
1717
+ role: RoleSchema,
1718
+ /**
1719
+ * Response content. Single content block (text, image, or audio).
1720
+ */
1721
+ content: SamplingContentSchema
1722
+ });
1723
+ var CreateMessageResultWithToolsSchema = ResultSchema.extend({
1724
+ /**
1725
+ * The name of the model that generated the message.
1726
+ */
1727
+ model: string(),
1728
+ /**
1729
+ * The reason why sampling stopped, if known.
1730
+ *
1731
+ * Standard values:
1732
+ * - "endTurn": Natural end of the assistant's turn
1733
+ * - "stopSequence": A stop sequence was encountered
1734
+ * - "maxTokens": Maximum token limit was reached
1735
+ * - "toolUse": The model wants to use one or more tools
1736
+ *
1737
+ * This field is an open string to allow for provider-specific stop reasons.
1738
+ */
1739
+ stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string())),
1740
+ role: RoleSchema,
1741
+ /**
1742
+ * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
1743
+ */
1744
+ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
1745
+ });
1746
+ var BooleanSchemaSchema = object({
1747
+ type: literal("boolean"),
1748
+ title: string().optional(),
1749
+ description: string().optional(),
1750
+ default: boolean().optional()
1751
+ });
1752
+ var StringSchemaSchema = object({
1753
+ type: literal("string"),
1754
+ title: string().optional(),
1755
+ description: string().optional(),
1756
+ minLength: number().optional(),
1757
+ maxLength: number().optional(),
1758
+ format: _enum(["email", "uri", "date", "date-time"]).optional(),
1759
+ default: string().optional()
1760
+ });
1761
+ var NumberSchemaSchema = object({
1762
+ type: _enum(["number", "integer"]),
1763
+ title: string().optional(),
1764
+ description: string().optional(),
1765
+ minimum: number().optional(),
1766
+ maximum: number().optional(),
1767
+ default: number().optional()
1768
+ });
1769
+ var UntitledSingleSelectEnumSchemaSchema = object({
1770
+ type: literal("string"),
1771
+ title: string().optional(),
1772
+ description: string().optional(),
1773
+ enum: array(string()),
1774
+ default: string().optional()
1775
+ });
1776
+ var TitledSingleSelectEnumSchemaSchema = object({
1777
+ type: literal("string"),
1778
+ title: string().optional(),
1779
+ description: string().optional(),
1780
+ oneOf: array(object({
1781
+ const: string(),
1782
+ title: string()
1783
+ })),
1784
+ default: string().optional()
1785
+ });
1786
+ var LegacyTitledEnumSchemaSchema = object({
1787
+ type: literal("string"),
1788
+ title: string().optional(),
1789
+ description: string().optional(),
1790
+ enum: array(string()),
1791
+ enumNames: array(string()).optional(),
1792
+ default: string().optional()
1793
+ });
1794
+ var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
1795
+ var UntitledMultiSelectEnumSchemaSchema = object({
1796
+ type: literal("array"),
1797
+ title: string().optional(),
1798
+ description: string().optional(),
1799
+ minItems: number().optional(),
1800
+ maxItems: number().optional(),
1801
+ items: object({
1802
+ type: literal("string"),
1803
+ enum: array(string())
1804
+ }),
1805
+ default: array(string()).optional()
1806
+ });
1807
+ var TitledMultiSelectEnumSchemaSchema = object({
1808
+ type: literal("array"),
1809
+ title: string().optional(),
1810
+ description: string().optional(),
1811
+ minItems: number().optional(),
1812
+ maxItems: number().optional(),
1813
+ items: object({
1814
+ anyOf: array(object({
1815
+ const: string(),
1816
+ title: string()
1817
+ }))
1818
+ }),
1819
+ default: array(string()).optional()
1820
+ });
1821
+ var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
1822
+ var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
1823
+ var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
1824
+ var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
1825
+ /**
1826
+ * The elicitation mode.
1827
+ *
1828
+ * Optional for backward compatibility. Clients MUST treat missing mode as "form".
1829
+ */
1830
+ mode: literal("form").optional(),
1831
+ /**
1832
+ * The message to present to the user describing what information is being requested.
1833
+ */
1834
+ message: string(),
1835
+ /**
1836
+ * A restricted subset of JSON Schema.
1837
+ * Only top-level properties are allowed, without nesting.
1838
+ */
1839
+ requestedSchema: object({
1840
+ type: literal("object"),
1841
+ properties: record(string(), PrimitiveSchemaDefinitionSchema),
1842
+ required: array(string()).optional()
1843
+ })
1844
+ });
1845
+ var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
1846
+ /**
1847
+ * The elicitation mode.
1848
+ */
1849
+ mode: literal("url"),
1850
+ /**
1851
+ * The message to present to the user explaining why the interaction is needed.
1852
+ */
1853
+ message: string(),
1854
+ /**
1855
+ * The ID of the elicitation, which must be unique within the context of the server.
1856
+ * The client MUST treat this ID as an opaque value.
1857
+ */
1858
+ elicitationId: string(),
1859
+ /**
1860
+ * The URL that the user should navigate to.
1861
+ */
1862
+ url: string().url()
1863
+ });
1864
+ var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
1865
+ var ElicitRequestSchema = RequestSchema.extend({
1866
+ method: literal("elicitation/create"),
1867
+ params: ElicitRequestParamsSchema
1868
+ });
1869
+ var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
1870
+ /**
1871
+ * The ID of the elicitation that completed.
1872
+ */
1873
+ elicitationId: string()
1874
+ });
1875
+ var ElicitationCompleteNotificationSchema = NotificationSchema.extend({
1876
+ method: literal("notifications/elicitation/complete"),
1877
+ params: ElicitationCompleteNotificationParamsSchema
1878
+ });
1879
+ var ElicitResultSchema = ResultSchema.extend({
1880
+ /**
1881
+ * The user action in response to the elicitation.
1882
+ * - "accept": User submitted the form/confirmed the action
1883
+ * - "decline": User explicitly decline the action
1884
+ * - "cancel": User dismissed without making an explicit choice
1885
+ */
1886
+ action: _enum(["accept", "decline", "cancel"]),
1887
+ /**
1888
+ * The submitted form data, only present when action is "accept".
1889
+ * Contains values matching the requested schema.
1890
+ * Per MCP spec, content is "typically omitted" for decline/cancel actions.
1891
+ * We normalize null to undefined for leniency while maintaining type compatibility.
1892
+ */
1893
+ content: preprocess((val) => val === null ? void 0 : val, record(string(), union([string(), number(), boolean(), array(string())])).optional())
1894
+ });
1895
+ var ResourceTemplateReferenceSchema = object({
1896
+ type: literal("ref/resource"),
1897
+ /**
1898
+ * The URI or URI template of the resource.
1899
+ */
1900
+ uri: string()
1901
+ });
1902
+ var PromptReferenceSchema = object({
1903
+ type: literal("ref/prompt"),
1904
+ /**
1905
+ * The name of the prompt or prompt template
1906
+ */
1907
+ name: string()
1908
+ });
1909
+ var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
1910
+ ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
1911
+ /**
1912
+ * The argument's information
1913
+ */
1914
+ argument: object({
1915
+ /**
1916
+ * The name of the argument
1917
+ */
1918
+ name: string(),
1919
+ /**
1920
+ * The value of the argument to use for completion matching.
1921
+ */
1922
+ value: string()
1923
+ }),
1924
+ context: object({
1925
+ /**
1926
+ * Previously-resolved variables in a URI template or prompt.
1927
+ */
1928
+ arguments: record(string(), string()).optional()
1929
+ }).optional()
1930
+ });
1931
+ var CompleteRequestSchema = RequestSchema.extend({
1932
+ method: literal("completion/complete"),
1933
+ params: CompleteRequestParamsSchema
1934
+ });
1935
+ var CompleteResultSchema = ResultSchema.extend({
1936
+ completion: looseObject({
1937
+ /**
1938
+ * An array of completion values. Must not exceed 100 items.
1939
+ */
1940
+ values: array(string()).max(100),
1941
+ /**
1942
+ * The total number of completion options available. This can exceed the number of values actually sent in the response.
1943
+ */
1944
+ total: optional(number().int()),
1945
+ /**
1946
+ * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
1947
+ */
1948
+ hasMore: optional(boolean())
1949
+ })
1950
+ });
1951
+ var RootSchema = object({
1952
+ /**
1953
+ * The URI identifying the root. This *must* start with file:// for now.
1954
+ */
1955
+ uri: string().startsWith("file://"),
1956
+ /**
1957
+ * An optional name for the root.
1958
+ */
1959
+ name: string().optional(),
1960
+ /**
1961
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1962
+ * for notes on _meta usage.
1963
+ */
1964
+ _meta: record(string(), unknown()).optional()
1965
+ });
1966
+ var ListRootsRequestSchema = RequestSchema.extend({
1967
+ method: literal("roots/list"),
1968
+ params: BaseRequestParamsSchema.optional()
1969
+ });
1970
+ var ListRootsResultSchema = ResultSchema.extend({
1971
+ roots: array(RootSchema)
1972
+ });
1973
+ var RootsListChangedNotificationSchema = NotificationSchema.extend({
1974
+ method: literal("notifications/roots/list_changed"),
1975
+ params: NotificationsParamsSchema.optional()
1976
+ });
1977
+ var ClientRequestSchema = union([
1978
+ PingRequestSchema,
1979
+ InitializeRequestSchema,
1980
+ CompleteRequestSchema,
1981
+ SetLevelRequestSchema,
1982
+ GetPromptRequestSchema,
1983
+ ListPromptsRequestSchema,
1984
+ ListResourcesRequestSchema,
1985
+ ListResourceTemplatesRequestSchema,
1986
+ ReadResourceRequestSchema,
1987
+ SubscribeRequestSchema,
1988
+ UnsubscribeRequestSchema,
1989
+ CallToolRequestSchema,
1990
+ ListToolsRequestSchema,
1991
+ GetTaskRequestSchema,
1992
+ GetTaskPayloadRequestSchema,
1993
+ ListTasksRequestSchema,
1994
+ CancelTaskRequestSchema
1995
+ ]);
1996
+ var ClientNotificationSchema = union([
1997
+ CancelledNotificationSchema,
1998
+ ProgressNotificationSchema,
1999
+ InitializedNotificationSchema,
2000
+ RootsListChangedNotificationSchema,
2001
+ TaskStatusNotificationSchema
2002
+ ]);
2003
+ var ClientResultSchema = union([
2004
+ EmptyResultSchema,
2005
+ CreateMessageResultSchema,
2006
+ CreateMessageResultWithToolsSchema,
2007
+ ElicitResultSchema,
2008
+ ListRootsResultSchema,
2009
+ GetTaskResultSchema,
2010
+ ListTasksResultSchema,
2011
+ CreateTaskResultSchema
2012
+ ]);
2013
+ var ServerRequestSchema = union([
2014
+ PingRequestSchema,
2015
+ CreateMessageRequestSchema,
2016
+ ElicitRequestSchema,
2017
+ ListRootsRequestSchema,
2018
+ GetTaskRequestSchema,
2019
+ GetTaskPayloadRequestSchema,
2020
+ ListTasksRequestSchema,
2021
+ CancelTaskRequestSchema
2022
+ ]);
2023
+ var ServerNotificationSchema = union([
2024
+ CancelledNotificationSchema,
2025
+ ProgressNotificationSchema,
2026
+ LoggingMessageNotificationSchema,
2027
+ ResourceUpdatedNotificationSchema,
2028
+ ResourceListChangedNotificationSchema,
2029
+ ToolListChangedNotificationSchema,
2030
+ PromptListChangedNotificationSchema,
2031
+ TaskStatusNotificationSchema,
2032
+ ElicitationCompleteNotificationSchema
2033
+ ]);
2034
+ var ServerResultSchema = union([
2035
+ EmptyResultSchema,
2036
+ InitializeResultSchema,
2037
+ CompleteResultSchema,
2038
+ GetPromptResultSchema,
2039
+ ListPromptsResultSchema,
2040
+ ListResourcesResultSchema,
2041
+ ListResourceTemplatesResultSchema,
2042
+ ReadResourceResultSchema,
2043
+ CallToolResultSchema,
2044
+ ListToolsResultSchema,
2045
+ GetTaskResultSchema,
2046
+ ListTasksResultSchema,
2047
+ CreateTaskResultSchema
2048
+ ]);
2049
+ var McpError = class _McpError extends Error {
2050
+ static {
2051
+ __name(this, "McpError");
2052
+ }
2053
+ constructor(code, message, data) {
2054
+ super(`MCP error ${code}: ${message}`);
2055
+ this.code = code;
2056
+ this.data = data;
2057
+ this.name = "McpError";
2058
+ }
2059
+ /**
2060
+ * Factory method to create the appropriate error type based on the error code and data
2061
+ */
2062
+ static fromError(code, message, data) {
2063
+ if (code === ErrorCode.UrlElicitationRequired && data) {
2064
+ const errorData = data;
2065
+ if (errorData.elicitations) {
2066
+ return new UrlElicitationRequiredError(errorData.elicitations, message);
2067
+ }
2068
+ }
2069
+ return new _McpError(code, message, data);
2070
+ }
2071
+ };
2072
+ var UrlElicitationRequiredError = class extends McpError {
2073
+ static {
2074
+ __name(this, "UrlElicitationRequiredError");
2075
+ }
2076
+ constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
2077
+ super(ErrorCode.UrlElicitationRequired, message, {
2078
+ elicitations
2079
+ });
2080
+ }
2081
+ get elicitations() {
2082
+ return this.data?.elicitations ?? [];
2083
+ }
2084
+ };
2085
+
2086
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
2087
+ init_esbuild_shims();
2088
+
2089
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
2090
+ init_esbuild_shims();
2091
+
2092
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
2093
+ init_esbuild_shims();
2094
+
2095
+ // node_modules/zod/v4/mini/parse.js
2096
+ init_esbuild_shims();
2097
+
2098
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
2099
+ function isZ4Schema(s) {
2100
+ const schema = s;
2101
+ return !!schema._zod;
2102
+ }
2103
+ __name(isZ4Schema, "isZ4Schema");
2104
+ function safeParse2(schema, data) {
2105
+ if (isZ4Schema(schema)) {
2106
+ const result2 = safeParse(schema, data);
2107
+ return result2;
2108
+ }
2109
+ const v3Schema = schema;
2110
+ const result = v3Schema.safeParse(data);
2111
+ return result;
2112
+ }
2113
+ __name(safeParse2, "safeParse");
2114
+ function getObjectShape(schema) {
2115
+ if (!schema)
2116
+ return void 0;
2117
+ let rawShape;
2118
+ if (isZ4Schema(schema)) {
2119
+ const v4Schema = schema;
2120
+ rawShape = v4Schema._zod?.def?.shape;
2121
+ } else {
2122
+ const v3Schema = schema;
2123
+ rawShape = v3Schema.shape;
2124
+ }
2125
+ if (!rawShape)
2126
+ return void 0;
2127
+ if (typeof rawShape === "function") {
2128
+ try {
2129
+ return rawShape();
2130
+ } catch {
2131
+ return void 0;
2132
+ }
2133
+ }
2134
+ return rawShape;
2135
+ }
2136
+ __name(getObjectShape, "getObjectShape");
2137
+ function getLiteralValue(schema) {
2138
+ if (isZ4Schema(schema)) {
2139
+ const v4Schema = schema;
2140
+ const def2 = v4Schema._zod?.def;
2141
+ if (def2) {
2142
+ if (def2.value !== void 0)
2143
+ return def2.value;
2144
+ if (Array.isArray(def2.values) && def2.values.length > 0) {
2145
+ return def2.values[0];
2146
+ }
2147
+ }
2148
+ }
2149
+ const v3Schema = schema;
2150
+ const def = v3Schema._def;
2151
+ if (def) {
2152
+ if (def.value !== void 0)
2153
+ return def.value;
2154
+ if (Array.isArray(def.values) && def.values.length > 0) {
2155
+ return def.values[0];
2156
+ }
2157
+ }
2158
+ const directValue = schema.value;
2159
+ if (directValue !== void 0)
2160
+ return directValue;
2161
+ return void 0;
2162
+ }
2163
+ __name(getLiteralValue, "getLiteralValue");
2164
+
2165
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
2166
+ init_esbuild_shims();
2167
+ function isTerminal(status) {
2168
+ return status === "completed" || status === "failed" || status === "cancelled";
2169
+ }
2170
+ __name(isTerminal, "isTerminal");
2171
+
2172
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
2173
+ init_esbuild_shims();
2174
+
2175
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/index.js
2176
+ init_esbuild_shims();
2177
+
2178
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/Options.js
2179
+ init_esbuild_shims();
2180
+ var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
2181
+
2182
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/Refs.js
2183
+ init_esbuild_shims();
2184
+
2185
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
2186
+ init_esbuild_shims();
2187
+
2188
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
2189
+ init_esbuild_shims();
2190
+
2191
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parseDef.js
2192
+ init_esbuild_shims();
2193
+
2194
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/selectParser.js
2195
+ init_esbuild_shims();
2196
+
2197
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
2198
+ init_esbuild_shims();
2199
+
2200
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
2201
+ init_esbuild_shims();
2202
+
2203
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
2204
+ init_esbuild_shims();
2205
+
2206
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
2207
+ init_esbuild_shims();
2208
+
2209
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
2210
+ init_esbuild_shims();
2211
+
2212
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
2213
+ init_esbuild_shims();
2214
+
2215
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/date.js
2216
+ init_esbuild_shims();
2217
+
2218
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/default.js
2219
+ init_esbuild_shims();
2220
+
2221
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
2222
+ init_esbuild_shims();
2223
+
2224
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
2225
+ init_esbuild_shims();
2226
+
2227
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
2228
+ init_esbuild_shims();
2229
+
2230
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
2231
+ init_esbuild_shims();
2232
+
2233
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/map.js
2234
+ init_esbuild_shims();
2235
+
2236
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
2237
+ init_esbuild_shims();
2238
+
2239
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
2240
+ init_esbuild_shims();
2241
+ var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
2242
+
2243
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
2244
+ init_esbuild_shims();
2245
+
2246
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
2247
+ init_esbuild_shims();
2248
+
2249
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/null.js
2250
+ init_esbuild_shims();
2251
+
2252
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
2253
+ init_esbuild_shims();
2254
+
2255
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/union.js
2256
+ init_esbuild_shims();
2257
+
2258
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/number.js
2259
+ init_esbuild_shims();
2260
+
2261
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/object.js
2262
+ init_esbuild_shims();
2263
+
2264
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
2265
+ init_esbuild_shims();
2266
+
2267
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
2268
+ init_esbuild_shims();
2269
+
2270
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
2271
+ init_esbuild_shims();
2272
+
2273
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/set.js
2274
+ init_esbuild_shims();
2275
+
2276
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
2277
+ init_esbuild_shims();
2278
+
2279
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
2280
+ init_esbuild_shims();
2281
+
2282
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
2283
+ init_esbuild_shims();
2284
+
2285
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
2286
+ init_esbuild_shims();
2287
+
2288
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/parseTypes.js
2289
+ init_esbuild_shims();
2290
+
2291
+ // packages/core/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
2292
+ init_esbuild_shims();
2293
+
2294
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
2295
+ function getMethodLiteral(schema) {
2296
+ const shape = getObjectShape(schema);
2297
+ const methodSchema = shape?.method;
2298
+ if (!methodSchema) {
2299
+ throw new Error("Schema is missing a method literal");
2300
+ }
2301
+ const value = getLiteralValue(methodSchema);
2302
+ if (typeof value !== "string") {
2303
+ throw new Error("Schema method literal must be a string");
2304
+ }
2305
+ return value;
2306
+ }
2307
+ __name(getMethodLiteral, "getMethodLiteral");
2308
+ function parseWithCompat(schema, data) {
2309
+ const result = safeParse2(schema, data);
2310
+ if (!result.success) {
2311
+ throw result.error;
2312
+ }
2313
+ return result.data;
2314
+ }
2315
+ __name(parseWithCompat, "parseWithCompat");
2316
+
2317
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
2318
+ var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;
2319
+ var Protocol = class {
2320
+ static {
2321
+ __name(this, "Protocol");
2322
+ }
2323
+ constructor(_options) {
2324
+ this._options = _options;
2325
+ this._requestMessageId = 0;
2326
+ this._requestHandlers = /* @__PURE__ */ new Map();
2327
+ this._requestHandlerAbortControllers = /* @__PURE__ */ new Map();
2328
+ this._notificationHandlers = /* @__PURE__ */ new Map();
2329
+ this._responseHandlers = /* @__PURE__ */ new Map();
2330
+ this._progressHandlers = /* @__PURE__ */ new Map();
2331
+ this._timeoutInfo = /* @__PURE__ */ new Map();
2332
+ this._pendingDebouncedNotifications = /* @__PURE__ */ new Set();
2333
+ this._taskProgressTokens = /* @__PURE__ */ new Map();
2334
+ this._requestResolvers = /* @__PURE__ */ new Map();
2335
+ this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
2336
+ this._oncancel(notification);
2337
+ });
2338
+ this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
2339
+ this._onprogress(notification);
2340
+ });
2341
+ this.setRequestHandler(
2342
+ PingRequestSchema,
2343
+ // Automatic pong by default.
2344
+ (_request) => ({})
2345
+ );
2346
+ this._taskStore = _options?.taskStore;
2347
+ this._taskMessageQueue = _options?.taskMessageQueue;
2348
+ if (this._taskStore) {
2349
+ this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {
2350
+ const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
2351
+ if (!task) {
2352
+ throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
2353
+ }
2354
+ return {
2355
+ ...task
2356
+ };
2357
+ });
2358
+ this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
2359
+ const handleTaskResult = /* @__PURE__ */ __name(async () => {
2360
+ const taskId = request.params.taskId;
2361
+ if (this._taskMessageQueue) {
2362
+ let queuedMessage;
2363
+ while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
2364
+ if (queuedMessage.type === "response" || queuedMessage.type === "error") {
2365
+ const message = queuedMessage.message;
2366
+ const requestId = message.id;
2367
+ const resolver = this._requestResolvers.get(requestId);
2368
+ if (resolver) {
2369
+ this._requestResolvers.delete(requestId);
2370
+ if (queuedMessage.type === "response") {
2371
+ resolver(message);
2372
+ } else {
2373
+ const errorMessage = message;
2374
+ const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
2375
+ resolver(error);
2376
+ }
2377
+ } else {
2378
+ const messageType = queuedMessage.type === "response" ? "Response" : "Error";
2379
+ this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
2380
+ }
2381
+ continue;
2382
+ }
2383
+ await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });
2384
+ }
2385
+ }
2386
+ const task = await this._taskStore.getTask(taskId, extra.sessionId);
2387
+ if (!task) {
2388
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
2389
+ }
2390
+ if (!isTerminal(task.status)) {
2391
+ await this._waitForTaskUpdate(taskId, extra.signal);
2392
+ return await handleTaskResult();
2393
+ }
2394
+ if (isTerminal(task.status)) {
2395
+ const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
2396
+ this._clearTaskQueue(taskId);
2397
+ return {
2398
+ ...result,
2399
+ _meta: {
2400
+ ...result._meta,
2401
+ [RELATED_TASK_META_KEY]: {
2402
+ taskId
2403
+ }
2404
+ }
2405
+ };
2406
+ }
2407
+ return await handleTaskResult();
2408
+ }, "handleTaskResult");
2409
+ return await handleTaskResult();
2410
+ });
2411
+ this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {
2412
+ try {
2413
+ const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);
2414
+ return {
2415
+ tasks,
2416
+ nextCursor,
2417
+ _meta: {}
2418
+ };
2419
+ } catch (error) {
2420
+ throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);
2421
+ }
2422
+ });
2423
+ this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {
2424
+ try {
2425
+ const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
2426
+ if (!task) {
2427
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);
2428
+ }
2429
+ if (isTerminal(task.status)) {
2430
+ throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
2431
+ }
2432
+ await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
2433
+ this._clearTaskQueue(request.params.taskId);
2434
+ const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
2435
+ if (!cancelledTask) {
2436
+ throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
2437
+ }
2438
+ return {
2439
+ _meta: {},
2440
+ ...cancelledTask
2441
+ };
2442
+ } catch (error) {
2443
+ if (error instanceof McpError) {
2444
+ throw error;
2445
+ }
2446
+ throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);
2447
+ }
2448
+ });
2449
+ }
2450
+ }
2451
+ async _oncancel(notification) {
2452
+ if (!notification.params.requestId) {
2453
+ return;
2454
+ }
2455
+ const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
2456
+ controller?.abort(notification.params.reason);
2457
+ }
2458
+ _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
2459
+ this._timeoutInfo.set(messageId, {
2460
+ timeoutId: setTimeout(onTimeout, timeout),
2461
+ startTime: Date.now(),
2462
+ timeout,
2463
+ maxTotalTimeout,
2464
+ resetTimeoutOnProgress,
2465
+ onTimeout
2466
+ });
2467
+ }
2468
+ _resetTimeout(messageId) {
2469
+ const info = this._timeoutInfo.get(messageId);
2470
+ if (!info)
2471
+ return false;
2472
+ const totalElapsed = Date.now() - info.startTime;
2473
+ if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
2474
+ this._timeoutInfo.delete(messageId);
2475
+ throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
2476
+ maxTotalTimeout: info.maxTotalTimeout,
2477
+ totalElapsed
2478
+ });
2479
+ }
2480
+ clearTimeout(info.timeoutId);
2481
+ info.timeoutId = setTimeout(info.onTimeout, info.timeout);
2482
+ return true;
2483
+ }
2484
+ _cleanupTimeout(messageId) {
2485
+ const info = this._timeoutInfo.get(messageId);
2486
+ if (info) {
2487
+ clearTimeout(info.timeoutId);
2488
+ this._timeoutInfo.delete(messageId);
2489
+ }
2490
+ }
2491
+ /**
2492
+ * Attaches to the given transport, starts it, and starts listening for messages.
2493
+ *
2494
+ * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
2495
+ */
2496
+ async connect(transport) {
2497
+ this._transport = transport;
2498
+ const _onclose = this.transport?.onclose;
2499
+ this._transport.onclose = () => {
2500
+ _onclose?.();
2501
+ this._onclose();
2502
+ };
2503
+ const _onerror = this.transport?.onerror;
2504
+ this._transport.onerror = (error) => {
2505
+ _onerror?.(error);
2506
+ this._onerror(error);
2507
+ };
2508
+ const _onmessage = this._transport?.onmessage;
2509
+ this._transport.onmessage = (message, extra) => {
2510
+ _onmessage?.(message, extra);
2511
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
2512
+ this._onresponse(message);
2513
+ } else if (isJSONRPCRequest(message)) {
2514
+ this._onrequest(message, extra);
2515
+ } else if (isJSONRPCNotification(message)) {
2516
+ this._onnotification(message);
2517
+ } else {
2518
+ this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
2519
+ }
2520
+ };
2521
+ await this._transport.start();
2522
+ }
2523
+ _onclose() {
2524
+ const responseHandlers = this._responseHandlers;
2525
+ this._responseHandlers = /* @__PURE__ */ new Map();
2526
+ this._progressHandlers.clear();
2527
+ this._taskProgressTokens.clear();
2528
+ this._pendingDebouncedNotifications.clear();
2529
+ const error = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
2530
+ this._transport = void 0;
2531
+ this.onclose?.();
2532
+ for (const handler of responseHandlers.values()) {
2533
+ handler(error);
2534
+ }
2535
+ }
2536
+ _onerror(error) {
2537
+ this.onerror?.(error);
2538
+ }
2539
+ _onnotification(notification) {
2540
+ const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
2541
+ if (handler === void 0) {
2542
+ return;
2543
+ }
2544
+ Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
2545
+ }
2546
+ _onrequest(request, extra) {
2547
+ const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
2548
+ const capturedTransport = this._transport;
2549
+ const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
2550
+ if (handler === void 0) {
2551
+ const errorResponse = {
2552
+ jsonrpc: "2.0",
2553
+ id: request.id,
2554
+ error: {
2555
+ code: ErrorCode.MethodNotFound,
2556
+ message: "Method not found"
2557
+ }
2558
+ };
2559
+ if (relatedTaskId && this._taskMessageQueue) {
2560
+ this._enqueueTaskMessage(relatedTaskId, {
2561
+ type: "error",
2562
+ message: errorResponse,
2563
+ timestamp: Date.now()
2564
+ }, capturedTransport?.sessionId).catch((error) => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));
2565
+ } else {
2566
+ capturedTransport?.send(errorResponse).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
2567
+ }
2568
+ return;
2569
+ }
2570
+ const abortController = new AbortController();
2571
+ this._requestHandlerAbortControllers.set(request.id, abortController);
2572
+ const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0;
2573
+ const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0;
2574
+ const fullExtra = {
2575
+ signal: abortController.signal,
2576
+ sessionId: capturedTransport?.sessionId,
2577
+ _meta: request.params?._meta,
2578
+ sendNotification: /* @__PURE__ */ __name(async (notification) => {
2579
+ const notificationOptions = { relatedRequestId: request.id };
2580
+ if (relatedTaskId) {
2581
+ notificationOptions.relatedTask = { taskId: relatedTaskId };
2582
+ }
2583
+ await this.notification(notification, notificationOptions);
2584
+ }, "sendNotification"),
2585
+ sendRequest: /* @__PURE__ */ __name(async (r, resultSchema, options) => {
2586
+ const requestOptions = { ...options, relatedRequestId: request.id };
2587
+ if (relatedTaskId && !requestOptions.relatedTask) {
2588
+ requestOptions.relatedTask = { taskId: relatedTaskId };
2589
+ }
2590
+ const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
2591
+ if (effectiveTaskId && taskStore) {
2592
+ await taskStore.updateTaskStatus(effectiveTaskId, "input_required");
2593
+ }
2594
+ return await this.request(r, resultSchema, requestOptions);
2595
+ }, "sendRequest"),
2596
+ authInfo: extra?.authInfo,
2597
+ requestId: request.id,
2598
+ requestInfo: extra?.requestInfo,
2599
+ taskId: relatedTaskId,
2600
+ taskStore,
2601
+ taskRequestedTtl: taskCreationParams?.ttl,
2602
+ closeSSEStream: extra?.closeSSEStream,
2603
+ closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
2604
+ };
2605
+ Promise.resolve().then(() => {
2606
+ if (taskCreationParams) {
2607
+ this.assertTaskHandlerCapability(request.method);
2608
+ }
2609
+ }).then(() => handler(request, fullExtra)).then(async (result) => {
2610
+ if (abortController.signal.aborted) {
2611
+ return;
2612
+ }
2613
+ const response = {
2614
+ result,
2615
+ jsonrpc: "2.0",
2616
+ id: request.id
2617
+ };
2618
+ if (relatedTaskId && this._taskMessageQueue) {
2619
+ await this._enqueueTaskMessage(relatedTaskId, {
2620
+ type: "response",
2621
+ message: response,
2622
+ timestamp: Date.now()
2623
+ }, capturedTransport?.sessionId);
2624
+ } else {
2625
+ await capturedTransport?.send(response);
2626
+ }
2627
+ }, async (error) => {
2628
+ if (abortController.signal.aborted) {
2629
+ return;
2630
+ }
2631
+ const errorResponse = {
2632
+ jsonrpc: "2.0",
2633
+ id: request.id,
2634
+ error: {
2635
+ code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError,
2636
+ message: error.message ?? "Internal error",
2637
+ ...error["data"] !== void 0 && { data: error["data"] }
2638
+ }
2639
+ };
2640
+ if (relatedTaskId && this._taskMessageQueue) {
2641
+ await this._enqueueTaskMessage(relatedTaskId, {
2642
+ type: "error",
2643
+ message: errorResponse,
2644
+ timestamp: Date.now()
2645
+ }, capturedTransport?.sessionId);
2646
+ } else {
2647
+ await capturedTransport?.send(errorResponse);
2648
+ }
2649
+ }).catch((error) => this._onerror(new Error(`Failed to send response: ${error}`))).finally(() => {
2650
+ this._requestHandlerAbortControllers.delete(request.id);
2651
+ });
2652
+ }
2653
+ _onprogress(notification) {
2654
+ const { progressToken, ...params } = notification.params;
2655
+ const messageId = Number(progressToken);
2656
+ const handler = this._progressHandlers.get(messageId);
2657
+ if (!handler) {
2658
+ this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
2659
+ return;
2660
+ }
2661
+ const responseHandler = this._responseHandlers.get(messageId);
2662
+ const timeoutInfo = this._timeoutInfo.get(messageId);
2663
+ if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {
2664
+ try {
2665
+ this._resetTimeout(messageId);
2666
+ } catch (error) {
2667
+ this._responseHandlers.delete(messageId);
2668
+ this._progressHandlers.delete(messageId);
2669
+ this._cleanupTimeout(messageId);
2670
+ responseHandler(error);
2671
+ return;
2672
+ }
2673
+ }
2674
+ handler(params);
2675
+ }
2676
+ _onresponse(response) {
2677
+ const messageId = Number(response.id);
2678
+ const resolver = this._requestResolvers.get(messageId);
2679
+ if (resolver) {
2680
+ this._requestResolvers.delete(messageId);
2681
+ if (isJSONRPCResultResponse(response)) {
2682
+ resolver(response);
2683
+ } else {
2684
+ const error = new McpError(response.error.code, response.error.message, response.error.data);
2685
+ resolver(error);
2686
+ }
2687
+ return;
2688
+ }
2689
+ const handler = this._responseHandlers.get(messageId);
2690
+ if (handler === void 0) {
2691
+ this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
2692
+ return;
2693
+ }
2694
+ this._responseHandlers.delete(messageId);
2695
+ this._cleanupTimeout(messageId);
2696
+ let isTaskResponse = false;
2697
+ if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") {
2698
+ const result = response.result;
2699
+ if (result.task && typeof result.task === "object") {
2700
+ const task = result.task;
2701
+ if (typeof task.taskId === "string") {
2702
+ isTaskResponse = true;
2703
+ this._taskProgressTokens.set(task.taskId, messageId);
2704
+ }
2705
+ }
2706
+ }
2707
+ if (!isTaskResponse) {
2708
+ this._progressHandlers.delete(messageId);
2709
+ }
2710
+ if (isJSONRPCResultResponse(response)) {
2711
+ handler(response);
2712
+ } else {
2713
+ const error = McpError.fromError(response.error.code, response.error.message, response.error.data);
2714
+ handler(error);
2715
+ }
2716
+ }
2717
+ get transport() {
2718
+ return this._transport;
2719
+ }
2720
+ /**
2721
+ * Closes the connection.
2722
+ */
2723
+ async close() {
2724
+ await this._transport?.close();
2725
+ }
2726
+ /**
2727
+ * Sends a request and returns an AsyncGenerator that yields response messages.
2728
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
2729
+ *
2730
+ * @example
2731
+ * ```typescript
2732
+ * const stream = protocol.requestStream(request, resultSchema, options);
2733
+ * for await (const message of stream) {
2734
+ * switch (message.type) {
2735
+ * case 'taskCreated':
2736
+ * console.log('Task created:', message.task.taskId);
2737
+ * break;
2738
+ * case 'taskStatus':
2739
+ * console.log('Task status:', message.task.status);
2740
+ * break;
2741
+ * case 'result':
2742
+ * console.log('Final result:', message.result);
2743
+ * break;
2744
+ * case 'error':
2745
+ * console.error('Error:', message.error);
2746
+ * break;
2747
+ * }
2748
+ * }
2749
+ * ```
2750
+ *
2751
+ * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
2752
+ */
2753
+ async *requestStream(request, resultSchema, options) {
2754
+ const { task } = options ?? {};
2755
+ if (!task) {
2756
+ try {
2757
+ const result = await this.request(request, resultSchema, options);
2758
+ yield { type: "result", result };
2759
+ } catch (error) {
2760
+ yield {
2761
+ type: "error",
2762
+ error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))
2763
+ };
2764
+ }
2765
+ return;
2766
+ }
2767
+ let taskId;
2768
+ try {
2769
+ const createResult = await this.request(request, CreateTaskResultSchema, options);
2770
+ if (createResult.task) {
2771
+ taskId = createResult.task.taskId;
2772
+ yield { type: "taskCreated", task: createResult.task };
2773
+ } else {
2774
+ throw new McpError(ErrorCode.InternalError, "Task creation did not return a task");
2775
+ }
2776
+ while (true) {
2777
+ const task2 = await this.getTask({ taskId }, options);
2778
+ yield { type: "taskStatus", task: task2 };
2779
+ if (isTerminal(task2.status)) {
2780
+ if (task2.status === "completed") {
2781
+ const result = await this.getTaskResult({ taskId }, resultSchema, options);
2782
+ yield { type: "result", result };
2783
+ } else if (task2.status === "failed") {
2784
+ yield {
2785
+ type: "error",
2786
+ error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)
2787
+ };
2788
+ } else if (task2.status === "cancelled") {
2789
+ yield {
2790
+ type: "error",
2791
+ error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)
2792
+ };
2793
+ }
2794
+ return;
2795
+ }
2796
+ if (task2.status === "input_required") {
2797
+ const result = await this.getTaskResult({ taskId }, resultSchema, options);
2798
+ yield { type: "result", result };
2799
+ return;
2800
+ }
2801
+ const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
2802
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
2803
+ options?.signal?.throwIfAborted();
2804
+ }
2805
+ } catch (error) {
2806
+ yield {
2807
+ type: "error",
2808
+ error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))
2809
+ };
2810
+ }
2811
+ }
2812
+ /**
2813
+ * Sends a request and waits for a response.
2814
+ *
2815
+ * Do not use this method to emit notifications! Use notification() instead.
2816
+ */
2817
+ request(request, resultSchema, options) {
2818
+ const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
2819
+ return new Promise((resolve, reject) => {
2820
+ const earlyReject = /* @__PURE__ */ __name((error) => {
2821
+ reject(error);
2822
+ }, "earlyReject");
2823
+ if (!this._transport) {
2824
+ earlyReject(new Error("Not connected"));
2825
+ return;
2826
+ }
2827
+ if (this._options?.enforceStrictCapabilities === true) {
2828
+ try {
2829
+ this.assertCapabilityForMethod(request.method);
2830
+ if (task) {
2831
+ this.assertTaskCapability(request.method);
2832
+ }
2833
+ } catch (e) {
2834
+ earlyReject(e);
2835
+ return;
2836
+ }
2837
+ }
2838
+ options?.signal?.throwIfAborted();
2839
+ const messageId = this._requestMessageId++;
2840
+ const jsonrpcRequest = {
2841
+ ...request,
2842
+ jsonrpc: "2.0",
2843
+ id: messageId
2844
+ };
2845
+ if (options?.onprogress) {
2846
+ this._progressHandlers.set(messageId, options.onprogress);
2847
+ jsonrpcRequest.params = {
2848
+ ...request.params,
2849
+ _meta: {
2850
+ ...request.params?._meta || {},
2851
+ progressToken: messageId
2852
+ }
2853
+ };
2854
+ }
2855
+ if (task) {
2856
+ jsonrpcRequest.params = {
2857
+ ...jsonrpcRequest.params,
2858
+ task
2859
+ };
2860
+ }
2861
+ if (relatedTask) {
2862
+ jsonrpcRequest.params = {
2863
+ ...jsonrpcRequest.params,
2864
+ _meta: {
2865
+ ...jsonrpcRequest.params?._meta || {},
2866
+ [RELATED_TASK_META_KEY]: relatedTask
2867
+ }
2868
+ };
2869
+ }
2870
+ const cancel = /* @__PURE__ */ __name((reason) => {
2871
+ this._responseHandlers.delete(messageId);
2872
+ this._progressHandlers.delete(messageId);
2873
+ this._cleanupTimeout(messageId);
2874
+ this._transport?.send({
2875
+ jsonrpc: "2.0",
2876
+ method: "notifications/cancelled",
2877
+ params: {
2878
+ requestId: messageId,
2879
+ reason: String(reason)
2880
+ }
2881
+ }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => this._onerror(new Error(`Failed to send cancellation: ${error2}`)));
2882
+ const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));
2883
+ reject(error);
2884
+ }, "cancel");
2885
+ this._responseHandlers.set(messageId, (response) => {
2886
+ if (options?.signal?.aborted) {
2887
+ return;
2888
+ }
2889
+ if (response instanceof Error) {
2890
+ return reject(response);
2891
+ }
2892
+ try {
2893
+ const parseResult = safeParse2(resultSchema, response.result);
2894
+ if (!parseResult.success) {
2895
+ reject(parseResult.error);
2896
+ } else {
2897
+ resolve(parseResult.data);
2898
+ }
2899
+ } catch (error) {
2900
+ reject(error);
2901
+ }
2902
+ });
2903
+ options?.signal?.addEventListener("abort", () => {
2904
+ cancel(options?.signal?.reason);
2905
+ });
2906
+ const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
2907
+ const timeoutHandler = /* @__PURE__ */ __name(() => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout })), "timeoutHandler");
2908
+ this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
2909
+ const relatedTaskId = relatedTask?.taskId;
2910
+ if (relatedTaskId) {
2911
+ const responseResolver = /* @__PURE__ */ __name((response) => {
2912
+ const handler = this._responseHandlers.get(messageId);
2913
+ if (handler) {
2914
+ handler(response);
2915
+ } else {
2916
+ this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));
2917
+ }
2918
+ }, "responseResolver");
2919
+ this._requestResolvers.set(messageId, responseResolver);
2920
+ this._enqueueTaskMessage(relatedTaskId, {
2921
+ type: "request",
2922
+ message: jsonrpcRequest,
2923
+ timestamp: Date.now()
2924
+ }).catch((error) => {
2925
+ this._cleanupTimeout(messageId);
2926
+ reject(error);
2927
+ });
2928
+ } else {
2929
+ this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => {
2930
+ this._cleanupTimeout(messageId);
2931
+ reject(error);
2932
+ });
2933
+ }
2934
+ });
2935
+ }
2936
+ /**
2937
+ * Gets the current status of a task.
2938
+ *
2939
+ * @experimental Use `client.experimental.tasks.getTask()` to access this method.
2940
+ */
2941
+ async getTask(params, options) {
2942
+ return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options);
2943
+ }
2944
+ /**
2945
+ * Retrieves the result of a completed task.
2946
+ *
2947
+ * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.
2948
+ */
2949
+ async getTaskResult(params, resultSchema, options) {
2950
+ return this.request({ method: "tasks/result", params }, resultSchema, options);
2951
+ }
2952
+ /**
2953
+ * Lists tasks, optionally starting from a pagination cursor.
2954
+ *
2955
+ * @experimental Use `client.experimental.tasks.listTasks()` to access this method.
2956
+ */
2957
+ async listTasks(params, options) {
2958
+ return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options);
2959
+ }
2960
+ /**
2961
+ * Cancels a specific task.
2962
+ *
2963
+ * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.
2964
+ */
2965
+ async cancelTask(params, options) {
2966
+ return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options);
2967
+ }
2968
+ /**
2969
+ * Emits a notification, which is a one-way message that does not expect a response.
2970
+ */
2971
+ async notification(notification, options) {
2972
+ if (!this._transport) {
2973
+ throw new Error("Not connected");
2974
+ }
2975
+ this.assertNotificationCapability(notification.method);
2976
+ const relatedTaskId = options?.relatedTask?.taskId;
2977
+ if (relatedTaskId) {
2978
+ const jsonrpcNotification2 = {
2979
+ ...notification,
2980
+ jsonrpc: "2.0",
2981
+ params: {
2982
+ ...notification.params,
2983
+ _meta: {
2984
+ ...notification.params?._meta || {},
2985
+ [RELATED_TASK_META_KEY]: options.relatedTask
2986
+ }
2987
+ }
2988
+ };
2989
+ await this._enqueueTaskMessage(relatedTaskId, {
2990
+ type: "notification",
2991
+ message: jsonrpcNotification2,
2992
+ timestamp: Date.now()
2993
+ });
2994
+ return;
2995
+ }
2996
+ const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];
2997
+ const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;
2998
+ if (canDebounce) {
2999
+ if (this._pendingDebouncedNotifications.has(notification.method)) {
3000
+ return;
3001
+ }
3002
+ this._pendingDebouncedNotifications.add(notification.method);
3003
+ Promise.resolve().then(() => {
3004
+ this._pendingDebouncedNotifications.delete(notification.method);
3005
+ if (!this._transport) {
3006
+ return;
3007
+ }
3008
+ let jsonrpcNotification2 = {
3009
+ ...notification,
3010
+ jsonrpc: "2.0"
3011
+ };
3012
+ if (options?.relatedTask) {
3013
+ jsonrpcNotification2 = {
3014
+ ...jsonrpcNotification2,
3015
+ params: {
3016
+ ...jsonrpcNotification2.params,
3017
+ _meta: {
3018
+ ...jsonrpcNotification2.params?._meta || {},
3019
+ [RELATED_TASK_META_KEY]: options.relatedTask
3020
+ }
3021
+ }
3022
+ };
3023
+ }
3024
+ this._transport?.send(jsonrpcNotification2, options).catch((error) => this._onerror(error));
3025
+ });
3026
+ return;
3027
+ }
3028
+ let jsonrpcNotification = {
3029
+ ...notification,
3030
+ jsonrpc: "2.0"
3031
+ };
3032
+ if (options?.relatedTask) {
3033
+ jsonrpcNotification = {
3034
+ ...jsonrpcNotification,
3035
+ params: {
3036
+ ...jsonrpcNotification.params,
3037
+ _meta: {
3038
+ ...jsonrpcNotification.params?._meta || {},
3039
+ [RELATED_TASK_META_KEY]: options.relatedTask
3040
+ }
3041
+ }
3042
+ };
3043
+ }
3044
+ await this._transport.send(jsonrpcNotification, options);
3045
+ }
3046
+ /**
3047
+ * Registers a handler to invoke when this protocol object receives a request with the given method.
3048
+ *
3049
+ * Note that this will replace any previous request handler for the same method.
3050
+ */
3051
+ setRequestHandler(requestSchema, handler) {
3052
+ const method = getMethodLiteral(requestSchema);
3053
+ this.assertRequestHandlerCapability(method);
3054
+ this._requestHandlers.set(method, (request, extra) => {
3055
+ const parsed = parseWithCompat(requestSchema, request);
3056
+ return Promise.resolve(handler(parsed, extra));
3057
+ });
3058
+ }
3059
+ /**
3060
+ * Removes the request handler for the given method.
3061
+ */
3062
+ removeRequestHandler(method) {
3063
+ this._requestHandlers.delete(method);
3064
+ }
3065
+ /**
3066
+ * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.
3067
+ */
3068
+ assertCanSetRequestHandler(method) {
3069
+ if (this._requestHandlers.has(method)) {
3070
+ throw new Error(`A request handler for ${method} already exists, which would be overridden`);
3071
+ }
3072
+ }
3073
+ /**
3074
+ * Registers a handler to invoke when this protocol object receives a notification with the given method.
3075
+ *
3076
+ * Note that this will replace any previous notification handler for the same method.
3077
+ */
3078
+ setNotificationHandler(notificationSchema, handler) {
3079
+ const method = getMethodLiteral(notificationSchema);
3080
+ this._notificationHandlers.set(method, (notification) => {
3081
+ const parsed = parseWithCompat(notificationSchema, notification);
3082
+ return Promise.resolve(handler(parsed));
3083
+ });
3084
+ }
3085
+ /**
3086
+ * Removes the notification handler for the given method.
3087
+ */
3088
+ removeNotificationHandler(method) {
3089
+ this._notificationHandlers.delete(method);
3090
+ }
3091
+ /**
3092
+ * Cleans up the progress handler associated with a task.
3093
+ * This should be called when a task reaches a terminal status.
3094
+ */
3095
+ _cleanupTaskProgressHandler(taskId) {
3096
+ const progressToken = this._taskProgressTokens.get(taskId);
3097
+ if (progressToken !== void 0) {
3098
+ this._progressHandlers.delete(progressToken);
3099
+ this._taskProgressTokens.delete(taskId);
3100
+ }
3101
+ }
3102
+ /**
3103
+ * Enqueues a task-related message for side-channel delivery via tasks/result.
3104
+ * @param taskId The task ID to associate the message with
3105
+ * @param message The message to enqueue
3106
+ * @param sessionId Optional session ID for binding the operation to a specific session
3107
+ * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
3108
+ *
3109
+ * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
3110
+ * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
3111
+ * simply propagates the error.
3112
+ */
3113
+ async _enqueueTaskMessage(taskId, message, sessionId) {
3114
+ if (!this._taskStore || !this._taskMessageQueue) {
3115
+ throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
3116
+ }
3117
+ const maxQueueSize = this._options?.maxTaskQueueSize;
3118
+ await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
3119
+ }
3120
+ /**
3121
+ * Clears the message queue for a task and rejects any pending request resolvers.
3122
+ * @param taskId The task ID whose queue should be cleared
3123
+ * @param sessionId Optional session ID for binding the operation to a specific session
3124
+ */
3125
+ async _clearTaskQueue(taskId, sessionId) {
3126
+ if (this._taskMessageQueue) {
3127
+ const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
3128
+ for (const message of messages) {
3129
+ if (message.type === "request" && isJSONRPCRequest(message.message)) {
3130
+ const requestId = message.message.id;
3131
+ const resolver = this._requestResolvers.get(requestId);
3132
+ if (resolver) {
3133
+ resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed"));
3134
+ this._requestResolvers.delete(requestId);
3135
+ } else {
3136
+ this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
3137
+ }
3138
+ }
3139
+ }
3140
+ }
3141
+ }
3142
+ /**
3143
+ * Waits for a task update (new messages or status change) with abort signal support.
3144
+ * Uses polling to check for updates at the task's configured poll interval.
3145
+ * @param taskId The task ID to wait for
3146
+ * @param signal Abort signal to cancel the wait
3147
+ * @returns Promise that resolves when an update occurs or rejects if aborted
3148
+ */
3149
+ async _waitForTaskUpdate(taskId, signal) {
3150
+ let interval = this._options?.defaultTaskPollInterval ?? 1e3;
3151
+ try {
3152
+ const task = await this._taskStore?.getTask(taskId);
3153
+ if (task?.pollInterval) {
3154
+ interval = task.pollInterval;
3155
+ }
3156
+ } catch {
3157
+ }
3158
+ return new Promise((resolve, reject) => {
3159
+ if (signal.aborted) {
3160
+ reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
3161
+ return;
3162
+ }
3163
+ const timeoutId = setTimeout(resolve, interval);
3164
+ signal.addEventListener("abort", () => {
3165
+ clearTimeout(timeoutId);
3166
+ reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
3167
+ }, { once: true });
3168
+ });
3169
+ }
3170
+ requestTaskStore(request, sessionId) {
3171
+ const taskStore = this._taskStore;
3172
+ if (!taskStore) {
3173
+ throw new Error("No task store configured");
3174
+ }
3175
+ return {
3176
+ createTask: /* @__PURE__ */ __name(async (taskParams) => {
3177
+ if (!request) {
3178
+ throw new Error("No request provided");
3179
+ }
3180
+ return await taskStore.createTask(taskParams, request.id, {
3181
+ method: request.method,
3182
+ params: request.params
3183
+ }, sessionId);
3184
+ }, "createTask"),
3185
+ getTask: /* @__PURE__ */ __name(async (taskId) => {
3186
+ const task = await taskStore.getTask(taskId, sessionId);
3187
+ if (!task) {
3188
+ throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
3189
+ }
3190
+ return task;
3191
+ }, "getTask"),
3192
+ storeTaskResult: /* @__PURE__ */ __name(async (taskId, status, result) => {
3193
+ await taskStore.storeTaskResult(taskId, status, result, sessionId);
3194
+ const task = await taskStore.getTask(taskId, sessionId);
3195
+ if (task) {
3196
+ const notification = TaskStatusNotificationSchema.parse({
3197
+ method: "notifications/tasks/status",
3198
+ params: task
3199
+ });
3200
+ await this.notification(notification);
3201
+ if (isTerminal(task.status)) {
3202
+ this._cleanupTaskProgressHandler(taskId);
3203
+ }
3204
+ }
3205
+ }, "storeTaskResult"),
3206
+ getTaskResult: /* @__PURE__ */ __name((taskId) => {
3207
+ return taskStore.getTaskResult(taskId, sessionId);
3208
+ }, "getTaskResult"),
3209
+ updateTaskStatus: /* @__PURE__ */ __name(async (taskId, status, statusMessage) => {
3210
+ const task = await taskStore.getTask(taskId, sessionId);
3211
+ if (!task) {
3212
+ throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
3213
+ }
3214
+ if (isTerminal(task.status)) {
3215
+ throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
3216
+ }
3217
+ await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
3218
+ const updatedTask = await taskStore.getTask(taskId, sessionId);
3219
+ if (updatedTask) {
3220
+ const notification = TaskStatusNotificationSchema.parse({
3221
+ method: "notifications/tasks/status",
3222
+ params: updatedTask
3223
+ });
3224
+ await this.notification(notification);
3225
+ if (isTerminal(updatedTask.status)) {
3226
+ this._cleanupTaskProgressHandler(taskId);
3227
+ }
3228
+ }
3229
+ }, "updateTaskStatus"),
3230
+ listTasks: /* @__PURE__ */ __name((cursor) => {
3231
+ return taskStore.listTasks(cursor, sessionId);
3232
+ }, "listTasks")
3233
+ };
3234
+ }
3235
+ };
3236
+ function isPlainObject(value) {
3237
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3238
+ }
3239
+ __name(isPlainObject, "isPlainObject");
3240
+ function mergeCapabilities(base, additional) {
3241
+ const result = { ...base };
3242
+ for (const key in additional) {
3243
+ const k = key;
3244
+ const addValue = additional[k];
3245
+ if (addValue === void 0)
3246
+ continue;
3247
+ const baseValue = result[k];
3248
+ if (isPlainObject(baseValue) && isPlainObject(addValue)) {
3249
+ result[k] = { ...baseValue, ...addValue };
3250
+ } else {
3251
+ result[k] = addValue;
3252
+ }
3253
+ }
3254
+ return result;
3255
+ }
3256
+ __name(mergeCapabilities, "mergeCapabilities");
3257
+
3258
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
3259
+ init_esbuild_shims();
3260
+ var import_ajv = __toESM(require_ajv(), 1);
3261
+ var import_ajv_formats = __toESM(require_dist(), 1);
3262
+ function createDefaultAjvInstance() {
3263
+ const ajv = new import_ajv.default({
3264
+ strict: false,
3265
+ validateFormats: true,
3266
+ validateSchema: false,
3267
+ allErrors: true
3268
+ });
3269
+ const addFormats = import_ajv_formats.default;
3270
+ addFormats(ajv);
3271
+ return ajv;
3272
+ }
3273
+ __name(createDefaultAjvInstance, "createDefaultAjvInstance");
3274
+ var AjvJsonSchemaValidator = class {
3275
+ static {
3276
+ __name(this, "AjvJsonSchemaValidator");
3277
+ }
3278
+ /**
3279
+ * Create an AJV validator
3280
+ *
3281
+ * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.
3282
+ *
3283
+ * @example
3284
+ * ```typescript
3285
+ * // Use default configuration (recommended for most cases)
3286
+ * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
3287
+ * const validator = new AjvJsonSchemaValidator();
3288
+ *
3289
+ * // Or provide custom AJV instance for advanced configuration
3290
+ * import { Ajv } from 'ajv';
3291
+ * import addFormats from 'ajv-formats';
3292
+ *
3293
+ * const ajv = new Ajv({ validateFormats: true });
3294
+ * addFormats(ajv);
3295
+ * const validator = new AjvJsonSchemaValidator(ajv);
3296
+ * ```
3297
+ */
3298
+ constructor(ajv) {
3299
+ this._ajv = ajv ?? createDefaultAjvInstance();
3300
+ }
3301
+ /**
3302
+ * Create a validator for the given JSON Schema
3303
+ *
3304
+ * The validator is compiled once and can be reused multiple times.
3305
+ * If the schema has an $id, it will be cached by AJV automatically.
3306
+ *
3307
+ * @param schema - Standard JSON Schema object
3308
+ * @returns A validator function that validates input data
3309
+ */
3310
+ getValidator(schema) {
3311
+ const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema);
3312
+ return (input) => {
3313
+ const valid = ajvValidator(input);
3314
+ if (valid) {
3315
+ return {
3316
+ valid: true,
3317
+ data: input,
3318
+ errorMessage: void 0
3319
+ };
3320
+ } else {
3321
+ return {
3322
+ valid: false,
3323
+ data: void 0,
3324
+ errorMessage: this._ajv.errorsText(ajvValidator.errors)
3325
+ };
3326
+ }
3327
+ };
3328
+ }
3329
+ };
3330
+
3331
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
3332
+ init_esbuild_shims();
3333
+ var ExperimentalClientTasks = class {
3334
+ static {
3335
+ __name(this, "ExperimentalClientTasks");
3336
+ }
3337
+ constructor(_client) {
3338
+ this._client = _client;
3339
+ }
3340
+ /**
3341
+ * Calls a tool and returns an AsyncGenerator that yields response messages.
3342
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
3343
+ *
3344
+ * This method provides streaming access to tool execution, allowing you to
3345
+ * observe intermediate task status updates for long-running tool calls.
3346
+ * Automatically validates structured output if the tool has an outputSchema.
3347
+ *
3348
+ * @example
3349
+ * ```typescript
3350
+ * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
3351
+ * for await (const message of stream) {
3352
+ * switch (message.type) {
3353
+ * case 'taskCreated':
3354
+ * console.log('Tool execution started:', message.task.taskId);
3355
+ * break;
3356
+ * case 'taskStatus':
3357
+ * console.log('Tool status:', message.task.status);
3358
+ * break;
3359
+ * case 'result':
3360
+ * console.log('Tool result:', message.result);
3361
+ * break;
3362
+ * case 'error':
3363
+ * console.error('Tool error:', message.error);
3364
+ * break;
3365
+ * }
3366
+ * }
3367
+ * ```
3368
+ *
3369
+ * @param params - Tool call parameters (name and arguments)
3370
+ * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
3371
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
3372
+ * @returns AsyncGenerator that yields ResponseMessage objects
3373
+ *
3374
+ * @experimental
3375
+ */
3376
+ async *callToolStream(params, resultSchema = CallToolResultSchema, options) {
3377
+ const clientInternal = this._client;
3378
+ const optionsWithTask = {
3379
+ ...options,
3380
+ // We check if the tool is known to be a task during auto-configuration, but assume
3381
+ // the caller knows what they're doing if they pass this explicitly
3382
+ task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : void 0)
3383
+ };
3384
+ const stream = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
3385
+ const validator = clientInternal.getToolOutputValidator(params.name);
3386
+ for await (const message of stream) {
3387
+ if (message.type === "result" && validator) {
3388
+ const result = message.result;
3389
+ if (!result.structuredContent && !result.isError) {
3390
+ yield {
3391
+ type: "error",
3392
+ error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
3393
+ };
3394
+ return;
3395
+ }
3396
+ if (result.structuredContent) {
3397
+ try {
3398
+ const validationResult = validator(result.structuredContent);
3399
+ if (!validationResult.valid) {
3400
+ yield {
3401
+ type: "error",
3402
+ error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
3403
+ };
3404
+ return;
3405
+ }
3406
+ } catch (error) {
3407
+ if (error instanceof McpError) {
3408
+ yield { type: "error", error };
3409
+ return;
3410
+ }
3411
+ yield {
3412
+ type: "error",
3413
+ error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)
3414
+ };
3415
+ return;
3416
+ }
3417
+ }
3418
+ }
3419
+ yield message;
3420
+ }
3421
+ }
3422
+ /**
3423
+ * Gets the current status of a task.
3424
+ *
3425
+ * @param taskId - The task identifier
3426
+ * @param options - Optional request options
3427
+ * @returns The task status
3428
+ *
3429
+ * @experimental
3430
+ */
3431
+ async getTask(taskId, options) {
3432
+ return this._client.getTask({ taskId }, options);
3433
+ }
3434
+ /**
3435
+ * Retrieves the result of a completed task.
3436
+ *
3437
+ * @param taskId - The task identifier
3438
+ * @param resultSchema - Zod schema for validating the result
3439
+ * @param options - Optional request options
3440
+ * @returns The task result
3441
+ *
3442
+ * @experimental
3443
+ */
3444
+ async getTaskResult(taskId, resultSchema, options) {
3445
+ return this._client.getTaskResult({ taskId }, resultSchema, options);
3446
+ }
3447
+ /**
3448
+ * Lists tasks with optional pagination.
3449
+ *
3450
+ * @param cursor - Optional pagination cursor
3451
+ * @param options - Optional request options
3452
+ * @returns List of tasks with optional next cursor
3453
+ *
3454
+ * @experimental
3455
+ */
3456
+ async listTasks(cursor, options) {
3457
+ return this._client.listTasks(cursor ? { cursor } : void 0, options);
3458
+ }
3459
+ /**
3460
+ * Cancels a running task.
3461
+ *
3462
+ * @param taskId - The task identifier
3463
+ * @param options - Optional request options
3464
+ *
3465
+ * @experimental
3466
+ */
3467
+ async cancelTask(taskId, options) {
3468
+ return this._client.cancelTask({ taskId }, options);
3469
+ }
3470
+ /**
3471
+ * Sends a request and returns an AsyncGenerator that yields response messages.
3472
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
3473
+ *
3474
+ * This method provides streaming access to request processing, allowing you to
3475
+ * observe intermediate task status updates for task-augmented requests.
3476
+ *
3477
+ * @param request - The request to send
3478
+ * @param resultSchema - Zod schema for validating the result
3479
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
3480
+ * @returns AsyncGenerator that yields ResponseMessage objects
3481
+ *
3482
+ * @experimental
3483
+ */
3484
+ requestStream(request, resultSchema, options) {
3485
+ return this._client.requestStream(request, resultSchema, options);
3486
+ }
3487
+ };
3488
+
3489
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js
3490
+ init_esbuild_shims();
3491
+ function assertToolsCallTaskCapability(requests, method, entityName) {
3492
+ if (!requests) {
3493
+ throw new Error(`${entityName} does not support task creation (required for ${method})`);
3494
+ }
3495
+ switch (method) {
3496
+ case "tools/call":
3497
+ if (!requests.tools?.call) {
3498
+ throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
3499
+ }
3500
+ break;
3501
+ default:
3502
+ break;
3503
+ }
3504
+ }
3505
+ __name(assertToolsCallTaskCapability, "assertToolsCallTaskCapability");
3506
+ function assertClientRequestTaskCapability(requests, method, entityName) {
3507
+ if (!requests) {
3508
+ throw new Error(`${entityName} does not support task creation (required for ${method})`);
3509
+ }
3510
+ switch (method) {
3511
+ case "sampling/createMessage":
3512
+ if (!requests.sampling?.createMessage) {
3513
+ throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
3514
+ }
3515
+ break;
3516
+ case "elicitation/create":
3517
+ if (!requests.elicitation?.create) {
3518
+ throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
3519
+ }
3520
+ break;
3521
+ default:
3522
+ break;
3523
+ }
3524
+ }
3525
+ __name(assertClientRequestTaskCapability, "assertClientRequestTaskCapability");
3526
+
3527
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
3528
+ function applyElicitationDefaults(schema, data) {
3529
+ if (!schema || data === null || typeof data !== "object")
3530
+ return;
3531
+ if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
3532
+ const obj = data;
3533
+ const props = schema.properties;
3534
+ for (const key of Object.keys(props)) {
3535
+ const propSchema = props[key];
3536
+ if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) {
3537
+ obj[key] = propSchema.default;
3538
+ }
3539
+ if (obj[key] !== void 0) {
3540
+ applyElicitationDefaults(propSchema, obj[key]);
3541
+ }
3542
+ }
3543
+ }
3544
+ if (Array.isArray(schema.anyOf)) {
3545
+ for (const sub of schema.anyOf) {
3546
+ if (typeof sub !== "boolean") {
3547
+ applyElicitationDefaults(sub, data);
3548
+ }
3549
+ }
3550
+ }
3551
+ if (Array.isArray(schema.oneOf)) {
3552
+ for (const sub of schema.oneOf) {
3553
+ if (typeof sub !== "boolean") {
3554
+ applyElicitationDefaults(sub, data);
3555
+ }
3556
+ }
3557
+ }
3558
+ }
3559
+ __name(applyElicitationDefaults, "applyElicitationDefaults");
3560
+ function getSupportedElicitationModes(capabilities) {
3561
+ if (!capabilities) {
3562
+ return { supportsFormMode: false, supportsUrlMode: false };
3563
+ }
3564
+ const hasFormCapability = capabilities.form !== void 0;
3565
+ const hasUrlCapability = capabilities.url !== void 0;
3566
+ const supportsFormMode = hasFormCapability || !hasFormCapability && !hasUrlCapability;
3567
+ const supportsUrlMode = hasUrlCapability;
3568
+ return { supportsFormMode, supportsUrlMode };
3569
+ }
3570
+ __name(getSupportedElicitationModes, "getSupportedElicitationModes");
3571
+ var Client = class extends Protocol {
3572
+ static {
3573
+ __name(this, "Client");
3574
+ }
3575
+ /**
3576
+ * Initializes this client with the given name and version information.
3577
+ */
3578
+ constructor(_clientInfo, options) {
3579
+ super(options);
3580
+ this._clientInfo = _clientInfo;
3581
+ this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
3582
+ this._cachedKnownTaskTools = /* @__PURE__ */ new Set();
3583
+ this._cachedRequiredTaskTools = /* @__PURE__ */ new Set();
3584
+ this._listChangedDebounceTimers = /* @__PURE__ */ new Map();
3585
+ this._capabilities = options?.capabilities ?? {};
3586
+ this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
3587
+ if (options?.listChanged) {
3588
+ this._pendingListChangedConfig = options.listChanged;
3589
+ }
3590
+ }
3591
+ /**
3592
+ * Set up handlers for list changed notifications based on config and server capabilities.
3593
+ * This should only be called after initialization when server capabilities are known.
3594
+ * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
3595
+ * @internal
3596
+ */
3597
+ _setupListChangedHandlers(config) {
3598
+ if (config.tools && this._serverCapabilities?.tools?.listChanged) {
3599
+ this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config.tools, async () => {
3600
+ const result = await this.listTools();
3601
+ return result.tools;
3602
+ });
3603
+ }
3604
+ if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {
3605
+ this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config.prompts, async () => {
3606
+ const result = await this.listPrompts();
3607
+ return result.prompts;
3608
+ });
3609
+ }
3610
+ if (config.resources && this._serverCapabilities?.resources?.listChanged) {
3611
+ this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config.resources, async () => {
3612
+ const result = await this.listResources();
3613
+ return result.resources;
3614
+ });
3615
+ }
3616
+ }
3617
+ /**
3618
+ * Access experimental features.
3619
+ *
3620
+ * WARNING: These APIs are experimental and may change without notice.
3621
+ *
3622
+ * @experimental
3623
+ */
3624
+ get experimental() {
3625
+ if (!this._experimental) {
3626
+ this._experimental = {
3627
+ tasks: new ExperimentalClientTasks(this)
3628
+ };
3629
+ }
3630
+ return this._experimental;
3631
+ }
3632
+ /**
3633
+ * Registers new capabilities. This can only be called before connecting to a transport.
3634
+ *
3635
+ * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
3636
+ */
3637
+ registerCapabilities(capabilities) {
3638
+ if (this.transport) {
3639
+ throw new Error("Cannot register capabilities after connecting to transport");
3640
+ }
3641
+ this._capabilities = mergeCapabilities(this._capabilities, capabilities);
3642
+ }
3643
+ /**
3644
+ * Override request handler registration to enforce client-side validation for elicitation.
3645
+ */
3646
+ setRequestHandler(requestSchema, handler) {
3647
+ const shape = getObjectShape(requestSchema);
3648
+ const methodSchema = shape?.method;
3649
+ if (!methodSchema) {
3650
+ throw new Error("Schema is missing a method literal");
3651
+ }
3652
+ let methodValue;
3653
+ if (isZ4Schema(methodSchema)) {
3654
+ const v4Schema = methodSchema;
3655
+ const v4Def = v4Schema._zod?.def;
3656
+ methodValue = v4Def?.value ?? v4Schema.value;
3657
+ } else {
3658
+ const v3Schema = methodSchema;
3659
+ const legacyDef = v3Schema._def;
3660
+ methodValue = legacyDef?.value ?? v3Schema.value;
3661
+ }
3662
+ if (typeof methodValue !== "string") {
3663
+ throw new Error("Schema method literal must be a string");
3664
+ }
3665
+ const method = methodValue;
3666
+ if (method === "elicitation/create") {
3667
+ const wrappedHandler = /* @__PURE__ */ __name(async (request, extra) => {
3668
+ const validatedRequest = safeParse2(ElicitRequestSchema, request);
3669
+ if (!validatedRequest.success) {
3670
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
3671
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
3672
+ }
3673
+ const { params } = validatedRequest.data;
3674
+ params.mode = params.mode ?? "form";
3675
+ const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
3676
+ if (params.mode === "form" && !supportsFormMode) {
3677
+ throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
3678
+ }
3679
+ if (params.mode === "url" && !supportsUrlMode) {
3680
+ throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
3681
+ }
3682
+ const result = await Promise.resolve(handler(request, extra));
3683
+ if (params.task) {
3684
+ const taskValidationResult = safeParse2(CreateTaskResultSchema, result);
3685
+ if (!taskValidationResult.success) {
3686
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
3687
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
3688
+ }
3689
+ return taskValidationResult.data;
3690
+ }
3691
+ const validationResult = safeParse2(ElicitResultSchema, result);
3692
+ if (!validationResult.success) {
3693
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
3694
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
3695
+ }
3696
+ const validatedResult = validationResult.data;
3697
+ const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
3698
+ if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
3699
+ if (this._capabilities.elicitation?.form?.applyDefaults) {
3700
+ try {
3701
+ applyElicitationDefaults(requestedSchema, validatedResult.content);
3702
+ } catch {
3703
+ }
3704
+ }
3705
+ }
3706
+ return validatedResult;
3707
+ }, "wrappedHandler");
3708
+ return super.setRequestHandler(requestSchema, wrappedHandler);
3709
+ }
3710
+ if (method === "sampling/createMessage") {
3711
+ const wrappedHandler = /* @__PURE__ */ __name(async (request, extra) => {
3712
+ const validatedRequest = safeParse2(CreateMessageRequestSchema, request);
3713
+ if (!validatedRequest.success) {
3714
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
3715
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
3716
+ }
3717
+ const { params } = validatedRequest.data;
3718
+ const result = await Promise.resolve(handler(request, extra));
3719
+ if (params.task) {
3720
+ const taskValidationResult = safeParse2(CreateTaskResultSchema, result);
3721
+ if (!taskValidationResult.success) {
3722
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
3723
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
3724
+ }
3725
+ return taskValidationResult.data;
3726
+ }
3727
+ const validationResult = safeParse2(CreateMessageResultSchema, result);
3728
+ if (!validationResult.success) {
3729
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
3730
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
3731
+ }
3732
+ return validationResult.data;
3733
+ }, "wrappedHandler");
3734
+ return super.setRequestHandler(requestSchema, wrappedHandler);
3735
+ }
3736
+ return super.setRequestHandler(requestSchema, handler);
3737
+ }
3738
+ assertCapability(capability, method) {
3739
+ if (!this._serverCapabilities?.[capability]) {
3740
+ throw new Error(`Server does not support ${capability} (required for ${method})`);
3741
+ }
3742
+ }
3743
+ async connect(transport, options) {
3744
+ await super.connect(transport);
3745
+ if (transport.sessionId !== void 0) {
3746
+ return;
3747
+ }
3748
+ try {
3749
+ const result = await this.request({
3750
+ method: "initialize",
3751
+ params: {
3752
+ protocolVersion: LATEST_PROTOCOL_VERSION,
3753
+ capabilities: this._capabilities,
3754
+ clientInfo: this._clientInfo
3755
+ }
3756
+ }, InitializeResultSchema, options);
3757
+ if (result === void 0) {
3758
+ throw new Error(`Server sent invalid initialize result: ${result}`);
3759
+ }
3760
+ if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
3761
+ throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
3762
+ }
3763
+ this._serverCapabilities = result.capabilities;
3764
+ this._serverVersion = result.serverInfo;
3765
+ if (transport.setProtocolVersion) {
3766
+ transport.setProtocolVersion(result.protocolVersion);
3767
+ }
3768
+ this._instructions = result.instructions;
3769
+ await this.notification({
3770
+ method: "notifications/initialized"
3771
+ });
3772
+ if (this._pendingListChangedConfig) {
3773
+ this._setupListChangedHandlers(this._pendingListChangedConfig);
3774
+ this._pendingListChangedConfig = void 0;
3775
+ }
3776
+ } catch (error) {
3777
+ void this.close();
3778
+ throw error;
3779
+ }
3780
+ }
3781
+ /**
3782
+ * After initialization has completed, this will be populated with the server's reported capabilities.
3783
+ */
3784
+ getServerCapabilities() {
3785
+ return this._serverCapabilities;
3786
+ }
3787
+ /**
3788
+ * After initialization has completed, this will be populated with information about the server's name and version.
3789
+ */
3790
+ getServerVersion() {
3791
+ return this._serverVersion;
3792
+ }
3793
+ /**
3794
+ * After initialization has completed, this may be populated with information about the server's instructions.
3795
+ */
3796
+ getInstructions() {
3797
+ return this._instructions;
3798
+ }
3799
+ assertCapabilityForMethod(method) {
3800
+ switch (method) {
3801
+ case "logging/setLevel":
3802
+ if (!this._serverCapabilities?.logging) {
3803
+ throw new Error(`Server does not support logging (required for ${method})`);
3804
+ }
3805
+ break;
3806
+ case "prompts/get":
3807
+ case "prompts/list":
3808
+ if (!this._serverCapabilities?.prompts) {
3809
+ throw new Error(`Server does not support prompts (required for ${method})`);
3810
+ }
3811
+ break;
3812
+ case "resources/list":
3813
+ case "resources/templates/list":
3814
+ case "resources/read":
3815
+ case "resources/subscribe":
3816
+ case "resources/unsubscribe":
3817
+ if (!this._serverCapabilities?.resources) {
3818
+ throw new Error(`Server does not support resources (required for ${method})`);
3819
+ }
3820
+ if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) {
3821
+ throw new Error(`Server does not support resource subscriptions (required for ${method})`);
3822
+ }
3823
+ break;
3824
+ case "tools/call":
3825
+ case "tools/list":
3826
+ if (!this._serverCapabilities?.tools) {
3827
+ throw new Error(`Server does not support tools (required for ${method})`);
3828
+ }
3829
+ break;
3830
+ case "completion/complete":
3831
+ if (!this._serverCapabilities?.completions) {
3832
+ throw new Error(`Server does not support completions (required for ${method})`);
3833
+ }
3834
+ break;
3835
+ case "initialize":
3836
+ break;
3837
+ case "ping":
3838
+ break;
3839
+ }
3840
+ }
3841
+ assertNotificationCapability(method) {
3842
+ switch (method) {
3843
+ case "notifications/roots/list_changed":
3844
+ if (!this._capabilities.roots?.listChanged) {
3845
+ throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
3846
+ }
3847
+ break;
3848
+ case "notifications/initialized":
3849
+ break;
3850
+ case "notifications/cancelled":
3851
+ break;
3852
+ case "notifications/progress":
3853
+ break;
3854
+ }
3855
+ }
3856
+ assertRequestHandlerCapability(method) {
3857
+ if (!this._capabilities) {
3858
+ return;
3859
+ }
3860
+ switch (method) {
3861
+ case "sampling/createMessage":
3862
+ if (!this._capabilities.sampling) {
3863
+ throw new Error(`Client does not support sampling capability (required for ${method})`);
3864
+ }
3865
+ break;
3866
+ case "elicitation/create":
3867
+ if (!this._capabilities.elicitation) {
3868
+ throw new Error(`Client does not support elicitation capability (required for ${method})`);
3869
+ }
3870
+ break;
3871
+ case "roots/list":
3872
+ if (!this._capabilities.roots) {
3873
+ throw new Error(`Client does not support roots capability (required for ${method})`);
3874
+ }
3875
+ break;
3876
+ case "tasks/get":
3877
+ case "tasks/list":
3878
+ case "tasks/result":
3879
+ case "tasks/cancel":
3880
+ if (!this._capabilities.tasks) {
3881
+ throw new Error(`Client does not support tasks capability (required for ${method})`);
3882
+ }
3883
+ break;
3884
+ case "ping":
3885
+ break;
3886
+ }
3887
+ }
3888
+ assertTaskCapability(method) {
3889
+ assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, "Server");
3890
+ }
3891
+ assertTaskHandlerCapability(method) {
3892
+ if (!this._capabilities) {
3893
+ return;
3894
+ }
3895
+ assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, "Client");
3896
+ }
3897
+ async ping(options) {
3898
+ return this.request({ method: "ping" }, EmptyResultSchema, options);
3899
+ }
3900
+ async complete(params, options) {
3901
+ return this.request({ method: "completion/complete", params }, CompleteResultSchema, options);
3902
+ }
3903
+ async setLoggingLevel(level, options) {
3904
+ return this.request({ method: "logging/setLevel", params: { level } }, EmptyResultSchema, options);
3905
+ }
3906
+ async getPrompt(params, options) {
3907
+ return this.request({ method: "prompts/get", params }, GetPromptResultSchema, options);
3908
+ }
3909
+ async listPrompts(params, options) {
3910
+ return this.request({ method: "prompts/list", params }, ListPromptsResultSchema, options);
3911
+ }
3912
+ async listResources(params, options) {
3913
+ return this.request({ method: "resources/list", params }, ListResourcesResultSchema, options);
3914
+ }
3915
+ async listResourceTemplates(params, options) {
3916
+ return this.request({ method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, options);
3917
+ }
3918
+ async readResource(params, options) {
3919
+ return this.request({ method: "resources/read", params }, ReadResourceResultSchema, options);
3920
+ }
3921
+ async subscribeResource(params, options) {
3922
+ return this.request({ method: "resources/subscribe", params }, EmptyResultSchema, options);
3923
+ }
3924
+ async unsubscribeResource(params, options) {
3925
+ return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options);
3926
+ }
3927
+ /**
3928
+ * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
3929
+ *
3930
+ * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
3931
+ */
3932
+ async callTool(params, resultSchema = CallToolResultSchema, options) {
3933
+ if (this.isToolTaskRequired(params.name)) {
3934
+ throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
3935
+ }
3936
+ const result = await this.request({ method: "tools/call", params }, resultSchema, options);
3937
+ const validator = this.getToolOutputValidator(params.name);
3938
+ if (validator) {
3939
+ if (!result.structuredContent && !result.isError) {
3940
+ throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
3941
+ }
3942
+ if (result.structuredContent) {
3943
+ try {
3944
+ const validationResult = validator(result.structuredContent);
3945
+ if (!validationResult.valid) {
3946
+ throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
3947
+ }
3948
+ } catch (error) {
3949
+ if (error instanceof McpError) {
3950
+ throw error;
3951
+ }
3952
+ throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
3953
+ }
3954
+ }
3955
+ }
3956
+ return result;
3957
+ }
3958
+ isToolTask(toolName) {
3959
+ if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {
3960
+ return false;
3961
+ }
3962
+ return this._cachedKnownTaskTools.has(toolName);
3963
+ }
3964
+ /**
3965
+ * Check if a tool requires task-based execution.
3966
+ * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
3967
+ */
3968
+ isToolTaskRequired(toolName) {
3969
+ return this._cachedRequiredTaskTools.has(toolName);
3970
+ }
3971
+ /**
3972
+ * Cache validators for tool output schemas.
3973
+ * Called after listTools() to pre-compile validators for better performance.
3974
+ */
3975
+ cacheToolMetadata(tools) {
3976
+ this._cachedToolOutputValidators.clear();
3977
+ this._cachedKnownTaskTools.clear();
3978
+ this._cachedRequiredTaskTools.clear();
3979
+ for (const tool of tools) {
3980
+ if (tool.outputSchema) {
3981
+ const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
3982
+ this._cachedToolOutputValidators.set(tool.name, toolValidator);
3983
+ }
3984
+ const taskSupport = tool.execution?.taskSupport;
3985
+ if (taskSupport === "required" || taskSupport === "optional") {
3986
+ this._cachedKnownTaskTools.add(tool.name);
3987
+ }
3988
+ if (taskSupport === "required") {
3989
+ this._cachedRequiredTaskTools.add(tool.name);
3990
+ }
3991
+ }
3992
+ }
3993
+ /**
3994
+ * Get cached validator for a tool
3995
+ */
3996
+ getToolOutputValidator(toolName) {
3997
+ return this._cachedToolOutputValidators.get(toolName);
3998
+ }
3999
+ async listTools(params, options) {
4000
+ const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options);
4001
+ this.cacheToolMetadata(result.tools);
4002
+ return result;
4003
+ }
4004
+ /**
4005
+ * Set up a single list changed handler.
4006
+ * @internal
4007
+ */
4008
+ _setupListChangedHandler(listType, notificationSchema, options, fetcher) {
4009
+ const parseResult = ListChangedOptionsBaseSchema.safeParse(options);
4010
+ if (!parseResult.success) {
4011
+ throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
4012
+ }
4013
+ if (typeof options.onChanged !== "function") {
4014
+ throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
4015
+ }
4016
+ const { autoRefresh, debounceMs } = parseResult.data;
4017
+ const { onChanged } = options;
4018
+ const refresh = /* @__PURE__ */ __name(async () => {
4019
+ if (!autoRefresh) {
4020
+ onChanged(null, null);
4021
+ return;
4022
+ }
4023
+ try {
4024
+ const items = await fetcher();
4025
+ onChanged(null, items);
4026
+ } catch (e) {
4027
+ const error = e instanceof Error ? e : new Error(String(e));
4028
+ onChanged(error, null);
4029
+ }
4030
+ }, "refresh");
4031
+ const handler = /* @__PURE__ */ __name(() => {
4032
+ if (debounceMs) {
4033
+ const existingTimer = this._listChangedDebounceTimers.get(listType);
4034
+ if (existingTimer) {
4035
+ clearTimeout(existingTimer);
4036
+ }
4037
+ const timer = setTimeout(refresh, debounceMs);
4038
+ this._listChangedDebounceTimers.set(listType, timer);
4039
+ } else {
4040
+ refresh();
4041
+ }
4042
+ }, "handler");
4043
+ this.setNotificationHandler(notificationSchema, handler);
4044
+ }
4045
+ async sendRootsListChanged() {
4046
+ return this.notification({ method: "notifications/roots/list_changed" });
4047
+ }
4048
+ };
4049
+
4050
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js
4051
+ init_esbuild_shims();
4052
+ var import_cross_spawn = __toESM(require_cross_spawn(), 1);
4053
+ import process2 from "node:process";
4054
+ import { PassThrough } from "node:stream";
4055
+
4056
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
4057
+ init_esbuild_shims();
4058
+ var ReadBuffer = class {
4059
+ static {
4060
+ __name(this, "ReadBuffer");
4061
+ }
4062
+ append(chunk) {
4063
+ this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
4064
+ }
4065
+ readMessage() {
4066
+ if (!this._buffer) {
4067
+ return null;
4068
+ }
4069
+ const index = this._buffer.indexOf("\n");
4070
+ if (index === -1) {
4071
+ return null;
4072
+ }
4073
+ const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
4074
+ this._buffer = this._buffer.subarray(index + 1);
4075
+ return deserializeMessage(line);
4076
+ }
4077
+ clear() {
4078
+ this._buffer = void 0;
4079
+ }
4080
+ };
4081
+ function deserializeMessage(line) {
4082
+ return JSONRPCMessageSchema.parse(JSON.parse(line));
4083
+ }
4084
+ __name(deserializeMessage, "deserializeMessage");
4085
+ function serializeMessage(message) {
4086
+ return JSON.stringify(message) + "\n";
4087
+ }
4088
+ __name(serializeMessage, "serializeMessage");
4089
+
4090
+ // packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js
4091
+ var DEFAULT_INHERITED_ENV_VARS = process2.platform === "win32" ? [
4092
+ "APPDATA",
4093
+ "HOMEDRIVE",
4094
+ "HOMEPATH",
4095
+ "LOCALAPPDATA",
4096
+ "PATH",
4097
+ "PROCESSOR_ARCHITECTURE",
4098
+ "SYSTEMDRIVE",
4099
+ "SYSTEMROOT",
4100
+ "TEMP",
4101
+ "USERNAME",
4102
+ "USERPROFILE",
4103
+ "PROGRAMFILES"
4104
+ ] : (
4105
+ /* list inspired by the default env inheritance of sudo */
4106
+ ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"]
4107
+ );
4108
+ function getDefaultEnvironment() {
4109
+ const env = {};
4110
+ for (const key of DEFAULT_INHERITED_ENV_VARS) {
4111
+ const value = process2.env[key];
4112
+ if (value === void 0) {
4113
+ continue;
4114
+ }
4115
+ if (value.startsWith("()")) {
4116
+ continue;
4117
+ }
4118
+ env[key] = value;
4119
+ }
4120
+ return env;
4121
+ }
4122
+ __name(getDefaultEnvironment, "getDefaultEnvironment");
4123
+ var StdioClientTransport = class {
4124
+ static {
4125
+ __name(this, "StdioClientTransport");
4126
+ }
4127
+ constructor(server) {
4128
+ this._readBuffer = new ReadBuffer();
4129
+ this._stderrStream = null;
4130
+ this._serverParams = server;
4131
+ if (server.stderr === "pipe" || server.stderr === "overlapped") {
4132
+ this._stderrStream = new PassThrough();
4133
+ }
4134
+ }
4135
+ /**
4136
+ * Starts the server process and prepares to communicate with it.
4137
+ */
4138
+ async start() {
4139
+ if (this._process) {
4140
+ throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");
4141
+ }
4142
+ return new Promise((resolve, reject) => {
4143
+ this._process = (0, import_cross_spawn.default)(this._serverParams.command, this._serverParams.args ?? [], {
4144
+ // merge default env with server env because mcp server needs some env vars
4145
+ env: {
4146
+ ...getDefaultEnvironment(),
4147
+ ...this._serverParams.env
4148
+ },
4149
+ stdio: ["pipe", "pipe", this._serverParams.stderr ?? "inherit"],
4150
+ shell: false,
4151
+ windowsHide: process2.platform === "win32" && isElectron(),
4152
+ cwd: this._serverParams.cwd
4153
+ });
4154
+ this._process.on("error", (error) => {
4155
+ reject(error);
4156
+ this.onerror?.(error);
4157
+ });
4158
+ this._process.on("spawn", () => {
4159
+ resolve();
4160
+ });
4161
+ this._process.on("close", (_code) => {
4162
+ this._process = void 0;
4163
+ this.onclose?.();
4164
+ });
4165
+ this._process.stdin?.on("error", (error) => {
4166
+ this.onerror?.(error);
4167
+ });
4168
+ this._process.stdout?.on("data", (chunk) => {
4169
+ this._readBuffer.append(chunk);
4170
+ this.processReadBuffer();
4171
+ });
4172
+ this._process.stdout?.on("error", (error) => {
4173
+ this.onerror?.(error);
4174
+ });
4175
+ if (this._stderrStream && this._process.stderr) {
4176
+ this._process.stderr.pipe(this._stderrStream);
4177
+ }
4178
+ });
4179
+ }
4180
+ /**
4181
+ * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped".
4182
+ *
4183
+ * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to
4184
+ * attach listeners before the start method is invoked. This prevents loss of any early
4185
+ * error output emitted by the child process.
4186
+ */
4187
+ get stderr() {
4188
+ if (this._stderrStream) {
4189
+ return this._stderrStream;
4190
+ }
4191
+ return this._process?.stderr ?? null;
4192
+ }
4193
+ /**
4194
+ * The child process pid spawned by this transport.
4195
+ *
4196
+ * This is only available after the transport has been started.
4197
+ */
4198
+ get pid() {
4199
+ return this._process?.pid ?? null;
4200
+ }
4201
+ processReadBuffer() {
4202
+ while (true) {
4203
+ try {
4204
+ const message = this._readBuffer.readMessage();
4205
+ if (message === null) {
4206
+ break;
4207
+ }
4208
+ this.onmessage?.(message);
4209
+ } catch (error) {
4210
+ this.onerror?.(error);
4211
+ }
4212
+ }
4213
+ }
4214
+ async close() {
4215
+ if (this._process) {
4216
+ const processToClose = this._process;
4217
+ this._process = void 0;
4218
+ const closePromise = new Promise((resolve) => {
4219
+ processToClose.once("close", () => {
4220
+ resolve();
4221
+ });
4222
+ });
4223
+ try {
4224
+ processToClose.stdin?.end();
4225
+ } catch {
4226
+ }
4227
+ await Promise.race([closePromise, new Promise((resolve) => setTimeout(resolve, 2e3).unref())]);
4228
+ if (processToClose.exitCode === null) {
4229
+ try {
4230
+ processToClose.kill("SIGTERM");
4231
+ } catch {
4232
+ }
4233
+ await Promise.race([closePromise, new Promise((resolve) => setTimeout(resolve, 2e3).unref())]);
4234
+ }
4235
+ if (processToClose.exitCode === null) {
4236
+ try {
4237
+ processToClose.kill("SIGKILL");
4238
+ } catch {
4239
+ }
4240
+ }
4241
+ }
4242
+ this._readBuffer.clear();
4243
+ }
4244
+ send(message) {
4245
+ return new Promise((resolve) => {
4246
+ if (!this._process?.stdin) {
4247
+ throw new Error("Not connected");
4248
+ }
4249
+ const json = serializeMessage(message);
4250
+ if (this._process.stdin.write(json)) {
4251
+ resolve();
4252
+ } else {
4253
+ this._process.stdin.once("drain", resolve);
4254
+ }
4255
+ });
4256
+ }
4257
+ };
4258
+ function isElectron() {
4259
+ return "type" in process2;
4260
+ }
4261
+ __name(isElectron, "isElectron");
4262
+
4263
+ export {
4264
+ LATEST_PROTOCOL_VERSION,
4265
+ isJSONRPCRequest,
4266
+ isJSONRPCResultResponse,
4267
+ JSONRPCMessageSchema,
4268
+ isInitializedNotification,
4269
+ ReadResourceResultSchema,
4270
+ ListPromptsResultSchema,
4271
+ GetPromptResultSchema,
4272
+ ListToolsResultSchema,
4273
+ CallToolResultSchema,
4274
+ ListRootsRequestSchema,
4275
+ Client,
4276
+ StdioClientTransport
4277
+ };