alus-ui-mcp 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,964 @@
1
1
  #!/usr/bin/env node
2
- var __defProp = Object.defineProperty;
3
- var __export = (target, all) => {
4
- for (var name in all)
5
- __defProp(target, name, { get: all[name], enumerable: true });
6
- };
2
+ import {
3
+ __commonJS,
4
+ __export,
5
+ __toESM
6
+ } from "./chunk-NSPRIPOP.js";
7
7
 
8
- // ../../node_modules/.pnpm/@tmcp+adapter-valibot@0.1.6_tmcp@1.19.4_typescript@5.9.3__valibot@1.4.1_typescript@5.9.3_/node_modules/@tmcp/adapter-valibot/src/index.js
9
- import { JsonSchemaAdapter } from "tmcp/adapter";
8
+ // ../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/models.js
9
+ var require_models = __commonJS({
10
+ "../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/models.js"(exports) {
11
+ "use strict";
12
+ var __extends = exports && exports.__extends || /* @__PURE__ */ (function() {
13
+ var extendStatics = function(d, b) {
14
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
15
+ d2.__proto__ = b2;
16
+ } || function(d2, b2) {
17
+ for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
18
+ };
19
+ return extendStatics(d, b);
20
+ };
21
+ return function(d, b) {
22
+ if (typeof b !== "function" && b !== null)
23
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
24
+ extendStatics(d, b);
25
+ function __() {
26
+ this.constructor = d;
27
+ }
28
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29
+ };
30
+ })();
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.createJSONRPCNotification = exports.createJSONRPCRequest = exports.createJSONRPCSuccessResponse = exports.createJSONRPCErrorResponse = exports.JSONRPCErrorCode = exports.JSONRPCErrorException = exports.isJSONRPCResponses = exports.isJSONRPCResponse = exports.isJSONRPCRequests = exports.isJSONRPCRequest = exports.isJSONRPCID = exports.JSONRPC = void 0;
33
+ exports.JSONRPC = "2.0";
34
+ var isJSONRPCID = function(id) {
35
+ return typeof id === "string" || typeof id === "number" || id === null;
36
+ };
37
+ exports.isJSONRPCID = isJSONRPCID;
38
+ var isJSONRPCRequest = function(payload) {
39
+ return payload.jsonrpc === exports.JSONRPC && payload.method !== void 0 && payload.result === void 0 && payload.error === void 0;
40
+ };
41
+ exports.isJSONRPCRequest = isJSONRPCRequest;
42
+ var isJSONRPCRequests = function(payload) {
43
+ return Array.isArray(payload) && payload.every(exports.isJSONRPCRequest);
44
+ };
45
+ exports.isJSONRPCRequests = isJSONRPCRequests;
46
+ var isJSONRPCResponse = function(payload) {
47
+ return payload.jsonrpc === exports.JSONRPC && payload.id !== void 0 && (payload.result !== void 0 || payload.error !== void 0);
48
+ };
49
+ exports.isJSONRPCResponse = isJSONRPCResponse;
50
+ var isJSONRPCResponses = function(payload) {
51
+ return Array.isArray(payload) && payload.every(exports.isJSONRPCResponse);
52
+ };
53
+ exports.isJSONRPCResponses = isJSONRPCResponses;
54
+ var createJSONRPCError = function(code, message, data) {
55
+ var error = { code, message };
56
+ if (data != null) {
57
+ error.data = data;
58
+ }
59
+ return error;
60
+ };
61
+ var JSONRPCErrorException = (
62
+ /** @class */
63
+ (function(_super) {
64
+ __extends(JSONRPCErrorException2, _super);
65
+ function JSONRPCErrorException2(message, code, data) {
66
+ var _this = _super.call(this, message) || this;
67
+ Object.setPrototypeOf(_this, JSONRPCErrorException2.prototype);
68
+ _this.code = code;
69
+ _this.data = data;
70
+ return _this;
71
+ }
72
+ JSONRPCErrorException2.prototype.toObject = function() {
73
+ return createJSONRPCError(this.code, this.message, this.data);
74
+ };
75
+ return JSONRPCErrorException2;
76
+ })(Error)
77
+ );
78
+ exports.JSONRPCErrorException = JSONRPCErrorException;
79
+ var JSONRPCErrorCode;
80
+ (function(JSONRPCErrorCode2) {
81
+ JSONRPCErrorCode2[JSONRPCErrorCode2["ParseError"] = -32700] = "ParseError";
82
+ JSONRPCErrorCode2[JSONRPCErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest";
83
+ JSONRPCErrorCode2[JSONRPCErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";
84
+ JSONRPCErrorCode2[JSONRPCErrorCode2["InvalidParams"] = -32602] = "InvalidParams";
85
+ JSONRPCErrorCode2[JSONRPCErrorCode2["InternalError"] = -32603] = "InternalError";
86
+ })(JSONRPCErrorCode = exports.JSONRPCErrorCode || (exports.JSONRPCErrorCode = {}));
87
+ var createJSONRPCErrorResponse = function(id, code, message, data) {
88
+ return {
89
+ jsonrpc: exports.JSONRPC,
90
+ id,
91
+ error: createJSONRPCError(code, message, data)
92
+ };
93
+ };
94
+ exports.createJSONRPCErrorResponse = createJSONRPCErrorResponse;
95
+ var createJSONRPCSuccessResponse = function(id, result) {
96
+ return {
97
+ jsonrpc: exports.JSONRPC,
98
+ id,
99
+ result: result !== null && result !== void 0 ? result : null
100
+ };
101
+ };
102
+ exports.createJSONRPCSuccessResponse = createJSONRPCSuccessResponse;
103
+ var createJSONRPCRequest = function(id, method, params) {
104
+ return {
105
+ jsonrpc: exports.JSONRPC,
106
+ id,
107
+ method,
108
+ params
109
+ };
110
+ };
111
+ exports.createJSONRPCRequest = createJSONRPCRequest;
112
+ var createJSONRPCNotification = function(method, params) {
113
+ return {
114
+ jsonrpc: exports.JSONRPC,
115
+ method,
116
+ params
117
+ };
118
+ };
119
+ exports.createJSONRPCNotification = createJSONRPCNotification;
120
+ }
121
+ });
122
+
123
+ // ../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/internal.js
124
+ var require_internal = __commonJS({
125
+ "../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/internal.js"(exports) {
126
+ "use strict";
127
+ Object.defineProperty(exports, "__esModule", { value: true });
128
+ exports.DefaultErrorCode = void 0;
129
+ exports.DefaultErrorCode = 0;
130
+ }
131
+ });
132
+
133
+ // ../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/client.js
134
+ var require_client = __commonJS({
135
+ "../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/client.js"(exports) {
136
+ "use strict";
137
+ var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
138
+ function adopt(value) {
139
+ return value instanceof P ? value : new P(function(resolve2) {
140
+ resolve2(value);
141
+ });
142
+ }
143
+ return new (P || (P = Promise))(function(resolve2, reject) {
144
+ function fulfilled(value) {
145
+ try {
146
+ step(generator.next(value));
147
+ } catch (e) {
148
+ reject(e);
149
+ }
150
+ }
151
+ function rejected(value) {
152
+ try {
153
+ step(generator["throw"](value));
154
+ } catch (e) {
155
+ reject(e);
156
+ }
157
+ }
158
+ function step(result) {
159
+ result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
160
+ }
161
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
162
+ });
163
+ };
164
+ var __generator = exports && exports.__generator || function(thisArg, body) {
165
+ var _ = { label: 0, sent: function() {
166
+ if (t[0] & 1) throw t[1];
167
+ return t[1];
168
+ }, trys: [], ops: [] }, f, y, t, g;
169
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
170
+ return this;
171
+ }), g;
172
+ function verb(n) {
173
+ return function(v) {
174
+ return step([n, v]);
175
+ };
176
+ }
177
+ function step(op) {
178
+ if (f) throw new TypeError("Generator is already executing.");
179
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
180
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
181
+ if (y = 0, t) op = [op[0] & 2, t.value];
182
+ switch (op[0]) {
183
+ case 0:
184
+ case 1:
185
+ t = op;
186
+ break;
187
+ case 4:
188
+ _.label++;
189
+ return { value: op[1], done: false };
190
+ case 5:
191
+ _.label++;
192
+ y = op[1];
193
+ op = [0];
194
+ continue;
195
+ case 7:
196
+ op = _.ops.pop();
197
+ _.trys.pop();
198
+ continue;
199
+ default:
200
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
201
+ _ = 0;
202
+ continue;
203
+ }
204
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
205
+ _.label = op[1];
206
+ break;
207
+ }
208
+ if (op[0] === 6 && _.label < t[1]) {
209
+ _.label = t[1];
210
+ t = op;
211
+ break;
212
+ }
213
+ if (t && _.label < t[2]) {
214
+ _.label = t[2];
215
+ _.ops.push(op);
216
+ break;
217
+ }
218
+ if (t[2]) _.ops.pop();
219
+ _.trys.pop();
220
+ continue;
221
+ }
222
+ op = body.call(thisArg, _);
223
+ } catch (e) {
224
+ op = [6, e];
225
+ y = 0;
226
+ } finally {
227
+ f = t = 0;
228
+ }
229
+ if (op[0] & 5) throw op[1];
230
+ return { value: op[0] ? op[1] : void 0, done: true };
231
+ }
232
+ };
233
+ Object.defineProperty(exports, "__esModule", { value: true });
234
+ exports.JSONRPCClient = void 0;
235
+ var models_1 = require_models();
236
+ var internal_1 = require_internal();
237
+ var JSONRPCClient2 = (
238
+ /** @class */
239
+ (function() {
240
+ function JSONRPCClient3(_send, createID) {
241
+ this._send = _send;
242
+ this.createID = createID;
243
+ this.idToResolveMap = /* @__PURE__ */ new Map();
244
+ this.id = 0;
245
+ }
246
+ JSONRPCClient3.prototype._createID = function() {
247
+ if (this.createID) {
248
+ return this.createID();
249
+ } else {
250
+ return ++this.id;
251
+ }
252
+ };
253
+ JSONRPCClient3.prototype.timeout = function(delay, overrideCreateJSONRPCErrorResponse) {
254
+ var _this = this;
255
+ if (overrideCreateJSONRPCErrorResponse === void 0) {
256
+ overrideCreateJSONRPCErrorResponse = function(id) {
257
+ return (0, models_1.createJSONRPCErrorResponse)(id, internal_1.DefaultErrorCode, "Request timeout");
258
+ };
259
+ }
260
+ var timeoutRequest = function(ids, request) {
261
+ var timeoutID = setTimeout(function() {
262
+ ids.forEach(function(id) {
263
+ var resolve2 = _this.idToResolveMap.get(id);
264
+ if (resolve2) {
265
+ _this.idToResolveMap.delete(id);
266
+ resolve2(overrideCreateJSONRPCErrorResponse(id));
267
+ }
268
+ });
269
+ }, delay);
270
+ return request().then(function(result) {
271
+ clearTimeout(timeoutID);
272
+ return result;
273
+ }, function(error) {
274
+ clearTimeout(timeoutID);
275
+ return Promise.reject(error);
276
+ });
277
+ };
278
+ var requestAdvanced = function(request, clientParams) {
279
+ var ids = (!Array.isArray(request) ? [request] : request).map(function(request2) {
280
+ return request2.id;
281
+ }).filter(isDefinedAndNonNull);
282
+ return timeoutRequest(ids, function() {
283
+ return _this.requestAdvanced(request, clientParams);
284
+ });
285
+ };
286
+ return {
287
+ request: function(method, params, clientParams) {
288
+ var id = _this._createID();
289
+ return timeoutRequest([id], function() {
290
+ return _this.requestWithID(method, params, clientParams, id);
291
+ });
292
+ },
293
+ requestAdvanced: function(request, clientParams) {
294
+ return requestAdvanced(request, clientParams);
295
+ }
296
+ };
297
+ };
298
+ JSONRPCClient3.prototype.request = function(method, params, clientParams) {
299
+ return this.requestWithID(method, params, clientParams, this._createID());
300
+ };
301
+ JSONRPCClient3.prototype.requestWithID = function(method, params, clientParams, id) {
302
+ return __awaiter(this, void 0, void 0, function() {
303
+ var request, response;
304
+ return __generator(this, function(_a) {
305
+ switch (_a.label) {
306
+ case 0:
307
+ request = (0, models_1.createJSONRPCRequest)(id, method, params);
308
+ return [4, this.requestAdvanced(request, clientParams)];
309
+ case 1:
310
+ response = _a.sent();
311
+ if (response.result !== void 0 && !response.error) {
312
+ return [2, response.result];
313
+ } else if (response.result === void 0 && response.error) {
314
+ return [2, Promise.reject(new models_1.JSONRPCErrorException(response.error.message, response.error.code, response.error.data))];
315
+ } else {
316
+ return [2, Promise.reject(new Error("An unexpected error occurred"))];
317
+ }
318
+ return [
319
+ 2
320
+ /*return*/
321
+ ];
322
+ }
323
+ });
324
+ });
325
+ };
326
+ JSONRPCClient3.prototype.requestAdvanced = function(requests, clientParams) {
327
+ var _this = this;
328
+ var areRequestsOriginallyArray = Array.isArray(requests);
329
+ if (!Array.isArray(requests)) {
330
+ requests = [requests];
331
+ }
332
+ var requestsWithID = requests.filter(function(request) {
333
+ return isDefinedAndNonNull(request.id);
334
+ });
335
+ var promises = requestsWithID.map(function(request) {
336
+ return new Promise(function(resolve2) {
337
+ return _this.idToResolveMap.set(request.id, resolve2);
338
+ });
339
+ });
340
+ var promise = Promise.all(promises).then(function(responses) {
341
+ if (areRequestsOriginallyArray || !responses.length) {
342
+ return responses;
343
+ } else {
344
+ return responses[0];
345
+ }
346
+ });
347
+ return this.send(areRequestsOriginallyArray ? requests : requests[0], clientParams).then(function() {
348
+ return promise;
349
+ }, function(error) {
350
+ requestsWithID.forEach(function(request) {
351
+ _this.receive((0, models_1.createJSONRPCErrorResponse)(request.id, internal_1.DefaultErrorCode, error && error.message || "Failed to send a request"));
352
+ });
353
+ return promise;
354
+ });
355
+ };
356
+ JSONRPCClient3.prototype.notify = function(method, params, clientParams) {
357
+ var request = (0, models_1.createJSONRPCNotification)(method, params);
358
+ this.send(request, clientParams).then(void 0, function() {
359
+ return void 0;
360
+ });
361
+ };
362
+ JSONRPCClient3.prototype.send = function(payload, clientParams) {
363
+ return __awaiter(this, void 0, void 0, function() {
364
+ return __generator(this, function(_a) {
365
+ return [2, this._send(payload, clientParams)];
366
+ });
367
+ });
368
+ };
369
+ JSONRPCClient3.prototype.rejectAllPendingRequests = function(message) {
370
+ this.idToResolveMap.forEach(function(resolve2, id) {
371
+ return resolve2((0, models_1.createJSONRPCErrorResponse)(id, internal_1.DefaultErrorCode, message));
372
+ });
373
+ this.idToResolveMap.clear();
374
+ };
375
+ JSONRPCClient3.prototype.receive = function(responses) {
376
+ var _this = this;
377
+ if (!Array.isArray(responses)) {
378
+ responses = [responses];
379
+ }
380
+ responses.forEach(function(response) {
381
+ var resolve2 = _this.idToResolveMap.get(response.id);
382
+ if (resolve2) {
383
+ _this.idToResolveMap.delete(response.id);
384
+ resolve2(response);
385
+ }
386
+ });
387
+ };
388
+ return JSONRPCClient3;
389
+ })()
390
+ );
391
+ exports.JSONRPCClient = JSONRPCClient2;
392
+ var isDefinedAndNonNull = function(value) {
393
+ return value !== void 0 && value !== null;
394
+ };
395
+ }
396
+ });
397
+
398
+ // ../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/interfaces.js
399
+ var require_interfaces = __commonJS({
400
+ "../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/interfaces.js"(exports) {
401
+ "use strict";
402
+ Object.defineProperty(exports, "__esModule", { value: true });
403
+ }
404
+ });
405
+
406
+ // ../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/server.js
407
+ var require_server = __commonJS({
408
+ "../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/server.js"(exports) {
409
+ "use strict";
410
+ var __assign = exports && exports.__assign || function() {
411
+ __assign = Object.assign || function(t) {
412
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
413
+ s = arguments[i];
414
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
415
+ t[p] = s[p];
416
+ }
417
+ return t;
418
+ };
419
+ return __assign.apply(this, arguments);
420
+ };
421
+ var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
422
+ function adopt(value) {
423
+ return value instanceof P ? value : new P(function(resolve2) {
424
+ resolve2(value);
425
+ });
426
+ }
427
+ return new (P || (P = Promise))(function(resolve2, reject) {
428
+ function fulfilled(value) {
429
+ try {
430
+ step(generator.next(value));
431
+ } catch (e) {
432
+ reject(e);
433
+ }
434
+ }
435
+ function rejected(value) {
436
+ try {
437
+ step(generator["throw"](value));
438
+ } catch (e) {
439
+ reject(e);
440
+ }
441
+ }
442
+ function step(result) {
443
+ result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
444
+ }
445
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
446
+ });
447
+ };
448
+ var __generator = exports && exports.__generator || function(thisArg, body) {
449
+ var _ = { label: 0, sent: function() {
450
+ if (t[0] & 1) throw t[1];
451
+ return t[1];
452
+ }, trys: [], ops: [] }, f, y, t, g;
453
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
454
+ return this;
455
+ }), g;
456
+ function verb(n) {
457
+ return function(v) {
458
+ return step([n, v]);
459
+ };
460
+ }
461
+ function step(op) {
462
+ if (f) throw new TypeError("Generator is already executing.");
463
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
464
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
465
+ if (y = 0, t) op = [op[0] & 2, t.value];
466
+ switch (op[0]) {
467
+ case 0:
468
+ case 1:
469
+ t = op;
470
+ break;
471
+ case 4:
472
+ _.label++;
473
+ return { value: op[1], done: false };
474
+ case 5:
475
+ _.label++;
476
+ y = op[1];
477
+ op = [0];
478
+ continue;
479
+ case 7:
480
+ op = _.ops.pop();
481
+ _.trys.pop();
482
+ continue;
483
+ default:
484
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
485
+ _ = 0;
486
+ continue;
487
+ }
488
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
489
+ _.label = op[1];
490
+ break;
491
+ }
492
+ if (op[0] === 6 && _.label < t[1]) {
493
+ _.label = t[1];
494
+ t = op;
495
+ break;
496
+ }
497
+ if (t && _.label < t[2]) {
498
+ _.label = t[2];
499
+ _.ops.push(op);
500
+ break;
501
+ }
502
+ if (t[2]) _.ops.pop();
503
+ _.trys.pop();
504
+ continue;
505
+ }
506
+ op = body.call(thisArg, _);
507
+ } catch (e) {
508
+ op = [6, e];
509
+ y = 0;
510
+ } finally {
511
+ f = t = 0;
512
+ }
513
+ if (op[0] & 5) throw op[1];
514
+ return { value: op[0] ? op[1] : void 0, done: true };
515
+ }
516
+ };
517
+ var __spreadArray = exports && exports.__spreadArray || function(to, from, pack) {
518
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
519
+ if (ar || !(i in from)) {
520
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
521
+ ar[i] = from[i];
522
+ }
523
+ }
524
+ return to.concat(ar || Array.prototype.slice.call(from));
525
+ };
526
+ Object.defineProperty(exports, "__esModule", { value: true });
527
+ exports.JSONRPCServer = void 0;
528
+ var models_1 = require_models();
529
+ var internal_1 = require_internal();
530
+ var createParseErrorResponse = function() {
531
+ return (0, models_1.createJSONRPCErrorResponse)(null, models_1.JSONRPCErrorCode.ParseError, "Parse error");
532
+ };
533
+ var createInvalidRequestResponse = function(request) {
534
+ return (0, models_1.createJSONRPCErrorResponse)((0, models_1.isJSONRPCID)(request.id) ? request.id : null, models_1.JSONRPCErrorCode.InvalidRequest, "Invalid Request");
535
+ };
536
+ var createMethodNotFoundResponse = function(id) {
537
+ return (0, models_1.createJSONRPCErrorResponse)(id, models_1.JSONRPCErrorCode.MethodNotFound, "Method not found");
538
+ };
539
+ var JSONRPCServer2 = (
540
+ /** @class */
541
+ (function() {
542
+ function JSONRPCServer3(options) {
543
+ if (options === void 0) {
544
+ options = {};
545
+ }
546
+ var _a;
547
+ this.mapErrorToJSONRPCErrorResponse = defaultMapErrorToJSONRPCErrorResponse;
548
+ this.nameToMethodDictionary = {};
549
+ this.middleware = null;
550
+ this.errorListener = (_a = options.errorListener) !== null && _a !== void 0 ? _a : console.warn;
551
+ }
552
+ JSONRPCServer3.prototype.hasMethod = function(name) {
553
+ return !!this.nameToMethodDictionary[name];
554
+ };
555
+ JSONRPCServer3.prototype.addMethod = function(name, method) {
556
+ this.addMethodAdvanced(name, this.toJSONRPCMethod(method));
557
+ };
558
+ JSONRPCServer3.prototype.removeMethod = function(name) {
559
+ delete this.nameToMethodDictionary[name];
560
+ };
561
+ JSONRPCServer3.prototype.toJSONRPCMethod = function(method) {
562
+ return function(request, serverParams) {
563
+ var response = method(request.params, serverParams);
564
+ return Promise.resolve(response).then(function(result) {
565
+ return mapResultToJSONRPCResponse(request.id, result);
566
+ });
567
+ };
568
+ };
569
+ JSONRPCServer3.prototype.addMethodAdvanced = function(name, method) {
570
+ var _a;
571
+ this.nameToMethodDictionary = __assign(__assign({}, this.nameToMethodDictionary), (_a = {}, _a[name] = method, _a));
572
+ };
573
+ JSONRPCServer3.prototype.receiveJSON = function(json, serverParams) {
574
+ var request = this.tryParseRequestJSON(json);
575
+ if (request) {
576
+ return this.receive(request, serverParams);
577
+ } else {
578
+ return Promise.resolve(createParseErrorResponse());
579
+ }
580
+ };
581
+ JSONRPCServer3.prototype.tryParseRequestJSON = function(json) {
582
+ try {
583
+ return JSON.parse(json);
584
+ } catch (_a) {
585
+ return null;
586
+ }
587
+ };
588
+ JSONRPCServer3.prototype.receive = function(request, serverParams) {
589
+ if (Array.isArray(request)) {
590
+ return this.receiveMultiple(request, serverParams);
591
+ } else {
592
+ return this.receiveSingle(request, serverParams);
593
+ }
594
+ };
595
+ JSONRPCServer3.prototype.receiveMultiple = function(requests, serverParams) {
596
+ return __awaiter(this, void 0, void 0, function() {
597
+ var responses;
598
+ var _this = this;
599
+ return __generator(this, function(_a) {
600
+ switch (_a.label) {
601
+ case 0:
602
+ return [4, Promise.all(requests.map(function(request) {
603
+ return _this.receiveSingle(request, serverParams);
604
+ }))];
605
+ case 1:
606
+ responses = _a.sent().filter(isNonNull);
607
+ if (responses.length === 1) {
608
+ return [2, responses[0]];
609
+ } else if (responses.length) {
610
+ return [2, responses];
611
+ } else {
612
+ return [2, null];
613
+ }
614
+ return [
615
+ 2
616
+ /*return*/
617
+ ];
618
+ }
619
+ });
620
+ });
621
+ };
622
+ JSONRPCServer3.prototype.receiveSingle = function(request, serverParams) {
623
+ return __awaiter(this, void 0, void 0, function() {
624
+ var method, response;
625
+ return __generator(this, function(_a) {
626
+ switch (_a.label) {
627
+ case 0:
628
+ method = this.nameToMethodDictionary[request.method];
629
+ if (!!(0, models_1.isJSONRPCRequest)(request)) return [3, 1];
630
+ return [2, createInvalidRequestResponse(request)];
631
+ case 1:
632
+ return [4, this.callMethod(method, request, serverParams)];
633
+ case 2:
634
+ response = _a.sent();
635
+ return [2, mapResponse(request, response)];
636
+ }
637
+ });
638
+ });
639
+ };
640
+ JSONRPCServer3.prototype.applyMiddleware = function() {
641
+ var middlewares = [];
642
+ for (var _i = 0; _i < arguments.length; _i++) {
643
+ middlewares[_i] = arguments[_i];
644
+ }
645
+ if (this.middleware) {
646
+ this.middleware = this.combineMiddlewares(__spreadArray([
647
+ this.middleware
648
+ ], middlewares, true));
649
+ } else {
650
+ this.middleware = this.combineMiddlewares(middlewares);
651
+ }
652
+ };
653
+ JSONRPCServer3.prototype.combineMiddlewares = function(middlewares) {
654
+ if (!middlewares.length) {
655
+ return null;
656
+ } else {
657
+ return middlewares.reduce(this.middlewareReducer);
658
+ }
659
+ };
660
+ JSONRPCServer3.prototype.middlewareReducer = function(prevMiddleware, nextMiddleware) {
661
+ return function(next, request, serverParams) {
662
+ return prevMiddleware(function(request2, serverParams2) {
663
+ return nextMiddleware(next, request2, serverParams2);
664
+ }, request, serverParams);
665
+ };
666
+ };
667
+ JSONRPCServer3.prototype.callMethod = function(method, request, serverParams) {
668
+ var _this = this;
669
+ var callMethod = function(request2, serverParams2) {
670
+ if (method) {
671
+ return method(request2, serverParams2);
672
+ } else if (request2.id !== void 0) {
673
+ return Promise.resolve(createMethodNotFoundResponse(request2.id));
674
+ } else {
675
+ return Promise.resolve(null);
676
+ }
677
+ };
678
+ var onError = function(error) {
679
+ _this.errorListener('An unexpected error occurred while executing "'.concat(request.method, '" JSON-RPC method:'), error);
680
+ return Promise.resolve(_this.mapErrorToJSONRPCErrorResponseIfNecessary(request.id, error));
681
+ };
682
+ try {
683
+ return (this.middleware || noopMiddleware)(callMethod, request, serverParams).then(void 0, onError);
684
+ } catch (error) {
685
+ return onError(error);
686
+ }
687
+ };
688
+ JSONRPCServer3.prototype.mapErrorToJSONRPCErrorResponseIfNecessary = function(id, error) {
689
+ if (id !== void 0) {
690
+ return this.mapErrorToJSONRPCErrorResponse(id, error);
691
+ } else {
692
+ return null;
693
+ }
694
+ };
695
+ return JSONRPCServer3;
696
+ })()
697
+ );
698
+ exports.JSONRPCServer = JSONRPCServer2;
699
+ var isNonNull = function(value) {
700
+ return value !== null;
701
+ };
702
+ var noopMiddleware = function(next, request, serverParams) {
703
+ return next(request, serverParams);
704
+ };
705
+ var mapResultToJSONRPCResponse = function(id, result) {
706
+ if (id !== void 0) {
707
+ return (0, models_1.createJSONRPCSuccessResponse)(id, result);
708
+ } else {
709
+ return null;
710
+ }
711
+ };
712
+ var defaultMapErrorToJSONRPCErrorResponse = function(id, error) {
713
+ var _a;
714
+ var message = (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : "An unexpected error occurred";
715
+ var code = internal_1.DefaultErrorCode;
716
+ var data;
717
+ if (error instanceof models_1.JSONRPCErrorException) {
718
+ code = error.code;
719
+ data = error.data;
720
+ }
721
+ return (0, models_1.createJSONRPCErrorResponse)(id, code, message, data);
722
+ };
723
+ var mapResponse = function(request, response) {
724
+ if (response) {
725
+ return response;
726
+ } else if (request.id !== void 0) {
727
+ return (0, models_1.createJSONRPCErrorResponse)(request.id, models_1.JSONRPCErrorCode.InternalError, "Internal error");
728
+ } else {
729
+ return null;
730
+ }
731
+ };
732
+ }
733
+ });
734
+
735
+ // ../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/server-and-client.js
736
+ var require_server_and_client = __commonJS({
737
+ "../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/server-and-client.js"(exports) {
738
+ "use strict";
739
+ var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
740
+ function adopt(value) {
741
+ return value instanceof P ? value : new P(function(resolve2) {
742
+ resolve2(value);
743
+ });
744
+ }
745
+ return new (P || (P = Promise))(function(resolve2, reject) {
746
+ function fulfilled(value) {
747
+ try {
748
+ step(generator.next(value));
749
+ } catch (e) {
750
+ reject(e);
751
+ }
752
+ }
753
+ function rejected(value) {
754
+ try {
755
+ step(generator["throw"](value));
756
+ } catch (e) {
757
+ reject(e);
758
+ }
759
+ }
760
+ function step(result) {
761
+ result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
762
+ }
763
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
764
+ });
765
+ };
766
+ var __generator = exports && exports.__generator || function(thisArg, body) {
767
+ var _ = { label: 0, sent: function() {
768
+ if (t[0] & 1) throw t[1];
769
+ return t[1];
770
+ }, trys: [], ops: [] }, f, y, t, g;
771
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
772
+ return this;
773
+ }), g;
774
+ function verb(n) {
775
+ return function(v) {
776
+ return step([n, v]);
777
+ };
778
+ }
779
+ function step(op) {
780
+ if (f) throw new TypeError("Generator is already executing.");
781
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
782
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
783
+ if (y = 0, t) op = [op[0] & 2, t.value];
784
+ switch (op[0]) {
785
+ case 0:
786
+ case 1:
787
+ t = op;
788
+ break;
789
+ case 4:
790
+ _.label++;
791
+ return { value: op[1], done: false };
792
+ case 5:
793
+ _.label++;
794
+ y = op[1];
795
+ op = [0];
796
+ continue;
797
+ case 7:
798
+ op = _.ops.pop();
799
+ _.trys.pop();
800
+ continue;
801
+ default:
802
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
803
+ _ = 0;
804
+ continue;
805
+ }
806
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
807
+ _.label = op[1];
808
+ break;
809
+ }
810
+ if (op[0] === 6 && _.label < t[1]) {
811
+ _.label = t[1];
812
+ t = op;
813
+ break;
814
+ }
815
+ if (t && _.label < t[2]) {
816
+ _.label = t[2];
817
+ _.ops.push(op);
818
+ break;
819
+ }
820
+ if (t[2]) _.ops.pop();
821
+ _.trys.pop();
822
+ continue;
823
+ }
824
+ op = body.call(thisArg, _);
825
+ } catch (e) {
826
+ op = [6, e];
827
+ y = 0;
828
+ } finally {
829
+ f = t = 0;
830
+ }
831
+ if (op[0] & 5) throw op[1];
832
+ return { value: op[0] ? op[1] : void 0, done: true };
833
+ }
834
+ };
835
+ Object.defineProperty(exports, "__esModule", { value: true });
836
+ exports.JSONRPCServerAndClient = void 0;
837
+ var models_1 = require_models();
838
+ var JSONRPCServerAndClient = (
839
+ /** @class */
840
+ (function() {
841
+ function JSONRPCServerAndClient2(server2, client, options) {
842
+ if (options === void 0) {
843
+ options = {};
844
+ }
845
+ var _a;
846
+ this.server = server2;
847
+ this.client = client;
848
+ this.errorListener = (_a = options.errorListener) !== null && _a !== void 0 ? _a : console.warn;
849
+ }
850
+ JSONRPCServerAndClient2.prototype.applyServerMiddleware = function() {
851
+ var _a;
852
+ var middlewares = [];
853
+ for (var _i = 0; _i < arguments.length; _i++) {
854
+ middlewares[_i] = arguments[_i];
855
+ }
856
+ (_a = this.server).applyMiddleware.apply(_a, middlewares);
857
+ };
858
+ JSONRPCServerAndClient2.prototype.hasMethod = function(name) {
859
+ return this.server.hasMethod(name);
860
+ };
861
+ JSONRPCServerAndClient2.prototype.addMethod = function(name, method) {
862
+ this.server.addMethod(name, method);
863
+ };
864
+ JSONRPCServerAndClient2.prototype.addMethodAdvanced = function(name, method) {
865
+ this.server.addMethodAdvanced(name, method);
866
+ };
867
+ JSONRPCServerAndClient2.prototype.removeMethod = function(name) {
868
+ this.server.removeMethod(name);
869
+ };
870
+ JSONRPCServerAndClient2.prototype.timeout = function(delay) {
871
+ return this.client.timeout(delay);
872
+ };
873
+ JSONRPCServerAndClient2.prototype.request = function(method, params, clientParams) {
874
+ return this.client.request(method, params, clientParams);
875
+ };
876
+ JSONRPCServerAndClient2.prototype.requestAdvanced = function(jsonRPCRequest, clientParams) {
877
+ return this.client.requestAdvanced(jsonRPCRequest, clientParams);
878
+ };
879
+ JSONRPCServerAndClient2.prototype.notify = function(method, params, clientParams) {
880
+ this.client.notify(method, params, clientParams);
881
+ };
882
+ JSONRPCServerAndClient2.prototype.rejectAllPendingRequests = function(message) {
883
+ this.client.rejectAllPendingRequests(message);
884
+ };
885
+ JSONRPCServerAndClient2.prototype.receiveAndSend = function(payload, serverParams, clientParams) {
886
+ return __awaiter(this, void 0, void 0, function() {
887
+ var response, message;
888
+ return __generator(this, function(_a) {
889
+ switch (_a.label) {
890
+ case 0:
891
+ if (!((0, models_1.isJSONRPCResponse)(payload) || (0, models_1.isJSONRPCResponses)(payload))) return [3, 1];
892
+ this.client.receive(payload);
893
+ return [3, 4];
894
+ case 1:
895
+ if (!((0, models_1.isJSONRPCRequest)(payload) || (0, models_1.isJSONRPCRequests)(payload))) return [3, 3];
896
+ return [4, this.server.receive(payload, serverParams)];
897
+ case 2:
898
+ response = _a.sent();
899
+ if (response) {
900
+ return [2, this.client.send(response, clientParams)];
901
+ }
902
+ return [3, 4];
903
+ case 3:
904
+ message = "Received an invalid JSON-RPC message";
905
+ this.errorListener(message, payload);
906
+ return [2, Promise.reject(new Error(message))];
907
+ case 4:
908
+ return [
909
+ 2
910
+ /*return*/
911
+ ];
912
+ }
913
+ });
914
+ });
915
+ };
916
+ return JSONRPCServerAndClient2;
917
+ })()
918
+ );
919
+ exports.JSONRPCServerAndClient = JSONRPCServerAndClient;
920
+ }
921
+ });
922
+
923
+ // ../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/index.js
924
+ var require_dist = __commonJS({
925
+ "../../node_modules/.pnpm/json-rpc-2.0@1.7.1/node_modules/json-rpc-2.0/dist/index.js"(exports) {
926
+ "use strict";
927
+ var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
928
+ if (k2 === void 0) k2 = k;
929
+ var desc = Object.getOwnPropertyDescriptor(m, k);
930
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
931
+ desc = { enumerable: true, get: function() {
932
+ return m[k];
933
+ } };
934
+ }
935
+ Object.defineProperty(o, k2, desc);
936
+ }) : (function(o, m, k, k2) {
937
+ if (k2 === void 0) k2 = k;
938
+ o[k2] = m[k];
939
+ }));
940
+ var __exportStar = exports && exports.__exportStar || function(m, exports2) {
941
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
942
+ };
943
+ Object.defineProperty(exports, "__esModule", { value: true });
944
+ __exportStar(require_client(), exports);
945
+ __exportStar(require_interfaces(), exports);
946
+ __exportStar(require_models(), exports);
947
+ __exportStar(require_server(), exports);
948
+ __exportStar(require_server_and_client(), exports);
949
+ }
950
+ });
951
+
952
+ // ../../node_modules/.pnpm/tmcp@1.19.4_typescript@5.9.3/node_modules/tmcp/src/adapter.js
953
+ var JsonSchemaAdapter = class {
954
+ /**
955
+ * @param {TSchema} schema
956
+ * @returns {Promise<JSONSchema7>}
957
+ */
958
+ toJsonSchema(schema6) {
959
+ throw new Error("toJsonSchema method not implemented");
960
+ }
961
+ };
10
962
 
11
963
  // ../../node_modules/.pnpm/@valibot+to-json-schema@1.7.0_valibot@1.4.1_typescript@5.9.3_/node_modules/@valibot/to-json-schema/dist/index.mjs
12
964
  function addError(errors, message) {
@@ -503,71 +1455,570 @@ var ValibotJsonSchemaAdapter = class extends JsonSchemaAdapter {
503
1455
  }
504
1456
  };
505
1457
 
506
- // ../mcp-server/src/mcp/index.ts
507
- import { McpServer } from "tmcp";
508
-
509
- // ../mcp-server/src/mcp/handlers/tools/index.ts
510
- var tools_exports = {};
511
- __export(tools_exports, {
512
- get_component: () => get_component,
513
- get_component_demo: () => get_component_demo,
514
- get_utils: () => get_utils,
515
- list_components: () => list_components,
516
- list_exports: () => list_exports,
517
- search_components: () => search_components
518
- });
1458
+ // ../../node_modules/.pnpm/tmcp@1.19.4_typescript@5.9.3/node_modules/tmcp/src/index.js
1459
+ var import_json_rpc_2 = __toESM(require_dist(), 1);
1460
+ import { AsyncLocalStorage } from "async_hooks";
519
1461
 
520
- // ../../node_modules/.pnpm/valibot@1.4.1_typescript@5.9.3/node_modules/valibot/dist/index.mjs
521
- var store$4;
522
- var DEFAULT_CONFIG = {
523
- lang: void 0,
524
- message: void 0,
525
- abortEarly: void 0,
526
- abortPipeEarly: void 0
527
- };
528
- // @__NO_SIDE_EFFECTS__
529
- function getGlobalConfig(config$1) {
530
- if (!config$1 && !store$4) return DEFAULT_CONFIG;
1462
+ // ../../node_modules/.pnpm/uri-template-matcher@1.1.2/node_modules/uri-template-matcher/src/parser.js
1463
+ function parse_template(template) {
1464
+ const parts = [];
1465
+ let current_literal = "";
1466
+ let i = 0;
1467
+ while (i < template.length) {
1468
+ const char = template[i];
1469
+ if (char === "{") {
1470
+ if (current_literal) {
1471
+ parts.push({ type: "literal", value: current_literal });
1472
+ current_literal = "";
1473
+ }
1474
+ const expression_start = i + 1;
1475
+ let expression_end = expression_start;
1476
+ let brace_count = 1;
1477
+ while (expression_end < template.length && brace_count > 0) {
1478
+ if (template[expression_end] === "{") {
1479
+ brace_count++;
1480
+ } else if (template[expression_end] === "}") {
1481
+ brace_count--;
1482
+ }
1483
+ expression_end++;
1484
+ }
1485
+ if (brace_count > 0) {
1486
+ throw new Error(`Unclosed expression in template: ${template}`);
1487
+ }
1488
+ const expression_content = template.slice(
1489
+ expression_start,
1490
+ expression_end - 1
1491
+ );
1492
+ const parsed_expression = parse_expression(expression_content);
1493
+ parts.push(parsed_expression);
1494
+ i = expression_end;
1495
+ } else {
1496
+ current_literal += char;
1497
+ i++;
1498
+ }
1499
+ }
1500
+ if (current_literal) {
1501
+ parts.push({ type: "literal", value: current_literal });
1502
+ }
1503
+ return { template, parts };
1504
+ }
1505
+ function parse_expression(content) {
1506
+ if (!content.trim()) {
1507
+ throw new Error("Empty expression");
1508
+ }
1509
+ const first_char = content[0];
1510
+ const operators = ["+", "#", ".", "/", ";", "?", "&"];
1511
+ let operator = void 0;
1512
+ let variables_part = content;
1513
+ if (operators.includes(first_char)) {
1514
+ operator = first_char;
1515
+ variables_part = content.slice(1);
1516
+ }
1517
+ const variable_names = split_variables(variables_part);
1518
+ const expressions = variable_names.map(parse_variable);
531
1519
  return {
532
- lang: config$1?.lang ?? store$4?.lang,
533
- message: config$1?.message,
534
- abortEarly: config$1?.abortEarly ?? store$4?.abortEarly,
535
- abortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly
1520
+ type: "expression",
1521
+ expressions,
1522
+ operator
536
1523
  };
537
1524
  }
538
- var store$3;
539
- // @__NO_SIDE_EFFECTS__
540
- function getGlobalMessage(lang) {
541
- return store$3?.get(lang);
1525
+ function split_variables(variables) {
1526
+ const result = [];
1527
+ let current = "";
1528
+ let i = 0;
1529
+ while (i < variables.length) {
1530
+ const char = variables[i];
1531
+ if (char === ",") {
1532
+ if (current.trim()) {
1533
+ result.push(current.trim());
1534
+ current = "";
1535
+ }
1536
+ } else {
1537
+ current += char;
1538
+ }
1539
+ i++;
1540
+ }
1541
+ if (current.trim()) {
1542
+ result.push(current.trim());
1543
+ }
1544
+ return result;
542
1545
  }
543
- var store$2;
544
- // @__NO_SIDE_EFFECTS__
545
- function getSchemaMessage(lang) {
546
- return store$2?.get(lang);
1546
+ function parse_variable(variable) {
1547
+ let name = variable;
1548
+ let prefix = void 0;
1549
+ let explode = false;
1550
+ if (name.endsWith("*")) {
1551
+ explode = true;
1552
+ name = name.slice(0, -1);
1553
+ }
1554
+ const colon_index = name.indexOf(":");
1555
+ if (colon_index !== -1) {
1556
+ const prefix_str = name.slice(colon_index + 1);
1557
+ prefix = parseInt(prefix_str, 10);
1558
+ if (isNaN(prefix) || prefix < 0) {
1559
+ throw new Error(`Invalid prefix length: ${prefix_str}`);
1560
+ }
1561
+ name = name.slice(0, colon_index);
1562
+ }
1563
+ if (!name) {
1564
+ throw new Error("Empty variable name");
1565
+ }
1566
+ return { name, prefix, explode };
547
1567
  }
548
- var store$1;
549
- // @__NO_SIDE_EFFECTS__
550
- function getSpecificMessage(reference, lang) {
551
- return store$1?.get(reference)?.get(lang);
1568
+ function match_uri(uri, parsed_template) {
1569
+ const params = {};
1570
+ const result = match_parts(uri, 0, parsed_template.parts, 0, params);
1571
+ if (!result || result.uri_index !== uri.length) {
1572
+ return null;
1573
+ }
1574
+ return params;
552
1575
  }
553
- // @__NO_SIDE_EFFECTS__
554
- function _stringify(input) {
555
- const type = typeof input;
556
- if (type === "string") return `"${input}"`;
557
- if (type === "number" || type === "bigint" || type === "boolean") return `${input}`;
558
- if (type === "object" || type === "function") return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
559
- return type;
1576
+ function match_parts(uri, uri_index, parts, part_index, params) {
1577
+ if (part_index >= parts.length) {
1578
+ return { uri_index };
1579
+ }
1580
+ const part = parts[part_index];
1581
+ if (part.type === "literal") {
1582
+ if (!uri.slice(uri_index).startsWith(part.value)) {
1583
+ return null;
1584
+ }
1585
+ return match_parts(
1586
+ uri,
1587
+ uri_index + part.value.length,
1588
+ parts,
1589
+ part_index + 1,
1590
+ params
1591
+ );
1592
+ } else {
1593
+ const next_part = parts[part_index + 1];
1594
+ const boundaries = find_expression_boundaries(
1595
+ uri,
1596
+ uri_index,
1597
+ next_part
1598
+ );
1599
+ const sorted_boundaries = boundaries.sort((a, b) => {
1600
+ if (next_part && next_part.type === "expression" && !next_part.operator) {
1601
+ return b - a;
1602
+ }
1603
+ return a - b;
1604
+ });
1605
+ for (const boundary of sorted_boundaries) {
1606
+ const segment = uri.slice(uri_index, boundary);
1607
+ const temp_params = { ...params };
1608
+ const match_result = match_simple_expression(
1609
+ segment,
1610
+ part,
1611
+ temp_params,
1612
+ uri,
1613
+ uri_index
1614
+ );
1615
+ if (match_result) {
1616
+ const rest_result = match_parts(
1617
+ uri,
1618
+ boundary,
1619
+ parts,
1620
+ part_index + 1,
1621
+ temp_params
1622
+ );
1623
+ if (rest_result) {
1624
+ Object.assign(params, temp_params);
1625
+ return rest_result;
1626
+ }
1627
+ }
1628
+ }
1629
+ return null;
1630
+ }
560
1631
  }
561
- function _addIssue(context, label, dataset, config$1, other) {
562
- const input = other && "input" in other ? other.input : dataset.value;
563
- const expected = other?.expected ?? context.expects ?? null;
564
- const received = other?.received ?? /* @__PURE__ */ _stringify(input);
565
- const issue = {
566
- kind: context.kind,
567
- type: context.type,
568
- input,
569
- expected,
570
- received,
1632
+ function find_expression_boundaries(uri, start_index, next_part) {
1633
+ const boundaries = [];
1634
+ if (next_part && next_part.type === "literal") {
1635
+ let search_index = start_index;
1636
+ while (search_index < uri.length) {
1637
+ const found_index = uri.indexOf(next_part.value, search_index);
1638
+ if (found_index === -1) break;
1639
+ boundaries.push(found_index);
1640
+ search_index = found_index + 1;
1641
+ }
1642
+ if (boundaries.length === 0) {
1643
+ return [];
1644
+ }
1645
+ } else if (next_part && next_part.type === "expression") {
1646
+ const next_expr = (
1647
+ /** @type {ExpressionPart} */
1648
+ next_part
1649
+ );
1650
+ if (next_expr.operator === ".") {
1651
+ for (let i = start_index; i < uri.length; i++) {
1652
+ if (uri[i] === ".") {
1653
+ boundaries.push(i);
1654
+ }
1655
+ }
1656
+ boundaries.push(uri.length);
1657
+ } else if (next_expr.operator === "/") {
1658
+ for (let i = start_index; i < uri.length; i++) {
1659
+ if (uri[i] === "/") {
1660
+ boundaries.push(i);
1661
+ }
1662
+ }
1663
+ } else {
1664
+ for (let i = start_index; i <= uri.length; i++) {
1665
+ boundaries.push(i);
1666
+ }
1667
+ }
1668
+ } else {
1669
+ boundaries.push(uri.length);
1670
+ }
1671
+ return boundaries.sort((a, b) => a - b);
1672
+ }
1673
+ function match_simple_expression(segment, expression, params, uri, uri_index) {
1674
+ if (expression.type !== "expression") {
1675
+ return false;
1676
+ }
1677
+ const operator = expression.operator;
1678
+ switch (operator) {
1679
+ case "+":
1680
+ return handle_reserved_match(segment, expression, params);
1681
+ case "#":
1682
+ return handle_fragment_match(segment, expression, params);
1683
+ case ".":
1684
+ return handle_dot_match(segment, expression, params);
1685
+ case "/":
1686
+ return handle_path_match(segment, expression, params);
1687
+ case ";":
1688
+ return handle_semicolon_match(segment, expression, params);
1689
+ case "?":
1690
+ case "&":
1691
+ return handle_query_match(segment, expression, params);
1692
+ default:
1693
+ return handle_simple_match(
1694
+ segment,
1695
+ expression,
1696
+ params,
1697
+ uri,
1698
+ uri_index
1699
+ );
1700
+ }
1701
+ }
1702
+ function handle_fragment_match(segment, expression, params) {
1703
+ if (expression.type !== "expression") {
1704
+ return false;
1705
+ }
1706
+ if (!segment.startsWith("#")) {
1707
+ for (const expr of expression.expressions) {
1708
+ params[expr.name] = "";
1709
+ }
1710
+ return segment === "";
1711
+ }
1712
+ const fragment_content = segment.slice(1);
1713
+ if (expression.expressions.length === 1) {
1714
+ const expr = expression.expressions[0];
1715
+ let value = fragment_content;
1716
+ if (expr.prefix && value.length > expr.prefix) {
1717
+ value = value.slice(0, expr.prefix);
1718
+ }
1719
+ params[expr.name] = decodeURIComponent(value);
1720
+ return true;
1721
+ } else {
1722
+ const values = fragment_content.split(",");
1723
+ for (let i = 0; i < expression.expressions.length; i++) {
1724
+ const expr = expression.expressions[i];
1725
+ let value = values[i] || "";
1726
+ if (expr.prefix && value.length > expr.prefix) {
1727
+ value = value.slice(0, expr.prefix);
1728
+ }
1729
+ params[expr.name] = decodeURIComponent(value);
1730
+ }
1731
+ return true;
1732
+ }
1733
+ }
1734
+ function handle_reserved_match(segment, expression, params) {
1735
+ if (expression.type !== "expression") {
1736
+ return false;
1737
+ }
1738
+ if (expression.expressions.length === 1) {
1739
+ const expr = expression.expressions[0];
1740
+ let value = segment;
1741
+ if (expr.prefix && value.length > expr.prefix) {
1742
+ value = value.slice(0, expr.prefix);
1743
+ }
1744
+ params[expr.name] = decodeURIComponent(value);
1745
+ return true;
1746
+ } else {
1747
+ const values = segment.split(",");
1748
+ for (let i = 0; i < expression.expressions.length; i++) {
1749
+ const expr = expression.expressions[i];
1750
+ let value = values[i] || "";
1751
+ if (expr.prefix && value.length > expr.prefix) {
1752
+ value = value.slice(0, expr.prefix);
1753
+ }
1754
+ params[expr.name] = decodeURIComponent(value);
1755
+ }
1756
+ return true;
1757
+ }
1758
+ }
1759
+ function handle_simple_match(segment, expression, params, uri, uri_index) {
1760
+ if (expression.type !== "expression") {
1761
+ return false;
1762
+ }
1763
+ if (expression.expressions.length === 1) {
1764
+ const expr = expression.expressions[0];
1765
+ let value = segment;
1766
+ if (value.includes("/")) {
1767
+ return false;
1768
+ }
1769
+ if (value === "" && uri_index + segment.length === uri.length && uri.endsWith("/")) {
1770
+ return false;
1771
+ }
1772
+ if (expr.prefix && value.length > expr.prefix) {
1773
+ value = value.slice(0, expr.prefix);
1774
+ }
1775
+ params[expr.name] = decodeURIComponent(value);
1776
+ return true;
1777
+ } else {
1778
+ const values = segment.split(",");
1779
+ for (let i = 0; i < expression.expressions.length; i++) {
1780
+ const expr = expression.expressions[i];
1781
+ let value = values[i] || "";
1782
+ if (value.includes("/")) {
1783
+ return false;
1784
+ }
1785
+ if (expr.prefix && value.length > expr.prefix) {
1786
+ value = value.slice(0, expr.prefix);
1787
+ }
1788
+ params[expr.name] = decodeURIComponent(value);
1789
+ }
1790
+ return true;
1791
+ }
1792
+ }
1793
+ function handle_dot_match(segment, expression, params) {
1794
+ if (expression.type !== "expression") {
1795
+ return false;
1796
+ }
1797
+ if (segment === "") {
1798
+ for (const expr of expression.expressions) {
1799
+ params[expr.name] = "";
1800
+ }
1801
+ return true;
1802
+ }
1803
+ const clean_segment = segment.startsWith(".") ? segment.slice(1) : segment;
1804
+ if (expression.expressions.length === 1) {
1805
+ const expr = expression.expressions[0];
1806
+ if (expr.explode) {
1807
+ const values = clean_segment.split(".");
1808
+ params[expr.name] = values.map((v) => decodeURIComponent(v));
1809
+ } else {
1810
+ params[expr.name] = decodeURIComponent(clean_segment);
1811
+ }
1812
+ return true;
1813
+ } else {
1814
+ const values = clean_segment.split(".");
1815
+ for (let i = 0; i < expression.expressions.length; i++) {
1816
+ const expr = expression.expressions[i];
1817
+ let value = values[i] || "";
1818
+ if (expr.prefix && value.length > expr.prefix) {
1819
+ value = value.slice(0, expr.prefix);
1820
+ }
1821
+ params[expr.name] = decodeURIComponent(value);
1822
+ }
1823
+ return true;
1824
+ }
1825
+ }
1826
+ function handle_path_match(segment, expression, params) {
1827
+ if (expression.type !== "expression") {
1828
+ return false;
1829
+ }
1830
+ const clean_segment = segment.startsWith("/") ? segment.slice(1) : segment;
1831
+ if (expression.expressions.length === 1) {
1832
+ const expr = expression.expressions[0];
1833
+ params[expr.name] = decodeURIComponent(clean_segment);
1834
+ return true;
1835
+ } else {
1836
+ const values = clean_segment.split(",");
1837
+ for (let i = 0; i < expression.expressions.length; i++) {
1838
+ const expr = expression.expressions[i];
1839
+ let value = values[i] || "";
1840
+ if (expr.prefix && value.length > expr.prefix) {
1841
+ value = value.slice(0, expr.prefix);
1842
+ }
1843
+ params[expr.name] = decodeURIComponent(value);
1844
+ }
1845
+ return true;
1846
+ }
1847
+ }
1848
+ function handle_semicolon_match(segment, expression, params) {
1849
+ if (expression.type !== "expression") {
1850
+ return false;
1851
+ }
1852
+ const parts = segment.split(";").filter((p) => p);
1853
+ for (const part of parts) {
1854
+ const eq_index = part.indexOf("=");
1855
+ if (eq_index !== -1) {
1856
+ const key = part.slice(0, eq_index);
1857
+ const value = part.slice(eq_index + 1);
1858
+ const expr = expression.expressions.find((e) => e.name === key);
1859
+ if (expr) {
1860
+ params[expr.name] = decodeURIComponent(value);
1861
+ }
1862
+ }
1863
+ }
1864
+ return true;
1865
+ }
1866
+ function handle_query_match(segment, expression, params) {
1867
+ if (expression.type !== "expression") {
1868
+ return false;
1869
+ }
1870
+ const clean_segment = segment.replace(/^[?&]/, "");
1871
+ if (expression.expressions.length === 1) {
1872
+ const expr = expression.expressions[0];
1873
+ if (expr.explode) {
1874
+ const values = clean_segment.split("&");
1875
+ params[expr.name] = values.map((v) => decodeURIComponent(v));
1876
+ } else {
1877
+ const parts = clean_segment.split("&");
1878
+ for (const part of parts) {
1879
+ const eq_index = part.indexOf("=");
1880
+ if (eq_index !== -1) {
1881
+ const key = part.slice(0, eq_index);
1882
+ const value = part.slice(eq_index + 1);
1883
+ if (key === expr.name) {
1884
+ params[expr.name] = decodeURIComponent(value);
1885
+ }
1886
+ }
1887
+ }
1888
+ }
1889
+ } else {
1890
+ const parts = clean_segment.split("&");
1891
+ for (const part of parts) {
1892
+ const eq_index = part.indexOf("=");
1893
+ if (eq_index !== -1) {
1894
+ const key = part.slice(0, eq_index);
1895
+ const value = part.slice(eq_index + 1);
1896
+ const expr = expression.expressions.find((e) => e.name === key);
1897
+ if (expr) {
1898
+ params[expr.name] = decodeURIComponent(value);
1899
+ }
1900
+ }
1901
+ }
1902
+ }
1903
+ return true;
1904
+ }
1905
+
1906
+ // ../../node_modules/.pnpm/uri-template-matcher@1.1.2/node_modules/uri-template-matcher/src/matcher.js
1907
+ var UriTemplateMatcher = class {
1908
+ /**
1909
+ * Create a new UriTemplateMatcher instance
1910
+ */
1911
+ constructor() {
1912
+ this.templates = [];
1913
+ }
1914
+ /**
1915
+ * Add a URI template to the matcher
1916
+ * @param {string} template - The URI template string to add
1917
+ * @throws {Error} If template is invalid
1918
+ */
1919
+ add(template) {
1920
+ if (typeof template !== "string") {
1921
+ throw new Error("Template must be a string");
1922
+ }
1923
+ if (template !== "" && template.trim() === "") {
1924
+ throw new Error("Template cannot be empty");
1925
+ }
1926
+ try {
1927
+ const parsed = parse_template(template);
1928
+ this.templates.push(parsed);
1929
+ } catch (error) {
1930
+ throw new Error(
1931
+ `Invalid template: ${template} - ${error instanceof Error ? error.message : String(error)}`
1932
+ );
1933
+ }
1934
+ }
1935
+ /**
1936
+ * Match a URI against all registered templates
1937
+ * @param {string} uri - The URI to match
1938
+ * @returns {MatchResult | null} Match result or null if no match found
1939
+ * @throws {Error} If URI is invalid
1940
+ */
1941
+ match(uri) {
1942
+ if (typeof uri !== "string") {
1943
+ throw new Error("URI must be a string");
1944
+ }
1945
+ for (const template of this.templates) {
1946
+ const params = match_uri(uri, template);
1947
+ if (params !== null) {
1948
+ return {
1949
+ template: template.template,
1950
+ params
1951
+ };
1952
+ }
1953
+ }
1954
+ return null;
1955
+ }
1956
+ /**
1957
+ * Clear all registered templates
1958
+ */
1959
+ clear() {
1960
+ this.templates = [];
1961
+ }
1962
+ /**
1963
+ * Get all registered template strings
1964
+ * @returns {string[]} Array of template strings
1965
+ */
1966
+ all() {
1967
+ return this.templates.map((t) => t.template);
1968
+ }
1969
+ };
1970
+
1971
+ // ../../node_modules/.pnpm/valibot@1.4.1_typescript@5.9.3/node_modules/valibot/dist/index.mjs
1972
+ var store$4;
1973
+ var DEFAULT_CONFIG = {
1974
+ lang: void 0,
1975
+ message: void 0,
1976
+ abortEarly: void 0,
1977
+ abortPipeEarly: void 0
1978
+ };
1979
+ // @__NO_SIDE_EFFECTS__
1980
+ function getGlobalConfig(config$1) {
1981
+ if (!config$1 && !store$4) return DEFAULT_CONFIG;
1982
+ return {
1983
+ lang: config$1?.lang ?? store$4?.lang,
1984
+ message: config$1?.message,
1985
+ abortEarly: config$1?.abortEarly ?? store$4?.abortEarly,
1986
+ abortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly
1987
+ };
1988
+ }
1989
+ var store$3;
1990
+ // @__NO_SIDE_EFFECTS__
1991
+ function getGlobalMessage(lang) {
1992
+ return store$3?.get(lang);
1993
+ }
1994
+ var store$2;
1995
+ // @__NO_SIDE_EFFECTS__
1996
+ function getSchemaMessage(lang) {
1997
+ return store$2?.get(lang);
1998
+ }
1999
+ var store$1;
2000
+ // @__NO_SIDE_EFFECTS__
2001
+ function getSpecificMessage(reference, lang) {
2002
+ return store$1?.get(reference)?.get(lang);
2003
+ }
2004
+ // @__NO_SIDE_EFFECTS__
2005
+ function _stringify(input) {
2006
+ const type = typeof input;
2007
+ if (type === "string") return `"${input}"`;
2008
+ if (type === "number" || type === "bigint" || type === "boolean") return `${input}`;
2009
+ if (type === "object" || type === "function") return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
2010
+ return type;
2011
+ }
2012
+ function _addIssue(context, label, dataset, config$1, other) {
2013
+ const input = other && "input" in other ? other.input : dataset.value;
2014
+ const expected = other?.expected ?? context.expects ?? null;
2015
+ const received = other?.received ?? /* @__PURE__ */ _stringify(input);
2016
+ const issue = {
2017
+ kind: context.kind,
2018
+ type: context.type,
2019
+ input,
2020
+ expected,
2021
+ received,
571
2022
  message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
572
2023
  requirement: context.requirement,
573
2024
  path: other?.path,
@@ -600,13 +2051,62 @@ function _getStandardProps(context) {
600
2051
  return cached;
601
2052
  }
602
2053
  // @__NO_SIDE_EFFECTS__
2054
+ function _isValidObjectKey(object$1, key) {
2055
+ return Object.prototype.hasOwnProperty.call(object$1, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor";
2056
+ }
2057
+ // @__NO_SIDE_EFFECTS__
603
2058
  function _joinExpects(values$1, separator) {
604
2059
  const list = [...new Set(values$1)];
605
2060
  if (list.length > 1) return `(${list.join(` ${separator} `)})`;
606
2061
  return list[0] ?? "never";
607
2062
  }
2063
+ var ValiError = class extends Error {
2064
+ /**
2065
+ * Creates a Valibot error with useful information.
2066
+ *
2067
+ * @param issues The error issues.
2068
+ */
2069
+ constructor(issues) {
2070
+ super(issues[0].message);
2071
+ this.name = "ValiError";
2072
+ this.issues = issues;
2073
+ }
2074
+ };
2075
+ var BASE64_REGEX = /^(?:[\da-z+/]{4})*(?:[\da-z+/]{2}==|[\da-z+/]{3}=)?$/iu;
608
2076
  var EMOJI_REGEX = new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$", "u");
609
2077
  // @__NO_SIDE_EFFECTS__
2078
+ function base64(message$1) {
2079
+ return {
2080
+ kind: "validation",
2081
+ type: "base64",
2082
+ reference: base64,
2083
+ async: false,
2084
+ expects: null,
2085
+ requirement: BASE64_REGEX,
2086
+ message: message$1,
2087
+ "~run"(dataset, config$1) {
2088
+ if (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, "Base64", dataset, config$1);
2089
+ return dataset;
2090
+ }
2091
+ };
2092
+ }
2093
+ // @__NO_SIDE_EFFECTS__
2094
+ function check(requirement, message$1) {
2095
+ return {
2096
+ kind: "validation",
2097
+ type: "check",
2098
+ reference: check,
2099
+ async: false,
2100
+ expects: null,
2101
+ requirement,
2102
+ message: message$1,
2103
+ "~run"(dataset, config$1) {
2104
+ if (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, "input", dataset, config$1);
2105
+ return dataset;
2106
+ }
2107
+ };
2108
+ }
2109
+ // @__NO_SIDE_EFFECTS__
610
2110
  function description(description_) {
611
2111
  return {
612
2112
  kind: "metadata",
@@ -632,6 +2132,22 @@ function integer(message$1) {
632
2132
  };
633
2133
  }
634
2134
  // @__NO_SIDE_EFFECTS__
2135
+ function maxLength(requirement, message$1) {
2136
+ return {
2137
+ kind: "validation",
2138
+ type: "max_length",
2139
+ reference: maxLength,
2140
+ async: false,
2141
+ expects: `<=${requirement}`,
2142
+ requirement,
2143
+ message: message$1,
2144
+ "~run"(dataset, config$1) {
2145
+ if (dataset.typed && dataset.value.length > this.requirement) _addIssue(this, "length", dataset, config$1, { received: `${dataset.value.length}` });
2146
+ return dataset;
2147
+ }
2148
+ };
2149
+ }
2150
+ // @__NO_SIDE_EFFECTS__
635
2151
  function maxValue(requirement, message$1) {
636
2152
  return {
637
2153
  kind: "validation",
@@ -680,6 +2196,39 @@ function minValue(requirement, message$1) {
680
2196
  };
681
2197
  }
682
2198
  // @__NO_SIDE_EFFECTS__
2199
+ function regex(requirement, message$1) {
2200
+ return {
2201
+ kind: "validation",
2202
+ type: "regex",
2203
+ reference: regex,
2204
+ async: false,
2205
+ expects: `${requirement}`,
2206
+ requirement,
2207
+ message: message$1,
2208
+ "~run"(dataset, config$1) {
2209
+ if (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, "format", dataset, config$1);
2210
+ return dataset;
2211
+ }
2212
+ };
2213
+ }
2214
+ // @__NO_SIDE_EFFECTS__
2215
+ function startsWith(requirement, message$1) {
2216
+ return {
2217
+ kind: "validation",
2218
+ type: "starts_with",
2219
+ reference: startsWith,
2220
+ async: false,
2221
+ expects: `"${requirement}"`,
2222
+ requirement,
2223
+ message: message$1,
2224
+ "~run"(dataset, config$1) {
2225
+ if (dataset.typed && !dataset.value.startsWith(this.requirement)) _addIssue(this, "start", dataset, config$1, { received: `"${dataset.value.slice(0, this.requirement.length)}"` });
2226
+ return dataset;
2227
+ }
2228
+ };
2229
+ }
2230
+ var ABORT_EARLY_CONFIG = { abortEarly: true };
2231
+ // @__NO_SIDE_EFFECTS__
683
2232
  function getFallback(schema6, dataset, config$1) {
684
2233
  return typeof schema6.fallback === "function" ? schema6.fallback(dataset, config$1) : schema6.fallback;
685
2234
  }
@@ -688,30 +2237,98 @@ function getDefault(schema6, dataset, config$1) {
688
2237
  return typeof schema6.default === "function" ? schema6.default(dataset, config$1) : schema6.default;
689
2238
  }
690
2239
  // @__NO_SIDE_EFFECTS__
691
- function number(message$1) {
2240
+ function array(item, message$1) {
692
2241
  return {
693
2242
  kind: "schema",
694
- type: "number",
695
- reference: number,
696
- expects: "number",
2243
+ type: "array",
2244
+ reference: array,
2245
+ expects: "Array",
697
2246
  async: false,
2247
+ item,
698
2248
  message: message$1,
699
2249
  get "~standard"() {
700
2250
  return /* @__PURE__ */ _getStandardProps(this);
701
2251
  },
702
2252
  "~run"(dataset, config$1) {
703
- if (typeof dataset.value === "number" && !isNaN(dataset.value)) dataset.typed = true;
2253
+ const input = dataset.value;
2254
+ if (Array.isArray(input)) {
2255
+ dataset.typed = true;
2256
+ dataset.value = [];
2257
+ for (let key = 0; key < input.length; key++) {
2258
+ const value$1 = input[key];
2259
+ const itemDataset = this.item["~run"]({ value: value$1 }, config$1);
2260
+ if (itemDataset.issues) {
2261
+ const pathItem = {
2262
+ type: "array",
2263
+ origin: "value",
2264
+ input,
2265
+ key,
2266
+ value: value$1
2267
+ };
2268
+ for (const issue of itemDataset.issues) {
2269
+ if (issue.path) issue.path.unshift(pathItem);
2270
+ else issue.path = [pathItem];
2271
+ dataset.issues?.push(issue);
2272
+ }
2273
+ if (!dataset.issues) dataset.issues = itemDataset.issues;
2274
+ if (config$1.abortEarly) {
2275
+ dataset.typed = false;
2276
+ break;
2277
+ }
2278
+ }
2279
+ if (!itemDataset.typed) dataset.typed = false;
2280
+ dataset.value.push(itemDataset.value);
2281
+ }
2282
+ } else _addIssue(this, "type", dataset, config$1);
2283
+ return dataset;
2284
+ }
2285
+ };
2286
+ }
2287
+ // @__NO_SIDE_EFFECTS__
2288
+ function boolean(message$1) {
2289
+ return {
2290
+ kind: "schema",
2291
+ type: "boolean",
2292
+ reference: boolean,
2293
+ expects: "boolean",
2294
+ async: false,
2295
+ message: message$1,
2296
+ get "~standard"() {
2297
+ return /* @__PURE__ */ _getStandardProps(this);
2298
+ },
2299
+ "~run"(dataset, config$1) {
2300
+ if (typeof dataset.value === "boolean") dataset.typed = true;
704
2301
  else _addIssue(this, "type", dataset, config$1);
705
2302
  return dataset;
706
2303
  }
707
2304
  };
708
2305
  }
709
2306
  // @__NO_SIDE_EFFECTS__
710
- function object(entries$1, message$1) {
2307
+ function literal(literal_, message$1) {
711
2308
  return {
712
2309
  kind: "schema",
713
- type: "object",
714
- reference: object,
2310
+ type: "literal",
2311
+ reference: literal,
2312
+ expects: /* @__PURE__ */ _stringify(literal_),
2313
+ async: false,
2314
+ literal: literal_,
2315
+ message: message$1,
2316
+ get "~standard"() {
2317
+ return /* @__PURE__ */ _getStandardProps(this);
2318
+ },
2319
+ "~run"(dataset, config$1) {
2320
+ if (dataset.value === this.literal) dataset.typed = true;
2321
+ else _addIssue(this, "type", dataset, config$1);
2322
+ return dataset;
2323
+ }
2324
+ };
2325
+ }
2326
+ // @__NO_SIDE_EFFECTS__
2327
+ function looseObject(entries$1, message$1) {
2328
+ return {
2329
+ kind: "schema",
2330
+ type: "loose_object",
2331
+ reference: looseObject,
715
2332
  expects: "Object",
716
2333
  async: false,
717
2334
  entries: entries$1,
@@ -766,98 +2383,2745 @@ function object(entries$1, message$1) {
766
2383
  if (config$1.abortEarly) break;
767
2384
  }
768
2385
  }
2386
+ if (!dataset.issues || !config$1.abortEarly) {
2387
+ for (const key in input) if (/* @__PURE__ */ _isValidObjectKey(input, key) && !(key in this.entries)) dataset.value[key] = input[key];
2388
+ }
769
2389
  } else _addIssue(this, "type", dataset, config$1);
770
2390
  return dataset;
771
2391
  }
772
- };
773
- }
774
- // @__NO_SIDE_EFFECTS__
775
- function optional(wrapped, default_) {
776
- return {
777
- kind: "schema",
778
- type: "optional",
779
- reference: optional,
780
- expects: `(${wrapped.expects} | undefined)`,
781
- async: false,
782
- wrapped,
783
- default: default_,
784
- get "~standard"() {
785
- return /* @__PURE__ */ _getStandardProps(this);
786
- },
787
- "~run"(dataset, config$1) {
788
- if (dataset.value === void 0) {
789
- if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
790
- if (dataset.value === void 0) {
791
- dataset.typed = true;
792
- return dataset;
793
- }
794
- }
795
- return this.wrapped["~run"](dataset, config$1);
2392
+ };
2393
+ }
2394
+ // @__NO_SIDE_EFFECTS__
2395
+ function number(message$1) {
2396
+ return {
2397
+ kind: "schema",
2398
+ type: "number",
2399
+ reference: number,
2400
+ expects: "number",
2401
+ async: false,
2402
+ message: message$1,
2403
+ get "~standard"() {
2404
+ return /* @__PURE__ */ _getStandardProps(this);
2405
+ },
2406
+ "~run"(dataset, config$1) {
2407
+ if (typeof dataset.value === "number" && !isNaN(dataset.value)) dataset.typed = true;
2408
+ else _addIssue(this, "type", dataset, config$1);
2409
+ return dataset;
2410
+ }
2411
+ };
2412
+ }
2413
+ // @__NO_SIDE_EFFECTS__
2414
+ function object(entries$1, message$1) {
2415
+ return {
2416
+ kind: "schema",
2417
+ type: "object",
2418
+ reference: object,
2419
+ expects: "Object",
2420
+ async: false,
2421
+ entries: entries$1,
2422
+ message: message$1,
2423
+ get "~standard"() {
2424
+ return /* @__PURE__ */ _getStandardProps(this);
2425
+ },
2426
+ "~run"(dataset, config$1) {
2427
+ const input = dataset.value;
2428
+ if (input && typeof input === "object") {
2429
+ dataset.typed = true;
2430
+ dataset.value = {};
2431
+ for (const key in this.entries) {
2432
+ const valueSchema = this.entries[key];
2433
+ if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
2434
+ const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
2435
+ const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
2436
+ if (valueDataset.issues) {
2437
+ const pathItem = {
2438
+ type: "object",
2439
+ origin: "value",
2440
+ input,
2441
+ key,
2442
+ value: value$1
2443
+ };
2444
+ for (const issue of valueDataset.issues) {
2445
+ if (issue.path) issue.path.unshift(pathItem);
2446
+ else issue.path = [pathItem];
2447
+ dataset.issues?.push(issue);
2448
+ }
2449
+ if (!dataset.issues) dataset.issues = valueDataset.issues;
2450
+ if (config$1.abortEarly) {
2451
+ dataset.typed = false;
2452
+ break;
2453
+ }
2454
+ }
2455
+ if (!valueDataset.typed) dataset.typed = false;
2456
+ dataset.value[key] = valueDataset.value;
2457
+ } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
2458
+ else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
2459
+ _addIssue(this, "key", dataset, config$1, {
2460
+ input: void 0,
2461
+ expected: `"${key}"`,
2462
+ path: [{
2463
+ type: "object",
2464
+ origin: "key",
2465
+ input,
2466
+ key,
2467
+ value: input[key]
2468
+ }]
2469
+ });
2470
+ if (config$1.abortEarly) break;
2471
+ }
2472
+ }
2473
+ } else _addIssue(this, "type", dataset, config$1);
2474
+ return dataset;
2475
+ }
2476
+ };
2477
+ }
2478
+ // @__NO_SIDE_EFFECTS__
2479
+ function optional(wrapped, default_) {
2480
+ return {
2481
+ kind: "schema",
2482
+ type: "optional",
2483
+ reference: optional,
2484
+ expects: `(${wrapped.expects} | undefined)`,
2485
+ async: false,
2486
+ wrapped,
2487
+ default: default_,
2488
+ get "~standard"() {
2489
+ return /* @__PURE__ */ _getStandardProps(this);
2490
+ },
2491
+ "~run"(dataset, config$1) {
2492
+ if (dataset.value === void 0) {
2493
+ if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
2494
+ if (dataset.value === void 0) {
2495
+ dataset.typed = true;
2496
+ return dataset;
2497
+ }
2498
+ }
2499
+ return this.wrapped["~run"](dataset, config$1);
2500
+ }
2501
+ };
2502
+ }
2503
+ // @__NO_SIDE_EFFECTS__
2504
+ function picklist(options, message$1) {
2505
+ return {
2506
+ kind: "schema",
2507
+ type: "picklist",
2508
+ reference: picklist,
2509
+ expects: /* @__PURE__ */ _joinExpects(options.map(_stringify), "|"),
2510
+ async: false,
2511
+ options,
2512
+ message: message$1,
2513
+ get "~standard"() {
2514
+ return /* @__PURE__ */ _getStandardProps(this);
2515
+ },
2516
+ "~run"(dataset, config$1) {
2517
+ if (this.options.includes(dataset.value)) dataset.typed = true;
2518
+ else _addIssue(this, "type", dataset, config$1);
2519
+ return dataset;
2520
+ }
2521
+ };
2522
+ }
2523
+ // @__NO_SIDE_EFFECTS__
2524
+ function record(key, value$1, message$1) {
2525
+ return {
2526
+ kind: "schema",
2527
+ type: "record",
2528
+ reference: record,
2529
+ expects: "Object",
2530
+ async: false,
2531
+ key,
2532
+ value: value$1,
2533
+ message: message$1,
2534
+ get "~standard"() {
2535
+ return /* @__PURE__ */ _getStandardProps(this);
2536
+ },
2537
+ "~run"(dataset, config$1) {
2538
+ const input = dataset.value;
2539
+ if (input && typeof input === "object") {
2540
+ dataset.typed = true;
2541
+ dataset.value = {};
2542
+ for (const entryKey in input) if (/* @__PURE__ */ _isValidObjectKey(input, entryKey)) {
2543
+ const entryValue = input[entryKey];
2544
+ const keyDataset = this.key["~run"]({ value: entryKey }, config$1);
2545
+ if (keyDataset.issues) {
2546
+ const pathItem = {
2547
+ type: "object",
2548
+ origin: "key",
2549
+ input,
2550
+ key: entryKey,
2551
+ value: entryValue
2552
+ };
2553
+ for (const issue of keyDataset.issues) {
2554
+ issue.path = [pathItem];
2555
+ dataset.issues?.push(issue);
2556
+ }
2557
+ if (!dataset.issues) dataset.issues = keyDataset.issues;
2558
+ if (config$1.abortEarly) {
2559
+ dataset.typed = false;
2560
+ break;
2561
+ }
2562
+ }
2563
+ const valueDataset = this.value["~run"]({ value: entryValue }, config$1);
2564
+ if (valueDataset.issues) {
2565
+ const pathItem = {
2566
+ type: "object",
2567
+ origin: "value",
2568
+ input,
2569
+ key: entryKey,
2570
+ value: entryValue
2571
+ };
2572
+ for (const issue of valueDataset.issues) {
2573
+ if (issue.path) issue.path.unshift(pathItem);
2574
+ else issue.path = [pathItem];
2575
+ dataset.issues?.push(issue);
2576
+ }
2577
+ if (!dataset.issues) dataset.issues = valueDataset.issues;
2578
+ if (config$1.abortEarly) {
2579
+ dataset.typed = false;
2580
+ break;
2581
+ }
2582
+ }
2583
+ if (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;
2584
+ if (keyDataset.typed) dataset.value[keyDataset.value] = valueDataset.value;
2585
+ }
2586
+ } else _addIssue(this, "type", dataset, config$1);
2587
+ return dataset;
2588
+ }
2589
+ };
2590
+ }
2591
+ // @__NO_SIDE_EFFECTS__
2592
+ function strictObject(entries$1, message$1) {
2593
+ return {
2594
+ kind: "schema",
2595
+ type: "strict_object",
2596
+ reference: strictObject,
2597
+ expects: "Object",
2598
+ async: false,
2599
+ entries: entries$1,
2600
+ message: message$1,
2601
+ get "~standard"() {
2602
+ return /* @__PURE__ */ _getStandardProps(this);
2603
+ },
2604
+ "~run"(dataset, config$1) {
2605
+ const input = dataset.value;
2606
+ if (input && typeof input === "object") {
2607
+ dataset.typed = true;
2608
+ dataset.value = {};
2609
+ for (const key in this.entries) {
2610
+ const valueSchema = this.entries[key];
2611
+ if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
2612
+ const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
2613
+ const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
2614
+ if (valueDataset.issues) {
2615
+ const pathItem = {
2616
+ type: "object",
2617
+ origin: "value",
2618
+ input,
2619
+ key,
2620
+ value: value$1
2621
+ };
2622
+ for (const issue of valueDataset.issues) {
2623
+ if (issue.path) issue.path.unshift(pathItem);
2624
+ else issue.path = [pathItem];
2625
+ dataset.issues?.push(issue);
2626
+ }
2627
+ if (!dataset.issues) dataset.issues = valueDataset.issues;
2628
+ if (config$1.abortEarly) {
2629
+ dataset.typed = false;
2630
+ break;
2631
+ }
2632
+ }
2633
+ if (!valueDataset.typed) dataset.typed = false;
2634
+ dataset.value[key] = valueDataset.value;
2635
+ } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
2636
+ else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
2637
+ _addIssue(this, "key", dataset, config$1, {
2638
+ input: void 0,
2639
+ expected: `"${key}"`,
2640
+ path: [{
2641
+ type: "object",
2642
+ origin: "key",
2643
+ input,
2644
+ key,
2645
+ value: input[key]
2646
+ }]
2647
+ });
2648
+ if (config$1.abortEarly) break;
2649
+ }
2650
+ }
2651
+ if (!dataset.issues || !config$1.abortEarly) {
2652
+ for (const key in input) if (!(key in this.entries)) {
2653
+ _addIssue(this, "key", dataset, config$1, {
2654
+ input: key,
2655
+ expected: "never",
2656
+ path: [{
2657
+ type: "object",
2658
+ origin: "key",
2659
+ input,
2660
+ key,
2661
+ value: input[key]
2662
+ }]
2663
+ });
2664
+ break;
2665
+ }
2666
+ }
2667
+ } else _addIssue(this, "type", dataset, config$1);
2668
+ return dataset;
2669
+ }
2670
+ };
2671
+ }
2672
+ // @__NO_SIDE_EFFECTS__
2673
+ function string(message$1) {
2674
+ return {
2675
+ kind: "schema",
2676
+ type: "string",
2677
+ reference: string,
2678
+ expects: "string",
2679
+ async: false,
2680
+ message: message$1,
2681
+ get "~standard"() {
2682
+ return /* @__PURE__ */ _getStandardProps(this);
2683
+ },
2684
+ "~run"(dataset, config$1) {
2685
+ if (typeof dataset.value === "string") dataset.typed = true;
2686
+ else _addIssue(this, "type", dataset, config$1);
2687
+ return dataset;
2688
+ }
2689
+ };
2690
+ }
2691
+ // @__NO_SIDE_EFFECTS__
2692
+ function _subIssues(datasets) {
2693
+ let issues;
2694
+ if (datasets) for (const dataset of datasets) if (issues) for (const issue of dataset.issues) issues.push(issue);
2695
+ else issues = dataset.issues;
2696
+ return issues;
2697
+ }
2698
+ // @__NO_SIDE_EFFECTS__
2699
+ function union(options, message$1) {
2700
+ return {
2701
+ kind: "schema",
2702
+ type: "union",
2703
+ reference: union,
2704
+ expects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), "|"),
2705
+ async: false,
2706
+ options,
2707
+ message: message$1,
2708
+ get "~standard"() {
2709
+ return /* @__PURE__ */ _getStandardProps(this);
2710
+ },
2711
+ "~run"(dataset, config$1) {
2712
+ let validDataset;
2713
+ let typedDatasets;
2714
+ let untypedDatasets;
2715
+ for (const schema6 of this.options) {
2716
+ const optionDataset = schema6["~run"]({ value: dataset.value }, config$1);
2717
+ if (optionDataset.typed) if (optionDataset.issues) if (typedDatasets) typedDatasets.push(optionDataset);
2718
+ else typedDatasets = [optionDataset];
2719
+ else {
2720
+ validDataset = optionDataset;
2721
+ break;
2722
+ }
2723
+ else if (untypedDatasets) untypedDatasets.push(optionDataset);
2724
+ else untypedDatasets = [optionDataset];
2725
+ }
2726
+ if (validDataset) return validDataset;
2727
+ if (typedDatasets) {
2728
+ if (typedDatasets.length === 1) return typedDatasets[0];
2729
+ _addIssue(this, "type", dataset, config$1, { issues: /* @__PURE__ */ _subIssues(typedDatasets) });
2730
+ dataset.typed = true;
2731
+ } else if (untypedDatasets?.length === 1) return untypedDatasets[0];
2732
+ else _addIssue(this, "type", dataset, config$1, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) });
2733
+ return dataset;
2734
+ }
2735
+ };
2736
+ }
2737
+ // @__NO_SIDE_EFFECTS__
2738
+ function unknown() {
2739
+ return {
2740
+ kind: "schema",
2741
+ type: "unknown",
2742
+ reference: unknown,
2743
+ expects: "unknown",
2744
+ async: false,
2745
+ get "~standard"() {
2746
+ return /* @__PURE__ */ _getStandardProps(this);
2747
+ },
2748
+ "~run"(dataset) {
2749
+ dataset.typed = true;
2750
+ return dataset;
2751
+ }
2752
+ };
2753
+ }
2754
+ // @__NO_SIDE_EFFECTS__
2755
+ function variant(key, options, message$1) {
2756
+ return {
2757
+ kind: "schema",
2758
+ type: "variant",
2759
+ reference: variant,
2760
+ expects: "Object",
2761
+ async: false,
2762
+ key,
2763
+ options,
2764
+ message: message$1,
2765
+ get "~standard"() {
2766
+ return /* @__PURE__ */ _getStandardProps(this);
2767
+ },
2768
+ "~run"(dataset, config$1) {
2769
+ const input = dataset.value;
2770
+ if (input && typeof input === "object") {
2771
+ let outputDataset;
2772
+ let maxDiscriminatorPriority = 0;
2773
+ let invalidDiscriminatorKey = this.key;
2774
+ let expectedDiscriminators = [];
2775
+ const parseOptions = (variant$1, allKeys) => {
2776
+ for (const schema6 of variant$1.options) {
2777
+ if (schema6.type === "variant") parseOptions(schema6, new Set(allKeys).add(schema6.key));
2778
+ else {
2779
+ let keysAreValid = true;
2780
+ let currentPriority = 0;
2781
+ for (const currentKey of allKeys) {
2782
+ const discriminatorSchema = schema6.entries[currentKey];
2783
+ if (currentKey in input ? discriminatorSchema["~run"]({
2784
+ typed: false,
2785
+ value: input[currentKey]
2786
+ }, ABORT_EARLY_CONFIG).issues : discriminatorSchema.type !== "exact_optional" && discriminatorSchema.type !== "optional" && discriminatorSchema.type !== "nullish") {
2787
+ keysAreValid = false;
2788
+ if (invalidDiscriminatorKey !== currentKey && (maxDiscriminatorPriority < currentPriority || maxDiscriminatorPriority === currentPriority && currentKey in input && !(invalidDiscriminatorKey in input))) {
2789
+ maxDiscriminatorPriority = currentPriority;
2790
+ invalidDiscriminatorKey = currentKey;
2791
+ expectedDiscriminators = [];
2792
+ }
2793
+ if (invalidDiscriminatorKey === currentKey) expectedDiscriminators.push(schema6.entries[currentKey].expects);
2794
+ break;
2795
+ }
2796
+ currentPriority++;
2797
+ }
2798
+ if (keysAreValid) {
2799
+ const optionDataset = schema6["~run"]({ value: input }, config$1);
2800
+ if (!outputDataset || !outputDataset.typed && optionDataset.typed) outputDataset = optionDataset;
2801
+ }
2802
+ }
2803
+ if (outputDataset && !outputDataset.issues) break;
2804
+ }
2805
+ };
2806
+ parseOptions(this, /* @__PURE__ */ new Set([this.key]));
2807
+ if (outputDataset) return outputDataset;
2808
+ _addIssue(this, "type", dataset, config$1, {
2809
+ input: input[invalidDiscriminatorKey],
2810
+ expected: /* @__PURE__ */ _joinExpects(expectedDiscriminators, "|"),
2811
+ path: [{
2812
+ type: "object",
2813
+ origin: "value",
2814
+ input,
2815
+ key: invalidDiscriminatorKey,
2816
+ value: input[invalidDiscriminatorKey]
2817
+ }]
2818
+ });
2819
+ } else _addIssue(this, "type", dataset, config$1);
2820
+ return dataset;
2821
+ }
2822
+ };
2823
+ }
2824
+ function parse(schema6, input, config$1) {
2825
+ const dataset = schema6["~run"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config$1));
2826
+ if (dataset.issues) throw new ValiError(dataset.issues);
2827
+ return dataset.value;
2828
+ }
2829
+ // @__NO_SIDE_EFFECTS__
2830
+ function pipe(...pipe$1) {
2831
+ return {
2832
+ ...pipe$1[0],
2833
+ pipe: pipe$1,
2834
+ get "~standard"() {
2835
+ return /* @__PURE__ */ _getStandardProps(this);
2836
+ },
2837
+ "~run"(dataset, config$1) {
2838
+ for (const item of pipe$1) if (item.kind !== "metadata") {
2839
+ if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
2840
+ dataset.typed = false;
2841
+ break;
2842
+ }
2843
+ if (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly) dataset = item["~run"](dataset, config$1);
2844
+ }
2845
+ return dataset;
2846
+ }
2847
+ };
2848
+ }
2849
+ // @__NO_SIDE_EFFECTS__
2850
+ function safeParse(schema6, input, config$1) {
2851
+ const dataset = schema6["~run"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config$1));
2852
+ return {
2853
+ typed: dataset.typed,
2854
+ success: !dataset.issues,
2855
+ output: dataset.value,
2856
+ issues: dataset.issues
2857
+ };
2858
+ }
2859
+
2860
+ // ../../node_modules/.pnpm/tmcp@1.19.4_typescript@5.9.3/node_modules/tmcp/src/validation/index.js
2861
+ var JSONRPC_VERSION = "2.0";
2862
+ var McpError = class extends Error {
2863
+ /**
2864
+ * @param {number} code
2865
+ * @param {string} message
2866
+ */
2867
+ constructor(code, message) {
2868
+ super(`MCP error ${code}: ${message}`);
2869
+ this.name = "McpError";
2870
+ }
2871
+ };
2872
+ var ProgressTokenSchema = union([
2873
+ string(),
2874
+ pipe(number(), integer())
2875
+ ]);
2876
+ var CursorSchema = string();
2877
+ var RequestMetaSchema = looseObject({
2878
+ /**
2879
+ * 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.
2880
+ */
2881
+ progressToken: optional(ProgressTokenSchema)
2882
+ });
2883
+ var BaseRequestParamsSchema = looseObject({
2884
+ _meta: optional(RequestMetaSchema)
2885
+ });
2886
+ var RequestSchema = object({
2887
+ method: string(),
2888
+ params: optional(BaseRequestParamsSchema)
2889
+ });
2890
+ var BaseNotificationParamsSchema = looseObject({
2891
+ /**
2892
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
2893
+ * for notes on _meta usage.
2894
+ */
2895
+ _meta: optional(looseObject({}))
2896
+ });
2897
+ var NotificationSchema = object({
2898
+ method: string(),
2899
+ params: optional(BaseNotificationParamsSchema)
2900
+ });
2901
+ var ResultSchema = looseObject({
2902
+ /**
2903
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
2904
+ * for notes on _meta usage.
2905
+ */
2906
+ _meta: optional(looseObject({}))
2907
+ });
2908
+ var RequestIdSchema = union([
2909
+ string(),
2910
+ pipe(number(), integer())
2911
+ ]);
2912
+ var JSONRPCRequestSchema = object({
2913
+ jsonrpc: literal(JSONRPC_VERSION),
2914
+ id: RequestIdSchema,
2915
+ ...RequestSchema.entries
2916
+ });
2917
+ var JSONRPCNotificationSchema = object({
2918
+ jsonrpc: literal(JSONRPC_VERSION),
2919
+ ...NotificationSchema.entries
2920
+ });
2921
+ var JSONRPCResponseSchema = strictObject({
2922
+ jsonrpc: literal(JSONRPC_VERSION),
2923
+ id: RequestIdSchema,
2924
+ result: ResultSchema
2925
+ });
2926
+ var JSONRPCErrorSchema = strictObject({
2927
+ jsonrpc: literal(JSONRPC_VERSION),
2928
+ id: RequestIdSchema,
2929
+ error: object({
2930
+ /**
2931
+ * The error type that occurred.
2932
+ */
2933
+ code: pipe(number(), integer()),
2934
+ /**
2935
+ * A short description of the error. The message SHOULD be limited to a concise single sentence.
2936
+ */
2937
+ message: string(),
2938
+ /**
2939
+ * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
2940
+ */
2941
+ data: optional(unknown())
2942
+ })
2943
+ });
2944
+ var JSONRPCMessageSchema = union([
2945
+ JSONRPCRequestSchema,
2946
+ JSONRPCNotificationSchema,
2947
+ JSONRPCResponseSchema,
2948
+ JSONRPCErrorSchema
2949
+ ]);
2950
+ var EmptyResultSchema = strictObject({ ...ResultSchema.entries });
2951
+ var CancelledNotificationSchema = object({
2952
+ ...NotificationSchema.entries,
2953
+ method: literal("notifications/cancelled"),
2954
+ params: object({
2955
+ ...BaseNotificationParamsSchema.entries,
2956
+ /**
2957
+ * The ID of the request to cancel.
2958
+ *
2959
+ * This MUST correspond to the ID of a request previously issued in the same direction.
2960
+ */
2961
+ requestId: RequestIdSchema,
2962
+ /**
2963
+ * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
2964
+ */
2965
+ reason: optional(string())
2966
+ })
2967
+ });
2968
+ var BaseMetadataSchema = object({
2969
+ /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
2970
+ name: string(),
2971
+ /**
2972
+ * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
2973
+ * even by those unfamiliar with domain-specific terminology.
2974
+ *
2975
+ * If not provided, the name should be used for display (except for Tool,
2976
+ * where `annotations.title` should be given precedence over using `name`,
2977
+ * if present).
2978
+ */
2979
+ title: optional(string())
2980
+ });
2981
+ var IconSchema = object({
2982
+ /**
2983
+ * URL or data URI for the icon.
2984
+ */
2985
+ src: string(),
2986
+ /**
2987
+ * Optional MIME type for the icon.
2988
+ */
2989
+ mimeType: optional(string()),
2990
+ /**
2991
+ * Optional array of strings that specify sizes at which the icon can be used.
2992
+ * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
2993
+ *
2994
+ * If not provided, the client should assume that the icon can be used at any size.
2995
+ */
2996
+ sizes: optional(array(string()))
2997
+ });
2998
+ var IconsSchema = object({
2999
+ /**
3000
+ * Optional set of sized icons that the client can display in a user interface.
3001
+ *
3002
+ * Clients that support rendering icons MUST support at least the following MIME types:
3003
+ * - `image/png` - PNG images (safe, universal compatibility)
3004
+ * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
3005
+ *
3006
+ * Clients that support rendering icons SHOULD also support:
3007
+ * - `image/svg+xml` - SVG images (scalable but requires security precautions)
3008
+ * - `image/webp` - WebP images (modern, efficient format)
3009
+ */
3010
+ icons: optional(array(IconSchema))
3011
+ });
3012
+ var ImplementationSchema = object({
3013
+ ...BaseMetadataSchema.entries,
3014
+ version: string(),
3015
+ websiteUrl: optional(string()),
3016
+ ...IconsSchema.entries
3017
+ });
3018
+ var ClientCapabilitiesSchema = looseObject({
3019
+ /**
3020
+ * Experimental, non-standard capabilities that the client supports.
3021
+ */
3022
+ experimental: optional(object({})),
3023
+ /**
3024
+ * Present if the client supports sampling from an LLM.
3025
+ */
3026
+ sampling: optional(object({})),
3027
+ /**
3028
+ * Present if the client supports eliciting user input.
3029
+ */
3030
+ elicitation: optional(object({})),
3031
+ /**
3032
+ * Present if the client supports listing roots.
3033
+ */
3034
+ roots: optional(
3035
+ object({
3036
+ /**
3037
+ * Whether the client supports issuing notifications for changes to the roots list.
3038
+ */
3039
+ listChanged: optional(boolean())
3040
+ })
3041
+ )
3042
+ });
3043
+ var InitializeRequestParamsSchema = object({
3044
+ ...BaseRequestParamsSchema.entries,
3045
+ /**
3046
+ * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
3047
+ */
3048
+ protocolVersion: string(),
3049
+ capabilities: ClientCapabilitiesSchema,
3050
+ clientInfo: ImplementationSchema
3051
+ });
3052
+ var InitializeRequestSchema = object({
3053
+ ...RequestSchema.entries,
3054
+ method: literal("initialize"),
3055
+ params: InitializeRequestParamsSchema
3056
+ });
3057
+ var ServerCapabilitiesSchema = object({
3058
+ /**
3059
+ * Experimental, non-standard capabilities that the server supports.
3060
+ */
3061
+ experimental: optional(object({})),
3062
+ /**
3063
+ * Present if the server supports sending log messages to the client.
3064
+ */
3065
+ logging: optional(object({})),
3066
+ /**
3067
+ * Present if the server supports sending completions to the client.
3068
+ */
3069
+ completions: optional(object({})),
3070
+ /**
3071
+ * Present if the server offers any prompt templates.
3072
+ */
3073
+ prompts: optional(
3074
+ object({
3075
+ /**
3076
+ * Whether this server supports issuing notifications for changes to the prompt list.
3077
+ */
3078
+ listChanged: optional(boolean())
3079
+ })
3080
+ ),
3081
+ /**
3082
+ * Present if the server offers any resources to read.
3083
+ */
3084
+ resources: optional(
3085
+ object({
3086
+ /**
3087
+ * Whether this server supports clients subscribing to resource updates.
3088
+ */
3089
+ subscribe: optional(boolean()),
3090
+ /**
3091
+ * Whether this server supports issuing notifications for changes to the resource list.
3092
+ */
3093
+ listChanged: optional(boolean())
3094
+ })
3095
+ ),
3096
+ /**
3097
+ * Present if the server offers any tools to call.
3098
+ */
3099
+ tools: optional(
3100
+ object({
3101
+ /**
3102
+ * Whether this server supports issuing notifications for changes to the tool list.
3103
+ */
3104
+ listChanged: optional(boolean())
3105
+ })
3106
+ )
3107
+ });
3108
+ var InitializeResultSchema = object({
3109
+ ...ResultSchema.entries,
3110
+ /**
3111
+ * 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.
3112
+ */
3113
+ protocolVersion: string(),
3114
+ capabilities: ServerCapabilitiesSchema,
3115
+ serverInfo: ImplementationSchema,
3116
+ /**
3117
+ * Instructions describing how to use the server and its features.
3118
+ *
3119
+ * 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.
3120
+ */
3121
+ instructions: optional(string())
3122
+ });
3123
+ var InitializedNotificationSchema = object({
3124
+ ...NotificationSchema.entries,
3125
+ method: literal("notifications/initialized")
3126
+ });
3127
+ var PingRequestSchema = object({
3128
+ ...RequestSchema.entries,
3129
+ method: literal("ping")
3130
+ });
3131
+ var ProgressSchema = object({
3132
+ /**
3133
+ * The progress thus far. This should increase every time progress is made, even if the total is unknown.
3134
+ */
3135
+ progress: number(),
3136
+ /**
3137
+ * Total number of items to process (or total progress required), if known.
3138
+ */
3139
+ total: optional(number()),
3140
+ /**
3141
+ * An optional message describing the current progress.
3142
+ */
3143
+ message: optional(string())
3144
+ });
3145
+ var ProgressNotificationSchema = object({
3146
+ ...NotificationSchema.entries,
3147
+ method: literal("notifications/progress"),
3148
+ params: object({
3149
+ ...BaseNotificationParamsSchema.entries,
3150
+ ...ProgressSchema.entries,
3151
+ /**
3152
+ * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
3153
+ */
3154
+ progressToken: ProgressTokenSchema
3155
+ })
3156
+ });
3157
+ var PaginatedRequestSchema = object({
3158
+ ...RequestSchema.entries,
3159
+ params: optional(
3160
+ object({
3161
+ ...BaseRequestParamsSchema.entries,
3162
+ /**
3163
+ * An opaque token representing the current pagination position.
3164
+ * If provided, the server should return results starting after this cursor.
3165
+ */
3166
+ cursor: optional(CursorSchema)
3167
+ })
3168
+ )
3169
+ });
3170
+ var PaginatedResultSchema = object({
3171
+ ...ResultSchema.entries,
3172
+ /**
3173
+ * An opaque token representing the pagination position after the last returned result.
3174
+ * If present, there may be more results available.
3175
+ */
3176
+ nextCursor: optional(CursorSchema)
3177
+ });
3178
+ var ResourceContentsSchema = object({
3179
+ /**
3180
+ * The URI of this resource.
3181
+ */
3182
+ uri: string(),
3183
+ /**
3184
+ * The MIME type of this resource, if known.
3185
+ */
3186
+ mimeType: optional(string()),
3187
+ /**
3188
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
3189
+ * for notes on _meta usage.
3190
+ */
3191
+ _meta: optional(looseObject({}))
3192
+ });
3193
+ var TextResourceContentsSchema = object({
3194
+ ...ResourceContentsSchema.entries,
3195
+ /**
3196
+ * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
3197
+ */
3198
+ text: string()
3199
+ });
3200
+ var BlobResourceContentsSchema = object({
3201
+ ...ResourceContentsSchema.entries,
3202
+ /**
3203
+ * A base64-encoded string representing the binary data of the item.
3204
+ */
3205
+ blob: pipe(string(), base64())
3206
+ });
3207
+ var ResourceSchema = object({
3208
+ ...BaseMetadataSchema.entries,
3209
+ /**
3210
+ * The URI of this resource.
3211
+ */
3212
+ uri: string(),
3213
+ /**
3214
+ * A description of what this resource represents.
3215
+ *
3216
+ * 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.
3217
+ */
3218
+ description: optional(string()),
3219
+ /**
3220
+ * The MIME type of this resource, if known.
3221
+ */
3222
+ mimeType: optional(string()),
3223
+ /**
3224
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
3225
+ * for notes on _meta usage.
3226
+ */
3227
+ _meta: optional(looseObject({})),
3228
+ ...IconsSchema.entries
3229
+ });
3230
+ var ResourceTemplateSchema = object({
3231
+ ...BaseMetadataSchema.entries,
3232
+ /**
3233
+ * A URI template (according to RFC 6570) that can be used to construct resource URIs.
3234
+ */
3235
+ uriTemplate: string(),
3236
+ /**
3237
+ * A description of what this template is for.
3238
+ *
3239
+ * 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.
3240
+ */
3241
+ description: optional(string()),
3242
+ /**
3243
+ * 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.
3244
+ */
3245
+ mimeType: optional(string()),
3246
+ /**
3247
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
3248
+ * for notes on _meta usage.
3249
+ */
3250
+ _meta: optional(looseObject({})),
3251
+ ...IconsSchema.entries
3252
+ });
3253
+ var ListResourcesRequestSchema = object({
3254
+ ...PaginatedRequestSchema.entries,
3255
+ method: literal("resources/list")
3256
+ });
3257
+ var ListResourcesResultSchema = object({
3258
+ ...PaginatedResultSchema.entries,
3259
+ resources: array(ResourceSchema)
3260
+ });
3261
+ var ListResourceTemplatesRequestSchema = object({
3262
+ ...PaginatedRequestSchema.entries,
3263
+ method: literal("resources/templates/list")
3264
+ });
3265
+ var ListResourceTemplatesResultSchema = object({
3266
+ ...PaginatedResultSchema.entries,
3267
+ resourceTemplates: array(ResourceTemplateSchema)
3268
+ });
3269
+ var ReadResourceRequestSchema = object({
3270
+ ...RequestSchema.entries,
3271
+ method: literal("resources/read"),
3272
+ params: object({
3273
+ ...BaseRequestParamsSchema.entries,
3274
+ /**
3275
+ * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
3276
+ */
3277
+ uri: string()
3278
+ })
3279
+ });
3280
+ var ReadResourceResultSchema = object({
3281
+ ...ResultSchema.entries,
3282
+ contents: array(
3283
+ union([TextResourceContentsSchema, BlobResourceContentsSchema])
3284
+ )
3285
+ });
3286
+ var ResourceListChangedNotificationSchema = object({
3287
+ ...NotificationSchema.entries,
3288
+ method: literal("notifications/resources/list_changed")
3289
+ });
3290
+ var SubscribeRequestSchema = object({
3291
+ ...RequestSchema.entries,
3292
+ method: literal("resources/subscribe"),
3293
+ params: object({
3294
+ ...BaseRequestParamsSchema.entries,
3295
+ /**
3296
+ * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.
3297
+ */
3298
+ uri: string()
3299
+ })
3300
+ });
3301
+ var UnsubscribeRequestSchema = object({
3302
+ ...RequestSchema.entries,
3303
+ method: literal("resources/unsubscribe"),
3304
+ params: object({
3305
+ ...BaseRequestParamsSchema.entries,
3306
+ /**
3307
+ * The URI of the resource to unsubscribe from.
3308
+ */
3309
+ uri: string()
3310
+ })
3311
+ });
3312
+ var ResourceUpdatedNotificationSchema = object({
3313
+ ...NotificationSchema.entries,
3314
+ method: literal("notifications/resources/updated"),
3315
+ params: object({
3316
+ ...BaseNotificationParamsSchema.entries,
3317
+ /**
3318
+ * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
3319
+ */
3320
+ uri: string()
3321
+ })
3322
+ });
3323
+ var PromptArgumentSchema = object({
3324
+ /**
3325
+ * The name of the argument.
3326
+ */
3327
+ name: string(),
3328
+ /**
3329
+ * A human-readable description of the argument.
3330
+ */
3331
+ description: optional(string()),
3332
+ /**
3333
+ * Whether this argument must be provided.
3334
+ */
3335
+ required: optional(boolean())
3336
+ });
3337
+ var PromptSchema = object({
3338
+ ...BaseMetadataSchema.entries,
3339
+ /**
3340
+ * An optional description of what this prompt provides
3341
+ */
3342
+ description: optional(string()),
3343
+ /**
3344
+ * A list of arguments to use for templating the prompt.
3345
+ */
3346
+ arguments: optional(array(PromptArgumentSchema)),
3347
+ /**
3348
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
3349
+ * for notes on _meta usage.
3350
+ */
3351
+ _meta: optional(looseObject({})),
3352
+ ...IconsSchema.entries
3353
+ });
3354
+ var ListPromptsRequestSchema = object({
3355
+ ...PaginatedRequestSchema.entries,
3356
+ method: literal("prompts/list")
3357
+ });
3358
+ var ListPromptsResultSchema = object({
3359
+ ...PaginatedResultSchema.entries,
3360
+ prompts: array(PromptSchema)
3361
+ });
3362
+ var GetPromptRequestSchema = object({
3363
+ ...RequestSchema.entries,
3364
+ method: literal("prompts/get"),
3365
+ params: object({
3366
+ ...BaseRequestParamsSchema.entries,
3367
+ /**
3368
+ * The name of the prompt or prompt template.
3369
+ */
3370
+ name: string(),
3371
+ /**
3372
+ * Arguments to use for templating the prompt.
3373
+ */
3374
+ arguments: optional(record(string(), string()))
3375
+ })
3376
+ });
3377
+ var TextContentSchema = object({
3378
+ type: literal("text"),
3379
+ /**
3380
+ * The text content of the message.
3381
+ */
3382
+ text: string(),
3383
+ /**
3384
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
3385
+ * for notes on _meta usage.
3386
+ */
3387
+ _meta: optional(looseObject({}))
3388
+ });
3389
+ var ImageContentSchema = object({
3390
+ type: literal("image"),
3391
+ /**
3392
+ * The base64-encoded image data.
3393
+ */
3394
+ data: pipe(string(), base64()),
3395
+ /**
3396
+ * The MIME type of the image. Different providers may support different image types.
3397
+ */
3398
+ mimeType: string(),
3399
+ /**
3400
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
3401
+ * for notes on _meta usage.
3402
+ */
3403
+ _meta: optional(looseObject({}))
3404
+ });
3405
+ var AudioContentSchema = object({
3406
+ type: literal("audio"),
3407
+ /**
3408
+ * The base64-encoded audio data.
3409
+ */
3410
+ data: pipe(string(), base64()),
3411
+ /**
3412
+ * The MIME type of the audio. Different providers may support different audio types.
3413
+ */
3414
+ mimeType: string(),
3415
+ /**
3416
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
3417
+ * for notes on _meta usage.
3418
+ */
3419
+ _meta: optional(looseObject({}))
3420
+ });
3421
+ var EmbeddedResourceSchema = object({
3422
+ type: literal("resource"),
3423
+ resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
3424
+ /**
3425
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
3426
+ * for notes on _meta usage.
3427
+ */
3428
+ _meta: optional(looseObject({}))
3429
+ });
3430
+ var ResourceLinkSchema = object({
3431
+ ...ResourceSchema.entries,
3432
+ type: literal("resource_link")
3433
+ });
3434
+ var ContentBlockSchema = union([
3435
+ TextContentSchema,
3436
+ ImageContentSchema,
3437
+ AudioContentSchema,
3438
+ ResourceLinkSchema,
3439
+ EmbeddedResourceSchema
3440
+ ]);
3441
+ var PromptMessageSchema = object({
3442
+ role: picklist(["user", "assistant"]),
3443
+ content: ContentBlockSchema
3444
+ });
3445
+ var GetPromptResultSchema = object({
3446
+ ...ResultSchema.entries,
3447
+ /**
3448
+ * An optional description for the prompt.
3449
+ */
3450
+ description: optional(string()),
3451
+ messages: array(PromptMessageSchema)
3452
+ });
3453
+ var PromptListChangedNotificationSchema = object({
3454
+ ...NotificationSchema.entries,
3455
+ method: literal("notifications/prompts/list_changed")
3456
+ });
3457
+ var ToolAnnotationsSchema = object({
3458
+ /**
3459
+ * A human-readable title for the tool.
3460
+ */
3461
+ title: optional(string()),
3462
+ /**
3463
+ * If true, the tool does not modify its environment.
3464
+ *
3465
+ * Default: false
3466
+ */
3467
+ readOnlyHint: optional(boolean()),
3468
+ /**
3469
+ * If true, the tool may perform destructive updates to its environment.
3470
+ * If false, the tool performs only additive updates.
3471
+ *
3472
+ * (This property is meaningful only when `readOnlyHint == false`)
3473
+ *
3474
+ * Default: true
3475
+ */
3476
+ destructiveHint: optional(boolean()),
3477
+ /**
3478
+ * If true, calling the tool repeatedly with the same arguments
3479
+ * will have no additional effect on the its environment.
3480
+ *
3481
+ * (This property is meaningful only when `readOnlyHint == false`)
3482
+ *
3483
+ * Default: false
3484
+ */
3485
+ idempotentHint: optional(boolean()),
3486
+ /**
3487
+ * If true, this tool may interact with an "open world" of external
3488
+ * entities. If false, the tool's domain of interaction is closed.
3489
+ * For example, the world of a web search tool is open, whereas that
3490
+ * of a memory tool is not.
3491
+ *
3492
+ * Default: true
3493
+ */
3494
+ openWorldHint: optional(boolean())
3495
+ });
3496
+ var ToolSchema = object({
3497
+ ...BaseMetadataSchema.entries,
3498
+ /**
3499
+ * A human-readable description of the tool.
3500
+ */
3501
+ description: optional(string()),
3502
+ /**
3503
+ * A JSON Schema object defining the expected parameters for the tool.
3504
+ */
3505
+ inputSchema: object({
3506
+ type: literal("object"),
3507
+ properties: optional(object({})),
3508
+ required: optional(array(string()))
3509
+ }),
3510
+ /**
3511
+ * An optional JSON Schema object defining the structure of the tool's output returned in
3512
+ * the structuredContent field of a CallToolResult.
3513
+ */
3514
+ outputSchema: optional(
3515
+ object({
3516
+ type: literal("object"),
3517
+ properties: optional(object({})),
3518
+ required: optional(array(string()))
3519
+ })
3520
+ ),
3521
+ /**
3522
+ * Optional additional tool information.
3523
+ */
3524
+ annotations: optional(ToolAnnotationsSchema),
3525
+ /**
3526
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
3527
+ * for notes on _meta usage.
3528
+ */
3529
+ _meta: optional(looseObject({})),
3530
+ ...IconsSchema.entries
3531
+ });
3532
+ var ListToolsRequestSchema = object({
3533
+ ...PaginatedRequestSchema.entries,
3534
+ method: literal("tools/list")
3535
+ });
3536
+ var ListToolsResultSchema = object({
3537
+ ...PaginatedResultSchema.entries,
3538
+ tools: array(ToolSchema)
3539
+ });
3540
+ var CallToolResultSchema = object({
3541
+ ...ResultSchema.entries,
3542
+ /**
3543
+ * A list of content objects that represent the result of the tool call.
3544
+ *
3545
+ * If the Tool does not define an outputSchema, this field MUST be present in the result.
3546
+ * For backwards compatibility, this field is always present, but it may be empty.
3547
+ */
3548
+ content: optional(array(ContentBlockSchema), []),
3549
+ /**
3550
+ * An object containing structured tool output.
3551
+ *
3552
+ * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
3553
+ */
3554
+ structuredContent: optional(looseObject({})),
3555
+ /**
3556
+ * Whether the tool call ended in an error.
3557
+ *
3558
+ * If not set, this is assumed to be false (the call was successful).
3559
+ *
3560
+ * Any errors that originate from the tool SHOULD be reported inside the result
3561
+ * object, with `isError` set to true, _not_ as an MCP protocol-level error
3562
+ * response. Otherwise, the LLM would not be able to see that an error occurred
3563
+ * and self-correct.
3564
+ *
3565
+ * However, any errors in _finding_ the tool, an error indicating that the
3566
+ * server does not support tool calls, or any other exceptional conditions,
3567
+ * should be reported as an MCP error response.
3568
+ */
3569
+ isError: optional(boolean())
3570
+ });
3571
+ var CompatibilityCallToolResultSchema = union([
3572
+ CallToolResultSchema,
3573
+ object({ ...ResultSchema.entries, toolResult: unknown() })
3574
+ ]);
3575
+ var CallToolRequestSchema = object({
3576
+ ...RequestSchema.entries,
3577
+ method: literal("tools/call"),
3578
+ params: object({
3579
+ ...BaseRequestParamsSchema.entries,
3580
+ name: string(),
3581
+ arguments: optional(record(string(), unknown()))
3582
+ })
3583
+ });
3584
+ var ToolListChangedNotificationSchema = object({
3585
+ ...NotificationSchema.entries,
3586
+ method: literal("notifications/tools/list_changed")
3587
+ });
3588
+ var LoggingLevelSchema = picklist([
3589
+ "debug",
3590
+ "info",
3591
+ "notice",
3592
+ "warning",
3593
+ "error",
3594
+ "critical",
3595
+ "alert",
3596
+ "emergency"
3597
+ ]);
3598
+ var SetLevelRequestSchema = object({
3599
+ ...RequestSchema.entries,
3600
+ method: literal("logging/setLevel"),
3601
+ params: object({
3602
+ ...BaseRequestParamsSchema.entries,
3603
+ /**
3604
+ * 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.
3605
+ */
3606
+ level: LoggingLevelSchema
3607
+ })
3608
+ });
3609
+ var LoggingMessageNotificationSchema = object({
3610
+ ...NotificationSchema.entries,
3611
+ method: literal("notifications/message"),
3612
+ params: object({
3613
+ ...BaseNotificationParamsSchema.entries,
3614
+ /**
3615
+ * The severity of this log message.
3616
+ */
3617
+ level: LoggingLevelSchema,
3618
+ /**
3619
+ * An optional name of the logger issuing this message.
3620
+ */
3621
+ logger: optional(string()),
3622
+ /**
3623
+ * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
3624
+ */
3625
+ data: unknown()
3626
+ })
3627
+ });
3628
+ var ModelHintSchema = object({
3629
+ /**
3630
+ * A hint for a model name.
3631
+ */
3632
+ name: optional(string())
3633
+ });
3634
+ var ModelPreferencesSchema = object({
3635
+ /**
3636
+ * Optional hints to use for model selection.
3637
+ */
3638
+ hints: optional(array(ModelHintSchema)),
3639
+ /**
3640
+ * How much to prioritize cost when selecting a model.
3641
+ */
3642
+ costPriority: optional(pipe(number(), minValue(0), maxValue(1))),
3643
+ /**
3644
+ * How much to prioritize sampling speed (latency) when selecting a model.
3645
+ */
3646
+ speedPriority: optional(pipe(number(), minValue(0), maxValue(1))),
3647
+ /**
3648
+ * How much to prioritize intelligence and capabilities when selecting a model.
3649
+ */
3650
+ intelligencePriority: optional(
3651
+ pipe(number(), minValue(0), maxValue(1))
3652
+ )
3653
+ });
3654
+ var SamplingMessageSchema = object({
3655
+ role: picklist(["user", "assistant"]),
3656
+ content: union([
3657
+ TextContentSchema,
3658
+ ImageContentSchema,
3659
+ AudioContentSchema
3660
+ ])
3661
+ });
3662
+ var CreateMessageRequestParamsSchema = object({
3663
+ ...BaseRequestParamsSchema.entries,
3664
+ messages: array(SamplingMessageSchema),
3665
+ /**
3666
+ * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
3667
+ */
3668
+ systemPrompt: optional(string()),
3669
+ /**
3670
+ * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request.
3671
+ */
3672
+ includeContext: optional(
3673
+ picklist(["none", "thisServer", "allServers"])
3674
+ ),
3675
+ temperature: optional(number()),
3676
+ /**
3677
+ * The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested.
3678
+ */
3679
+ maxTokens: pipe(number(), integer()),
3680
+ stopSequences: optional(array(string())),
3681
+ /**
3682
+ * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
3683
+ */
3684
+ metadata: optional(object({})),
3685
+ /**
3686
+ * The server's preferences for which model to select.
3687
+ */
3688
+ modelPreferences: optional(ModelPreferencesSchema)
3689
+ });
3690
+ var CreateMessageRequestSchema = object({
3691
+ ...RequestSchema.entries,
3692
+ method: literal("sampling/createMessage"),
3693
+ params: CreateMessageRequestParamsSchema
3694
+ });
3695
+ var CreateMessageResultSchema = object({
3696
+ ...ResultSchema.entries,
3697
+ /**
3698
+ * The name of the model that generated the message.
3699
+ */
3700
+ model: string(),
3701
+ /**
3702
+ * The reason why sampling stopped.
3703
+ */
3704
+ stopReason: optional(
3705
+ union([
3706
+ picklist(["endTurn", "stopSequence", "maxTokens"]),
3707
+ string()
3708
+ ])
3709
+ ),
3710
+ role: picklist(["user", "assistant"]),
3711
+ content: variant("type", [
3712
+ TextContentSchema,
3713
+ ImageContentSchema,
3714
+ AudioContentSchema
3715
+ ])
3716
+ });
3717
+ var BooleanSchemaSchema = object({
3718
+ type: literal("boolean"),
3719
+ title: optional(string()),
3720
+ description: optional(string()),
3721
+ default: optional(boolean())
3722
+ });
3723
+ var StringSchemaSchema = object({
3724
+ type: literal("string"),
3725
+ title: optional(string()),
3726
+ description: optional(string()),
3727
+ minLength: optional(number()),
3728
+ maxLength: optional(number()),
3729
+ format: optional(picklist(["email", "uri", "date", "date-time"]))
3730
+ });
3731
+ var NumberSchemaSchema = object({
3732
+ type: picklist(["number", "integer"]),
3733
+ title: optional(string()),
3734
+ description: optional(string()),
3735
+ minimum: optional(number()),
3736
+ maximum: optional(number())
3737
+ });
3738
+ var EnumSchemaSchema = object({
3739
+ type: literal("string"),
3740
+ title: optional(string()),
3741
+ description: optional(string()),
3742
+ enum: array(string()),
3743
+ enumNames: optional(array(string()))
3744
+ });
3745
+ var PrimitiveSchemaDefinitionSchema = union([
3746
+ BooleanSchemaSchema,
3747
+ StringSchemaSchema,
3748
+ NumberSchemaSchema,
3749
+ EnumSchemaSchema
3750
+ ]);
3751
+ var ElicitRequestSchema = object({
3752
+ ...RequestSchema.entries,
3753
+ method: literal("elicitation/create"),
3754
+ params: object({
3755
+ ...BaseRequestParamsSchema.entries,
3756
+ /**
3757
+ * The message to present to the user.
3758
+ */
3759
+ message: string(),
3760
+ /**
3761
+ * The schema for the requested user input.
3762
+ */
3763
+ requestedSchema: object({
3764
+ type: literal("object"),
3765
+ properties: record(string(), PrimitiveSchemaDefinitionSchema),
3766
+ required: optional(array(string()))
3767
+ })
3768
+ })
3769
+ });
3770
+ var ElicitResultSchema = object({
3771
+ ...ResultSchema.entries,
3772
+ /**
3773
+ * The user's response action.
3774
+ */
3775
+ action: picklist(["accept", "decline", "cancel"]),
3776
+ /**
3777
+ * The collected user input content (only present if action is "accept").
3778
+ */
3779
+ content: optional(record(string(), unknown()))
3780
+ });
3781
+ var ResourceTemplateReferenceSchema = object({
3782
+ type: literal("ref/resource"),
3783
+ /**
3784
+ * The URI or URI template of the resource.
3785
+ */
3786
+ uri: string()
3787
+ });
3788
+ var PromptReferenceSchema = object({
3789
+ type: literal("ref/prompt"),
3790
+ /**
3791
+ * The name of the prompt or prompt template
3792
+ */
3793
+ name: string()
3794
+ });
3795
+ var CompleteRequestSchema = object({
3796
+ ...RequestSchema.entries,
3797
+ method: literal("completion/complete"),
3798
+ params: object({
3799
+ ...BaseRequestParamsSchema.entries,
3800
+ ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
3801
+ /**
3802
+ * The argument's information
3803
+ */
3804
+ argument: object({
3805
+ /**
3806
+ * The name of the argument
3807
+ */
3808
+ name: string(),
3809
+ /**
3810
+ * The value of the argument to use for completion matching.
3811
+ */
3812
+ value: string()
3813
+ }),
3814
+ context: optional(
3815
+ object({
3816
+ /**
3817
+ * Previously-resolved variables in a URI template or prompt.
3818
+ */
3819
+ arguments: optional(record(string(), string()))
3820
+ })
3821
+ )
3822
+ })
3823
+ });
3824
+ var CompleteResultSchema = object({
3825
+ ...ResultSchema.entries,
3826
+ completion: object({
3827
+ /**
3828
+ * An array of completion values. Must not exceed 100 items.
3829
+ */
3830
+ values: pipe(array(string()), maxLength(100)),
3831
+ /**
3832
+ * The total number of completion options available. This can exceed the number of values actually sent in the response.
3833
+ */
3834
+ total: optional(pipe(number(), integer())),
3835
+ /**
3836
+ * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
3837
+ */
3838
+ hasMore: optional(boolean())
3839
+ })
3840
+ });
3841
+ var RootSchema = object({
3842
+ /**
3843
+ * The URI identifying the root. This *must* start with file:// for now.
3844
+ */
3845
+ uri: pipe(string(), startsWith("file://")),
3846
+ /**
3847
+ * An optional name for the root.
3848
+ */
3849
+ name: optional(string()),
3850
+ /**
3851
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
3852
+ * for notes on _meta usage.
3853
+ */
3854
+ _meta: optional(looseObject({}))
3855
+ });
3856
+ var ListRootsRequestSchema = object({
3857
+ ...RequestSchema.entries,
3858
+ method: literal("roots/list")
3859
+ });
3860
+ var ListRootsResultSchema = object({
3861
+ ...ResultSchema.entries,
3862
+ roots: array(RootSchema)
3863
+ });
3864
+ var RootsListChangedNotificationSchema = object({
3865
+ ...NotificationSchema.entries,
3866
+ method: literal("notifications/roots/list_changed")
3867
+ });
3868
+ var ClientRequestSchema = union([
3869
+ PingRequestSchema,
3870
+ InitializeRequestSchema,
3871
+ CompleteRequestSchema,
3872
+ SetLevelRequestSchema,
3873
+ GetPromptRequestSchema,
3874
+ ListPromptsRequestSchema,
3875
+ ListResourcesRequestSchema,
3876
+ ListResourceTemplatesRequestSchema,
3877
+ ReadResourceRequestSchema,
3878
+ SubscribeRequestSchema,
3879
+ UnsubscribeRequestSchema,
3880
+ CallToolRequestSchema,
3881
+ ListToolsRequestSchema
3882
+ ]);
3883
+ var ClientNotificationSchema = union([
3884
+ CancelledNotificationSchema,
3885
+ ProgressNotificationSchema,
3886
+ InitializedNotificationSchema,
3887
+ RootsListChangedNotificationSchema
3888
+ ]);
3889
+ var ClientResultSchema = union([
3890
+ EmptyResultSchema,
3891
+ CreateMessageResultSchema,
3892
+ ElicitResultSchema,
3893
+ ListRootsResultSchema
3894
+ ]);
3895
+ var ServerRequestSchema = union([
3896
+ PingRequestSchema,
3897
+ CreateMessageRequestSchema,
3898
+ ElicitRequestSchema,
3899
+ ListRootsRequestSchema
3900
+ ]);
3901
+ var ServerNotificationSchema = union([
3902
+ CancelledNotificationSchema,
3903
+ ProgressNotificationSchema,
3904
+ LoggingMessageNotificationSchema,
3905
+ ResourceUpdatedNotificationSchema,
3906
+ ResourceListChangedNotificationSchema,
3907
+ ToolListChangedNotificationSchema,
3908
+ PromptListChangedNotificationSchema
3909
+ ]);
3910
+ var ServerResultSchema = union([
3911
+ EmptyResultSchema,
3912
+ InitializeResultSchema,
3913
+ CompleteResultSchema,
3914
+ GetPromptResultSchema,
3915
+ ListPromptsResultSchema,
3916
+ ListResourcesResultSchema,
3917
+ ListResourceTemplatesResultSchema,
3918
+ ReadResourceResultSchema,
3919
+ CallToolResultSchema,
3920
+ ListToolsResultSchema
3921
+ ]);
3922
+
3923
+ // ../../node_modules/.pnpm/tmcp@1.19.4_typescript@5.9.3/node_modules/tmcp/src/validation/version.js
3924
+ var SUPPORTED_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
3925
+ var LATEST_PROTOCOL_VERSION = SUPPORTED_VERSIONS[0];
3926
+ var ProtocolVersionSchema = pipe(
3927
+ string(),
3928
+ regex(
3929
+ /^\d{4}-\d{2}-\d{2}$/,
3930
+ "Protocol version must be in YYYY-MM-DD format"
3931
+ )
3932
+ );
3933
+ var SupportedProtocolVersionSchema = pipe(
3934
+ ProtocolVersionSchema,
3935
+ check(
3936
+ (version) => SUPPORTED_VERSIONS.includes(version),
3937
+ "Unsupported protocol version"
3938
+ )
3939
+ );
3940
+ function is_supported_version(version) {
3941
+ return SUPPORTED_VERSIONS.includes(version);
3942
+ }
3943
+ function get_latest_version() {
3944
+ return LATEST_PROTOCOL_VERSION;
3945
+ }
3946
+ function get_supported_versions() {
3947
+ return [...SUPPORTED_VERSIONS];
3948
+ }
3949
+ function negotiate_protocol_version(client_version) {
3950
+ if (is_supported_version(client_version)) {
3951
+ return client_version;
3952
+ }
3953
+ return get_latest_version();
3954
+ }
3955
+ function should_version_negotiation_fail(client_version) {
3956
+ try {
3957
+ const date = new Date(client_version);
3958
+ const regex2 = /^\d{4}-\d{2}-\d{2}$/;
3959
+ return !regex2.test(client_version) || isNaN(date.getTime());
3960
+ } catch {
3961
+ return true;
3962
+ }
3963
+ }
3964
+
3965
+ // ../../node_modules/.pnpm/tmcp@1.19.4_typescript@5.9.3/node_modules/tmcp/src/internal/utils.js
3966
+ function event(type, detail) {
3967
+ return new CustomEvent(type, { detail });
3968
+ }
3969
+
3970
+ // ../../node_modules/.pnpm/tmcp@1.19.4_typescript@5.9.3/node_modules/tmcp/src/index.js
3971
+ var Sqids;
3972
+ async function get_sqids() {
3973
+ if (!Sqids) {
3974
+ Sqids = new (await import("./sqids-5NZI6U3E.js")).default();
3975
+ }
3976
+ return Sqids;
3977
+ }
3978
+ async function encode_cursor(offset) {
3979
+ return (await get_sqids()).encode([offset]);
3980
+ }
3981
+ async function decode_cursor(cursor) {
3982
+ const [decoded] = (await get_sqids()).decode(cursor);
3983
+ return decoded;
3984
+ }
3985
+ async function safe_enabled(enabled) {
3986
+ try {
3987
+ return await enabled();
3988
+ } catch {
3989
+ return false;
3990
+ }
3991
+ }
3992
+ var McpServer = class {
3993
+ #server = new import_json_rpc_2.JSONRPCServer();
3994
+ /**
3995
+ * @type {JSONRPCClient<"broadcast" | "standalone"> | undefined}
3996
+ */
3997
+ #client;
3998
+ #options;
3999
+ /**
4000
+ * @type {Map<string, Tool<any, any>>}
4001
+ */
4002
+ #tools = /* @__PURE__ */ new Map();
4003
+ /**
4004
+ * @type {Map<string, Prompt<any>>}
4005
+ */
4006
+ #prompts = /* @__PURE__ */ new Map();
4007
+ /**
4008
+ * @type {Map<string, StoredResource>}
4009
+ */
4010
+ #resources = /* @__PURE__ */ new Map();
4011
+ #templates = new UriTemplateMatcher();
4012
+ /**
4013
+ * @type {Array<{uri: string, name?: string}>}
4014
+ */
4015
+ roots = [];
4016
+ /**
4017
+ * @type {{ [ref: string]: Map<string, Partial<Record<string, Completion>>> }}
4018
+ */
4019
+ #completions = {
4020
+ "ref/prompt": /* @__PURE__ */ new Map(),
4021
+ "ref/resource": /* @__PURE__ */ new Map()
4022
+ };
4023
+ #event_target = new EventTarget();
4024
+ /**
4025
+ * @type {AsyncLocalStorage<Context<CustomContext> & { progress_token?: string }>}
4026
+ */
4027
+ #ctx_storage = new AsyncLocalStorage();
4028
+ /**
4029
+ * @param {ServerInfo} server_info
4030
+ * @param {ServerOptions<StandardSchema>} options
4031
+ */
4032
+ constructor(server_info, options) {
4033
+ this.#options = options;
4034
+ this.#server.addMethod("initialize", (initialize_request) => {
4035
+ try {
4036
+ const validated_initialize = parse(
4037
+ InitializeRequestParamsSchema,
4038
+ initialize_request
4039
+ );
4040
+ if (should_version_negotiation_fail(
4041
+ validated_initialize.protocolVersion
4042
+ )) {
4043
+ const error = new McpError(
4044
+ -32602,
4045
+ "Invalid protocol version format"
4046
+ );
4047
+ throw error;
4048
+ }
4049
+ const negotiated_version = negotiate_protocol_version(
4050
+ validated_initialize.protocolVersion
4051
+ );
4052
+ this.#event_target.dispatchEvent(
4053
+ event("initialize", validated_initialize)
4054
+ );
4055
+ return {
4056
+ protocolVersion: negotiated_version,
4057
+ ...options,
4058
+ serverInfo: server_info
4059
+ };
4060
+ } catch (error) {
4061
+ if (error instanceof McpError) {
4062
+ throw error;
4063
+ }
4064
+ if (
4065
+ /** @type {Error} */
4066
+ error.message?.includes(
4067
+ "Protocol version"
4068
+ )
4069
+ ) {
4070
+ const rpc_error2 = new McpError(
4071
+ -32602,
4072
+ `Protocol version validation failed: ${/** @type {Error} */
4073
+ error.message}. Server supports: ${get_supported_versions().join(", ")}`
4074
+ );
4075
+ throw rpc_error2;
4076
+ }
4077
+ const rpc_error = new McpError(
4078
+ -32603,
4079
+ `Initialization failed: ${/** @type {Error} */
4080
+ error.message}`
4081
+ );
4082
+ throw rpc_error;
4083
+ }
4084
+ });
4085
+ this.#server.addMethod("ping", () => {
4086
+ return {};
4087
+ });
4088
+ this.#server.addMethod("notifications/initialized", () => {
4089
+ return null;
4090
+ });
4091
+ this.#init_tools();
4092
+ this.#init_prompts();
4093
+ this.#init_resources();
4094
+ this.#init_roots();
4095
+ this.#init_completion();
4096
+ this.#init_logging();
4097
+ }
4098
+ /**
4099
+ * Utility method to specify the type of the custom context for this server instance without the need to specify the standard schema type.
4100
+ * @example
4101
+ * const server = new McpServer({ ... }, { ... }).withContext<{ name: string }>();
4102
+ * @template {Record<string, unknown>} TCustom
4103
+ * @returns {McpServer<StandardSchema, TCustom>}
4104
+ */
4105
+ withContext() {
4106
+ return (
4107
+ /** @type {McpServer<StandardSchema, TCustom>} */
4108
+ /** @type {unknown} */
4109
+ this
4110
+ );
4111
+ }
4112
+ get #progress_token() {
4113
+ return this.#ctx_storage.getStore()?.progress_token;
4114
+ }
4115
+ /**
4116
+ * The context of the current request, include the session ID, any auth information, and custom data.
4117
+ * @type {Context<CustomContext>}
4118
+ */
4119
+ get ctx() {
4120
+ const { progress_token, ...rest } = this.#ctx_storage.getStore() ?? {};
4121
+ return rest;
4122
+ }
4123
+ get #client_capabilities() {
4124
+ return this.#ctx_storage.getStore()?.sessionInfo?.clientCapabilities;
4125
+ }
4126
+ /**
4127
+ * Get the client information (name, version, etc.) of the client that initiated the current request...useful if you want to do something different based on the client.
4128
+ * @deprecated Use `server.ctx.sessionInfo.clientInfo` instead.
4129
+ */
4130
+ currentClientInfo() {
4131
+ return this.#ctx_storage.getStore()?.sessionInfo?.clientInfo;
4132
+ }
4133
+ /**
4134
+ * Get the client capabilities of the client that initiated the current request, you can use this to verify the client support something before invoking the respective method.
4135
+ * @deprecated Use `server.ctx.sessionInfo.clientCapabilities` instead.
4136
+ */
4137
+ currentClientCapabilities() {
4138
+ return this.#client_capabilities;
4139
+ }
4140
+ #lazyily_create_client() {
4141
+ if (!this.#client) {
4142
+ this.#client = new import_json_rpc_2.JSONRPCClient((payload, kind) => {
4143
+ if (kind === "broadcast") {
4144
+ this.#event_target.dispatchEvent(
4145
+ event("broadcast", { request: payload })
4146
+ );
4147
+ return;
4148
+ }
4149
+ this.#event_target.dispatchEvent(
4150
+ event("send", { request: payload })
4151
+ );
4152
+ });
4153
+ }
4154
+ }
4155
+ /**
4156
+ * @template {keyof McpEvents} TEvent
4157
+ * @param {TEvent} event
4158
+ * @param {McpEvents[TEvent]} callback
4159
+ * @param {AddEventListenerOptions} [options]
4160
+ */
4161
+ on(event2, callback, options) {
4162
+ if (event2 === "send" || event2 === "broadcast") {
4163
+ this.#lazyily_create_client();
4164
+ }
4165
+ const listener = (e) => {
4166
+ callback(
4167
+ /** @type {CustomEvent} */
4168
+ e.detail
4169
+ );
4170
+ };
4171
+ this.#event_target.addEventListener(event2, listener, options);
4172
+ return () => {
4173
+ this.#event_target.removeEventListener(event2, listener, options);
4174
+ };
4175
+ }
4176
+ /**
4177
+ * @param {string} method
4178
+ * @param {JSONRPCParams} [params]
4179
+ * @param {"broadcast" | "standalone"} [kind]
4180
+ */
4181
+ #notify(method, params, kind = "standalone") {
4182
+ this.#client?.notify(method, params, kind);
4183
+ }
4184
+ /**
4185
+ *
4186
+ */
4187
+ #init_tools() {
4188
+ if (!this.#options.capabilities?.tools) return;
4189
+ this.#server.addMethod("tools/list", async ({ cursor } = {}) => {
4190
+ const all_tools = (await Promise.all(
4191
+ [...this.#tools].map(async ([name, tool2]) => {
4192
+ if (tool2.enabled != null && await safe_enabled(tool2.enabled) === false)
4193
+ return null;
4194
+ return {
4195
+ name,
4196
+ title: tool2.title || tool2.description,
4197
+ description: tool2.description,
4198
+ icons: tool2.icons,
4199
+ _meta: tool2._meta,
4200
+ inputSchema: tool2.schema && this.#options.adapter ? await this.#options.adapter.toJsonSchema(
4201
+ tool2.schema
4202
+ ) : { type: "object", properties: {} },
4203
+ ...tool2.outputSchema && this.#options.adapter ? {
4204
+ outputSchema: await this.#options.adapter.toJsonSchema(
4205
+ tool2.outputSchema
4206
+ )
4207
+ } : {},
4208
+ ...tool2.annotations ? {
4209
+ annotations: tool2.annotations
4210
+ } : {}
4211
+ };
4212
+ })
4213
+ )).filter((tool2) => tool2 !== null);
4214
+ const pagination_options = this.#options.pagination?.tools;
4215
+ if (!pagination_options || pagination_options.size == null) {
4216
+ return { tools: all_tools };
4217
+ }
4218
+ const page_length = pagination_options.size;
4219
+ const offset = cursor ? await decode_cursor(cursor) : 0;
4220
+ const start_index = offset;
4221
+ const end_index = start_index + page_length;
4222
+ const tools = all_tools.slice(start_index, end_index);
4223
+ const has_next = end_index < all_tools.length;
4224
+ const next_cursor = has_next ? await encode_cursor(end_index) : null;
4225
+ return {
4226
+ tools,
4227
+ ...next_cursor && { nextCursor: next_cursor }
4228
+ };
4229
+ });
4230
+ this.#server.addMethod(
4231
+ "tools/call",
4232
+ async ({ name, arguments: args }) => {
4233
+ const tool2 = this.#tools.get(name);
4234
+ if (!tool2) {
4235
+ return (
4236
+ /** @type {CallToolResult<any>} */
4237
+ {
4238
+ isError: true,
4239
+ content: [
4240
+ {
4241
+ type: "text",
4242
+ text: `Tool ${name} not found`
4243
+ }
4244
+ ]
4245
+ }
4246
+ );
4247
+ }
4248
+ let validated_args = args;
4249
+ if (tool2.schema) {
4250
+ let validation_result = tool2.schema["~standard"].validate(args);
4251
+ if (validation_result instanceof Promise)
4252
+ validation_result = await validation_result;
4253
+ if (validation_result.issues) {
4254
+ return (
4255
+ /** @type {CallToolResult<any>} */
4256
+ {
4257
+ isError: true,
4258
+ content: [
4259
+ {
4260
+ type: "text",
4261
+ text: `Invalid arguments for tool ${name}: ${JSON.stringify(validation_result.issues)}`
4262
+ }
4263
+ ]
4264
+ }
4265
+ );
4266
+ }
4267
+ validated_args = validation_result.value;
4268
+ }
4269
+ const tool_result = tool2.schema ? await tool2.execute(validated_args) : await tool2.execute();
4270
+ const parsed_result = parse(
4271
+ CallToolResultSchema,
4272
+ tool_result
4273
+ );
4274
+ if (tool2.outputSchema && parsed_result.structuredContent !== void 0) {
4275
+ let output_validation = tool2.outputSchema["~standard"].validate(parsed_result.structuredContent);
4276
+ if (output_validation instanceof Promise)
4277
+ output_validation = await output_validation;
4278
+ if (output_validation.issues) {
4279
+ return (
4280
+ /** @type {CallToolResult<any>} */
4281
+ {
4282
+ isError: true,
4283
+ content: [
4284
+ {
4285
+ type: "text",
4286
+ text: `Tool ${name} returned invalid structured content: ${JSON.stringify(output_validation.issues)}`
4287
+ }
4288
+ ]
4289
+ }
4290
+ );
4291
+ }
4292
+ parsed_result.structuredContent = output_validation.value;
4293
+ }
4294
+ return parsed_result;
4295
+ }
4296
+ );
4297
+ }
4298
+ /**
4299
+ *
4300
+ */
4301
+ #init_prompts() {
4302
+ if (!this.#options.capabilities?.prompts) return;
4303
+ this.#server.addMethod("prompts/list", async ({ cursor } = {}) => {
4304
+ const all_prompts = (await Promise.all(
4305
+ [...this.#prompts].map(async ([name, prompt]) => {
4306
+ if (prompt.enabled != null && await safe_enabled(prompt.enabled) === false)
4307
+ return null;
4308
+ const arguments_schema = prompt.schema && this.#options.adapter ? await this.#options.adapter.toJsonSchema(
4309
+ prompt.schema
4310
+ ) : {
4311
+ type: "object",
4312
+ properties: (
4313
+ /** @type {Record<string, {description: string}>} */
4314
+ {}
4315
+ ),
4316
+ required: []
4317
+ };
4318
+ const keys = Object.keys(
4319
+ arguments_schema.properties ?? {}
4320
+ );
4321
+ const required = arguments_schema.required ?? [];
4322
+ return {
4323
+ name,
4324
+ title: prompt.title || prompt.description,
4325
+ icons: prompt.icons,
4326
+ description: prompt.description,
4327
+ arguments: keys.map((key) => {
4328
+ const property = arguments_schema.properties?.[key];
4329
+ const description2 = property && property !== true ? property.description : key;
4330
+ return {
4331
+ name: key,
4332
+ required: required.includes(key),
4333
+ description: description2
4334
+ };
4335
+ })
4336
+ };
4337
+ })
4338
+ )).filter((prompt) => prompt !== null);
4339
+ const pagination_options = this.#options.pagination?.prompts;
4340
+ if (!pagination_options || pagination_options.size == null) {
4341
+ return { prompts: all_prompts };
4342
+ }
4343
+ const page_length = pagination_options.size;
4344
+ const offset = cursor ? await decode_cursor(cursor) : 0;
4345
+ const start_index = offset;
4346
+ const end_index = start_index + page_length;
4347
+ const prompts = all_prompts.slice(start_index, end_index);
4348
+ const has_next = end_index < all_prompts.length;
4349
+ const next_cursor = has_next ? await encode_cursor(end_index) : null;
4350
+ return {
4351
+ prompts,
4352
+ ...next_cursor && { nextCursor: next_cursor }
4353
+ };
4354
+ });
4355
+ this.#server.addMethod(
4356
+ "prompts/get",
4357
+ async ({ name, arguments: args }) => {
4358
+ const prompt = this.#prompts.get(name);
4359
+ if (!prompt) {
4360
+ throw new McpError(-32601, `Prompt ${name} not found`);
4361
+ }
4362
+ if (!prompt.schema) {
4363
+ return parse(
4364
+ GetPromptResultSchema,
4365
+ await prompt.execute()
4366
+ );
4367
+ }
4368
+ let validated_args = prompt.schema["~standard"].validate(args);
4369
+ if (validated_args instanceof Promise)
4370
+ validated_args = await validated_args;
4371
+ if (validated_args.issues) {
4372
+ throw new McpError(
4373
+ -32602,
4374
+ `Invalid arguments for prompt ${name}: ${JSON.stringify(validated_args.issues)}`
4375
+ );
4376
+ }
4377
+ return parse(
4378
+ GetPromptResultSchema,
4379
+ await prompt.execute(validated_args.value)
4380
+ );
4381
+ }
4382
+ );
4383
+ }
4384
+ /**
4385
+ *
4386
+ */
4387
+ #init_resources() {
4388
+ if (!this.#options.capabilities?.resources) return;
4389
+ if (this.#options.capabilities?.resources?.subscribe) {
4390
+ this.#server.addMethod("resources/subscribe", async ({ uri }) => {
4391
+ this.#event_target.dispatchEvent(
4392
+ event("subscription", { uri, action: "add" })
4393
+ );
4394
+ return {};
4395
+ });
4396
+ this.#server.addMethod("resources/unsubscribe", async ({ uri }) => {
4397
+ this.#event_target.dispatchEvent(
4398
+ event("subscription", { uri, action: "remove" })
4399
+ );
4400
+ return {};
4401
+ });
4402
+ }
4403
+ this.#server.addMethod("resources/list", async ({ cursor } = {}) => {
4404
+ const all_resources = [];
4405
+ for (const [uri, resource] of this.#resources) {
4406
+ if (!resource.template) {
4407
+ if (resource.enabled != null && await safe_enabled(resource.enabled) === false)
4408
+ continue;
4409
+ all_resources.push({
4410
+ name: resource.name,
4411
+ title: resource.title || resource.description,
4412
+ description: resource.description,
4413
+ uri,
4414
+ mimeType: resource.mimeType,
4415
+ icons: resource.icons
4416
+ });
4417
+ } else if (resource.list_resources) {
4418
+ if (resource.enabled != null && await safe_enabled(resource.enabled) === false)
4419
+ continue;
4420
+ const template_resources = await resource.list_resources();
4421
+ all_resources.push(...template_resources);
4422
+ }
4423
+ }
4424
+ const pagination_options = this.#options.pagination?.resources;
4425
+ if (!pagination_options || pagination_options.size == null) {
4426
+ return { resources: all_resources };
4427
+ }
4428
+ const page_length = pagination_options.size;
4429
+ const offset = cursor ? await decode_cursor(cursor) : 0;
4430
+ const start_index = offset;
4431
+ const end_index = start_index + page_length;
4432
+ const resources = all_resources.slice(start_index, end_index);
4433
+ const has_next = end_index < all_resources.length;
4434
+ const next_cursor = has_next ? await encode_cursor(end_index) : null;
4435
+ return {
4436
+ resources,
4437
+ ...next_cursor && { nextCursor: next_cursor }
4438
+ };
4439
+ });
4440
+ this.#server.addMethod("resources/templates/list", async () => {
4441
+ return {
4442
+ resourceTemplates: (await Promise.all(
4443
+ [...this.#resources].map(async ([uri, resource]) => {
4444
+ if (!resource.template) return null;
4445
+ if (resource.enabled != null && await safe_enabled(resource.enabled) === false)
4446
+ return null;
4447
+ return {
4448
+ name: resource.name,
4449
+ icons: resource.icons,
4450
+ title: resource.title || resource.description,
4451
+ description: resource.description,
4452
+ mimeType: resource.mimeType,
4453
+ uriTemplate: uri
4454
+ };
4455
+ })
4456
+ )).filter((resource) => resource != null)
4457
+ };
4458
+ });
4459
+ this.#server.addMethod("resources/read", async ({ uri }) => {
4460
+ let resource = this.#resources.get(uri);
4461
+ let params;
4462
+ if (!resource) {
4463
+ const match = this.#templates.match(uri);
4464
+ if (match) {
4465
+ resource = this.#resources.get(match.template);
4466
+ params = match.params;
4467
+ }
4468
+ if (!resource) {
4469
+ throw new McpError(-32601, `Resource ${uri} not found`);
4470
+ }
4471
+ }
4472
+ if (resource.template) {
4473
+ if (!params)
4474
+ throw new McpError(
4475
+ -32602,
4476
+ "Missing parameters for template resource"
4477
+ );
4478
+ return parse(
4479
+ ReadResourceResultSchema,
4480
+ await resource.execute(uri, params)
4481
+ );
4482
+ }
4483
+ return parse(
4484
+ ReadResourceResultSchema,
4485
+ await resource.execute(uri)
4486
+ );
4487
+ });
4488
+ }
4489
+ /**
4490
+ *
4491
+ */
4492
+ #init_roots() {
4493
+ this.#server.addMethod("notifications/roots/list_changed", () => {
4494
+ this.#refresh_roots();
4495
+ return null;
4496
+ });
4497
+ }
4498
+ /**
4499
+ * Request roots list from client
4500
+ */
4501
+ async #refresh_roots() {
4502
+ if (!this.#client_capabilities?.roots) return;
4503
+ this.#lazyily_create_client();
4504
+ try {
4505
+ const response = await this.#client?.request(
4506
+ "roots/list",
4507
+ void 0,
4508
+ "standalone"
4509
+ );
4510
+ this.roots = response?.roots || [];
4511
+ } catch {
4512
+ this.roots = [];
4513
+ }
4514
+ }
4515
+ #init_completion() {
4516
+ this.#server.addMethod(
4517
+ "completion/complete",
4518
+ async ({ argument, ref, context }) => {
4519
+ const completions = this.#completions[ref.type];
4520
+ if (!completions) return null;
4521
+ const complete = completions.get(ref.uri ?? ref.name);
4522
+ if (!complete) return null;
4523
+ const actual_complete = complete[argument.name];
4524
+ if (!actual_complete) return null;
4525
+ return parse(
4526
+ CompleteResultSchema,
4527
+ await actual_complete(argument.value, context)
4528
+ );
4529
+ }
4530
+ );
4531
+ }
4532
+ #init_logging() {
4533
+ if (!this.#options.capabilities?.logging) return;
4534
+ this.#server.addMethod("logging/setLevel", ({ level }) => {
4535
+ this.#event_target.dispatchEvent(
4536
+ event("loglevelchange", { level })
4537
+ );
4538
+ return {};
4539
+ });
4540
+ }
4541
+ #notify_tools_list_changed() {
4542
+ if (this.#options.capabilities?.tools?.listChanged) {
4543
+ this.#notify("notifications/tools/list_changed", {}, "broadcast");
4544
+ }
4545
+ }
4546
+ #notify_prompts_list_changed() {
4547
+ if (this.#options.capabilities?.prompts?.listChanged) {
4548
+ this.#notify("notifications/prompts/list_changed", {}, "broadcast");
4549
+ }
4550
+ }
4551
+ #notify_resources_list_changed() {
4552
+ if (this.#options.capabilities?.resources?.listChanged) {
4553
+ this.#notify(
4554
+ "notifications/resources/list_changed",
4555
+ {},
4556
+ "broadcast"
4557
+ );
4558
+ }
4559
+ }
4560
+ /**
4561
+ * Use the `defineTool` utility to create a reusable tool and pass it to this method to add it to the server.
4562
+ * @template {Array<CreatedTool<any, any>>} T
4563
+ * @template {T extends Array<CreatedTool<infer TSchema, infer TOutputSchema>> ? AllSame<TSchema, StandardSchema | undefined> extends true ? AllSame<TOutputSchema, StandardSchema | undefined> extends true ? T : never : never : never} U
4564
+ * @param {T & NoInfer<U>} tools
4565
+ */
4566
+ tools(tools) {
4567
+ for (const tool2 of tools) {
4568
+ this.tool(tool2);
4569
+ }
4570
+ }
4571
+ /**
4572
+ * Use the `definePrompt` utility to create a reusable tool and pass it to this method to add it to the server.
4573
+ * @template {Array<CreatedPrompt<any>>} T
4574
+ * @template {T extends Array<CreatedPrompt<infer TSchema>> ? AllSame<TSchema, StandardSchema | undefined> extends true ? T : never : never} U
4575
+ * @param {T & NoInfer<U>} prompts
4576
+ */
4577
+ prompts(prompts) {
4578
+ for (const prompt of prompts) {
4579
+ this.prompt(prompt);
4580
+ }
4581
+ }
4582
+ /**
4583
+ * Use the `defineResource` utility to create a reusable resource and pass it to this method to add it to the server.
4584
+ *
4585
+ * @param {CreatedResource[]} resources
4586
+ */
4587
+ resources(resources) {
4588
+ for (const resource of resources) {
4589
+ this.resource(resource);
4590
+ }
4591
+ }
4592
+ /**
4593
+ * Use the `defineTemplate` utility to create a reusable template and pass it to this method to add it to the server.
4594
+ *
4595
+ * @param {CreatedTemplate<any>[]} templates
4596
+ */
4597
+ templates(templates) {
4598
+ for (const template of templates) {
4599
+ this.template(template);
4600
+ }
4601
+ }
4602
+ /**
4603
+ * Add a tool to the server. If you want to receive any input you need to provide a schema. The schema needs to be a valid Standard Schema V1 schema and needs to be an Object with the properties you need,
4604
+ * Use the description and title to help the LLM to understand what the tool does and when to use it. If you provide an outputSchema, you need to return a structuredContent that matches the schema.
4605
+ *
4606
+ * Tools will be invoked by the LLM when it thinks it needs to use them, you can use the annotations to provide additional information about the tool, like what it does, how to use it, etc.
4607
+ * @template {StandardSchema | undefined} [TSchema=undefined]
4608
+ * @template {StandardSchema | undefined} [TOutputSchema=undefined]
4609
+ * @overload
4610
+ * @param {CreatedTool<TSchema, TOutputSchema>} tool_or_options
4611
+ * @returns {void}
4612
+ */
4613
+ /**
4614
+ * Add a tool to the server. If you want to receive any input you need to provide a schema. The schema needs to be a valid Standard Schema V1 schema and needs to be an Object with the properties you need,
4615
+ * Use the description and title to help the LLM to understand what the tool does and when to use it. If you provide an outputSchema, you need to return a structuredContent that matches the schema.
4616
+ *
4617
+ * Tools will be invoked by the LLM when it thinks it needs to use them, you can use the annotations to provide additional information about the tool, like what it does, how to use it, etc.
4618
+ * @template {StandardSchema | undefined} [TSchema=undefined]
4619
+ * @template {StandardSchema | undefined} [TOutputSchema=undefined]
4620
+ * @overload
4621
+ * @param {ToolOptions<TSchema, TOutputSchema>} tool_or_options
4622
+ * @param {TSchema extends undefined ? (()=>Promise<CallToolResult<TOutputSchema extends undefined ? undefined : StandardSchemaV1.InferInput<TOutputSchema extends undefined ? never : TOutputSchema>>> | CallToolResult<TOutputSchema extends undefined ? undefined : StandardSchemaV1.InferInput<TOutputSchema extends undefined ? never : TOutputSchema>>) : ((input: StandardSchemaV1.InferInput<TSchema extends undefined ? never : TSchema>) => Promise<CallToolResult<TOutputSchema extends undefined ? undefined : StandardSchemaV1.InferInput<TOutputSchema extends undefined ? never : TOutputSchema>>> | CallToolResult<TOutputSchema extends undefined ? undefined : StandardSchemaV1.InferInput<TOutputSchema extends undefined ? never : TOutputSchema>>)} execute
4623
+ * @returns {void}
4624
+ * */
4625
+ /**
4626
+ * Add a tool to the server. If you want to receive any input you need to provide a schema. The schema needs to be a valid Standard Schema V1 schema and needs to be an Object with the properties you need,
4627
+ * Use the description and title to help the LLM to understand what the tool does and when to use it. If you provide an outputSchema, you need to return a structuredContent that matches the schema.
4628
+ *
4629
+ * Tools will be invoked by the LLM when it thinks it needs to use them, you can use the annotations to provide additional information about the tool, like what it does, how to use it, etc.
4630
+ * @template {StandardSchema | undefined} [TSchema=undefined]
4631
+ * @template {StandardSchema | undefined} [TOutputSchema=undefined]
4632
+ * @param {CreatedTool<TSchema, TOutputSchema> | ToolOptions<TSchema, TOutputSchema>} tool_or_options
4633
+ * @param {undefined | TSchema extends undefined ? (()=>Promise<CallToolResult<TOutputSchema extends undefined ? undefined : StandardSchemaV1.InferInput<TOutputSchema extends undefined ? never : TOutputSchema>>> | CallToolResult<TOutputSchema extends undefined ? undefined : StandardSchemaV1.InferInput<TOutputSchema extends undefined ? never : TOutputSchema>>) : ((input: StandardSchemaV1.InferInput<TSchema extends undefined ? never : TSchema>) => Promise<CallToolResult<TOutputSchema extends undefined ? undefined : StandardSchemaV1.InferInput<TOutputSchema extends undefined ? never : TOutputSchema>>> | CallToolResult<TOutputSchema extends undefined ? undefined : StandardSchemaV1.InferInput<TOutputSchema extends undefined ? never : TOutputSchema>>)} [execute]
4634
+ */
4635
+ tool(tool_or_options, execute) {
4636
+ if ("execute" in tool_or_options) {
4637
+ execute = tool_or_options.execute;
796
4638
  }
797
- };
798
- }
799
- // @__NO_SIDE_EFFECTS__
800
- function picklist(options, message$1) {
801
- return {
802
- kind: "schema",
803
- type: "picklist",
804
- reference: picklist,
805
- expects: /* @__PURE__ */ _joinExpects(options.map(_stringify), "|"),
806
- async: false,
807
- options,
808
- message: message$1,
809
- get "~standard"() {
810
- return /* @__PURE__ */ _getStandardProps(this);
811
- },
812
- "~run"(dataset, config$1) {
813
- if (this.options.includes(dataset.value)) dataset.typed = true;
814
- else _addIssue(this, "type", dataset, config$1);
815
- return dataset;
4639
+ this.#notify_tools_list_changed();
4640
+ const stored_tool = (
4641
+ /** @type {Tool<any, any>} */
4642
+ tool_or_options
4643
+ );
4644
+ stored_tool.execute = /** @type {NonNullable<typeof execute>} */
4645
+ execute;
4646
+ this.#tools.set(tool_or_options.name, stored_tool);
4647
+ }
4648
+ /**
4649
+ * Add a prompt to the server. Prompts are used to provide the user with pre-defined messages that adds context to the LLM.
4650
+ * Use the description and title to help the user to understand what the prompt does and when to use it.
4651
+ *
4652
+ * A prompt can also have a schema that defines the input it expects, the user will be prompted to enter the inputs you request. It can also have a complete function
4653
+ * for each input that will be used to provide completions for the user.
4654
+ * @template {StandardSchema | undefined} [TSchema=undefined]
4655
+ * @overload
4656
+ * @param {CreatedPrompt<TSchema>} prompt_or_options
4657
+ * @returns {void}
4658
+ */
4659
+ /**
4660
+ * Add a prompt to the server. Prompts are used to provide the user with pre-defined messages that adds context to the LLM.
4661
+ * Use the description and title to help the user to understand what the prompt does and when to use it.
4662
+ *
4663
+ * A prompt can also have a schema that defines the input it expects, the user will be prompted to enter the inputs you request. It can also have a complete function
4664
+ * for each input that will be used to provide completions for the user.
4665
+ * @template {StandardSchema | undefined} [TSchema=undefined]
4666
+ * @overload
4667
+ * @param {PromptOptions<TSchema>} prompt_or_options
4668
+ * @param {TSchema extends undefined ? (()=>Promise<GetPromptResult> | GetPromptResult) : (input: StandardSchemaV1.InferInput<TSchema extends undefined ? never : TSchema>) => Promise<GetPromptResult> | GetPromptResult} execute
4669
+ * @returns {void}
4670
+ * */
4671
+ /**
4672
+ * Add a prompt to the server. Prompts are used to provide the user with pre-defined messages that adds context to the LLM.
4673
+ * Use the description and title to help the user to understand what the prompt does and when to use it.
4674
+ *
4675
+ * A prompt can also have a schema that defines the input it expects, the user will be prompted to enter the inputs you request. It can also have a complete function
4676
+ * for each input that will be used to provide completions for the user.
4677
+ * @template {StandardSchema | undefined} [TSchema=undefined]
4678
+ * @param {CreatedPrompt<TSchema> | PromptOptions<TSchema>} prompt_or_options
4679
+ * @param {TSchema extends undefined ? (()=>Promise<GetPromptResult> | GetPromptResult) : (input: StandardSchemaV1.InferInput<TSchema extends undefined ? never : TSchema>) => Promise<GetPromptResult> | GetPromptResult} [execute]
4680
+ */
4681
+ prompt(prompt_or_options, execute) {
4682
+ if ("execute" in prompt_or_options) {
4683
+ execute = /** @type {NonNullable<typeof execute>} */
4684
+ prompt_or_options.execute;
816
4685
  }
817
- };
818
- }
819
- // @__NO_SIDE_EFFECTS__
820
- function string(message$1) {
821
- return {
822
- kind: "schema",
823
- type: "string",
824
- reference: string,
825
- expects: "string",
826
- async: false,
827
- message: message$1,
828
- get "~standard"() {
829
- return /* @__PURE__ */ _getStandardProps(this);
830
- },
831
- "~run"(dataset, config$1) {
832
- if (typeof dataset.value === "string") dataset.typed = true;
833
- else _addIssue(this, "type", dataset, config$1);
834
- return dataset;
4686
+ if (prompt_or_options.complete) {
4687
+ this.#completions["ref/prompt"].set(
4688
+ prompt_or_options.name,
4689
+ prompt_or_options.complete
4690
+ );
835
4691
  }
836
- };
837
- }
838
- // @__NO_SIDE_EFFECTS__
839
- function pipe(...pipe$1) {
840
- return {
841
- ...pipe$1[0],
842
- pipe: pipe$1,
843
- get "~standard"() {
844
- return /* @__PURE__ */ _getStandardProps(this);
845
- },
846
- "~run"(dataset, config$1) {
847
- for (const item of pipe$1) if (item.kind !== "metadata") {
848
- if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
849
- dataset.typed = false;
850
- break;
851
- }
852
- if (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly) dataset = item["~run"](dataset, config$1);
853
- }
854
- return dataset;
4692
+ this.#notify_prompts_list_changed();
4693
+ const stored_prompt = (
4694
+ /** @type {Prompt<any>} */
4695
+ prompt_or_options
4696
+ );
4697
+ stored_prompt.execute = /** @type {NonNullable<typeof execute>} */
4698
+ execute;
4699
+ this.#prompts.set(prompt_or_options.name, stored_prompt);
4700
+ }
4701
+ /**
4702
+ * @type {(resource: StoredResource & { uri: string })=> void}
4703
+ */
4704
+ #resource(resource) {
4705
+ if (resource.template && resource.complete) {
4706
+ this.#completions["ref/resource"].set(
4707
+ resource.uri,
4708
+ resource.complete
4709
+ );
855
4710
  }
856
- };
857
- }
4711
+ if (resource.template) {
4712
+ this.#templates.add(resource.uri);
4713
+ }
4714
+ this.#notify_resources_list_changed();
4715
+ this.#resources.set(resource.uri, resource);
4716
+ }
4717
+ /**
4718
+ * Add a resource to the server. Resources are added manually to the context by the user to provide the LLM with additional context.
4719
+ * Use the description and title to help the user to understand what the resource is.
4720
+ * @overload
4721
+ * @param {CreatedResource} resource_or_options
4722
+ * @returns {void}
4723
+ */
4724
+ /**
4725
+ * Add a resource to the server. Resources are added manually to the context by the user to provide the LLM with additional context.
4726
+ * Use the description and title to help the user to understand what the resource is.
4727
+ * @overload
4728
+ * @param {ResourceOptions} resource_or_options
4729
+ * @param {(uri: string) => Promise<ReadResourceResult> | ReadResourceResult} execute
4730
+ * @returns {void}
4731
+ */
4732
+ /**
4733
+ * Add a resource to the server. Resources are added manually to the context by the user to provide the LLM with additional context.
4734
+ * Use the description and title to help the user to understand what the resource is.
4735
+ * @param {CreatedResource | ResourceOptions} resource_or_options
4736
+ * @param {(uri: string) => Promise<ReadResourceResult> | ReadResourceResult} [execute]
4737
+ */
4738
+ resource(resource_or_options, execute) {
4739
+ if ("execute" in resource_or_options) {
4740
+ execute = resource_or_options.execute;
4741
+ }
4742
+ const stored_resource = (
4743
+ /** @type {StoredResource & { uri: string }} */
4744
+ resource_or_options
4745
+ );
4746
+ stored_resource.execute = /** @type {NonNullable<typeof execute>} */
4747
+ execute;
4748
+ stored_resource.template = false;
4749
+ this.#resource(stored_resource);
4750
+ }
4751
+ /**
4752
+ * Add a resource template to the server. Resources are added manually to the context by the user to provide the LLM with additional context.
4753
+ * Resource templates are used to create resources dynamically based on a URI template. The URI template should be a valid URI template as defined in RFC 6570.
4754
+ * Resource templates can have a list method that returns a list of resources that match the template and a complete method that returns a list of resources given one of the template variables, this method will
4755
+ * be invoked to provide completions for the template variables to the user.
4756
+ * Use the description and title to help the user to understand what the resource is.
4757
+ * @template {string} TUri
4758
+ * @template {ExtractURITemplateVariables<TUri>} TVariables
4759
+ * @overload
4760
+ * @param {CreatedTemplate<TUri>} template_or_options
4761
+ * @returns {void}
4762
+ */
4763
+ /**
4764
+ * Add a resource template to the server. Resources are added manually to the context by the user to provide the LLM with additional context.
4765
+ * Resource templates are used to create resources dynamically based on a URI template. The URI template should be a valid URI template as defined in RFC 6570.
4766
+ * Resource templates can have a list method that returns a list of resources that match the template and a complete method that returns a list of resources given one of the template variables, this method will
4767
+ * be invoked to provide completions for the template variables to the user.
4768
+ * Use the description and title to help the user to understand what the resource is.
4769
+ * @template {string} TUri
4770
+ * @template {ExtractURITemplateVariables<TUri>} TVariables
4771
+ * @overload
4772
+ * @param {TemplateOptions<TUri>} template_or_options
4773
+ * @param {(uri: string, params: Record<TVariables, string | string[]>) => Promise<ReadResourceResult> | ReadResourceResult} execute
4774
+ * @returns {void}
4775
+ */
4776
+ /**
4777
+ * Add a resource template to the server. Resources are added manually to the context by the user to provide the LLM with additional context.
4778
+ * Resource templates are used to create resources dynamically based on a URI template. The URI template should be a valid URI template as defined in RFC 6570.
4779
+ * Resource templates can have a list method that returns a list of resources that match the template and a complete method that returns a list of resources given one of the template variables, this method will
4780
+ * be invoked to provide completions for the template variables to the user.
4781
+ * Use the description and title to help the user to understand what the resource is.
4782
+ * @template {string} TUri
4783
+ * @template {ExtractURITemplateVariables<TUri>} TVariables
4784
+ * @param {CreatedTemplate<TUri> | TemplateOptions<TUri>} template_or_options
4785
+ * @param {(uri: string, params: Record<TVariables, string | string[]>) => Promise<ReadResourceResult> | ReadResourceResult} [execute]
4786
+ */
4787
+ template(template_or_options, execute) {
4788
+ if ("execute" in template_or_options) {
4789
+ execute = template_or_options.execute;
4790
+ }
4791
+ const stored_template = (
4792
+ /** @type {StoredResource & { uri: string }} */
4793
+ /** @type {unknown} */
4794
+ template_or_options
4795
+ );
4796
+ stored_template.execute = /** @type {NonNullable<typeof execute>} */
4797
+ execute;
4798
+ stored_template.list_resources = template_or_options.list;
4799
+ stored_template.template = true;
4800
+ this.#resource(stored_template);
4801
+ }
4802
+ /**
4803
+ * The main function that receive a JSONRpc message and either dispatch a `send` event or process the request.
4804
+ *
4805
+ * @param {JSONRPCMessage} message
4806
+ * @param {Context<CustomContext>} [ctx]
4807
+ * @returns {ReturnType<JSONRPCServer['receive']> | ReturnType<JSONRPCClient['receive'] | undefined>}
4808
+ */
4809
+ receive(message, ctx) {
4810
+ const validated_message = safeParse(
4811
+ union([JSONRPCRequestSchema, JSONRPCNotificationSchema]),
4812
+ message
4813
+ );
4814
+ if (validated_message.success) {
4815
+ const progress_token = (
4816
+ /** @type {string | undefined} */
4817
+ validated_message.output.params?._meta?.progressToken
4818
+ );
4819
+ return this.#ctx_storage.run(
4820
+ { ...ctx ?? {}, progress_token },
4821
+ async () => await this.#server.receive(validated_message.output)
4822
+ );
4823
+ }
4824
+ const validated_response = parse(
4825
+ union([JSONRPCResponseSchema, JSONRPCErrorSchema]),
4826
+ message
4827
+ );
4828
+ this.#lazyily_create_client();
4829
+ return this.#ctx_storage.run(
4830
+ ctx ?? {},
4831
+ async () => this.#client?.receive(validated_response)
4832
+ );
4833
+ }
4834
+ /**
4835
+ * Lower level api to send a request to the client, mostly useful to call client methods that not yet supported by the server or
4836
+ * if you want to send requests with json schema that is not expressible with your validation library.
4837
+ * @param {{ method: string, params?: JSONRPCParams }} request
4838
+ * @returns {Promise<unknown>}
4839
+ */
4840
+ async request({ method, params }) {
4841
+ this.#lazyily_create_client();
4842
+ return this.#client?.request(method, params, "standalone");
4843
+ }
4844
+ /**
4845
+ * Send a notification for subscriptions
4846
+ * @template {keyof ChangedArgs} TWhat
4847
+ * @param {[what: TWhat, ...ChangedArgs[TWhat]]} args
4848
+ */
4849
+ changed(...args) {
4850
+ const [what, id] = args;
4851
+ if (what === "prompts") {
4852
+ this.#notify_prompts_list_changed();
4853
+ } else if (what === "tools") {
4854
+ this.#notify_tools_list_changed();
4855
+ } else if (what === "resources") {
4856
+ this.#notify_resources_list_changed();
4857
+ } else {
4858
+ const resource = this.#resources.get(id);
4859
+ if (!resource) return;
4860
+ this.#notify(
4861
+ `notifications/resources/updated`,
4862
+ {
4863
+ uri: id,
4864
+ title: resource.name
4865
+ },
4866
+ "broadcast"
4867
+ );
4868
+ }
4869
+ }
4870
+ /**
4871
+ * Refresh roots list from client
4872
+ */
4873
+ async refreshRoots() {
4874
+ await this.#refresh_roots();
4875
+ }
4876
+ /**
4877
+ * Emit an elicitation request to the client. Elicitations are used to ask the user for input in a structured way, the client will show a UI to the user to fill the input.
4878
+ * The schema should be a valid Standard Schema V1 schema and should be an Object with the properties you need.
4879
+ * The client will return the validated input as a JSON object that matches the schema.
4880
+ *
4881
+ * If the client doesn't support elicitation, it will throw an error.
4882
+ *
4883
+ * @template {StandardSchema extends undefined ? never : StandardSchema} TSchema
4884
+ * @param {string} message
4885
+ * @param {TSchema} schema
4886
+ * @returns {Promise<ElicitResult & { content?: StandardSchemaV1.InferOutput<TSchema> }>}
4887
+ */
4888
+ async elicitation(message, schema6) {
4889
+ if (!this.#client_capabilities?.elicitation)
4890
+ throw new McpError(-32601, "Client doesn't support elicitation");
4891
+ this.#lazyily_create_client();
4892
+ const result = await this.#client?.request(
4893
+ "elicitation/create",
4894
+ {
4895
+ message,
4896
+ requestedSchema: await this.#options.adapter?.toJsonSchema(schema6)
4897
+ },
4898
+ "standalone"
4899
+ );
4900
+ const elicit_result = parse(ElicitResultSchema, result);
4901
+ let validated_result = schema6["~standard"].validate(
4902
+ elicit_result.content
4903
+ );
4904
+ if (validated_result instanceof Promise)
4905
+ validated_result = await validated_result;
4906
+ if (validated_result.issues) {
4907
+ throw new McpError(
4908
+ -32603,
4909
+ `Invalid elicitation result: ${JSON.stringify(validated_result.issues)}`
4910
+ );
4911
+ }
4912
+ return { ...elicit_result, content: validated_result.value };
4913
+ }
4914
+ /**
4915
+ * Request language model sampling from the client
4916
+ * @param {CreateMessageRequestParams} request
4917
+ * @returns {Promise<CreateMessageResult>}
4918
+ */
4919
+ async message(request) {
4920
+ if (!this.#client_capabilities?.sampling)
4921
+ throw new McpError(-32601, "Client doesn't support sampling");
4922
+ this.#lazyily_create_client();
4923
+ const validated_request = parse(
4924
+ CreateMessageRequestParamsSchema,
4925
+ request
4926
+ );
4927
+ const response = await this.#client?.request(
4928
+ "sampling/createMessage",
4929
+ validated_request,
4930
+ "standalone"
4931
+ );
4932
+ return parse(CreateMessageResultSchema, response);
4933
+ }
4934
+ /**
4935
+ * Send a progress notification to the client. This is useful for long-running operations where you want to inform the user about the progress.
4936
+ *
4937
+ * @param {number} progress The current progress value, it should be between 0 and total and should always increase
4938
+ * @param {number} [total] The total value, defaults to 1
4939
+ * @param {string} [message] An optional message to accompany the progress update
4940
+ */
4941
+ progress(progress, total = 1, message = void 0) {
4942
+ if (this.#progress_token != null) {
4943
+ this.#notify("notifications/progress", {
4944
+ progress,
4945
+ total,
4946
+ message,
4947
+ progressToken: this.#progress_token
4948
+ });
4949
+ }
4950
+ }
4951
+ /**
4952
+ * Log a message to the client if logging is enabled and the level is appropriate
4953
+ *
4954
+ * @param {LoggingLevel} level
4955
+ * @param {unknown} data
4956
+ * @param {string} [logger]
4957
+ */
4958
+ log(level, data, logger) {
4959
+ if (!this.#options.capabilities?.logging) {
4960
+ throw new McpError(
4961
+ -32601,
4962
+ "The server doesn't support logging, please enable it in capabilities"
4963
+ );
4964
+ }
4965
+ const current_session_level = this.#ctx_storage.getStore()?.sessionInfo?.logLevel ?? this.#options.logging?.default ?? "info";
4966
+ if (current_session_level && this.#should_log(level, current_session_level)) {
4967
+ this.#notify("notifications/message", {
4968
+ level,
4969
+ data,
4970
+ logger
4971
+ });
4972
+ }
4973
+ }
4974
+ /**
4975
+ * Check if a log message should be sent based on severity levels
4976
+ * @param {LoggingLevel} message_level
4977
+ * @param {LoggingLevel} session_level
4978
+ * @returns {boolean}
4979
+ */
4980
+ #should_log(message_level, session_level) {
4981
+ const levels = [
4982
+ "debug",
4983
+ "info",
4984
+ "notice",
4985
+ "warning",
4986
+ "error",
4987
+ "critical",
4988
+ "alert",
4989
+ "emergency"
4990
+ ];
4991
+ const message_severity = levels.indexOf(message_level);
4992
+ const session_severity = levels.indexOf(session_level);
4993
+ return message_severity >= session_severity;
4994
+ }
4995
+ };
858
4996
 
859
- // ../mcp-server/src/mcp/handlers/tools/list-components.ts
860
- import { tool } from "tmcp/utils";
4997
+ // ../mcp-server/src/mcp/handlers/tools/index.ts
4998
+ var tools_exports = {};
4999
+ __export(tools_exports, {
5000
+ get_component: () => get_component,
5001
+ get_component_demo: () => get_component_demo,
5002
+ get_utils: () => get_utils,
5003
+ list_components: () => list_components,
5004
+ list_exports: () => list_exports,
5005
+ search_components: () => search_components
5006
+ });
5007
+
5008
+ // ../../node_modules/.pnpm/tmcp@1.19.4_typescript@5.9.3/node_modules/tmcp/src/utils/index.js
5009
+ var tool = {
5010
+ /**
5011
+ * @param {string} text
5012
+ */
5013
+ text(text) {
5014
+ return {
5015
+ content: [
5016
+ {
5017
+ type: (
5018
+ /** @type {const} */
5019
+ "text"
5020
+ ),
5021
+ text
5022
+ }
5023
+ ]
5024
+ };
5025
+ },
5026
+ /**
5027
+ * @param {string} text
5028
+ */
5029
+ error(text) {
5030
+ return {
5031
+ isError: true,
5032
+ content: [
5033
+ {
5034
+ type: (
5035
+ /** @type {const} */
5036
+ "text"
5037
+ ),
5038
+ text
5039
+ }
5040
+ ]
5041
+ };
5042
+ },
5043
+ /**
5044
+ * @param {"audio" | "image"} type
5045
+ * @param {string} data
5046
+ * @param {string} mime_type
5047
+ */
5048
+ media(type, data, mime_type) {
5049
+ return {
5050
+ content: [
5051
+ {
5052
+ type,
5053
+ data,
5054
+ mimeType: mime_type
5055
+ }
5056
+ ]
5057
+ };
5058
+ },
5059
+ /**
5060
+ * @param {EmbeddedResource["resource"]} resource
5061
+ */
5062
+ resource(resource) {
5063
+ return {
5064
+ content: [
5065
+ {
5066
+ type: (
5067
+ /** @type {const} */
5068
+ "resource"
5069
+ ),
5070
+ resource
5071
+ }
5072
+ ]
5073
+ };
5074
+ },
5075
+ /**
5076
+ * @param {Omit<ResourceLink, "type">} resource_link
5077
+ */
5078
+ resourceLink(resource_link) {
5079
+ return {
5080
+ content: [
5081
+ {
5082
+ type: (
5083
+ /** @type {const} */
5084
+ "resource_link"
5085
+ ),
5086
+ ...resource_link
5087
+ }
5088
+ ]
5089
+ };
5090
+ },
5091
+ /**
5092
+ * @template {Record<string, unknown>} T
5093
+ * @param {T} obj
5094
+ */
5095
+ structured(obj) {
5096
+ return (
5097
+ /** @type {const} */
5098
+ {
5099
+ content: [
5100
+ {
5101
+ type: "text",
5102
+ text: JSON.stringify(obj)
5103
+ }
5104
+ ],
5105
+ structuredContent: obj
5106
+ }
5107
+ );
5108
+ },
5109
+ /**
5110
+ * @template {Record<string, unknown> | undefined} [T=undefined]
5111
+ * @param {Array<CallToolResult<undefined>>} results
5112
+ * @param {T} [obj]
5113
+ */
5114
+ mix(results, obj) {
5115
+ return (
5116
+ /** @type {CallToolResult<T>} */
5117
+ {
5118
+ isError: results.some((r) => r.isError),
5119
+ content: results.flatMap((r) => r.content ? r.content : []),
5120
+ structuredContent: obj
5121
+ }
5122
+ );
5123
+ }
5124
+ };
861
5125
 
862
5126
  // ../mcp-server/src/constants.ts
863
5127
  import { resolve } from "path";
@@ -977,7 +5241,6 @@ function list_components(server2) {
977
5241
  }
978
5242
 
979
5243
  // ../mcp-server/src/mcp/handlers/tools/get-component.ts
980
- import { tool as tool2 } from "tmcp/utils";
981
5244
  var schema2 = object({
982
5245
  name: pipe(
983
5246
  string(),
@@ -1005,13 +5268,13 @@ function get_component(server2) {
1005
5268
  const similar = all.filter(
1006
5269
  (c) => c.name.toLowerCase().includes(needle) || needle.includes(c.name.toLowerCase())
1007
5270
  ).map((c) => `${c.name} (${c.category})`).slice(0, 5).join(", ");
1008
- return tool2.text(
5271
+ return tool.text(
1009
5272
  `Component '${name}' not found.${similar ? ` Similar: ${similar}` : " Use alus_list_components to browse."}`
1010
5273
  );
1011
5274
  }
1012
5275
  const entry = matches[0];
1013
5276
  const src = await read_component_source(entry);
1014
- return tool2.text(
5277
+ return tool.text(
1015
5278
  truncate(
1016
5279
  `# ${entry.name} (${entry.category})
1017
5280
 
@@ -1020,14 +5283,13 @@ ${src}`,
1020
5283
  )
1021
5284
  );
1022
5285
  } catch (e) {
1023
- return tool2.error(e.message);
5286
+ return tool.error(e.message);
1024
5287
  }
1025
5288
  }
1026
5289
  );
1027
5290
  }
1028
5291
 
1029
5292
  // ../mcp-server/src/mcp/handlers/tools/search-components.ts
1030
- import { tool as tool3 } from "tmcp/utils";
1031
5293
  import { readFile as readFile2 } from "fs/promises";
1032
5294
  var schema3 = object({
1033
5295
  query: pipe(string(), minLength(2), description("Case-insensitive search string")),
@@ -1071,9 +5333,9 @@ function search_components(server2) {
1071
5333
  }
1072
5334
  }
1073
5335
  }
1074
- if (!hits.length) return tool3.text(`No results for '${query}'.`);
5336
+ if (!hits.length) return tool.text(`No results for '${query}'.`);
1075
5337
  if (response_format === "json") {
1076
- return tool3.text(JSON.stringify({ query, total: hits.length, hits }, null, 2));
5338
+ return tool.text(JSON.stringify({ query, total: hits.length, hits }, null, 2));
1077
5339
  }
1078
5340
  const lines = [`# Search: '${query}' \u2014 ${hits.length} hit(s)`, ""];
1079
5341
  for (const h of hits) {
@@ -1085,16 +5347,15 @@ function search_components(server2) {
1085
5347
  ""
1086
5348
  );
1087
5349
  }
1088
- return tool3.text(truncate(lines.join("\n"), "Narrow with category or a more specific query."));
5350
+ return tool.text(truncate(lines.join("\n"), "Narrow with category or a more specific query."));
1089
5351
  } catch (e) {
1090
- return tool3.error(e.message);
5352
+ return tool.error(e.message);
1091
5353
  }
1092
5354
  }
1093
5355
  );
1094
5356
  }
1095
5357
 
1096
5358
  // ../mcp-server/src/mcp/handlers/tools/get-component-demo.ts
1097
- import { tool as tool4 } from "tmcp/utils";
1098
5359
  import { readFile as readFile3, readdir as readdir2 } from "fs/promises";
1099
5360
  var schema4 = object({
1100
5361
  name: pipe(
@@ -1123,9 +5384,9 @@ function get_component_demo(server2) {
1123
5384
  } catch {
1124
5385
  }
1125
5386
  const hint = available.length ? ` Available: ${available.slice(0, 10).join(", ")}${available.length > 10 ? "\u2026" : ""}` : "";
1126
- return tool4.text(`Demo not found for '${name}'.${hint}`);
5387
+ return tool.text(`Demo not found for '${name}'.${hint}`);
1127
5388
  }
1128
- return tool4.text(
5389
+ return tool.text(
1129
5390
  truncate(
1130
5391
  `# Demo: ${name}
1131
5392
  \`\`\`svelte
@@ -1135,14 +5396,13 @@ ${content}
1135
5396
  )
1136
5397
  );
1137
5398
  } catch (e) {
1138
- return tool4.error(e.message);
5399
+ return tool.error(e.message);
1139
5400
  }
1140
5401
  }
1141
5402
  );
1142
5403
  }
1143
5404
 
1144
5405
  // ../mcp-server/src/mcp/handlers/tools/list-exports.ts
1145
- import { tool as tool5 } from "tmcp/utils";
1146
5406
  import { readFile as readFile4 } from "fs/promises";
1147
5407
  function list_exports(server2) {
1148
5408
  server2.tool(
@@ -1154,18 +5414,17 @@ function list_exports(server2) {
1154
5414
  async () => {
1155
5415
  try {
1156
5416
  const content = await readFile4(`${COMPONENTS_DIR}/index.ts`, "utf-8");
1157
- return tool5.text(`\`\`\`typescript
5417
+ return tool.text(`\`\`\`typescript
1158
5418
  ${content}
1159
5419
  \`\`\``);
1160
5420
  } catch (e) {
1161
- return tool5.error(e.message);
5421
+ return tool.error(e.message);
1162
5422
  }
1163
5423
  }
1164
5424
  );
1165
5425
  }
1166
5426
 
1167
5427
  // ../mcp-server/src/mcp/handlers/tools/get-utils.ts
1168
- import { tool as tool6 } from "tmcp/utils";
1169
5428
  import { readFile as readFile5 } from "fs/promises";
1170
5429
  var MODULES = ["aria", "focus", "id", "keyboard", "index", "form/state"];
1171
5430
  var schema5 = object({
@@ -1183,11 +5442,11 @@ function get_utils(server2) {
1183
5442
  try {
1184
5443
  const path = module === "index" ? `${UTILS_ROOT}/a11y/index.ts` : module === "form/state" ? `${UTILS_ROOT}/form/state.ts` : `${UTILS_ROOT}/a11y/${module}.ts`;
1185
5444
  const content = await readFile5(path, "utf-8");
1186
- return tool6.text(`\`\`\`typescript
5445
+ return tool.text(`\`\`\`typescript
1187
5446
  ${content}
1188
5447
  \`\`\``);
1189
5448
  } catch (e) {
1190
- return tool6.error(e.message);
5449
+ return tool.error(e.message);
1191
5450
  }
1192
5451
  }
1193
5452
  );
@@ -1195,8 +5454,8 @@ ${content}
1195
5454
 
1196
5455
  // ../mcp-server/src/mcp/handlers/index.ts
1197
5456
  function setup_tools(server2) {
1198
- for (const tool7 in tools_exports) {
1199
- tools_exports[tool7](server2);
5457
+ for (const tool2 in tools_exports) {
5458
+ tools_exports[tool2](server2);
1200
5459
  }
1201
5460
  }
1202
5461
 
@@ -1215,7 +5474,128 @@ var server = new McpServer(
1215
5474
  ).withContext();
1216
5475
  setup_tools(server);
1217
5476
 
5477
+ // ../../node_modules/.pnpm/@tmcp+transport-stdio@0.4.3_tmcp@1.19.4_typescript@6.0.3_/node_modules/@tmcp/transport-stdio/src/index.js
5478
+ import process2 from "process";
5479
+ var StdioTransport = class {
5480
+ /**
5481
+ * @type {McpServer<any, TCustom>}
5482
+ */
5483
+ #server;
5484
+ /**
5485
+ * @type {Set<() => void>}
5486
+ */
5487
+ #cleaners = /* @__PURE__ */ new Set();
5488
+ /**
5489
+ * @type {NonNullable<Partial<Context["sessionInfo"]>>}
5490
+ */
5491
+ #session_info = {};
5492
+ /**
5493
+ * @type {Subscriptions}
5494
+ */
5495
+ #subscriptions = {
5496
+ resource: []
5497
+ };
5498
+ /**
5499
+ *
5500
+ * @param {McpServer<any, TCustom>} server
5501
+ */
5502
+ constructor(server2) {
5503
+ this.#server = server2;
5504
+ this.#cleaners.add(
5505
+ this.#server.on("initialize", ({ capabilities, clientInfo }) => {
5506
+ this.#session_info.clientCapabilities = capabilities;
5507
+ this.#session_info.clientInfo = clientInfo;
5508
+ this.#cleaners.add(
5509
+ this.#server.on("send", ({ request }) => {
5510
+ process2.stdout.write(JSON.stringify(request) + "\n");
5511
+ })
5512
+ );
5513
+ this.#cleaners.add(
5514
+ this.#server.on("broadcast", ({ request }) => {
5515
+ if (request.method === "notifications/resources/updated" && !this.#subscriptions.resource.includes(
5516
+ request.params.uri
5517
+ )) {
5518
+ return;
5519
+ }
5520
+ process2.stdout.write(JSON.stringify(request) + "\n");
5521
+ })
5522
+ );
5523
+ this.#cleaners.add(
5524
+ this.#server.on("loglevelchange", ({ level }) => {
5525
+ this.#session_info.logLevel = level;
5526
+ })
5527
+ );
5528
+ this.#cleaners.add(
5529
+ this.#server.on("subscription", ({ uri, action }) => {
5530
+ this.#subscriptions ??= {
5531
+ resource: []
5532
+ };
5533
+ if (action === "remove") {
5534
+ this.#subscriptions.resource = this.#subscriptions.resource?.filter(
5535
+ (item) => item !== uri
5536
+ );
5537
+ } else {
5538
+ this.#subscriptions.resource?.push(uri);
5539
+ }
5540
+ })
5541
+ );
5542
+ })
5543
+ );
5544
+ }
5545
+ #close() {
5546
+ for (const cleaner of this.#cleaners) {
5547
+ cleaner();
5548
+ }
5549
+ process2.exit(0);
5550
+ }
5551
+ /**
5552
+ * @param {TCustom} [ctx]
5553
+ */
5554
+ listen(ctx) {
5555
+ process2.stdin.setEncoding("utf8");
5556
+ let buffer = "";
5557
+ process2.stdin.on("data", async (chunk) => {
5558
+ buffer += chunk;
5559
+ const lines = buffer.split("\n");
5560
+ buffer = lines.pop() || "";
5561
+ for (const line of lines) {
5562
+ if (line.trim()) {
5563
+ try {
5564
+ const message = JSON.parse(line);
5565
+ const is_init = message.method === "initialize";
5566
+ const session_info = is_init ? {
5567
+ clientCapabilities: message.params?.capabilities,
5568
+ clientInfo: message.params?.clientInfo
5569
+ } : this.#session_info;
5570
+ const response = await this.#server.receive(message, {
5571
+ custom: ctx,
5572
+ sessionInfo: (
5573
+ /** @type {Context["sessionInfo"]} */
5574
+ session_info
5575
+ )
5576
+ });
5577
+ if (response) {
5578
+ process2.stdout.write(
5579
+ JSON.stringify(response) + "\n"
5580
+ );
5581
+ }
5582
+ } catch {
5583
+ }
5584
+ }
5585
+ }
5586
+ });
5587
+ process2.stdin.on("end", () => {
5588
+ this.#close();
5589
+ });
5590
+ process2.on("SIGINT", () => {
5591
+ this.#close();
5592
+ });
5593
+ process2.on("SIGTERM", () => {
5594
+ this.#close();
5595
+ });
5596
+ }
5597
+ };
5598
+
1218
5599
  // src/index.ts
1219
- import { StdioTransport } from "@tmcp/transport-stdio";
1220
5600
  var transport = new StdioTransport(server);
1221
5601
  transport.listen();