@mcp-use/cli 2.5.6 → 2.6.0-canary.10

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.cjs ADDED
@@ -0,0 +1,4087 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3_yaml@2.8.1/node_modules/tsup/assets/cjs_shims.js
27
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
28
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
29
+
30
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
31
+ var ANSI_BACKGROUND_OFFSET = 10;
32
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
33
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
34
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
35
+ var styles = {
36
+ modifier: {
37
+ reset: [0, 0],
38
+ // 21 isn't widely supported and 22 does the same thing
39
+ bold: [1, 22],
40
+ dim: [2, 22],
41
+ italic: [3, 23],
42
+ underline: [4, 24],
43
+ overline: [53, 55],
44
+ inverse: [7, 27],
45
+ hidden: [8, 28],
46
+ strikethrough: [9, 29]
47
+ },
48
+ color: {
49
+ black: [30, 39],
50
+ red: [31, 39],
51
+ green: [32, 39],
52
+ yellow: [33, 39],
53
+ blue: [34, 39],
54
+ magenta: [35, 39],
55
+ cyan: [36, 39],
56
+ white: [37, 39],
57
+ // Bright color
58
+ blackBright: [90, 39],
59
+ gray: [90, 39],
60
+ // Alias of `blackBright`
61
+ grey: [90, 39],
62
+ // Alias of `blackBright`
63
+ redBright: [91, 39],
64
+ greenBright: [92, 39],
65
+ yellowBright: [93, 39],
66
+ blueBright: [94, 39],
67
+ magentaBright: [95, 39],
68
+ cyanBright: [96, 39],
69
+ whiteBright: [97, 39]
70
+ },
71
+ bgColor: {
72
+ bgBlack: [40, 49],
73
+ bgRed: [41, 49],
74
+ bgGreen: [42, 49],
75
+ bgYellow: [43, 49],
76
+ bgBlue: [44, 49],
77
+ bgMagenta: [45, 49],
78
+ bgCyan: [46, 49],
79
+ bgWhite: [47, 49],
80
+ // Bright color
81
+ bgBlackBright: [100, 49],
82
+ bgGray: [100, 49],
83
+ // Alias of `bgBlackBright`
84
+ bgGrey: [100, 49],
85
+ // Alias of `bgBlackBright`
86
+ bgRedBright: [101, 49],
87
+ bgGreenBright: [102, 49],
88
+ bgYellowBright: [103, 49],
89
+ bgBlueBright: [104, 49],
90
+ bgMagentaBright: [105, 49],
91
+ bgCyanBright: [106, 49],
92
+ bgWhiteBright: [107, 49]
93
+ }
94
+ };
95
+ var modifierNames = Object.keys(styles.modifier);
96
+ var foregroundColorNames = Object.keys(styles.color);
97
+ var backgroundColorNames = Object.keys(styles.bgColor);
98
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
99
+ function assembleStyles() {
100
+ const codes = /* @__PURE__ */ new Map();
101
+ for (const [groupName, group] of Object.entries(styles)) {
102
+ for (const [styleName, style] of Object.entries(group)) {
103
+ styles[styleName] = {
104
+ open: `\x1B[${style[0]}m`,
105
+ close: `\x1B[${style[1]}m`
106
+ };
107
+ group[styleName] = styles[styleName];
108
+ codes.set(style[0], style[1]);
109
+ }
110
+ Object.defineProperty(styles, groupName, {
111
+ value: group,
112
+ enumerable: false
113
+ });
114
+ }
115
+ Object.defineProperty(styles, "codes", {
116
+ value: codes,
117
+ enumerable: false
118
+ });
119
+ styles.color.close = "\x1B[39m";
120
+ styles.bgColor.close = "\x1B[49m";
121
+ styles.color.ansi = wrapAnsi16();
122
+ styles.color.ansi256 = wrapAnsi256();
123
+ styles.color.ansi16m = wrapAnsi16m();
124
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
125
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
126
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
127
+ Object.defineProperties(styles, {
128
+ rgbToAnsi256: {
129
+ value(red, green, blue) {
130
+ if (red === green && green === blue) {
131
+ if (red < 8) {
132
+ return 16;
133
+ }
134
+ if (red > 248) {
135
+ return 231;
136
+ }
137
+ return Math.round((red - 8) / 247 * 24) + 232;
138
+ }
139
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
140
+ },
141
+ enumerable: false
142
+ },
143
+ hexToRgb: {
144
+ value(hex) {
145
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
146
+ if (!matches) {
147
+ return [0, 0, 0];
148
+ }
149
+ let [colorString] = matches;
150
+ if (colorString.length === 3) {
151
+ colorString = [...colorString].map((character) => character + character).join("");
152
+ }
153
+ const integer = Number.parseInt(colorString, 16);
154
+ return [
155
+ /* eslint-disable no-bitwise */
156
+ integer >> 16 & 255,
157
+ integer >> 8 & 255,
158
+ integer & 255
159
+ /* eslint-enable no-bitwise */
160
+ ];
161
+ },
162
+ enumerable: false
163
+ },
164
+ hexToAnsi256: {
165
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
166
+ enumerable: false
167
+ },
168
+ ansi256ToAnsi: {
169
+ value(code) {
170
+ if (code < 8) {
171
+ return 30 + code;
172
+ }
173
+ if (code < 16) {
174
+ return 90 + (code - 8);
175
+ }
176
+ let red;
177
+ let green;
178
+ let blue;
179
+ if (code >= 232) {
180
+ red = ((code - 232) * 10 + 8) / 255;
181
+ green = red;
182
+ blue = red;
183
+ } else {
184
+ code -= 16;
185
+ const remainder = code % 36;
186
+ red = Math.floor(code / 36) / 5;
187
+ green = Math.floor(remainder / 6) / 5;
188
+ blue = remainder % 6 / 5;
189
+ }
190
+ const value = Math.max(red, green, blue) * 2;
191
+ if (value === 0) {
192
+ return 30;
193
+ }
194
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
195
+ if (value === 2) {
196
+ result += 60;
197
+ }
198
+ return result;
199
+ },
200
+ enumerable: false
201
+ },
202
+ rgbToAnsi: {
203
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
204
+ enumerable: false
205
+ },
206
+ hexToAnsi: {
207
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
208
+ enumerable: false
209
+ }
210
+ });
211
+ return styles;
212
+ }
213
+ var ansiStyles = assembleStyles();
214
+ var ansi_styles_default = ansiStyles;
215
+
216
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/supports-color/index.js
217
+ var import_node_process = __toESM(require("process"), 1);
218
+ var import_node_os = __toESM(require("os"), 1);
219
+ var import_node_tty = __toESM(require("tty"), 1);
220
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
221
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
222
+ const position = argv.indexOf(prefix + flag);
223
+ const terminatorPosition = argv.indexOf("--");
224
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
225
+ }
226
+ var { env } = import_node_process.default;
227
+ var flagForceColor;
228
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
229
+ flagForceColor = 0;
230
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
231
+ flagForceColor = 1;
232
+ }
233
+ function envForceColor() {
234
+ if ("FORCE_COLOR" in env) {
235
+ if (env.FORCE_COLOR === "true") {
236
+ return 1;
237
+ }
238
+ if (env.FORCE_COLOR === "false") {
239
+ return 0;
240
+ }
241
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
242
+ }
243
+ }
244
+ function translateLevel(level) {
245
+ if (level === 0) {
246
+ return false;
247
+ }
248
+ return {
249
+ level,
250
+ hasBasic: true,
251
+ has256: level >= 2,
252
+ has16m: level >= 3
253
+ };
254
+ }
255
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
256
+ const noFlagForceColor = envForceColor();
257
+ if (noFlagForceColor !== void 0) {
258
+ flagForceColor = noFlagForceColor;
259
+ }
260
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
261
+ if (forceColor === 0) {
262
+ return 0;
263
+ }
264
+ if (sniffFlags) {
265
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
266
+ return 3;
267
+ }
268
+ if (hasFlag("color=256")) {
269
+ return 2;
270
+ }
271
+ }
272
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
273
+ return 1;
274
+ }
275
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
276
+ return 0;
277
+ }
278
+ const min = forceColor || 0;
279
+ if (env.TERM === "dumb") {
280
+ return min;
281
+ }
282
+ if (import_node_process.default.platform === "win32") {
283
+ const osRelease = import_node_os.default.release().split(".");
284
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
285
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
286
+ }
287
+ return 1;
288
+ }
289
+ if ("CI" in env) {
290
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
291
+ return 3;
292
+ }
293
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
294
+ return 1;
295
+ }
296
+ return min;
297
+ }
298
+ if ("TEAMCITY_VERSION" in env) {
299
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
300
+ }
301
+ if (env.COLORTERM === "truecolor") {
302
+ return 3;
303
+ }
304
+ if (env.TERM === "xterm-kitty") {
305
+ return 3;
306
+ }
307
+ if (env.TERM === "xterm-ghostty") {
308
+ return 3;
309
+ }
310
+ if (env.TERM === "wezterm") {
311
+ return 3;
312
+ }
313
+ if ("TERM_PROGRAM" in env) {
314
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
315
+ switch (env.TERM_PROGRAM) {
316
+ case "iTerm.app": {
317
+ return version >= 3 ? 3 : 2;
318
+ }
319
+ case "Apple_Terminal": {
320
+ return 2;
321
+ }
322
+ }
323
+ }
324
+ if (/-256(color)?$/i.test(env.TERM)) {
325
+ return 2;
326
+ }
327
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
328
+ return 1;
329
+ }
330
+ if ("COLORTERM" in env) {
331
+ return 1;
332
+ }
333
+ return min;
334
+ }
335
+ function createSupportsColor(stream, options = {}) {
336
+ const level = _supportsColor(stream, {
337
+ streamIsTTY: stream && stream.isTTY,
338
+ ...options
339
+ });
340
+ return translateLevel(level);
341
+ }
342
+ var supportsColor = {
343
+ stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
344
+ stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
345
+ };
346
+ var supports_color_default = supportsColor;
347
+
348
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js
349
+ function stringReplaceAll(string, substring, replacer) {
350
+ let index = string.indexOf(substring);
351
+ if (index === -1) {
352
+ return string;
353
+ }
354
+ const substringLength = substring.length;
355
+ let endIndex = 0;
356
+ let returnValue = "";
357
+ do {
358
+ returnValue += string.slice(endIndex, index) + substring + replacer;
359
+ endIndex = index + substringLength;
360
+ index = string.indexOf(substring, endIndex);
361
+ } while (index !== -1);
362
+ returnValue += string.slice(endIndex);
363
+ return returnValue;
364
+ }
365
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
366
+ let endIndex = 0;
367
+ let returnValue = "";
368
+ do {
369
+ const gotCR = string[index - 1] === "\r";
370
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
371
+ endIndex = index + 1;
372
+ index = string.indexOf("\n", endIndex);
373
+ } while (index !== -1);
374
+ returnValue += string.slice(endIndex);
375
+ return returnValue;
376
+ }
377
+
378
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js
379
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
380
+ var GENERATOR = Symbol("GENERATOR");
381
+ var STYLER = Symbol("STYLER");
382
+ var IS_EMPTY = Symbol("IS_EMPTY");
383
+ var levelMapping = [
384
+ "ansi",
385
+ "ansi",
386
+ "ansi256",
387
+ "ansi16m"
388
+ ];
389
+ var styles2 = /* @__PURE__ */ Object.create(null);
390
+ var applyOptions = (object, options = {}) => {
391
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
392
+ throw new Error("The `level` option should be an integer from 0 to 3");
393
+ }
394
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
395
+ object.level = options.level === void 0 ? colorLevel : options.level;
396
+ };
397
+ var chalkFactory = (options) => {
398
+ const chalk2 = (...strings) => strings.join(" ");
399
+ applyOptions(chalk2, options);
400
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
401
+ return chalk2;
402
+ };
403
+ function createChalk(options) {
404
+ return chalkFactory(options);
405
+ }
406
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
407
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
408
+ styles2[styleName] = {
409
+ get() {
410
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
411
+ Object.defineProperty(this, styleName, { value: builder });
412
+ return builder;
413
+ }
414
+ };
415
+ }
416
+ styles2.visible = {
417
+ get() {
418
+ const builder = createBuilder(this, this[STYLER], true);
419
+ Object.defineProperty(this, "visible", { value: builder });
420
+ return builder;
421
+ }
422
+ };
423
+ var getModelAnsi = (model, level, type, ...arguments_) => {
424
+ if (model === "rgb") {
425
+ if (level === "ansi16m") {
426
+ return ansi_styles_default[type].ansi16m(...arguments_);
427
+ }
428
+ if (level === "ansi256") {
429
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
430
+ }
431
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
432
+ }
433
+ if (model === "hex") {
434
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
435
+ }
436
+ return ansi_styles_default[type][model](...arguments_);
437
+ };
438
+ var usedModels = ["rgb", "hex", "ansi256"];
439
+ for (const model of usedModels) {
440
+ styles2[model] = {
441
+ get() {
442
+ const { level } = this;
443
+ return function(...arguments_) {
444
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
445
+ return createBuilder(this, styler, this[IS_EMPTY]);
446
+ };
447
+ }
448
+ };
449
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
450
+ styles2[bgModel] = {
451
+ get() {
452
+ const { level } = this;
453
+ return function(...arguments_) {
454
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
455
+ return createBuilder(this, styler, this[IS_EMPTY]);
456
+ };
457
+ }
458
+ };
459
+ }
460
+ var proto = Object.defineProperties(() => {
461
+ }, {
462
+ ...styles2,
463
+ level: {
464
+ enumerable: true,
465
+ get() {
466
+ return this[GENERATOR].level;
467
+ },
468
+ set(level) {
469
+ this[GENERATOR].level = level;
470
+ }
471
+ }
472
+ });
473
+ var createStyler = (open2, close, parent) => {
474
+ let openAll;
475
+ let closeAll;
476
+ if (parent === void 0) {
477
+ openAll = open2;
478
+ closeAll = close;
479
+ } else {
480
+ openAll = parent.openAll + open2;
481
+ closeAll = close + parent.closeAll;
482
+ }
483
+ return {
484
+ open: open2,
485
+ close,
486
+ openAll,
487
+ closeAll,
488
+ parent
489
+ };
490
+ };
491
+ var createBuilder = (self, _styler, _isEmpty) => {
492
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
493
+ Object.setPrototypeOf(builder, proto);
494
+ builder[GENERATOR] = self;
495
+ builder[STYLER] = _styler;
496
+ builder[IS_EMPTY] = _isEmpty;
497
+ return builder;
498
+ };
499
+ var applyStyle = (self, string) => {
500
+ if (self.level <= 0 || !string) {
501
+ return self[IS_EMPTY] ? "" : string;
502
+ }
503
+ let styler = self[STYLER];
504
+ if (styler === void 0) {
505
+ return string;
506
+ }
507
+ const { openAll, closeAll } = styler;
508
+ if (string.includes("\x1B")) {
509
+ while (styler !== void 0) {
510
+ string = stringReplaceAll(string, styler.close, styler.open);
511
+ styler = styler.parent;
512
+ }
513
+ }
514
+ const lfIndex = string.indexOf("\n");
515
+ if (lfIndex !== -1) {
516
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
517
+ }
518
+ return openAll + string + closeAll;
519
+ };
520
+ Object.defineProperties(createChalk.prototype, styles2);
521
+ var chalk = createChalk();
522
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
523
+ var source_default = chalk;
524
+
525
+ // src/index.ts
526
+ var import_commander2 = require("commander");
527
+ var import_config4 = require("dotenv/config");
528
+ var import_node_child_process10 = require("child_process");
529
+ var import_node_fs7 = require("fs");
530
+ var import_promises5 = require("fs/promises");
531
+ var import_node_path5 = __toESM(require("path"), 1);
532
+
533
+ // ../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js
534
+ var import_node_process8 = __toESM(require("process"), 1);
535
+ var import_node_path = __toESM(require("path"), 1);
536
+ var import_node_url = require("url");
537
+ var import_node_child_process7 = __toESM(require("child_process"), 1);
538
+ var import_promises3 = __toESM(require("fs/promises"), 1);
539
+
540
+ // ../../node_modules/.pnpm/wsl-utils@0.3.0/node_modules/wsl-utils/index.js
541
+ var import_node_util2 = require("util");
542
+ var import_node_child_process2 = __toESM(require("child_process"), 1);
543
+ var import_promises2 = __toESM(require("fs/promises"), 1);
544
+
545
+ // ../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
546
+ var import_node_process2 = __toESM(require("process"), 1);
547
+ var import_node_os2 = __toESM(require("os"), 1);
548
+ var import_node_fs3 = __toESM(require("fs"), 1);
549
+
550
+ // ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
551
+ var import_node_fs2 = __toESM(require("fs"), 1);
552
+
553
+ // ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
554
+ var import_node_fs = __toESM(require("fs"), 1);
555
+ var isDockerCached;
556
+ function hasDockerEnv() {
557
+ try {
558
+ import_node_fs.default.statSync("/.dockerenv");
559
+ return true;
560
+ } catch {
561
+ return false;
562
+ }
563
+ }
564
+ function hasDockerCGroup() {
565
+ try {
566
+ return import_node_fs.default.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
567
+ } catch {
568
+ return false;
569
+ }
570
+ }
571
+ function isDocker() {
572
+ if (isDockerCached === void 0) {
573
+ isDockerCached = hasDockerEnv() || hasDockerCGroup();
574
+ }
575
+ return isDockerCached;
576
+ }
577
+
578
+ // ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
579
+ var cachedResult;
580
+ var hasContainerEnv = () => {
581
+ try {
582
+ import_node_fs2.default.statSync("/run/.containerenv");
583
+ return true;
584
+ } catch {
585
+ return false;
586
+ }
587
+ };
588
+ function isInsideContainer() {
589
+ if (cachedResult === void 0) {
590
+ cachedResult = hasContainerEnv() || isDocker();
591
+ }
592
+ return cachedResult;
593
+ }
594
+
595
+ // ../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
596
+ var isWsl = () => {
597
+ if (import_node_process2.default.platform !== "linux") {
598
+ return false;
599
+ }
600
+ if (import_node_os2.default.release().toLowerCase().includes("microsoft")) {
601
+ if (isInsideContainer()) {
602
+ return false;
603
+ }
604
+ return true;
605
+ }
606
+ try {
607
+ return import_node_fs3.default.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
608
+ } catch {
609
+ return false;
610
+ }
611
+ };
612
+ var is_wsl_default = import_node_process2.default.env.__IS_WSL_TEST__ ? isWsl : isWsl();
613
+
614
+ // ../../node_modules/.pnpm/powershell-utils@0.1.0/node_modules/powershell-utils/index.js
615
+ var import_node_process3 = __toESM(require("process"), 1);
616
+ var import_node_buffer = require("buffer");
617
+ var import_node_util = require("util");
618
+ var import_node_child_process = __toESM(require("child_process"), 1);
619
+ var import_promises = __toESM(require("fs/promises"), 1);
620
+ var execFile = (0, import_node_util.promisify)(import_node_child_process.default.execFile);
621
+ var powerShellPath = () => `${import_node_process3.default.env.SYSTEMROOT || import_node_process3.default.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
622
+ var executePowerShell = async (command, options = {}) => {
623
+ const {
624
+ powerShellPath: psPath,
625
+ ...execFileOptions
626
+ } = options;
627
+ const encodedCommand = executePowerShell.encodeCommand(command);
628
+ return execFile(
629
+ psPath ?? powerShellPath(),
630
+ [
631
+ ...executePowerShell.argumentsPrefix,
632
+ encodedCommand
633
+ ],
634
+ {
635
+ encoding: "utf8",
636
+ ...execFileOptions
637
+ }
638
+ );
639
+ };
640
+ executePowerShell.argumentsPrefix = [
641
+ "-NoProfile",
642
+ "-NonInteractive",
643
+ "-ExecutionPolicy",
644
+ "Bypass",
645
+ "-EncodedCommand"
646
+ ];
647
+ executePowerShell.encodeCommand = (command) => import_node_buffer.Buffer.from(command, "utf16le").toString("base64");
648
+ executePowerShell.escapeArgument = (value) => `'${String(value).replaceAll("'", "''")}'`;
649
+
650
+ // ../../node_modules/.pnpm/wsl-utils@0.3.0/node_modules/wsl-utils/index.js
651
+ var execFile2 = (0, import_node_util2.promisify)(import_node_child_process2.default.execFile);
652
+ var wslDrivesMountPoint = /* @__PURE__ */ (() => {
653
+ const defaultMountPoint = "/mnt/";
654
+ let mountPoint;
655
+ return async function() {
656
+ if (mountPoint) {
657
+ return mountPoint;
658
+ }
659
+ const configFilePath = "/etc/wsl.conf";
660
+ let isConfigFileExists = false;
661
+ try {
662
+ await import_promises2.default.access(configFilePath, import_promises2.constants.F_OK);
663
+ isConfigFileExists = true;
664
+ } catch {
665
+ }
666
+ if (!isConfigFileExists) {
667
+ return defaultMountPoint;
668
+ }
669
+ const configContent = await import_promises2.default.readFile(configFilePath, { encoding: "utf8" });
670
+ const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
671
+ if (!configMountPoint) {
672
+ return defaultMountPoint;
673
+ }
674
+ mountPoint = configMountPoint.groups.mountPoint.trim();
675
+ mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
676
+ return mountPoint;
677
+ };
678
+ })();
679
+ var powerShellPathFromWsl = async () => {
680
+ const mountPoint = await wslDrivesMountPoint();
681
+ return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
682
+ };
683
+ var powerShellPath2 = is_wsl_default ? powerShellPathFromWsl : powerShellPath;
684
+ var canAccessPowerShellPromise;
685
+ var canAccessPowerShell = async () => {
686
+ canAccessPowerShellPromise ??= (async () => {
687
+ try {
688
+ const psPath = await powerShellPath2();
689
+ await import_promises2.default.access(psPath, import_promises2.constants.X_OK);
690
+ return true;
691
+ } catch {
692
+ return false;
693
+ }
694
+ })();
695
+ return canAccessPowerShellPromise;
696
+ };
697
+ var wslDefaultBrowser = async () => {
698
+ const psPath = await powerShellPath2();
699
+ const command = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
700
+ const { stdout } = await executePowerShell(command, { powerShellPath: psPath });
701
+ return stdout.trim();
702
+ };
703
+ var convertWslPathToWindows = async (path5) => {
704
+ if (/^[a-z]+:\/\//i.test(path5)) {
705
+ return path5;
706
+ }
707
+ try {
708
+ const { stdout } = await execFile2("wslpath", ["-aw", path5], { encoding: "utf8" });
709
+ return stdout.trim();
710
+ } catch {
711
+ return path5;
712
+ }
713
+ };
714
+
715
+ // ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
716
+ function defineLazyProperty(object, propertyName, valueGetter) {
717
+ const define = (value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true });
718
+ Object.defineProperty(object, propertyName, {
719
+ configurable: true,
720
+ enumerable: true,
721
+ get() {
722
+ const result = valueGetter();
723
+ define(result);
724
+ return result;
725
+ },
726
+ set(value) {
727
+ define(value);
728
+ }
729
+ });
730
+ return object;
731
+ }
732
+
733
+ // ../../node_modules/.pnpm/default-browser@5.4.0/node_modules/default-browser/index.js
734
+ var import_node_util6 = require("util");
735
+ var import_node_process6 = __toESM(require("process"), 1);
736
+ var import_node_child_process6 = require("child_process");
737
+
738
+ // ../../node_modules/.pnpm/default-browser-id@5.0.0/node_modules/default-browser-id/index.js
739
+ var import_node_util3 = require("util");
740
+ var import_node_process4 = __toESM(require("process"), 1);
741
+ var import_node_child_process3 = require("child_process");
742
+ var execFileAsync = (0, import_node_util3.promisify)(import_node_child_process3.execFile);
743
+ async function defaultBrowserId() {
744
+ if (import_node_process4.default.platform !== "darwin") {
745
+ throw new Error("macOS only");
746
+ }
747
+ const { stdout } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
748
+ const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
749
+ return match?.groups.id ?? "com.apple.Safari";
750
+ }
751
+
752
+ // ../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js
753
+ var import_node_process5 = __toESM(require("process"), 1);
754
+ var import_node_util4 = require("util");
755
+ var import_node_child_process4 = require("child_process");
756
+ var execFileAsync2 = (0, import_node_util4.promisify)(import_node_child_process4.execFile);
757
+ async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
758
+ if (import_node_process5.default.platform !== "darwin") {
759
+ throw new Error("macOS only");
760
+ }
761
+ const outputArguments = humanReadableOutput ? [] : ["-ss"];
762
+ const execOptions = {};
763
+ if (signal) {
764
+ execOptions.signal = signal;
765
+ }
766
+ const { stdout } = await execFileAsync2("osascript", ["-e", script, outputArguments], execOptions);
767
+ return stdout.trim();
768
+ }
769
+
770
+ // ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
771
+ async function bundleName(bundleId) {
772
+ return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
773
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
774
+ }
775
+
776
+ // ../../node_modules/.pnpm/default-browser@5.4.0/node_modules/default-browser/windows.js
777
+ var import_node_util5 = require("util");
778
+ var import_node_child_process5 = require("child_process");
779
+ var execFileAsync3 = (0, import_node_util5.promisify)(import_node_child_process5.execFile);
780
+ var windowsBrowserProgIds = {
781
+ MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
782
+ // The missing `L` is correct.
783
+ MSEdgeBHTML: { name: "Edge Beta", id: "com.microsoft.edge.beta" },
784
+ MSEdgeDHTML: { name: "Edge Dev", id: "com.microsoft.edge.dev" },
785
+ AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
786
+ ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
787
+ ChromeBHTML: { name: "Chrome Beta", id: "com.google.chrome.beta" },
788
+ ChromeDHTML: { name: "Chrome Dev", id: "com.google.chrome.dev" },
789
+ ChromiumHTM: { name: "Chromium", id: "org.chromium.Chromium" },
790
+ BraveHTML: { name: "Brave", id: "com.brave.Browser" },
791
+ BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
792
+ BraveDHTML: { name: "Brave Dev", id: "com.brave.Browser.dev" },
793
+ BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" },
794
+ FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
795
+ OperaStable: { name: "Opera", id: "com.operasoftware.Opera" },
796
+ VivaldiHTM: { name: "Vivaldi", id: "com.vivaldi.Vivaldi" },
797
+ "IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" }
798
+ };
799
+ var _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
800
+ var UnknownBrowserError = class extends Error {
801
+ };
802
+ async function defaultBrowser(_execFileAsync = execFileAsync3) {
803
+ const { stdout } = await _execFileAsync("reg", [
804
+ "QUERY",
805
+ " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
806
+ "/v",
807
+ "ProgId"
808
+ ]);
809
+ const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
810
+ if (!match) {
811
+ throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
812
+ }
813
+ const { id } = match.groups;
814
+ const browser = windowsBrowserProgIds[id];
815
+ if (!browser) {
816
+ throw new UnknownBrowserError(`Unknown browser ID: ${id}`);
817
+ }
818
+ return browser;
819
+ }
820
+
821
+ // ../../node_modules/.pnpm/default-browser@5.4.0/node_modules/default-browser/index.js
822
+ var execFileAsync4 = (0, import_node_util6.promisify)(import_node_child_process6.execFile);
823
+ var titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
824
+ async function defaultBrowser2() {
825
+ if (import_node_process6.default.platform === "darwin") {
826
+ const id = await defaultBrowserId();
827
+ const name = await bundleName(id);
828
+ return { name, id };
829
+ }
830
+ if (import_node_process6.default.platform === "linux") {
831
+ const { stdout } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
832
+ const id = stdout.trim();
833
+ const name = titleize(id.replace(/.desktop$/, "").replace("-", " "));
834
+ return { name, id };
835
+ }
836
+ if (import_node_process6.default.platform === "win32") {
837
+ return defaultBrowser();
838
+ }
839
+ throw new Error("Only macOS, Linux, and Windows are supported");
840
+ }
841
+
842
+ // ../../node_modules/.pnpm/is-in-ssh@1.0.0/node_modules/is-in-ssh/index.js
843
+ var import_node_process7 = __toESM(require("process"), 1);
844
+ var isInSsh = Boolean(import_node_process7.default.env.SSH_CONNECTION || import_node_process7.default.env.SSH_CLIENT || import_node_process7.default.env.SSH_TTY);
845
+ var is_in_ssh_default = isInSsh;
846
+
847
+ // ../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js
848
+ var fallbackAttemptSymbol = Symbol("fallbackAttempt");
849
+ var __dirname2 = importMetaUrl ? import_node_path.default.dirname((0, import_node_url.fileURLToPath)(importMetaUrl)) : "";
850
+ var localXdgOpenPath = import_node_path.default.join(__dirname2, "xdg-open");
851
+ var { platform, arch } = import_node_process8.default;
852
+ var tryEachApp = async (apps2, opener) => {
853
+ if (apps2.length === 0) {
854
+ return;
855
+ }
856
+ const errors = [];
857
+ for (const app of apps2) {
858
+ try {
859
+ return await opener(app);
860
+ } catch (error) {
861
+ errors.push(error);
862
+ }
863
+ }
864
+ throw new AggregateError(errors, "Failed to open in all supported apps");
865
+ };
866
+ var baseOpen = async (options) => {
867
+ options = {
868
+ wait: false,
869
+ background: false,
870
+ newInstance: false,
871
+ allowNonzeroExitCode: false,
872
+ ...options
873
+ };
874
+ const isFallbackAttempt = options[fallbackAttemptSymbol] === true;
875
+ delete options[fallbackAttemptSymbol];
876
+ if (Array.isArray(options.app)) {
877
+ return tryEachApp(options.app, (singleApp) => baseOpen({
878
+ ...options,
879
+ app: singleApp,
880
+ [fallbackAttemptSymbol]: true
881
+ }));
882
+ }
883
+ let { name: app, arguments: appArguments = [] } = options.app ?? {};
884
+ appArguments = [...appArguments];
885
+ if (Array.isArray(app)) {
886
+ return tryEachApp(app, (appName) => baseOpen({
887
+ ...options,
888
+ app: {
889
+ name: appName,
890
+ arguments: appArguments
891
+ },
892
+ [fallbackAttemptSymbol]: true
893
+ }));
894
+ }
895
+ if (app === "browser" || app === "browserPrivate") {
896
+ const ids = {
897
+ "com.google.chrome": "chrome",
898
+ "google-chrome.desktop": "chrome",
899
+ "com.brave.browser": "brave",
900
+ "org.mozilla.firefox": "firefox",
901
+ "firefox.desktop": "firefox",
902
+ "com.microsoft.msedge": "edge",
903
+ "com.microsoft.edge": "edge",
904
+ "com.microsoft.edgemac": "edge",
905
+ "microsoft-edge.desktop": "edge",
906
+ "com.apple.safari": "safari"
907
+ };
908
+ const flags = {
909
+ chrome: "--incognito",
910
+ brave: "--incognito",
911
+ firefox: "--private-window",
912
+ edge: "--inPrivate"
913
+ // Safari doesn't support private mode via command line
914
+ };
915
+ let browser;
916
+ if (is_wsl_default) {
917
+ const progId = await wslDefaultBrowser();
918
+ const browserInfo = _windowsBrowserProgIdMap.get(progId);
919
+ browser = browserInfo ?? {};
920
+ } else {
921
+ browser = await defaultBrowser2();
922
+ }
923
+ if (browser.id in ids) {
924
+ const browserName = ids[browser.id.toLowerCase()];
925
+ if (app === "browserPrivate") {
926
+ if (browserName === "safari") {
927
+ throw new Error("Safari doesn't support opening in private mode via command line");
928
+ }
929
+ appArguments.push(flags[browserName]);
930
+ }
931
+ return baseOpen({
932
+ ...options,
933
+ app: {
934
+ name: apps[browserName],
935
+ arguments: appArguments
936
+ }
937
+ });
938
+ }
939
+ throw new Error(`${browser.name} is not supported as a default browser`);
940
+ }
941
+ let command;
942
+ const cliArguments = [];
943
+ const childProcessOptions = {};
944
+ let shouldUseWindowsInWsl = false;
945
+ if (is_wsl_default && !isInsideContainer() && !is_in_ssh_default && !app) {
946
+ shouldUseWindowsInWsl = await canAccessPowerShell();
947
+ }
948
+ if (platform === "darwin") {
949
+ command = "open";
950
+ if (options.wait) {
951
+ cliArguments.push("--wait-apps");
952
+ }
953
+ if (options.background) {
954
+ cliArguments.push("--background");
955
+ }
956
+ if (options.newInstance) {
957
+ cliArguments.push("--new");
958
+ }
959
+ if (app) {
960
+ cliArguments.push("-a", app);
961
+ }
962
+ } else if (platform === "win32" || shouldUseWindowsInWsl) {
963
+ command = await powerShellPath2();
964
+ cliArguments.push(...executePowerShell.argumentsPrefix);
965
+ if (!is_wsl_default) {
966
+ childProcessOptions.windowsVerbatimArguments = true;
967
+ }
968
+ if (is_wsl_default && options.target) {
969
+ options.target = await convertWslPathToWindows(options.target);
970
+ }
971
+ const encodedArguments = ["$ProgressPreference = 'SilentlyContinue';", "Start"];
972
+ if (options.wait) {
973
+ encodedArguments.push("-Wait");
974
+ }
975
+ if (app) {
976
+ encodedArguments.push(executePowerShell.escapeArgument(app));
977
+ if (options.target) {
978
+ appArguments.push(options.target);
979
+ }
980
+ } else if (options.target) {
981
+ encodedArguments.push(executePowerShell.escapeArgument(options.target));
982
+ }
983
+ if (appArguments.length > 0) {
984
+ appArguments = appArguments.map((argument) => executePowerShell.escapeArgument(argument));
985
+ encodedArguments.push("-ArgumentList", appArguments.join(","));
986
+ }
987
+ options.target = executePowerShell.encodeCommand(encodedArguments.join(" "));
988
+ if (!options.wait) {
989
+ childProcessOptions.stdio = "ignore";
990
+ }
991
+ } else {
992
+ if (app) {
993
+ command = app;
994
+ } else {
995
+ const isBundled = !__dirname2 || __dirname2 === "/";
996
+ let exeLocalXdgOpen = false;
997
+ try {
998
+ await import_promises3.default.access(localXdgOpenPath, import_promises3.constants.X_OK);
999
+ exeLocalXdgOpen = true;
1000
+ } catch {
1001
+ }
1002
+ const useSystemXdgOpen = import_node_process8.default.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen);
1003
+ command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
1004
+ }
1005
+ if (appArguments.length > 0) {
1006
+ cliArguments.push(...appArguments);
1007
+ }
1008
+ if (!options.wait) {
1009
+ childProcessOptions.stdio = "ignore";
1010
+ childProcessOptions.detached = true;
1011
+ }
1012
+ }
1013
+ if (platform === "darwin" && appArguments.length > 0) {
1014
+ cliArguments.push("--args", ...appArguments);
1015
+ }
1016
+ if (options.target) {
1017
+ cliArguments.push(options.target);
1018
+ }
1019
+ const subprocess = import_node_child_process7.default.spawn(command, cliArguments, childProcessOptions);
1020
+ if (options.wait) {
1021
+ return new Promise((resolve, reject) => {
1022
+ subprocess.once("error", reject);
1023
+ subprocess.once("close", (exitCode) => {
1024
+ if (!options.allowNonzeroExitCode && exitCode !== 0) {
1025
+ reject(new Error(`Exited with code ${exitCode}`));
1026
+ return;
1027
+ }
1028
+ resolve(subprocess);
1029
+ });
1030
+ });
1031
+ }
1032
+ if (isFallbackAttempt) {
1033
+ return new Promise((resolve, reject) => {
1034
+ subprocess.once("error", reject);
1035
+ subprocess.once("spawn", () => {
1036
+ subprocess.once("close", (exitCode) => {
1037
+ subprocess.off("error", reject);
1038
+ if (exitCode !== 0) {
1039
+ reject(new Error(`Exited with code ${exitCode}`));
1040
+ return;
1041
+ }
1042
+ subprocess.unref();
1043
+ resolve(subprocess);
1044
+ });
1045
+ });
1046
+ });
1047
+ }
1048
+ subprocess.unref();
1049
+ return new Promise((resolve, reject) => {
1050
+ subprocess.once("error", reject);
1051
+ subprocess.once("spawn", () => {
1052
+ subprocess.off("error", reject);
1053
+ resolve(subprocess);
1054
+ });
1055
+ });
1056
+ };
1057
+ var open = (target, options) => {
1058
+ if (typeof target !== "string") {
1059
+ throw new TypeError("Expected a `target`");
1060
+ }
1061
+ return baseOpen({
1062
+ ...options,
1063
+ target
1064
+ });
1065
+ };
1066
+ function detectArchBinary(binary) {
1067
+ if (typeof binary === "string" || Array.isArray(binary)) {
1068
+ return binary;
1069
+ }
1070
+ const { [arch]: archBinary } = binary;
1071
+ if (!archBinary) {
1072
+ throw new Error(`${arch} is not supported`);
1073
+ }
1074
+ return archBinary;
1075
+ }
1076
+ function detectPlatformBinary({ [platform]: platformBinary }, { wsl } = {}) {
1077
+ if (wsl && is_wsl_default) {
1078
+ return detectArchBinary(wsl);
1079
+ }
1080
+ if (!platformBinary) {
1081
+ throw new Error(`${platform} is not supported`);
1082
+ }
1083
+ return detectArchBinary(platformBinary);
1084
+ }
1085
+ var apps = {
1086
+ browser: "browser",
1087
+ browserPrivate: "browserPrivate"
1088
+ };
1089
+ defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
1090
+ darwin: "google chrome",
1091
+ win32: "chrome",
1092
+ // `chromium-browser` is the older deb package name used by Ubuntu/Debian before snap.
1093
+ linux: ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]
1094
+ }, {
1095
+ wsl: {
1096
+ ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
1097
+ x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
1098
+ }
1099
+ }));
1100
+ defineLazyProperty(apps, "brave", () => detectPlatformBinary({
1101
+ darwin: "brave browser",
1102
+ win32: "brave",
1103
+ linux: ["brave-browser", "brave"]
1104
+ }, {
1105
+ wsl: {
1106
+ ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
1107
+ x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
1108
+ }
1109
+ }));
1110
+ defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
1111
+ darwin: "firefox",
1112
+ win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
1113
+ linux: "firefox"
1114
+ }, {
1115
+ wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
1116
+ }));
1117
+ defineLazyProperty(apps, "edge", () => detectPlatformBinary({
1118
+ darwin: "microsoft edge",
1119
+ win32: "msedge",
1120
+ linux: ["microsoft-edge", "microsoft-edge-dev"]
1121
+ }, {
1122
+ wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
1123
+ }));
1124
+ defineLazyProperty(apps, "safari", () => detectPlatformBinary({
1125
+ darwin: "Safari"
1126
+ }));
1127
+ var open_default = open;
1128
+
1129
+ // src/commands/auth.ts
1130
+ var import_node_http = require("http");
1131
+
1132
+ // src/utils/config.ts
1133
+ var import_node_fs4 = require("fs");
1134
+ var import_node_path2 = __toESM(require("path"), 1);
1135
+ var import_node_os3 = __toESM(require("os"), 1);
1136
+ var CONFIG_DIR = import_node_path2.default.join(import_node_os3.default.homedir(), ".mcp-use");
1137
+ var CONFIG_FILE = import_node_path2.default.join(CONFIG_DIR, "config.json");
1138
+ var DEFAULT_API_URL = process.env.MCP_API_URL ? process.env.MCP_API_URL.replace(/\/api\/v1$/, "") + "/api/v1" : "https://cloud.mcp-use.com/api/v1";
1139
+ var DEFAULT_WEB_URL = process.env.MCP_WEB_URL ? process.env.MCP_WEB_URL : "https://mcp-use.com";
1140
+ async function ensureConfigDir() {
1141
+ try {
1142
+ await import_node_fs4.promises.mkdir(CONFIG_DIR, { recursive: true });
1143
+ } catch (error) {
1144
+ }
1145
+ }
1146
+ async function readConfig() {
1147
+ try {
1148
+ const content = await import_node_fs4.promises.readFile(CONFIG_FILE, "utf-8");
1149
+ return JSON.parse(content);
1150
+ } catch (error) {
1151
+ return {};
1152
+ }
1153
+ }
1154
+ async function writeConfig(config) {
1155
+ await ensureConfigDir();
1156
+ await import_node_fs4.promises.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8");
1157
+ }
1158
+ async function deleteConfig() {
1159
+ try {
1160
+ await import_node_fs4.promises.unlink(CONFIG_FILE);
1161
+ } catch (error) {
1162
+ }
1163
+ }
1164
+ async function getApiUrl() {
1165
+ const config = await readConfig();
1166
+ return config.apiUrl || DEFAULT_API_URL;
1167
+ }
1168
+ async function getApiKey() {
1169
+ const config = await readConfig();
1170
+ return config.apiKey || null;
1171
+ }
1172
+ async function isLoggedIn() {
1173
+ const apiKey = await getApiKey();
1174
+ return !!apiKey;
1175
+ }
1176
+ async function getWebUrl() {
1177
+ return DEFAULT_WEB_URL;
1178
+ }
1179
+
1180
+ // src/utils/api.ts
1181
+ var McpUseAPI = class _McpUseAPI {
1182
+ baseUrl;
1183
+ apiKey;
1184
+ constructor(baseUrl, apiKey) {
1185
+ this.baseUrl = baseUrl || "";
1186
+ this.apiKey = apiKey;
1187
+ }
1188
+ /**
1189
+ * Initialize API client with config
1190
+ */
1191
+ static async create() {
1192
+ const baseUrl = await getApiUrl();
1193
+ const apiKey = await getApiKey();
1194
+ return new _McpUseAPI(baseUrl, apiKey ?? void 0);
1195
+ }
1196
+ /**
1197
+ * Make authenticated request
1198
+ */
1199
+ async request(endpoint, options = {}) {
1200
+ const url = `${this.baseUrl}${endpoint}`;
1201
+ const headers = {
1202
+ "Content-Type": "application/json",
1203
+ ...options.headers || {}
1204
+ };
1205
+ if (this.apiKey) {
1206
+ headers["x-api-key"] = this.apiKey;
1207
+ }
1208
+ const response = await fetch(url, {
1209
+ ...options,
1210
+ headers
1211
+ });
1212
+ if (!response.ok) {
1213
+ const error = await response.text();
1214
+ throw new Error(`API request failed: ${response.status} ${error}`);
1215
+ }
1216
+ return response.json();
1217
+ }
1218
+ /**
1219
+ * Create API key using JWT token
1220
+ */
1221
+ async createApiKey(jwtToken, name = "CLI") {
1222
+ const url = `${this.baseUrl}/api-key`;
1223
+ const response = await fetch(url, {
1224
+ method: "POST",
1225
+ headers: {
1226
+ "Content-Type": "application/json",
1227
+ Authorization: `Bearer ${jwtToken}`
1228
+ },
1229
+ body: JSON.stringify({ name })
1230
+ });
1231
+ if (!response.ok) {
1232
+ const error = await response.text();
1233
+ throw new Error(`Failed to create API key: ${response.status} ${error}`);
1234
+ }
1235
+ return response.json();
1236
+ }
1237
+ /**
1238
+ * Test authentication
1239
+ */
1240
+ async testAuth() {
1241
+ return this.request("/test-auth");
1242
+ }
1243
+ /**
1244
+ * Create deployment
1245
+ */
1246
+ async createDeployment(request) {
1247
+ return this.request("/deployments", {
1248
+ method: "POST",
1249
+ body: JSON.stringify(request)
1250
+ });
1251
+ }
1252
+ /**
1253
+ * Get deployment by ID
1254
+ */
1255
+ async getDeployment(deploymentId) {
1256
+ return this.request(`/deployments/${deploymentId}`);
1257
+ }
1258
+ /**
1259
+ * Stream deployment logs
1260
+ */
1261
+ async *streamDeploymentLogs(deploymentId) {
1262
+ const url = `${this.baseUrl}/deployments/${deploymentId}/logs/stream`;
1263
+ const headers = {};
1264
+ if (this.apiKey) {
1265
+ headers["x-api-key"] = this.apiKey;
1266
+ }
1267
+ const response = await fetch(url, { headers });
1268
+ if (!response.ok) {
1269
+ throw new Error(`Failed to stream logs: ${response.status}`);
1270
+ }
1271
+ if (!response.body) {
1272
+ throw new Error("Response body is null");
1273
+ }
1274
+ const reader = response.body.getReader();
1275
+ const decoder = new TextDecoder();
1276
+ let buffer = "";
1277
+ try {
1278
+ while (true) {
1279
+ const { done, value } = await reader.read();
1280
+ if (done) break;
1281
+ buffer += decoder.decode(value, { stream: true });
1282
+ const lines = buffer.split("\n");
1283
+ buffer = lines.pop() || "";
1284
+ for (const line of lines) {
1285
+ if (line.startsWith("data: ")) {
1286
+ const data = line.slice(6);
1287
+ try {
1288
+ const parsed = JSON.parse(data);
1289
+ if (parsed.log) {
1290
+ yield parsed.log;
1291
+ } else if (parsed.error) {
1292
+ throw new Error(parsed.error);
1293
+ }
1294
+ } catch (e) {
1295
+ }
1296
+ }
1297
+ }
1298
+ }
1299
+ } finally {
1300
+ reader.releaseLock();
1301
+ }
1302
+ }
1303
+ /**
1304
+ * Create deployment with source code upload
1305
+ */
1306
+ async createDeploymentWithUpload(request, filePath) {
1307
+ const { readFile: readFile3 } = await import("fs/promises");
1308
+ const { basename } = await import("path");
1309
+ const { stat } = await import("fs/promises");
1310
+ const stats = await stat(filePath);
1311
+ const maxSize = 2 * 1024 * 1024;
1312
+ if (stats.size > maxSize) {
1313
+ throw new Error(
1314
+ `File size (${(stats.size / 1024 / 1024).toFixed(2)}MB) exceeds maximum of 2MB`
1315
+ );
1316
+ }
1317
+ const fileBuffer = await readFile3(filePath);
1318
+ const filename = basename(filePath);
1319
+ const formData = new FormData();
1320
+ const blob = new Blob([fileBuffer], { type: "application/gzip" });
1321
+ formData.append("source_file", blob, filename);
1322
+ formData.append("name", request.name);
1323
+ formData.append("source_type", "upload");
1324
+ if (request.source.type === "upload") {
1325
+ formData.append("runtime", request.source.runtime || "node");
1326
+ formData.append("port", String(request.source.port || 3e3));
1327
+ if (request.source.startCommand) {
1328
+ formData.append("startCommand", request.source.startCommand);
1329
+ }
1330
+ if (request.source.buildCommand) {
1331
+ formData.append("buildCommand", request.source.buildCommand);
1332
+ }
1333
+ if (request.source.env && Object.keys(request.source.env).length > 0) {
1334
+ formData.append("env", JSON.stringify(request.source.env));
1335
+ }
1336
+ }
1337
+ if (request.customDomain) {
1338
+ formData.append("customDomain", request.customDomain);
1339
+ }
1340
+ if (request.healthCheckPath) {
1341
+ formData.append("healthCheckPath", request.healthCheckPath);
1342
+ }
1343
+ const url = `${this.baseUrl}/deployments`;
1344
+ const headers = {};
1345
+ if (this.apiKey) {
1346
+ headers["x-api-key"] = this.apiKey;
1347
+ }
1348
+ const response = await fetch(url, {
1349
+ method: "POST",
1350
+ headers,
1351
+ body: formData
1352
+ });
1353
+ if (!response.ok) {
1354
+ const error = await response.text();
1355
+ throw new Error(`Deployment failed: ${error}`);
1356
+ }
1357
+ return response.json();
1358
+ }
1359
+ };
1360
+
1361
+ // src/commands/auth.ts
1362
+ var LOGIN_TIMEOUT = 3e5;
1363
+ async function findAvailablePort(startPort = 8765) {
1364
+ for (let port = startPort; port < startPort + 100; port++) {
1365
+ try {
1366
+ await new Promise((resolve, reject) => {
1367
+ const server = (0, import_node_http.createServer)();
1368
+ server.once("error", reject);
1369
+ server.once("listening", () => {
1370
+ server.close();
1371
+ resolve();
1372
+ });
1373
+ server.listen(port);
1374
+ });
1375
+ return port;
1376
+ } catch {
1377
+ continue;
1378
+ }
1379
+ }
1380
+ throw new Error("No available ports found");
1381
+ }
1382
+ async function startCallbackServer(port) {
1383
+ return new Promise((resolve, reject) => {
1384
+ let tokenResolver = null;
1385
+ const tokenPromise = new Promise((res) => {
1386
+ tokenResolver = res;
1387
+ });
1388
+ const server = (0, import_node_http.createServer)((req, res) => {
1389
+ if (req.url?.startsWith("/callback")) {
1390
+ const url = new URL(req.url, `http://localhost:${port}`);
1391
+ const token = url.searchParams.get("token");
1392
+ if (token && tokenResolver) {
1393
+ res.writeHead(200, { "Content-Type": "text/html" });
1394
+ res.end(`
1395
+ <!DOCTYPE html>
1396
+ <html>
1397
+ <head>
1398
+ <title>Login Successful</title>
1399
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1400
+ <style>
1401
+ * {
1402
+ margin: 0;
1403
+ padding: 0;
1404
+ box-sizing: border-box;
1405
+ }
1406
+ body {
1407
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
1408
+ display: flex;
1409
+ justify-content: center;
1410
+ align-items: center;
1411
+ min-height: 100vh;
1412
+ background: #000;
1413
+ padding: 1rem;
1414
+ }
1415
+ .container {
1416
+ width: 100%;
1417
+ max-width: 28rem;
1418
+ padding: 3rem;
1419
+ text-align: center;
1420
+ -webkit-backdrop-filter: blur(40px);
1421
+ border: 1px solid rgba(255, 255, 255, 0.2);
1422
+ border-radius: 1.5rem;
1423
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
1424
+ }
1425
+ .icon-container {
1426
+ display: inline-flex;
1427
+ align-items: center;
1428
+ justify-content: center;
1429
+ width: 6rem;
1430
+ height: 6rem;
1431
+ margin-bottom: 2rem;
1432
+ background: rgba(255, 255, 255, 0.1);
1433
+ backdrop-filter: blur(10px);
1434
+ -webkit-backdrop-filter: blur(10px);
1435
+ border-radius: 50%;
1436
+ }
1437
+ .checkmark {
1438
+ font-size: 4rem;
1439
+ color: #fff;
1440
+ line-height: 1;
1441
+ animation: scaleIn 0.5s ease-out;
1442
+ }
1443
+ @keyframes scaleIn {
1444
+ from {
1445
+ transform: scale(0);
1446
+ opacity: 0;
1447
+ }
1448
+ to {
1449
+ transform: scale(1);
1450
+ opacity: 1;
1451
+ }
1452
+ }
1453
+ h1 {
1454
+ color: #fff;
1455
+ margin: 0 0 1rem 0;
1456
+ font-size: 2.5rem;
1457
+ font-weight: 700;
1458
+ letter-spacing: -0.025em;
1459
+ }
1460
+ p {
1461
+ color: rgba(255, 255, 255, 0.8);
1462
+ margin: 0 0 2rem 0;
1463
+ font-size: 1.125rem;
1464
+ line-height: 1.5;
1465
+ }
1466
+ .spinner {
1467
+ display: inline-block;
1468
+ width: 2rem;
1469
+ height: 2rem;
1470
+ border: 3px solid rgba(255, 255, 255, 0.3);
1471
+ border-top-color: #fff;
1472
+ border-radius: 50%;
1473
+ animation: spin 0.8s linear infinite;
1474
+ }
1475
+ @keyframes spin {
1476
+ to { transform: rotate(360deg); }
1477
+ }
1478
+ .footer {
1479
+ margin-top: 2rem;
1480
+ color: rgba(255, 255, 255, 0.6);
1481
+ font-size: 0.875rem;
1482
+ }
1483
+ </style>
1484
+ </head>
1485
+ <body>
1486
+ <div class="container">
1487
+ <h1>Authentication Successful!</h1>
1488
+ <p>You can now close this window and return to the CLI.</p>
1489
+ </div>
1490
+ </body>
1491
+ </html>
1492
+ `);
1493
+ tokenResolver(token);
1494
+ } else {
1495
+ res.writeHead(400, { "Content-Type": "text/html" });
1496
+ res.end(`
1497
+ <!DOCTYPE html>
1498
+ <html>
1499
+ <head>
1500
+ <title>Login Failed</title>
1501
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1502
+ <style>
1503
+ * {
1504
+ margin: 0;
1505
+ padding: 0;
1506
+ box-sizing: border-box;
1507
+ }
1508
+ body {
1509
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
1510
+ display: flex;
1511
+ justify-content: center;
1512
+ align-items: center;
1513
+ min-height: 100vh;
1514
+ background: #000;
1515
+ padding: 1rem;
1516
+ }
1517
+ .container {
1518
+ width: 100%;
1519
+ max-width: 28rem;
1520
+ padding: 3rem;
1521
+ text-align: center;
1522
+ background: rgba(255, 255, 255, 0.1);
1523
+ backdrop-filter: blur(40px);
1524
+ -webkit-backdrop-filter: blur(40px);
1525
+ border: 1px solid rgba(255, 255, 255, 0.2);
1526
+ border-radius: 1.5rem;
1527
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
1528
+ }
1529
+ .icon-container {
1530
+ display: inline-flex;
1531
+ align-items: center;
1532
+ justify-content: center;
1533
+ width: 6rem;
1534
+ height: 6rem;
1535
+ margin-bottom: 2rem;
1536
+ background: rgba(255, 255, 255, 0.1);
1537
+ backdrop-filter: blur(10px);
1538
+ -webkit-backdrop-filter: blur(10px);
1539
+ border-radius: 50%;
1540
+ }
1541
+ .cross {
1542
+ font-size: 4rem;
1543
+ color: #fff;
1544
+ line-height: 1;
1545
+ }
1546
+ h1 {
1547
+ color: #fff;
1548
+ margin: 0 0 1rem 0;
1549
+ font-size: 2.5rem;
1550
+ font-weight: 700;
1551
+ letter-spacing: -0.025em;
1552
+ }
1553
+ p {
1554
+ color: rgba(255, 255, 255, 0.8);
1555
+ margin: 0;
1556
+ font-size: 1.125rem;
1557
+ line-height: 1.5;
1558
+ }
1559
+ </style>
1560
+ </head>
1561
+ <body>
1562
+ <div class="container">
1563
+ <div class="icon-container">
1564
+ <div class="cross">\u2717</div>
1565
+ </div>
1566
+ <h1>Login Failed</h1>
1567
+ <p>No token received. Please try again.</p>
1568
+ </div>
1569
+ </body>
1570
+ </html>
1571
+ `);
1572
+ }
1573
+ }
1574
+ });
1575
+ server.listen(port, () => {
1576
+ resolve({ server, token: tokenPromise });
1577
+ });
1578
+ server.on("error", reject);
1579
+ });
1580
+ }
1581
+ async function loginCommand() {
1582
+ try {
1583
+ if (await isLoggedIn()) {
1584
+ console.log(
1585
+ source_default.yellow(
1586
+ "\u26A0\uFE0F You are already logged in. Run 'mcp-use logout' first if you want to login with a different account."
1587
+ )
1588
+ );
1589
+ return;
1590
+ }
1591
+ console.log(source_default.cyan.bold("\u{1F510} Logging in to mcp-use cloud...\n"));
1592
+ const port = await findAvailablePort();
1593
+ const redirectUri = `http://localhost:${port}/callback`;
1594
+ console.log(source_default.gray(`Starting local server on port ${port}...`));
1595
+ const { server, token } = await startCallbackServer(port);
1596
+ const webUrl = await getWebUrl();
1597
+ const loginUrl = `${webUrl}/auth/cli?redirect_uri=${encodeURIComponent(redirectUri)}`;
1598
+ console.log(source_default.gray(`Opening browser to ${webUrl}/auth/cli...
1599
+ `));
1600
+ console.log(
1601
+ source_default.white(
1602
+ "If the browser doesn't open automatically, please visit:\n" + source_default.cyan(loginUrl)
1603
+ )
1604
+ );
1605
+ await open_default(loginUrl);
1606
+ console.log(
1607
+ source_default.gray("\nWaiting for authentication... (this may take a moment)")
1608
+ );
1609
+ const jwtToken = await Promise.race([
1610
+ token,
1611
+ new Promise(
1612
+ (_, reject) => setTimeout(
1613
+ () => reject(new Error("Login timeout - please try again")),
1614
+ LOGIN_TIMEOUT
1615
+ )
1616
+ )
1617
+ ]);
1618
+ server.close();
1619
+ console.log(
1620
+ source_default.gray("Received authentication token, creating API key...")
1621
+ );
1622
+ const api = await McpUseAPI.create();
1623
+ const apiKeyResponse = await api.createApiKey(jwtToken, "CLI");
1624
+ await writeConfig({
1625
+ apiKey: apiKeyResponse.api_key
1626
+ });
1627
+ console.log(source_default.green.bold("\n\u2713 Successfully logged in!"));
1628
+ console.log(
1629
+ source_default.gray(
1630
+ `
1631
+ Your API key has been saved to ${source_default.white("~/.mcp-use/config.json")}`
1632
+ )
1633
+ );
1634
+ console.log(
1635
+ source_default.gray(
1636
+ "You can now deploy your MCP servers with " + source_default.white("mcp-use deploy")
1637
+ )
1638
+ );
1639
+ process.exit(0);
1640
+ } catch (error) {
1641
+ console.error(
1642
+ source_default.red.bold("\n\u2717 Login failed:"),
1643
+ source_default.red(error instanceof Error ? error.message : "Unknown error")
1644
+ );
1645
+ process.exit(1);
1646
+ }
1647
+ }
1648
+ async function logoutCommand() {
1649
+ try {
1650
+ if (!await isLoggedIn()) {
1651
+ console.log(source_default.yellow("\u26A0\uFE0F You are not logged in."));
1652
+ return;
1653
+ }
1654
+ console.log(source_default.cyan.bold("\u{1F513} Logging out...\n"));
1655
+ await deleteConfig();
1656
+ console.log(source_default.green.bold("\u2713 Successfully logged out!"));
1657
+ console.log(
1658
+ source_default.gray(
1659
+ "\nYour local config has been deleted. The API key will remain active until revoked from the web interface."
1660
+ )
1661
+ );
1662
+ } catch (error) {
1663
+ console.error(
1664
+ source_default.red.bold("\n\u2717 Logout failed:"),
1665
+ source_default.red(error instanceof Error ? error.message : "Unknown error")
1666
+ );
1667
+ process.exit(1);
1668
+ }
1669
+ }
1670
+ async function whoamiCommand() {
1671
+ try {
1672
+ if (!await isLoggedIn()) {
1673
+ console.log(source_default.yellow("\u26A0\uFE0F You are not logged in."));
1674
+ console.log(
1675
+ source_default.gray("Run " + source_default.white("mcp-use login") + " to get started.")
1676
+ );
1677
+ return;
1678
+ }
1679
+ console.log(source_default.cyan.bold("\u{1F464} Current user:\n"));
1680
+ const api = await McpUseAPI.create();
1681
+ const authInfo = await api.testAuth();
1682
+ console.log(source_default.white("Email: ") + source_default.cyan(authInfo.email));
1683
+ console.log(source_default.white("User ID: ") + source_default.gray(authInfo.user_id));
1684
+ const apiKey = await getApiKey();
1685
+ if (apiKey) {
1686
+ const masked = apiKey.substring(0, 6) + "...";
1687
+ console.log(source_default.white("API Key: ") + source_default.gray(masked));
1688
+ }
1689
+ } catch (error) {
1690
+ console.error(
1691
+ source_default.red.bold("\n\u2717 Failed to get user info:"),
1692
+ source_default.red(error instanceof Error ? error.message : "Unknown error")
1693
+ );
1694
+ process.exit(1);
1695
+ }
1696
+ }
1697
+
1698
+ // src/commands/deploy.ts
1699
+ var import_node_fs5 = require("fs");
1700
+ var import_node_path3 = __toESM(require("path"), 1);
1701
+ var import_node_os4 = __toESM(require("os"), 1);
1702
+ var import_node_child_process9 = require("child_process");
1703
+ var import_node_util8 = require("util");
1704
+
1705
+ // src/utils/git.ts
1706
+ var import_node_child_process8 = require("child_process");
1707
+ var import_node_util7 = require("util");
1708
+ var execAsync = (0, import_node_util7.promisify)(import_node_child_process8.exec);
1709
+ async function gitCommand(command, cwd = process.cwd()) {
1710
+ try {
1711
+ const { stdout } = await execAsync(command, { cwd });
1712
+ return stdout.trim();
1713
+ } catch (error) {
1714
+ return null;
1715
+ }
1716
+ }
1717
+ async function isGitRepo(cwd = process.cwd()) {
1718
+ const result = await gitCommand("git rev-parse --is-inside-work-tree", cwd);
1719
+ return result === "true";
1720
+ }
1721
+ async function getRemoteUrl(cwd = process.cwd()) {
1722
+ return gitCommand("git config --get remote.origin.url", cwd);
1723
+ }
1724
+ function parseGitHubUrl(url) {
1725
+ const sshMatch = url.match(/git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/);
1726
+ const httpsMatch = url.match(
1727
+ /https:\/\/github\.com\/([^/]+)\/(.+?)(?:\.git)?$/
1728
+ );
1729
+ const match = sshMatch || httpsMatch;
1730
+ if (!match) return null;
1731
+ return {
1732
+ owner: match[1],
1733
+ repo: match[2]
1734
+ };
1735
+ }
1736
+ async function getCurrentBranch(cwd = process.cwd()) {
1737
+ return gitCommand("git rev-parse --abbrev-ref HEAD", cwd);
1738
+ }
1739
+ async function getCommitSha(cwd = process.cwd()) {
1740
+ return gitCommand("git rev-parse HEAD", cwd);
1741
+ }
1742
+ async function getCommitMessage(cwd = process.cwd()) {
1743
+ return gitCommand("git log -1 --pretty=%B", cwd);
1744
+ }
1745
+ async function getGitInfo(cwd = process.cwd()) {
1746
+ const isRepo = await isGitRepo(cwd);
1747
+ if (!isRepo) {
1748
+ return { isGitRepo: false };
1749
+ }
1750
+ const remoteUrl = await getRemoteUrl(cwd);
1751
+ const branch = await getCurrentBranch(cwd);
1752
+ const commitSha = await getCommitSha(cwd);
1753
+ const commitMessage = await getCommitMessage(cwd);
1754
+ let owner;
1755
+ let repo;
1756
+ if (remoteUrl) {
1757
+ const parsed = parseGitHubUrl(remoteUrl);
1758
+ if (parsed) {
1759
+ owner = parsed.owner;
1760
+ repo = parsed.repo;
1761
+ }
1762
+ }
1763
+ return {
1764
+ isGitRepo: true,
1765
+ remoteUrl: remoteUrl || void 0,
1766
+ owner,
1767
+ repo,
1768
+ branch: branch || void 0,
1769
+ commitSha: commitSha || void 0,
1770
+ commitMessage: commitMessage || void 0
1771
+ };
1772
+ }
1773
+ function isGitHubUrl(url) {
1774
+ try {
1775
+ const parsedUrl = new URL(url);
1776
+ return parsedUrl.hostname === "github.com" || parsedUrl.hostname === "www.github.com";
1777
+ } catch {
1778
+ const sshMatch = url.match(/^git@([^:/]+)[:/]/);
1779
+ if (sshMatch) {
1780
+ const host = sshMatch[1];
1781
+ return host === "github.com" || host === "www.github.com";
1782
+ }
1783
+ }
1784
+ return false;
1785
+ }
1786
+
1787
+ // src/commands/deploy.ts
1788
+ var execAsync2 = (0, import_node_util8.promisify)(import_node_child_process9.exec);
1789
+ async function isMcpProject(cwd = process.cwd()) {
1790
+ try {
1791
+ const packageJsonPath = import_node_path3.default.join(cwd, "package.json");
1792
+ const content = await import_node_fs5.promises.readFile(packageJsonPath, "utf-8");
1793
+ const packageJson2 = JSON.parse(content);
1794
+ const hasMcpDeps = packageJson2.dependencies?.["mcp-use"] || packageJson2.dependencies?.["@modelcontextprotocol/sdk"] || packageJson2.devDependencies?.["mcp-use"] || packageJson2.devDependencies?.["@modelcontextprotocol/sdk"];
1795
+ const hasMcpScripts = packageJson2.scripts?.mcp || packageJson2.scripts?.["mcp:dev"];
1796
+ return !!(hasMcpDeps || hasMcpScripts);
1797
+ } catch {
1798
+ return false;
1799
+ }
1800
+ }
1801
+ async function getProjectName(cwd = process.cwd()) {
1802
+ try {
1803
+ const packageJsonPath = import_node_path3.default.join(cwd, "package.json");
1804
+ const content = await import_node_fs5.promises.readFile(packageJsonPath, "utf-8");
1805
+ const packageJson2 = JSON.parse(content);
1806
+ if (packageJson2.name) {
1807
+ return packageJson2.name;
1808
+ }
1809
+ } catch {
1810
+ }
1811
+ return import_node_path3.default.basename(cwd);
1812
+ }
1813
+ async function detectBuildCommand(cwd = process.cwd()) {
1814
+ try {
1815
+ const packageJsonPath = import_node_path3.default.join(cwd, "package.json");
1816
+ const content = await import_node_fs5.promises.readFile(packageJsonPath, "utf-8");
1817
+ const packageJson2 = JSON.parse(content);
1818
+ if (packageJson2.scripts?.build) {
1819
+ return "npm run build";
1820
+ }
1821
+ } catch {
1822
+ }
1823
+ return void 0;
1824
+ }
1825
+ async function detectStartCommand(cwd = process.cwd()) {
1826
+ try {
1827
+ const packageJsonPath = import_node_path3.default.join(cwd, "package.json");
1828
+ const content = await import_node_fs5.promises.readFile(packageJsonPath, "utf-8");
1829
+ const packageJson2 = JSON.parse(content);
1830
+ if (packageJson2.scripts?.start) {
1831
+ return "npm start";
1832
+ }
1833
+ if (packageJson2.main) {
1834
+ return `node ${packageJson2.main}`;
1835
+ }
1836
+ } catch {
1837
+ }
1838
+ return void 0;
1839
+ }
1840
+ async function detectRuntime(cwd = process.cwd()) {
1841
+ try {
1842
+ const pythonFiles = ["requirements.txt", "pyproject.toml", "setup.py"];
1843
+ for (const file of pythonFiles) {
1844
+ try {
1845
+ await import_node_fs5.promises.access(import_node_path3.default.join(cwd, file));
1846
+ return "python";
1847
+ } catch {
1848
+ continue;
1849
+ }
1850
+ }
1851
+ try {
1852
+ await import_node_fs5.promises.access(import_node_path3.default.join(cwd, "package.json"));
1853
+ return "node";
1854
+ } catch {
1855
+ }
1856
+ } catch {
1857
+ }
1858
+ return "node";
1859
+ }
1860
+ async function prompt(question, defaultValue = "n") {
1861
+ const readline = await import("readline");
1862
+ const rl = readline.createInterface({
1863
+ input: process.stdin,
1864
+ output: process.stdout
1865
+ });
1866
+ const defaultIndicator = defaultValue === "y" ? "Y/n" : "y/N";
1867
+ const questionWithDefault = question.replace(
1868
+ /(\(y\/n\):)/,
1869
+ `(${defaultIndicator}):`
1870
+ );
1871
+ return new Promise((resolve) => {
1872
+ rl.question(questionWithDefault, (answer) => {
1873
+ rl.close();
1874
+ const trimmedAnswer = answer.trim().toLowerCase();
1875
+ if (trimmedAnswer === "") {
1876
+ resolve(defaultValue === "y");
1877
+ } else {
1878
+ resolve(trimmedAnswer === "y" || trimmedAnswer === "yes");
1879
+ }
1880
+ });
1881
+ });
1882
+ }
1883
+ async function createTarball(cwd) {
1884
+ const tmpDir = import_node_os4.default.tmpdir();
1885
+ const tarballPath = import_node_path3.default.join(tmpDir, `mcp-deploy-${Date.now()}.tar.gz`);
1886
+ const excludePatterns = [
1887
+ "node_modules",
1888
+ ".git",
1889
+ "dist",
1890
+ "build",
1891
+ ".next",
1892
+ ".venv",
1893
+ "__pycache__",
1894
+ "*.pyc",
1895
+ ".DS_Store",
1896
+ "._*",
1897
+ // macOS resource fork files
1898
+ ".mcp-use",
1899
+ // Build artifacts directory
1900
+ ".env",
1901
+ ".env.local",
1902
+ "*.log"
1903
+ ];
1904
+ const excludeFlags = excludePatterns.map((pattern) => `--exclude=${pattern}`).join(" ");
1905
+ const command = `tar ${excludeFlags} -czf "${tarballPath}" -C "${cwd}" . 2>&1 || true`;
1906
+ try {
1907
+ await execAsync2(command);
1908
+ return tarballPath;
1909
+ } catch (error) {
1910
+ throw new Error(
1911
+ `Failed to create tarball: ${error instanceof Error ? error.message : "Unknown error"}`
1912
+ );
1913
+ }
1914
+ }
1915
+ function formatFileSize(bytes) {
1916
+ if (bytes === 0) return "0 B";
1917
+ const k = 1024;
1918
+ const sizes = ["B", "KB", "MB", "GB"];
1919
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
1920
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
1921
+ }
1922
+ async function displayDeploymentProgress(api, deployment) {
1923
+ const frames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1924
+ let frameIndex = 0;
1925
+ let spinnerInterval = null;
1926
+ let lastStep = "";
1927
+ const startSpinner = (message) => {
1928
+ if (spinnerInterval) {
1929
+ clearInterval(spinnerInterval);
1930
+ }
1931
+ process.stdout.write("\r\x1B[K");
1932
+ spinnerInterval = setInterval(() => {
1933
+ const frame = frames[frameIndex];
1934
+ frameIndex = (frameIndex + 1) % frames.length;
1935
+ process.stdout.write(
1936
+ "\r" + source_default.cyan(frame) + " " + source_default.gray(message)
1937
+ );
1938
+ }, 80);
1939
+ };
1940
+ const stopSpinner = () => {
1941
+ if (spinnerInterval) {
1942
+ clearInterval(spinnerInterval);
1943
+ spinnerInterval = null;
1944
+ process.stdout.write("\r\x1B[K");
1945
+ }
1946
+ };
1947
+ console.log();
1948
+ startSpinner("Deploying...");
1949
+ try {
1950
+ for await (const log of api.streamDeploymentLogs(deployment.id)) {
1951
+ try {
1952
+ const logData = JSON.parse(log);
1953
+ if (logData.step && logData.step !== lastStep) {
1954
+ lastStep = logData.step;
1955
+ const stepMessages = {
1956
+ clone: "Preparing source code...",
1957
+ analyze: "Analyzing project...",
1958
+ build: "Building container image...",
1959
+ deploy: "Deploying to cloud..."
1960
+ };
1961
+ const message = stepMessages[logData.step] || "Deploying...";
1962
+ startSpinner(message);
1963
+ }
1964
+ if (logData.line) {
1965
+ stopSpinner();
1966
+ const levelColor = logData.level === "error" ? source_default.red : logData.level === "warn" ? source_default.yellow : source_default.gray;
1967
+ const stepPrefix = logData.step ? source_default.cyan(`[${logData.step}]`) + " " : "";
1968
+ console.log(stepPrefix + levelColor(logData.line));
1969
+ }
1970
+ } catch {
1971
+ }
1972
+ }
1973
+ } catch (error) {
1974
+ stopSpinner();
1975
+ }
1976
+ let checkCount = 0;
1977
+ const maxChecks = 60;
1978
+ let delay = 3e3;
1979
+ const maxDelay = 1e4;
1980
+ let lastDisplayedLogLength = 0;
1981
+ while (checkCount < maxChecks) {
1982
+ const currentDelay = delay;
1983
+ await new Promise((resolve) => setTimeout(resolve, currentDelay));
1984
+ const finalDeployment = await api.getDeployment(deployment.id);
1985
+ if (finalDeployment.buildLogs && finalDeployment.buildLogs.length > lastDisplayedLogLength) {
1986
+ const newLogs = finalDeployment.buildLogs.substring(
1987
+ lastDisplayedLogLength
1988
+ );
1989
+ const logLines = newLogs.split("\n").filter((l) => l.trim());
1990
+ for (const line of logLines) {
1991
+ try {
1992
+ const logData = JSON.parse(line);
1993
+ if (logData.line) {
1994
+ stopSpinner();
1995
+ const levelColor = logData.level === "error" ? source_default.red : logData.level === "warn" ? source_default.yellow : source_default.gray;
1996
+ const stepPrefix = logData.step ? source_default.cyan(`[${logData.step}]`) + " " : "";
1997
+ console.log(stepPrefix + levelColor(logData.line));
1998
+ }
1999
+ } catch {
2000
+ }
2001
+ }
2002
+ lastDisplayedLogLength = finalDeployment.buildLogs.length;
2003
+ }
2004
+ if (finalDeployment.status === "running") {
2005
+ const mcpUrl = `https://${finalDeployment.domain}/mcp`;
2006
+ const inspectorUrl = `https://inspector.mcp-use.com/inspector?autoConnect=${encodeURIComponent(mcpUrl)}`;
2007
+ console.log(source_default.green.bold("\u2713 Deployment successful!\n"));
2008
+ console.log(source_default.white("\u{1F310} MCP Server URL:"));
2009
+ console.log(source_default.cyan.bold(` ${mcpUrl}
2010
+ `));
2011
+ console.log(source_default.white("\u{1F50D} Inspector URL:"));
2012
+ console.log(source_default.cyan.bold(` ${inspectorUrl}
2013
+ `));
2014
+ if (finalDeployment.customDomain) {
2015
+ const customMcpUrl = `https://${finalDeployment.customDomain}/mcp`;
2016
+ const customInspectorUrl = `https://inspector.mcp-use.com/inspect?autoConnect=${encodeURIComponent(customMcpUrl)}`;
2017
+ console.log(source_default.white("\u{1F517} Custom Domain:"));
2018
+ console.log(source_default.cyan.bold(` ${customMcpUrl}
2019
+ `));
2020
+ console.log(source_default.white("\u{1F50D} Custom Inspector:"));
2021
+ console.log(source_default.cyan.bold(` ${customInspectorUrl}
2022
+ `));
2023
+ }
2024
+ console.log(
2025
+ source_default.gray("Deployment ID: ") + source_default.white(finalDeployment.id)
2026
+ );
2027
+ return;
2028
+ } else if (finalDeployment.status === "failed") {
2029
+ console.log(source_default.red.bold("\u2717 Deployment failed\n"));
2030
+ if (finalDeployment.error) {
2031
+ console.log(source_default.red("Error: ") + finalDeployment.error);
2032
+ }
2033
+ if (finalDeployment.buildLogs) {
2034
+ console.log(source_default.gray("\nBuild logs:"));
2035
+ try {
2036
+ const logs = finalDeployment.buildLogs.split("\n").filter((l) => l.trim());
2037
+ for (const log of logs) {
2038
+ try {
2039
+ const logData = JSON.parse(log);
2040
+ if (logData.line) {
2041
+ console.log(source_default.gray(` ${logData.line}`));
2042
+ }
2043
+ } catch {
2044
+ console.log(source_default.gray(` ${log}`));
2045
+ }
2046
+ }
2047
+ } catch {
2048
+ console.log(source_default.gray(finalDeployment.buildLogs));
2049
+ }
2050
+ }
2051
+ process.exit(1);
2052
+ } else if (finalDeployment.status === "building") {
2053
+ startSpinner("Building and deploying...");
2054
+ checkCount++;
2055
+ delay = Math.min(delay * 1.2, maxDelay);
2056
+ } else {
2057
+ console.log(
2058
+ source_default.yellow("\u26A0\uFE0F Deployment status: ") + finalDeployment.status
2059
+ );
2060
+ return;
2061
+ }
2062
+ }
2063
+ stopSpinner();
2064
+ console.log(source_default.yellow("\u26A0\uFE0F Deployment is taking longer than expected."));
2065
+ console.log(
2066
+ source_default.gray("Check status with: ") + source_default.white(`mcp-use status ${deployment.id}`)
2067
+ );
2068
+ }
2069
+ async function deployCommand(options) {
2070
+ try {
2071
+ const cwd = process.cwd();
2072
+ if (!await isLoggedIn()) {
2073
+ console.log(source_default.red("\u2717 You are not logged in."));
2074
+ console.log(
2075
+ source_default.gray("Run " + source_default.white("mcp-use login") + " to get started.")
2076
+ );
2077
+ process.exit(1);
2078
+ }
2079
+ console.log(source_default.cyan.bold("\u{1F680} Deploying to mcp-use cloud...\n"));
2080
+ const isMcp = await isMcpProject(cwd);
2081
+ if (!isMcp) {
2082
+ console.log(
2083
+ source_default.yellow(
2084
+ "\u26A0\uFE0F This doesn't appear to be an MCP server project (no mcp-use or @modelcontextprotocol/sdk dependency found)."
2085
+ )
2086
+ );
2087
+ const shouldContinue = await prompt(
2088
+ source_default.white("Continue anyway? (y/n): ")
2089
+ );
2090
+ if (!shouldContinue) {
2091
+ console.log(source_default.gray("Deployment cancelled."));
2092
+ process.exit(0);
2093
+ }
2094
+ console.log();
2095
+ }
2096
+ const gitInfo = await getGitInfo(cwd);
2097
+ if (!options.fromSource && gitInfo.isGitRepo && gitInfo.remoteUrl && isGitHubUrl(gitInfo.remoteUrl)) {
2098
+ if (!gitInfo.owner || !gitInfo.repo) {
2099
+ console.log(
2100
+ source_default.red(
2101
+ "\u2717 Could not parse GitHub repository information from remote URL."
2102
+ )
2103
+ );
2104
+ process.exit(1);
2105
+ }
2106
+ console.log(source_default.white("GitHub repository detected:"));
2107
+ console.log(
2108
+ source_default.gray(` Repository: `) + source_default.cyan(`${gitInfo.owner}/${gitInfo.repo}`)
2109
+ );
2110
+ console.log(
2111
+ source_default.gray(` Branch: `) + source_default.cyan(gitInfo.branch || "main")
2112
+ );
2113
+ if (gitInfo.commitSha) {
2114
+ console.log(
2115
+ source_default.gray(` Commit: `) + source_default.gray(gitInfo.commitSha.substring(0, 7))
2116
+ );
2117
+ }
2118
+ if (gitInfo.commitMessage) {
2119
+ console.log(
2120
+ source_default.gray(` Message: `) + source_default.gray(gitInfo.commitMessage.split("\n")[0])
2121
+ );
2122
+ }
2123
+ console.log();
2124
+ const shouldDeploy = await prompt(
2125
+ source_default.white(
2126
+ `Deploy from GitHub repository ${gitInfo.owner}/${gitInfo.repo}? (y/n): `
2127
+ )
2128
+ );
2129
+ if (!shouldDeploy) {
2130
+ console.log(source_default.gray("Deployment cancelled."));
2131
+ process.exit(0);
2132
+ }
2133
+ const projectName = options.name || await getProjectName(cwd);
2134
+ const runtime = options.runtime || await detectRuntime(cwd);
2135
+ const port = options.port || 3e3;
2136
+ const buildCommand = await detectBuildCommand(cwd);
2137
+ const startCommand = await detectStartCommand(cwd);
2138
+ console.log();
2139
+ console.log(source_default.white("Deployment configuration:"));
2140
+ console.log(source_default.gray(` Name: `) + source_default.cyan(projectName));
2141
+ console.log(source_default.gray(` Runtime: `) + source_default.cyan(runtime));
2142
+ console.log(source_default.gray(` Port: `) + source_default.cyan(port));
2143
+ if (buildCommand) {
2144
+ console.log(source_default.gray(` Build command: `) + source_default.cyan(buildCommand));
2145
+ }
2146
+ if (startCommand) {
2147
+ console.log(source_default.gray(` Start command: `) + source_default.cyan(startCommand));
2148
+ }
2149
+ console.log();
2150
+ const deploymentRequest = {
2151
+ name: projectName,
2152
+ source: {
2153
+ type: "github",
2154
+ repo: `${gitInfo.owner}/${gitInfo.repo}`,
2155
+ branch: gitInfo.branch || "main",
2156
+ runtime,
2157
+ port,
2158
+ buildCommand,
2159
+ startCommand
2160
+ },
2161
+ healthCheckPath: "/healthz"
2162
+ };
2163
+ console.log(source_default.gray("Creating deployment..."));
2164
+ const api = await McpUseAPI.create();
2165
+ const deployment = await api.createDeployment(deploymentRequest);
2166
+ console.log(
2167
+ source_default.green("\u2713 Deployment created: ") + source_default.gray(deployment.id)
2168
+ );
2169
+ await displayDeploymentProgress(api, deployment);
2170
+ if (options.open && deployment.domain) {
2171
+ console.log();
2172
+ console.log(source_default.gray("Opening deployment in browser..."));
2173
+ await open_default(`https://${deployment.domain}`);
2174
+ }
2175
+ } else {
2176
+ if (options.fromSource) {
2177
+ console.log(
2178
+ source_default.white("\u{1F4E6} Deploying from local source code (--from-source)...")
2179
+ );
2180
+ } else {
2181
+ console.log(
2182
+ source_default.yellow(
2183
+ "\u26A0\uFE0F This is not a GitHub repository or no remote is configured."
2184
+ )
2185
+ );
2186
+ console.log(source_default.white("Deploying from local source code instead..."));
2187
+ }
2188
+ console.log();
2189
+ const projectName = options.name || await getProjectName(cwd);
2190
+ const runtime = options.runtime || await detectRuntime(cwd);
2191
+ const port = options.port || 3e3;
2192
+ const buildCommand = await detectBuildCommand(cwd);
2193
+ const startCommand = await detectStartCommand(cwd);
2194
+ console.log(source_default.white("Deployment configuration:"));
2195
+ console.log(source_default.gray(` Name: `) + source_default.cyan(projectName));
2196
+ console.log(source_default.gray(` Runtime: `) + source_default.cyan(runtime));
2197
+ console.log(source_default.gray(` Port: `) + source_default.cyan(port));
2198
+ if (buildCommand) {
2199
+ console.log(source_default.gray(` Build command: `) + source_default.cyan(buildCommand));
2200
+ }
2201
+ if (startCommand) {
2202
+ console.log(source_default.gray(` Start command: `) + source_default.cyan(startCommand));
2203
+ }
2204
+ console.log();
2205
+ const shouldDeploy = await prompt(
2206
+ source_default.white("Deploy from local source? (y/n): "),
2207
+ "y"
2208
+ );
2209
+ if (!shouldDeploy) {
2210
+ console.log(source_default.gray("Deployment cancelled."));
2211
+ process.exit(0);
2212
+ }
2213
+ console.log();
2214
+ console.log(source_default.gray("Packaging source code..."));
2215
+ const tarballPath = await createTarball(cwd);
2216
+ const stats = await import_node_fs5.promises.stat(tarballPath);
2217
+ console.log(
2218
+ source_default.green("\u2713 Packaged: ") + source_default.gray(formatFileSize(stats.size))
2219
+ );
2220
+ const maxSize = 2 * 1024 * 1024;
2221
+ if (stats.size > maxSize) {
2222
+ console.log(
2223
+ source_default.red(
2224
+ `\u2717 File size (${formatFileSize(stats.size)}) exceeds maximum of 2MB`
2225
+ )
2226
+ );
2227
+ await import_node_fs5.promises.unlink(tarballPath);
2228
+ process.exit(1);
2229
+ }
2230
+ const deploymentRequest = {
2231
+ name: projectName,
2232
+ source: {
2233
+ type: "upload",
2234
+ runtime,
2235
+ port,
2236
+ buildCommand,
2237
+ startCommand
2238
+ },
2239
+ healthCheckPath: "/healthz"
2240
+ };
2241
+ console.log(source_default.gray("Creating deployment..."));
2242
+ const api = await McpUseAPI.create();
2243
+ const deployment = await api.createDeploymentWithUpload(
2244
+ deploymentRequest,
2245
+ tarballPath
2246
+ );
2247
+ await import_node_fs5.promises.unlink(tarballPath);
2248
+ console.log(
2249
+ source_default.green("\u2713 Deployment created: ") + source_default.gray(deployment.id)
2250
+ );
2251
+ await displayDeploymentProgress(api, deployment);
2252
+ if (options.open && deployment.domain) {
2253
+ console.log();
2254
+ console.log(source_default.gray("Opening deployment in browser..."));
2255
+ await open_default(`https://${deployment.domain}`);
2256
+ }
2257
+ }
2258
+ } catch (error) {
2259
+ console.error(
2260
+ source_default.red.bold("\n\u2717 Deployment failed:"),
2261
+ source_default.red(error instanceof Error ? error.message : "Unknown error")
2262
+ );
2263
+ process.exit(1);
2264
+ }
2265
+ }
2266
+
2267
+ // src/commands/client.ts
2268
+ var import_commander = require("commander");
2269
+ var import_node_readline = require("readline");
2270
+ var import_mcp_use = require("mcp-use");
2271
+
2272
+ // src/utils/session-storage.ts
2273
+ var import_node_os5 = require("os");
2274
+ var import_node_path4 = require("path");
2275
+ var import_promises4 = require("fs/promises");
2276
+ var import_node_fs6 = require("fs");
2277
+ var SESSION_FILE_PATH = (0, import_node_path4.join)((0, import_node_os5.homedir)(), ".mcp-use", "cli-sessions.json");
2278
+ async function ensureSessionDir() {
2279
+ const dir = (0, import_node_path4.join)((0, import_node_os5.homedir)(), ".mcp-use");
2280
+ if (!(0, import_node_fs6.existsSync)(dir)) {
2281
+ await (0, import_promises4.mkdir)(dir, { recursive: true });
2282
+ }
2283
+ }
2284
+ async function loadSessions() {
2285
+ try {
2286
+ await ensureSessionDir();
2287
+ if (!(0, import_node_fs6.existsSync)(SESSION_FILE_PATH)) {
2288
+ return { activeSession: null, sessions: {} };
2289
+ }
2290
+ const content = await (0, import_promises4.readFile)(SESSION_FILE_PATH, "utf-8");
2291
+ return JSON.parse(content);
2292
+ } catch (error) {
2293
+ return { activeSession: null, sessions: {} };
2294
+ }
2295
+ }
2296
+ async function saveSessions(storage) {
2297
+ await ensureSessionDir();
2298
+ await (0, import_promises4.writeFile)(SESSION_FILE_PATH, JSON.stringify(storage, null, 2), "utf-8");
2299
+ }
2300
+ async function saveSession(name, config) {
2301
+ const storage = await loadSessions();
2302
+ storage.sessions[name] = {
2303
+ ...config,
2304
+ lastUsed: (/* @__PURE__ */ new Date()).toISOString()
2305
+ };
2306
+ if (!storage.activeSession) {
2307
+ storage.activeSession = name;
2308
+ }
2309
+ await saveSessions(storage);
2310
+ }
2311
+ async function getActiveSession() {
2312
+ const storage = await loadSessions();
2313
+ if (!storage.activeSession || !storage.sessions[storage.activeSession]) {
2314
+ return null;
2315
+ }
2316
+ return {
2317
+ name: storage.activeSession,
2318
+ config: storage.sessions[storage.activeSession]
2319
+ };
2320
+ }
2321
+ async function getSession(name) {
2322
+ const storage = await loadSessions();
2323
+ return storage.sessions[name] || null;
2324
+ }
2325
+ async function setActiveSession(name) {
2326
+ const storage = await loadSessions();
2327
+ if (!storage.sessions[name]) {
2328
+ throw new Error(`Session '${name}' not found`);
2329
+ }
2330
+ storage.activeSession = name;
2331
+ storage.sessions[name].lastUsed = (/* @__PURE__ */ new Date()).toISOString();
2332
+ await saveSessions(storage);
2333
+ }
2334
+ async function listAllSessions() {
2335
+ const storage = await loadSessions();
2336
+ return Object.entries(storage.sessions).map(([name, config]) => ({
2337
+ name,
2338
+ config,
2339
+ isActive: name === storage.activeSession
2340
+ }));
2341
+ }
2342
+ async function updateSessionInfo(name, serverInfo, capabilities) {
2343
+ const storage = await loadSessions();
2344
+ if (storage.sessions[name]) {
2345
+ storage.sessions[name].serverInfo = serverInfo;
2346
+ storage.sessions[name].capabilities = capabilities;
2347
+ storage.sessions[name].lastUsed = (/* @__PURE__ */ new Date()).toISOString();
2348
+ await saveSessions(storage);
2349
+ }
2350
+ }
2351
+
2352
+ // src/utils/format.ts
2353
+ function formatTable(data, columns) {
2354
+ if (data.length === 0) {
2355
+ return source_default.gray("No items found");
2356
+ }
2357
+ const widths = columns.map((col) => {
2358
+ const maxDataWidth = Math.max(
2359
+ ...data.map((row) => String(row[col.key] || "").length)
2360
+ );
2361
+ const headerWidth = col.header.length;
2362
+ return col.width || Math.max(maxDataWidth, headerWidth, 10);
2363
+ });
2364
+ const createRow = (values, bold = false) => {
2365
+ const cells = values.map((val, i) => {
2366
+ const padded = val.padEnd(widths[i]);
2367
+ return bold ? source_default.bold(padded) : padded;
2368
+ });
2369
+ return `\u2502 ${cells.join(" \u2502 ")} \u2502`;
2370
+ };
2371
+ const separator = (char) => {
2372
+ const parts = widths.map((w) => char.repeat(w + 2));
2373
+ if (char === "\u2500") {
2374
+ return `\u251C${parts.join("\u253C")}\u2524`;
2375
+ }
2376
+ return `\u2514${parts.join("\u2534")}\u2518`;
2377
+ };
2378
+ const lines = [];
2379
+ lines.push(`\u250C${widths.map((w) => "\u2500".repeat(w + 2)).join("\u252C")}\u2510`);
2380
+ lines.push(
2381
+ createRow(
2382
+ columns.map((c) => c.header),
2383
+ true
2384
+ )
2385
+ );
2386
+ lines.push(separator("\u2500"));
2387
+ data.forEach((row) => {
2388
+ lines.push(createRow(columns.map((c) => String(row[c.key] || ""))));
2389
+ });
2390
+ lines.push(separator("\u2500"));
2391
+ return lines.join("\n");
2392
+ }
2393
+ function formatJson(data, pretty = true) {
2394
+ if (pretty) {
2395
+ return JSON.stringify(data, null, 2);
2396
+ }
2397
+ return JSON.stringify(data);
2398
+ }
2399
+ function formatToolCall(result) {
2400
+ const lines = [];
2401
+ if (result.isError) {
2402
+ lines.push(source_default.red("\u2717 Tool execution failed"));
2403
+ lines.push("");
2404
+ } else {
2405
+ lines.push(source_default.green("\u2713 Tool executed successfully"));
2406
+ lines.push("");
2407
+ }
2408
+ if (result.content && result.content.length > 0) {
2409
+ result.content.forEach((item, index) => {
2410
+ if (result.content.length > 1) {
2411
+ lines.push(source_default.bold(`Content ${index + 1}:`));
2412
+ }
2413
+ if (item.type === "text") {
2414
+ lines.push(item.text);
2415
+ } else if (item.type === "image") {
2416
+ lines.push(source_default.cyan(`[Image: ${item.mimeType || "unknown type"}]`));
2417
+ if (item.data) {
2418
+ lines.push(source_default.gray(`Data: ${item.data.substring(0, 50)}...`));
2419
+ }
2420
+ } else if (item.type === "resource") {
2421
+ lines.push(source_default.cyan(`[Resource]`));
2422
+ if (item.resource?.uri) {
2423
+ lines.push(source_default.gray(`URI: ${item.resource.uri}`));
2424
+ }
2425
+ if (item.resource && "text" in item.resource && item.resource.text) {
2426
+ lines.push(item.resource.text);
2427
+ }
2428
+ } else {
2429
+ lines.push(source_default.gray(`[Unknown content type: ${item.type}]`));
2430
+ }
2431
+ if (index < result.content.length - 1) {
2432
+ lines.push("");
2433
+ }
2434
+ });
2435
+ }
2436
+ return lines.join("\n");
2437
+ }
2438
+ function formatResourceContent(content) {
2439
+ if (!content || !content.contents) {
2440
+ return source_default.gray("No content");
2441
+ }
2442
+ const lines = [];
2443
+ content.contents.forEach((item, index) => {
2444
+ if (content.contents.length > 1) {
2445
+ lines.push(source_default.bold(`Content ${index + 1}:`));
2446
+ }
2447
+ if (item.uri) {
2448
+ lines.push(source_default.gray(`URI: ${item.uri}`));
2449
+ }
2450
+ if (item.mimeType) {
2451
+ lines.push(source_default.gray(`Type: ${item.mimeType}`));
2452
+ }
2453
+ if ("text" in item && item.text) {
2454
+ lines.push("");
2455
+ lines.push(item.text);
2456
+ } else if ("blob" in item && item.blob) {
2457
+ lines.push("");
2458
+ lines.push(source_default.cyan(`[Binary data: ${item.blob.length} bytes]`));
2459
+ }
2460
+ if (index < content.contents.length - 1) {
2461
+ lines.push("");
2462
+ lines.push(source_default.gray("\u2500".repeat(50)));
2463
+ lines.push("");
2464
+ }
2465
+ });
2466
+ return lines.join("\n");
2467
+ }
2468
+ function formatSchema(schema, indent = 0) {
2469
+ if (!schema) {
2470
+ return source_default.gray("No schema");
2471
+ }
2472
+ const lines = [];
2473
+ const pad = " ".repeat(indent);
2474
+ if (schema.type === "object" && schema.properties) {
2475
+ Object.entries(schema.properties).forEach(([key, value]) => {
2476
+ const required = schema.required?.includes(key);
2477
+ const type = value.type || "any";
2478
+ const desc = value.description || "";
2479
+ const keyStr = required ? source_default.bold(key) : key;
2480
+ const typeStr = source_default.cyan(`(${type})`);
2481
+ const requiredStr = required ? source_default.red(" *required") : "";
2482
+ lines.push(`${pad}${keyStr} ${typeStr}${requiredStr}`);
2483
+ if (desc) {
2484
+ lines.push(`${pad} ${source_default.gray(desc)}`);
2485
+ }
2486
+ if (value.type === "object" && value.properties) {
2487
+ lines.push(formatSchema(value, indent + 1));
2488
+ }
2489
+ if (value.type === "array" && value.items) {
2490
+ lines.push(`${pad} ${source_default.gray("Items:")}`);
2491
+ if (value.items.type === "object") {
2492
+ lines.push(formatSchema(value.items, indent + 2));
2493
+ } else {
2494
+ lines.push(
2495
+ `${pad} ${source_default.cyan(`(${value.items.type || "any"})`)}`
2496
+ );
2497
+ }
2498
+ }
2499
+ });
2500
+ } else {
2501
+ lines.push(`${pad}${source_default.cyan(`Type: ${schema.type || "any"}`)}`);
2502
+ if (schema.description) {
2503
+ lines.push(`${pad}${source_default.gray(schema.description)}`);
2504
+ }
2505
+ }
2506
+ return lines.join("\n");
2507
+ }
2508
+ function formatError(error) {
2509
+ const message = typeof error === "string" ? error : error.message;
2510
+ return source_default.red(`\u2717 Error: ${message}`);
2511
+ }
2512
+ function formatSuccess(message) {
2513
+ return source_default.green(`\u2713 ${message}`);
2514
+ }
2515
+ function formatInfo(message) {
2516
+ return source_default.cyan(message);
2517
+ }
2518
+ function formatWarning(message) {
2519
+ return source_default.yellow(`\u26A0 ${message}`);
2520
+ }
2521
+ function formatHeader(text) {
2522
+ return source_default.bold.white(text);
2523
+ }
2524
+ function formatKeyValue(pairs) {
2525
+ const maxKeyLength = Math.max(...Object.keys(pairs).map((k) => k.length), 0);
2526
+ return Object.entries(pairs).map(([key, value]) => {
2527
+ const paddedKey = key.padEnd(maxKeyLength);
2528
+ return ` ${source_default.gray(paddedKey)}: ${value}`;
2529
+ }).join("\n");
2530
+ }
2531
+ function formatPromptMessages(messages) {
2532
+ if (!messages || messages.length === 0) {
2533
+ return source_default.gray("No messages");
2534
+ }
2535
+ const lines = [];
2536
+ messages.forEach((msg, index) => {
2537
+ const role = msg.role || "unknown";
2538
+ const roleStr = role === "user" ? source_default.blue("[User]") : role === "assistant" ? source_default.green("[Assistant]") : source_default.gray(`[${role}]`);
2539
+ lines.push(`${roleStr}`);
2540
+ if (msg.content) {
2541
+ if (typeof msg.content === "string") {
2542
+ lines.push(msg.content);
2543
+ } else if (msg.content.type === "text") {
2544
+ lines.push(msg.content.text);
2545
+ } else if (msg.content.type === "image") {
2546
+ lines.push(source_default.cyan(`[Image: ${msg.content.mimeType}]`));
2547
+ } else if (msg.content.type === "resource") {
2548
+ lines.push(source_default.cyan(`[Resource: ${msg.content.resource?.uri}]`));
2549
+ if (msg.content.resource?.text) {
2550
+ lines.push(msg.content.resource.text);
2551
+ }
2552
+ }
2553
+ }
2554
+ if (index < messages.length - 1) {
2555
+ lines.push("");
2556
+ }
2557
+ });
2558
+ return lines.join("\n");
2559
+ }
2560
+
2561
+ // src/commands/client.ts
2562
+ var activeSessions = /* @__PURE__ */ new Map();
2563
+ async function getOrRestoreSession(sessionName) {
2564
+ if (!sessionName) {
2565
+ const active = await getActiveSession();
2566
+ if (!active) {
2567
+ console.error(
2568
+ formatError("No active session. Connect to a server first.")
2569
+ );
2570
+ console.error(
2571
+ formatInfo("Use: npx mcp-use client connect <url> --name <name>")
2572
+ );
2573
+ return null;
2574
+ }
2575
+ sessionName = active.name;
2576
+ }
2577
+ if (activeSessions.has(sessionName)) {
2578
+ const { session } = activeSessions.get(sessionName);
2579
+ return { name: sessionName, session };
2580
+ }
2581
+ const config = await getSession(sessionName);
2582
+ if (!config) {
2583
+ console.error(formatError(`Session '${sessionName}' not found`));
2584
+ return null;
2585
+ }
2586
+ try {
2587
+ const client = new import_mcp_use.MCPClient();
2588
+ if (config.type === "http") {
2589
+ client.addServer(sessionName, {
2590
+ url: config.url,
2591
+ headers: config.authToken ? { Authorization: `Bearer ${config.authToken}` } : void 0
2592
+ });
2593
+ } else if (config.type === "stdio") {
2594
+ client.addServer(sessionName, {
2595
+ command: config.command,
2596
+ args: config.args || [],
2597
+ env: config.env
2598
+ });
2599
+ } else {
2600
+ console.error(formatError(`Unknown session type: ${config.type}`));
2601
+ return null;
2602
+ }
2603
+ const session = await client.createSession(sessionName);
2604
+ activeSessions.set(sessionName, { client, session });
2605
+ console.error(formatInfo(`Reconnected to session '${sessionName}'`));
2606
+ return { name: sessionName, session };
2607
+ } catch (error) {
2608
+ console.error(formatError(`Failed to restore session: ${error.message}`));
2609
+ return null;
2610
+ }
2611
+ }
2612
+ async function connectCommand(urlOrCommand, options) {
2613
+ try {
2614
+ const sessionName = options.name || `session-${Date.now()}`;
2615
+ const client = new import_mcp_use.MCPClient();
2616
+ let session;
2617
+ if (options.stdio) {
2618
+ const parts = urlOrCommand.split(" ");
2619
+ const command = parts[0];
2620
+ const args = parts.slice(1);
2621
+ console.error(
2622
+ formatInfo(`Connecting to stdio server: ${command} ${args.join(" ")}`)
2623
+ );
2624
+ client.addServer(sessionName, {
2625
+ command,
2626
+ args
2627
+ });
2628
+ session = await client.createSession(sessionName);
2629
+ await saveSession(sessionName, {
2630
+ type: "stdio",
2631
+ command,
2632
+ args,
2633
+ lastUsed: (/* @__PURE__ */ new Date()).toISOString()
2634
+ });
2635
+ } else {
2636
+ console.error(formatInfo(`Connecting to ${urlOrCommand}...`));
2637
+ client.addServer(sessionName, {
2638
+ url: urlOrCommand,
2639
+ headers: options.auth ? { Authorization: `Bearer ${options.auth}` } : void 0
2640
+ });
2641
+ session = await client.createSession(sessionName);
2642
+ await saveSession(sessionName, {
2643
+ type: "http",
2644
+ url: urlOrCommand,
2645
+ authToken: options.auth,
2646
+ lastUsed: (/* @__PURE__ */ new Date()).toISOString()
2647
+ });
2648
+ }
2649
+ activeSessions.set(sessionName, { client, session });
2650
+ const serverInfo = session.serverInfo;
2651
+ const capabilities = session.serverCapabilities;
2652
+ if (serverInfo) {
2653
+ await updateSessionInfo(sessionName, serverInfo, capabilities);
2654
+ }
2655
+ console.log(formatSuccess(`Connected to ${sessionName}`));
2656
+ if (serverInfo) {
2657
+ console.log("");
2658
+ console.log(formatHeader("Server Information:"));
2659
+ console.log(
2660
+ formatKeyValue({
2661
+ Name: serverInfo.name,
2662
+ Version: serverInfo.version || "unknown"
2663
+ })
2664
+ );
2665
+ }
2666
+ if (capabilities) {
2667
+ console.log("");
2668
+ console.log(formatHeader("Capabilities:"));
2669
+ const caps = Object.keys(capabilities).join(", ");
2670
+ console.log(` ${caps || "none"}`);
2671
+ }
2672
+ const tools = session.tools;
2673
+ console.log("");
2674
+ console.log(
2675
+ formatInfo(
2676
+ `Available: ${tools.length} tool${tools.length !== 1 ? "s" : ""}`
2677
+ )
2678
+ );
2679
+ } catch (error) {
2680
+ console.error(formatError(`Connection failed: ${error.message}`));
2681
+ process.exit(1);
2682
+ }
2683
+ }
2684
+ async function disconnectCommand(sessionName, options) {
2685
+ try {
2686
+ if (options?.all) {
2687
+ for (const [name, { client }] of activeSessions.entries()) {
2688
+ await client.closeAllSessions();
2689
+ activeSessions.delete(name);
2690
+ console.log(formatSuccess(`Disconnected from ${name}`));
2691
+ }
2692
+ return;
2693
+ }
2694
+ if (!sessionName) {
2695
+ const active = await getActiveSession();
2696
+ if (!active) {
2697
+ console.error(formatError("No active session to disconnect"));
2698
+ return;
2699
+ }
2700
+ sessionName = active.name;
2701
+ }
2702
+ const sessionData = activeSessions.get(sessionName);
2703
+ if (sessionData) {
2704
+ await sessionData.client.closeAllSessions();
2705
+ activeSessions.delete(sessionName);
2706
+ console.log(formatSuccess(`Disconnected from ${sessionName}`));
2707
+ } else {
2708
+ console.log(formatInfo(`Session '${sessionName}' is not connected`));
2709
+ }
2710
+ } catch (error) {
2711
+ console.error(formatError(`Failed to disconnect: ${error.message}`));
2712
+ process.exit(1);
2713
+ }
2714
+ }
2715
+ async function listSessionsCommand() {
2716
+ try {
2717
+ const sessions = await listAllSessions();
2718
+ if (sessions.length === 0) {
2719
+ console.log(formatInfo("No saved sessions"));
2720
+ console.log(
2721
+ formatInfo("Connect to a server with: npx mcp-use client connect <url>")
2722
+ );
2723
+ return;
2724
+ }
2725
+ console.log(formatHeader("Saved Sessions:"));
2726
+ console.log("");
2727
+ const tableData = sessions.map((s) => ({
2728
+ name: s.isActive ? source_default.green.bold(`${s.name} *`) : s.name,
2729
+ type: s.config.type,
2730
+ target: s.config.type === "http" ? s.config.url || "" : `${s.config.command} ${(s.config.args || []).join(" ")}`,
2731
+ server: s.config.serverInfo?.name || "unknown",
2732
+ status: activeSessions.has(s.name) ? source_default.green("connected") : source_default.gray("disconnected")
2733
+ }));
2734
+ console.log(
2735
+ formatTable(tableData, [
2736
+ { key: "name", header: "Name" },
2737
+ { key: "type", header: "Type" },
2738
+ { key: "target", header: "Target", width: 40 },
2739
+ { key: "server", header: "Server" },
2740
+ { key: "status", header: "Status" }
2741
+ ])
2742
+ );
2743
+ console.log("");
2744
+ console.log(source_default.gray("* = active session"));
2745
+ } catch (error) {
2746
+ console.error(formatError(`Failed to list sessions: ${error.message}`));
2747
+ process.exit(1);
2748
+ }
2749
+ }
2750
+ async function switchSessionCommand(name) {
2751
+ try {
2752
+ await setActiveSession(name);
2753
+ console.log(formatSuccess(`Switched to session '${name}'`));
2754
+ } catch (error) {
2755
+ console.error(formatError(`Failed to switch session: ${error.message}`));
2756
+ process.exit(1);
2757
+ }
2758
+ }
2759
+ async function listToolsCommand(options) {
2760
+ try {
2761
+ const result = await getOrRestoreSession(options.session || null);
2762
+ if (!result) return;
2763
+ const { session } = result;
2764
+ const tools = await session.listTools();
2765
+ if (options.json) {
2766
+ console.log(formatJson(tools));
2767
+ return;
2768
+ }
2769
+ if (tools.length === 0) {
2770
+ console.log(formatInfo("No tools available"));
2771
+ return;
2772
+ }
2773
+ console.log(formatHeader(`Available Tools (${tools.length}):`));
2774
+ console.log("");
2775
+ const tableData = tools.map((tool) => ({
2776
+ name: source_default.bold(tool.name),
2777
+ description: tool.description || source_default.gray("No description")
2778
+ }));
2779
+ console.log(
2780
+ formatTable(tableData, [
2781
+ { key: "name", header: "Tool", width: 25 },
2782
+ { key: "description", header: "Description", width: 50 }
2783
+ ])
2784
+ );
2785
+ } catch (error) {
2786
+ console.error(formatError(`Failed to list tools: ${error.message}`));
2787
+ process.exit(1);
2788
+ }
2789
+ }
2790
+ async function describeToolCommand(toolName, options) {
2791
+ try {
2792
+ const result = await getOrRestoreSession(options.session || null);
2793
+ if (!result) return;
2794
+ const { session } = result;
2795
+ const tools = session.tools;
2796
+ const tool = tools.find((t) => t.name === toolName);
2797
+ if (!tool) {
2798
+ console.error(formatError(`Tool '${toolName}' not found`));
2799
+ console.log("");
2800
+ console.log(formatInfo("Available tools:"));
2801
+ tools.forEach((t) => console.log(` \u2022 ${t.name}`));
2802
+ return;
2803
+ }
2804
+ console.log(formatHeader(`Tool: ${tool.name}`));
2805
+ console.log("");
2806
+ if (tool.description) {
2807
+ console.log(tool.description);
2808
+ console.log("");
2809
+ }
2810
+ if (tool.inputSchema) {
2811
+ console.log(formatHeader("Input Schema:"));
2812
+ console.log(formatSchema(tool.inputSchema));
2813
+ }
2814
+ } catch (error) {
2815
+ console.error(formatError(`Failed to describe tool: ${error.message}`));
2816
+ process.exit(1);
2817
+ }
2818
+ }
2819
+ async function callToolCommand(toolName, argsJson, options) {
2820
+ try {
2821
+ const result = await getOrRestoreSession(options?.session || null);
2822
+ if (!result) return;
2823
+ const { session } = result;
2824
+ let args = {};
2825
+ if (argsJson) {
2826
+ try {
2827
+ args = JSON.parse(argsJson);
2828
+ } catch (error) {
2829
+ console.error(formatError("Invalid JSON arguments"));
2830
+ return;
2831
+ }
2832
+ } else {
2833
+ const tools = session.tools;
2834
+ const tool = tools.find((t) => t.name === toolName);
2835
+ if (tool?.inputSchema?.required && tool.inputSchema.required.length > 0) {
2836
+ console.error(
2837
+ formatError(
2838
+ "This tool requires arguments. Provide them as a JSON string."
2839
+ )
2840
+ );
2841
+ console.log("");
2842
+ console.log(formatInfo("Example:"));
2843
+ console.log(
2844
+ ` npx mcp-use client tools call ${toolName} '{"param": "value"}'`
2845
+ );
2846
+ console.log("");
2847
+ console.log(formatInfo("Tool schema:"));
2848
+ console.log(formatSchema(tool.inputSchema));
2849
+ return;
2850
+ }
2851
+ }
2852
+ console.error(formatInfo(`Calling tool '${toolName}'...`));
2853
+ const callResult = await session.callTool(toolName, args, {
2854
+ timeout: options?.timeout
2855
+ });
2856
+ if (options?.json) {
2857
+ console.log(formatJson(callResult));
2858
+ } else {
2859
+ console.log(formatToolCall(callResult));
2860
+ }
2861
+ } catch (error) {
2862
+ console.error(formatError(`Failed to call tool: ${error.message}`));
2863
+ process.exit(1);
2864
+ }
2865
+ }
2866
+ async function listResourcesCommand(options) {
2867
+ try {
2868
+ const result = await getOrRestoreSession(options.session || null);
2869
+ if (!result) return;
2870
+ const { session } = result;
2871
+ const resourcesResult = await session.listAllResources();
2872
+ const resources = resourcesResult.resources;
2873
+ if (options.json) {
2874
+ console.log(formatJson(resources));
2875
+ return;
2876
+ }
2877
+ if (resources.length === 0) {
2878
+ console.log(formatInfo("No resources available"));
2879
+ return;
2880
+ }
2881
+ console.log(formatHeader(`Available Resources (${resources.length}):`));
2882
+ console.log("");
2883
+ const tableData = resources.map((resource) => ({
2884
+ uri: resource.uri,
2885
+ name: resource.name || source_default.gray("(no name)"),
2886
+ type: resource.mimeType || source_default.gray("unknown")
2887
+ }));
2888
+ console.log(
2889
+ formatTable(tableData, [
2890
+ { key: "uri", header: "URI", width: 40 },
2891
+ { key: "name", header: "Name", width: 20 },
2892
+ { key: "type", header: "Type", width: 15 }
2893
+ ])
2894
+ );
2895
+ } catch (error) {
2896
+ console.error(formatError(`Failed to list resources: ${error.message}`));
2897
+ process.exit(1);
2898
+ }
2899
+ }
2900
+ async function readResourceCommand(uri, options) {
2901
+ try {
2902
+ const result = await getOrRestoreSession(options.session || null);
2903
+ if (!result) return;
2904
+ const { session } = result;
2905
+ console.error(formatInfo(`Reading resource: ${uri}`));
2906
+ const resource = await session.readResource(uri);
2907
+ if (options.json) {
2908
+ console.log(formatJson(resource));
2909
+ } else {
2910
+ console.log(formatResourceContent(resource));
2911
+ }
2912
+ } catch (error) {
2913
+ console.error(formatError(`Failed to read resource: ${error.message}`));
2914
+ process.exit(1);
2915
+ }
2916
+ }
2917
+ async function subscribeResourceCommand(uri, options) {
2918
+ try {
2919
+ const result = await getOrRestoreSession(options.session || null);
2920
+ if (!result) return;
2921
+ const { session } = result;
2922
+ await session.subscribeToResource(uri);
2923
+ console.log(formatSuccess(`Subscribed to resource: ${uri}`));
2924
+ session.on("notification", async (notification) => {
2925
+ if (notification.method === "notifications/resources/updated") {
2926
+ console.log("");
2927
+ console.log(formatInfo("Resource updated:"));
2928
+ console.log(formatJson(notification.params));
2929
+ }
2930
+ });
2931
+ console.log(formatInfo("Listening for updates... (Press Ctrl+C to stop)"));
2932
+ await new Promise(() => {
2933
+ });
2934
+ } catch (error) {
2935
+ console.error(
2936
+ formatError(`Failed to subscribe to resource: ${error.message}`)
2937
+ );
2938
+ process.exit(1);
2939
+ }
2940
+ }
2941
+ async function unsubscribeResourceCommand(uri, options) {
2942
+ try {
2943
+ const result = await getOrRestoreSession(options.session || null);
2944
+ if (!result) return;
2945
+ const { session } = result;
2946
+ await session.unsubscribeFromResource(uri);
2947
+ console.log(formatSuccess(`Unsubscribed from resource: ${uri}`));
2948
+ } catch (error) {
2949
+ console.error(
2950
+ formatError(`Failed to unsubscribe from resource: ${error.message}`)
2951
+ );
2952
+ process.exit(1);
2953
+ }
2954
+ }
2955
+ async function listPromptsCommand(options) {
2956
+ try {
2957
+ const result = await getOrRestoreSession(options.session || null);
2958
+ if (!result) return;
2959
+ const { session } = result;
2960
+ const promptsResult = await session.listPrompts();
2961
+ const prompts = promptsResult.prompts;
2962
+ if (options.json) {
2963
+ console.log(formatJson(prompts));
2964
+ return;
2965
+ }
2966
+ if (prompts.length === 0) {
2967
+ console.log(formatInfo("No prompts available"));
2968
+ return;
2969
+ }
2970
+ console.log(formatHeader(`Available Prompts (${prompts.length}):`));
2971
+ console.log("");
2972
+ const tableData = prompts.map((prompt2) => ({
2973
+ name: source_default.bold(prompt2.name),
2974
+ description: prompt2.description || source_default.gray("No description")
2975
+ }));
2976
+ console.log(
2977
+ formatTable(tableData, [
2978
+ { key: "name", header: "Prompt", width: 25 },
2979
+ { key: "description", header: "Description", width: 50 }
2980
+ ])
2981
+ );
2982
+ } catch (error) {
2983
+ console.error(formatError(`Failed to list prompts: ${error.message}`));
2984
+ process.exit(1);
2985
+ }
2986
+ }
2987
+ async function getPromptCommand(promptName, argsJson, options) {
2988
+ try {
2989
+ const result = await getOrRestoreSession(options?.session || null);
2990
+ if (!result) return;
2991
+ const { session } = result;
2992
+ let args = {};
2993
+ if (argsJson) {
2994
+ try {
2995
+ args = JSON.parse(argsJson);
2996
+ } catch (error) {
2997
+ console.error(formatError("Invalid JSON arguments"));
2998
+ return;
2999
+ }
3000
+ }
3001
+ console.error(formatInfo(`Getting prompt '${promptName}'...`));
3002
+ const prompt2 = await session.getPrompt(promptName, args);
3003
+ if (options?.json) {
3004
+ console.log(formatJson(prompt2));
3005
+ } else {
3006
+ console.log(formatHeader(`Prompt: ${promptName}`));
3007
+ console.log("");
3008
+ if (prompt2.description) {
3009
+ console.log(prompt2.description);
3010
+ console.log("");
3011
+ }
3012
+ if (prompt2.messages) {
3013
+ console.log(formatHeader("Messages:"));
3014
+ console.log("");
3015
+ console.log(formatPromptMessages(prompt2.messages));
3016
+ }
3017
+ }
3018
+ } catch (error) {
3019
+ console.error(formatError(`Failed to get prompt: ${error.message}`));
3020
+ process.exit(1);
3021
+ }
3022
+ }
3023
+ async function interactiveCommand(options) {
3024
+ try {
3025
+ const result = await getOrRestoreSession(options.session || null);
3026
+ if (!result) return;
3027
+ const { name: sessionName, session } = result;
3028
+ console.log(formatHeader("MCP Interactive Mode"));
3029
+ console.log("");
3030
+ console.log(formatInfo(`Connected to: ${sessionName}`));
3031
+ console.log("");
3032
+ console.log(source_default.gray("Commands:"));
3033
+ console.log(source_default.gray(" tools list - List available tools"));
3034
+ console.log(
3035
+ source_default.gray(
3036
+ " tools call <name> - Call a tool (will prompt for args)"
3037
+ )
3038
+ );
3039
+ console.log(source_default.gray(" tools describe <name> - Show tool details"));
3040
+ console.log(
3041
+ source_default.gray(" resources list - List available resources")
3042
+ );
3043
+ console.log(source_default.gray(" resources read <uri> - Read a resource"));
3044
+ console.log(
3045
+ source_default.gray(" prompts list - List available prompts")
3046
+ );
3047
+ console.log(source_default.gray(" prompts get <name> - Get a prompt"));
3048
+ console.log(source_default.gray(" sessions list - List all sessions"));
3049
+ console.log(
3050
+ source_default.gray(" sessions switch <name> - Switch to another session")
3051
+ );
3052
+ console.log(
3053
+ source_default.gray(" exit, quit - Exit interactive mode")
3054
+ );
3055
+ console.log("");
3056
+ const rl = (0, import_node_readline.createInterface)({
3057
+ input: process.stdin,
3058
+ output: process.stdout,
3059
+ prompt: source_default.cyan("mcp> ")
3060
+ });
3061
+ rl.prompt();
3062
+ rl.on("line", async (line) => {
3063
+ const trimmed = line.trim();
3064
+ if (!trimmed) {
3065
+ rl.prompt();
3066
+ return;
3067
+ }
3068
+ if (trimmed === "exit" || trimmed === "quit") {
3069
+ console.log(formatInfo("Goodbye!"));
3070
+ rl.close();
3071
+ process.exit(0);
3072
+ }
3073
+ const parts = trimmed.split(" ");
3074
+ const scope = parts[0];
3075
+ const command = parts[1];
3076
+ const arg = parts[2];
3077
+ try {
3078
+ if (scope === "tools") {
3079
+ if (command === "list") {
3080
+ const tools = await session.listTools();
3081
+ console.log(
3082
+ formatInfo(
3083
+ `Available tools: ${tools.map((t) => t.name).join(", ")}`
3084
+ )
3085
+ );
3086
+ } else if (command === "call" && arg) {
3087
+ rl.question(
3088
+ "Arguments (JSON, or press Enter for none): ",
3089
+ async (argsInput) => {
3090
+ try {
3091
+ const args = argsInput.trim() ? JSON.parse(argsInput) : {};
3092
+ const result2 = await session.callTool(arg, args);
3093
+ console.log(formatToolCall(result2));
3094
+ } catch (error) {
3095
+ console.error(formatError(error.message));
3096
+ }
3097
+ rl.prompt();
3098
+ }
3099
+ );
3100
+ return;
3101
+ } else if (command === "describe" && arg) {
3102
+ const tools = session.tools;
3103
+ const tool = tools.find((t) => t.name === arg);
3104
+ if (tool) {
3105
+ console.log(formatHeader(`Tool: ${tool.name}`));
3106
+ if (tool.description) console.log(tool.description);
3107
+ if (tool.inputSchema) {
3108
+ console.log("");
3109
+ console.log(formatSchema(tool.inputSchema));
3110
+ }
3111
+ } else {
3112
+ console.error(formatError(`Tool '${arg}' not found`));
3113
+ }
3114
+ } else {
3115
+ console.error(
3116
+ formatError(
3117
+ "Invalid command. Try: tools list, tools call <name>, tools describe <name>"
3118
+ )
3119
+ );
3120
+ }
3121
+ } else if (scope === "resources") {
3122
+ if (command === "list") {
3123
+ const result2 = await session.listAllResources();
3124
+ const resources = result2.resources;
3125
+ console.log(
3126
+ formatInfo(
3127
+ `Available resources: ${resources.map((r) => r.uri).join(", ")}`
3128
+ )
3129
+ );
3130
+ } else if (command === "read" && arg) {
3131
+ const resource = await session.readResource(arg);
3132
+ console.log(formatResourceContent(resource));
3133
+ } else {
3134
+ console.error(
3135
+ formatError(
3136
+ "Invalid command. Try: resources list, resources read <uri>"
3137
+ )
3138
+ );
3139
+ }
3140
+ } else if (scope === "prompts") {
3141
+ if (command === "list") {
3142
+ const result2 = await session.listPrompts();
3143
+ const prompts = result2.prompts;
3144
+ console.log(
3145
+ formatInfo(
3146
+ `Available prompts: ${prompts.map((p) => p.name).join(", ")}`
3147
+ )
3148
+ );
3149
+ } else if (command === "get" && arg) {
3150
+ rl.question(
3151
+ "Arguments (JSON, or press Enter for none): ",
3152
+ async (argsInput) => {
3153
+ try {
3154
+ const args = argsInput.trim() ? JSON.parse(argsInput) : {};
3155
+ const prompt2 = await session.getPrompt(arg, args);
3156
+ console.log(formatPromptMessages(prompt2.messages));
3157
+ } catch (error) {
3158
+ console.error(formatError(error.message));
3159
+ }
3160
+ rl.prompt();
3161
+ }
3162
+ );
3163
+ return;
3164
+ } else {
3165
+ console.error(
3166
+ formatError(
3167
+ "Invalid command. Try: prompts list, prompts get <name>"
3168
+ )
3169
+ );
3170
+ }
3171
+ } else if (scope === "sessions") {
3172
+ if (command === "list") {
3173
+ await listSessionsCommand();
3174
+ } else if (command === "switch" && arg) {
3175
+ console.log(
3176
+ formatWarning(
3177
+ "Session switching in interactive mode will be available in a future version"
3178
+ )
3179
+ );
3180
+ } else {
3181
+ console.error(formatError("Invalid command. Try: sessions list"));
3182
+ }
3183
+ } else {
3184
+ console.error(
3185
+ formatError(
3186
+ "Unknown command. Type a valid scope: tools, resources, prompts, sessions"
3187
+ )
3188
+ );
3189
+ }
3190
+ } catch (error) {
3191
+ console.error(formatError(error.message));
3192
+ }
3193
+ rl.prompt();
3194
+ });
3195
+ rl.on("close", () => {
3196
+ console.log("");
3197
+ console.log(formatInfo("Goodbye!"));
3198
+ process.exit(0);
3199
+ });
3200
+ } catch (error) {
3201
+ console.error(
3202
+ formatError(`Failed to start interactive mode: ${error.message}`)
3203
+ );
3204
+ process.exit(1);
3205
+ }
3206
+ }
3207
+ function createClientCommand() {
3208
+ const clientCommand = new import_commander.Command("client").description(
3209
+ "Interactive MCP client for terminal usage"
3210
+ );
3211
+ clientCommand.command("connect <url>").description("Connect to an MCP server").option("--name <name>", "Session name").option("--stdio", "Use stdio connector instead of HTTP").option("--auth <token>", "Authentication token").action(connectCommand);
3212
+ clientCommand.command("disconnect [session]").description("Disconnect from a session").option("--all", "Disconnect all sessions").action(disconnectCommand);
3213
+ const sessionsCommand = new import_commander.Command("sessions").description(
3214
+ "Manage CLI sessions"
3215
+ );
3216
+ sessionsCommand.command("list").description("List all saved sessions").action(listSessionsCommand);
3217
+ sessionsCommand.command("switch <name>").description("Switch to a different session").action(switchSessionCommand);
3218
+ clientCommand.addCommand(sessionsCommand);
3219
+ const toolsCommand = new import_commander.Command("tools").description(
3220
+ "Interact with MCP tools"
3221
+ );
3222
+ toolsCommand.command("list").description("List available tools").option("--session <name>", "Use specific session").option("--json", "Output as JSON").action(listToolsCommand);
3223
+ toolsCommand.command("call <name> [args]").description("Call a tool with arguments (JSON string)").option("--session <name>", "Use specific session").option("--timeout <ms>", "Request timeout in milliseconds", parseInt).option("--json", "Output as JSON").action(callToolCommand);
3224
+ toolsCommand.command("describe <name>").description("Show tool details and schema").option("--session <name>", "Use specific session").action(describeToolCommand);
3225
+ clientCommand.addCommand(toolsCommand);
3226
+ const resourcesCommand = new import_commander.Command("resources").description(
3227
+ "Interact with MCP resources"
3228
+ );
3229
+ resourcesCommand.command("list").description("List available resources").option("--session <name>", "Use specific session").option("--json", "Output as JSON").action(listResourcesCommand);
3230
+ resourcesCommand.command("read <uri>").description("Read a resource by URI").option("--session <name>", "Use specific session").option("--json", "Output as JSON").action(readResourceCommand);
3231
+ resourcesCommand.command("subscribe <uri>").description("Subscribe to resource updates").option("--session <name>", "Use specific session").action(subscribeResourceCommand);
3232
+ resourcesCommand.command("unsubscribe <uri>").description("Unsubscribe from resource updates").option("--session <name>", "Use specific session").action(unsubscribeResourceCommand);
3233
+ clientCommand.addCommand(resourcesCommand);
3234
+ const promptsCommand = new import_commander.Command("prompts").description(
3235
+ "Interact with MCP prompts"
3236
+ );
3237
+ promptsCommand.command("list").description("List available prompts").option("--session <name>", "Use specific session").option("--json", "Output as JSON").action(listPromptsCommand);
3238
+ promptsCommand.command("get <name> [args]").description("Get a prompt with arguments (JSON string)").option("--session <name>", "Use specific session").option("--json", "Output as JSON").action(getPromptCommand);
3239
+ clientCommand.addCommand(promptsCommand);
3240
+ clientCommand.command("interactive").description("Start interactive REPL mode").option("--session <name>", "Use specific session").action(interactiveCommand);
3241
+ return clientCommand;
3242
+ }
3243
+
3244
+ // src/index.ts
3245
+ var program = new import_commander2.Command();
3246
+ var packageContent = (0, import_node_fs7.readFileSync)(
3247
+ import_node_path5.default.join(__dirname, "../package.json"),
3248
+ "utf-8"
3249
+ );
3250
+ var packageJson = JSON.parse(packageContent);
3251
+ var packageVersion = packageJson.version || "unknown";
3252
+ program.name("mcp-use").description("Create and run MCP servers with ui resources widgets").version(packageVersion);
3253
+ async function isPortAvailable(port, host = "localhost") {
3254
+ try {
3255
+ await fetch(`http://${host}:${port}`);
3256
+ return false;
3257
+ } catch {
3258
+ return true;
3259
+ }
3260
+ }
3261
+ async function findAvailablePort2(startPort, host = "localhost") {
3262
+ for (let port = startPort; port < startPort + 100; port++) {
3263
+ if (await isPortAvailable(port, host)) {
3264
+ return port;
3265
+ }
3266
+ }
3267
+ throw new Error("No available ports found");
3268
+ }
3269
+ async function waitForServer(port, host = "localhost", maxAttempts = 30) {
3270
+ for (let i = 0; i < maxAttempts; i++) {
3271
+ const controller = new AbortController();
3272
+ try {
3273
+ const response = await fetch(`http://${host}:${port}/inspector/health`, {
3274
+ signal: controller.signal
3275
+ });
3276
+ if (response.ok) {
3277
+ return true;
3278
+ }
3279
+ } catch {
3280
+ } finally {
3281
+ controller.abort();
3282
+ }
3283
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
3284
+ }
3285
+ return false;
3286
+ }
3287
+ function runCommand(command, args, cwd, env2, filterStderr = false) {
3288
+ const proc = (0, import_node_child_process10.spawn)(command, args, {
3289
+ cwd,
3290
+ stdio: filterStderr ? ["inherit", "inherit", "pipe"] : "inherit",
3291
+ shell: false,
3292
+ env: env2 ? { ...process.env, ...env2 } : process.env
3293
+ });
3294
+ if (filterStderr && proc.stderr) {
3295
+ proc.stderr.on("data", (data) => {
3296
+ const text = data.toString();
3297
+ if (!text.includes("Previous process hasn't exited yet") && !text.includes("Force killing")) {
3298
+ process.stderr.write(data);
3299
+ }
3300
+ });
3301
+ }
3302
+ const promise = new Promise((resolve, reject) => {
3303
+ proc.on("error", reject);
3304
+ proc.on("exit", (code) => {
3305
+ if (code === 0 || code === 130 || code === 143) {
3306
+ resolve();
3307
+ } else {
3308
+ reject(new Error(`Command failed with exit code ${code}`));
3309
+ }
3310
+ });
3311
+ });
3312
+ return { promise, process: proc };
3313
+ }
3314
+ async function startTunnel(port, subdomain) {
3315
+ return new Promise((resolve, reject) => {
3316
+ console.log(source_default.gray(`Starting tunnel for port ${port}...`));
3317
+ const tunnelArgs = ["--yes", "@mcp-use/tunnel", String(port)];
3318
+ if (subdomain) {
3319
+ tunnelArgs.push("--subdomain", subdomain);
3320
+ }
3321
+ const proc = (0, import_node_child_process10.spawn)("npx", tunnelArgs, {
3322
+ stdio: ["ignore", "pipe", "pipe"],
3323
+ shell: false
3324
+ });
3325
+ let resolved = false;
3326
+ let isShuttingDown = false;
3327
+ proc.stdout?.on("data", (data) => {
3328
+ const text = data.toString();
3329
+ const isShutdownMessage = text.includes("Shutting down") || text.includes("\u{1F6D1}");
3330
+ if (!isShuttingDown && !isShutdownMessage) {
3331
+ process.stdout.write(text);
3332
+ }
3333
+ const urlMatch = text.match(/https?:\/\/([a-z0-9-]+\.[a-z0-9.-]+)/i);
3334
+ if (urlMatch && !resolved) {
3335
+ const url = urlMatch[0];
3336
+ const fullDomain = urlMatch[1];
3337
+ const subdomainMatch = fullDomain.match(/^([a-z0-9-]+)\./i);
3338
+ let extractedSubdomain = subdomainMatch ? subdomainMatch[1] : fullDomain.split(".")[0];
3339
+ if (!/^[a-z0-9-]+$/i.test(extractedSubdomain)) {
3340
+ console.warn(
3341
+ source_default.yellow(
3342
+ `Warning: Extracted subdomain "${extractedSubdomain}" does not match expected format.`
3343
+ )
3344
+ );
3345
+ extractedSubdomain = "";
3346
+ }
3347
+ resolved = true;
3348
+ clearTimeout(setupTimeout);
3349
+ console.log(source_default.green.bold(`\u2713 Tunnel established: ${url}/mcp`));
3350
+ resolve({ url, subdomain: extractedSubdomain, process: proc });
3351
+ }
3352
+ });
3353
+ proc.stderr?.on("data", (data) => {
3354
+ const text = data.toString();
3355
+ if (!isShuttingDown && !text.includes("INFO") && !text.includes("bore_cli") && !text.includes("Shutting down")) {
3356
+ process.stderr.write(data);
3357
+ }
3358
+ });
3359
+ proc.on("error", (error) => {
3360
+ if (!resolved) {
3361
+ clearTimeout(setupTimeout);
3362
+ reject(new Error(`Failed to start tunnel: ${error.message}`));
3363
+ }
3364
+ });
3365
+ proc.on("exit", (code) => {
3366
+ if (code !== 0 && !resolved) {
3367
+ clearTimeout(setupTimeout);
3368
+ reject(new Error(`Tunnel process exited with code ${code}`));
3369
+ }
3370
+ });
3371
+ proc.markShutdown = () => {
3372
+ isShuttingDown = true;
3373
+ };
3374
+ const setupTimeout = setTimeout(() => {
3375
+ if (!resolved) {
3376
+ proc.kill();
3377
+ reject(new Error("Tunnel setup timed out"));
3378
+ }
3379
+ }, 3e4);
3380
+ });
3381
+ }
3382
+ async function findServerFile(projectPath) {
3383
+ const candidates = ["index.ts", "src/index.ts", "server.ts", "src/server.ts"];
3384
+ for (const candidate of candidates) {
3385
+ try {
3386
+ await (0, import_promises5.access)(import_node_path5.default.join(projectPath, candidate));
3387
+ return candidate;
3388
+ } catch {
3389
+ continue;
3390
+ }
3391
+ }
3392
+ throw new Error("No server file found");
3393
+ }
3394
+ async function buildWidgets(projectPath) {
3395
+ const { promises: fs9 } = await import("fs");
3396
+ const { build } = await import("vite");
3397
+ const resourcesDir = import_node_path5.default.join(projectPath, "resources");
3398
+ const mcpUrl = process.env.MCP_URL;
3399
+ try {
3400
+ await (0, import_promises5.access)(resourcesDir);
3401
+ } catch {
3402
+ console.log(
3403
+ source_default.gray("No resources/ directory found - skipping widget build")
3404
+ );
3405
+ return [];
3406
+ }
3407
+ const entries = [];
3408
+ try {
3409
+ const files = await fs9.readdir(resourcesDir, { withFileTypes: true });
3410
+ for (const dirent of files) {
3411
+ if (dirent.name.startsWith("._") || dirent.name.startsWith(".DS_Store")) {
3412
+ continue;
3413
+ }
3414
+ if (dirent.isFile() && (dirent.name.endsWith(".tsx") || dirent.name.endsWith(".ts"))) {
3415
+ entries.push({
3416
+ name: dirent.name.replace(/\.tsx?$/, ""),
3417
+ path: import_node_path5.default.join(resourcesDir, dirent.name)
3418
+ });
3419
+ } else if (dirent.isDirectory()) {
3420
+ const widgetPath = import_node_path5.default.join(resourcesDir, dirent.name, "widget.tsx");
3421
+ try {
3422
+ await fs9.access(widgetPath);
3423
+ entries.push({
3424
+ name: dirent.name,
3425
+ path: widgetPath
3426
+ });
3427
+ } catch {
3428
+ }
3429
+ }
3430
+ }
3431
+ } catch (error) {
3432
+ console.log(source_default.gray("No widgets found in resources/ directory"));
3433
+ return [];
3434
+ }
3435
+ if (entries.length === 0) {
3436
+ console.log(source_default.gray("No widgets found in resources/ directory"));
3437
+ return [];
3438
+ }
3439
+ console.log(source_default.gray(`Building ${entries.length} widget(s)...`));
3440
+ const react = (await import("@vitejs/plugin-react")).default;
3441
+ const tailwindcss = (await import("@tailwindcss/vite")).default;
3442
+ const packageJsonPath = import_node_path5.default.join(projectPath, "package.json");
3443
+ let favicon = "";
3444
+ try {
3445
+ const pkgContent = await fs9.readFile(packageJsonPath, "utf-8");
3446
+ const pkg = JSON.parse(pkgContent);
3447
+ favicon = pkg.mcpUse?.favicon || "";
3448
+ } catch {
3449
+ }
3450
+ const builtWidgets = [];
3451
+ for (const entry of entries) {
3452
+ const widgetName = entry.name;
3453
+ const entryPath = entry.path;
3454
+ console.log(source_default.gray(` - Building ${widgetName}...`));
3455
+ const tempDir = import_node_path5.default.join(projectPath, ".mcp-use", widgetName);
3456
+ await fs9.mkdir(tempDir, { recursive: true });
3457
+ const relativeResourcesPath = import_node_path5.default.relative(tempDir, resourcesDir).replace(/\\/g, "/");
3458
+ const mcpUsePath = import_node_path5.default.join(projectPath, "node_modules", "mcp-use");
3459
+ const relativeMcpUsePath = import_node_path5.default.relative(tempDir, mcpUsePath).replace(/\\/g, "/");
3460
+ const cssContent = `@import "tailwindcss";
3461
+
3462
+ /* Configure Tailwind to scan the resources directory and mcp-use package */
3463
+ @source "${relativeResourcesPath}";
3464
+ @source "${relativeMcpUsePath}/**/*.{ts,tsx,js,jsx}";
3465
+ `;
3466
+ await fs9.writeFile(import_node_path5.default.join(tempDir, "styles.css"), cssContent, "utf8");
3467
+ const entryContent = `import React from 'react'
3468
+ import { createRoot } from 'react-dom/client'
3469
+ import './styles.css'
3470
+ import Component from '${entryPath}'
3471
+
3472
+ const container = document.getElementById('widget-root')
3473
+ if (container && Component) {
3474
+ const root = createRoot(container)
3475
+ root.render(<Component />)
3476
+ }
3477
+ `;
3478
+ const htmlContent = `<!doctype html>
3479
+ <html lang="en">
3480
+ <head>
3481
+ <meta charset="UTF-8" />
3482
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
3483
+ <title>${widgetName} Widget</title>${favicon ? `
3484
+ <link rel="icon" href="/mcp-use/public/${favicon}" />` : ""}
3485
+ </head>
3486
+ <body>
3487
+ <div id="widget-root"></div>
3488
+ <script type="module" src="/entry.tsx"></script>
3489
+ </body>
3490
+ </html>`;
3491
+ await fs9.writeFile(import_node_path5.default.join(tempDir, "entry.tsx"), entryContent, "utf8");
3492
+ await fs9.writeFile(import_node_path5.default.join(tempDir, "index.html"), htmlContent, "utf8");
3493
+ const outDir = import_node_path5.default.join(
3494
+ projectPath,
3495
+ "dist",
3496
+ "resources",
3497
+ "widgets",
3498
+ widgetName
3499
+ );
3500
+ const baseUrl = mcpUrl ? `${mcpUrl}/${widgetName}/` : `/mcp-use/widgets/${widgetName}/`;
3501
+ let widgetMetadata = {};
3502
+ try {
3503
+ const metadataTempDir = import_node_path5.default.join(
3504
+ projectPath,
3505
+ ".mcp-use",
3506
+ `${widgetName}-metadata`
3507
+ );
3508
+ await fs9.mkdir(metadataTempDir, { recursive: true });
3509
+ const { createServer: createServer2 } = await import("vite");
3510
+ const nodeStubsPlugin = {
3511
+ name: "node-stubs",
3512
+ enforce: "pre",
3513
+ resolveId(id) {
3514
+ if (id === "posthog-node" || id.startsWith("posthog-node/")) {
3515
+ return "\0virtual:posthog-node-stub";
3516
+ }
3517
+ return null;
3518
+ },
3519
+ load(id) {
3520
+ if (id === "\0virtual:posthog-node-stub") {
3521
+ return `
3522
+ export class PostHog {
3523
+ constructor() {}
3524
+ capture() {}
3525
+ identify() {}
3526
+ alias() {}
3527
+ flush() { return Promise.resolve(); }
3528
+ shutdown() { return Promise.resolve(); }
3529
+ }
3530
+ export default PostHog;
3531
+ `;
3532
+ }
3533
+ return null;
3534
+ }
3535
+ };
3536
+ const metadataServer = await createServer2({
3537
+ root: metadataTempDir,
3538
+ cacheDir: import_node_path5.default.join(metadataTempDir, ".vite-cache"),
3539
+ plugins: [nodeStubsPlugin, tailwindcss(), react()],
3540
+ resolve: {
3541
+ alias: {
3542
+ "@": resourcesDir
3543
+ }
3544
+ },
3545
+ server: {
3546
+ middlewareMode: true
3547
+ },
3548
+ optimizeDeps: {
3549
+ // Exclude Node.js-only packages from browser bundling
3550
+ exclude: ["posthog-node"]
3551
+ },
3552
+ ssr: {
3553
+ // Force Vite to transform these packages in SSR instead of using external requires
3554
+ noExternal: ["@openai/apps-sdk-ui", "react-router"],
3555
+ // Mark Node.js-only packages as external in SSR mode
3556
+ external: ["posthog-node"]
3557
+ },
3558
+ define: {
3559
+ // Define process.env for SSR context
3560
+ "process.env.NODE_ENV": JSON.stringify(
3561
+ process.env.NODE_ENV || "development"
3562
+ ),
3563
+ "import.meta.env.DEV": true,
3564
+ "import.meta.env.PROD": false,
3565
+ "import.meta.env.MODE": JSON.stringify("development"),
3566
+ "import.meta.env.SSR": true
3567
+ },
3568
+ clearScreen: false,
3569
+ logLevel: "silent",
3570
+ customLogger: {
3571
+ info: () => {
3572
+ },
3573
+ warn: () => {
3574
+ },
3575
+ error: () => {
3576
+ },
3577
+ clearScreen: () => {
3578
+ },
3579
+ hasErrorLogged: () => false,
3580
+ hasWarned: false,
3581
+ warnOnce: () => {
3582
+ }
3583
+ }
3584
+ });
3585
+ try {
3586
+ const mod = await metadataServer.ssrLoadModule(entryPath);
3587
+ if (mod.widgetMetadata) {
3588
+ widgetMetadata = {
3589
+ ...mod.widgetMetadata,
3590
+ title: mod.widgetMetadata.title || widgetName,
3591
+ description: mod.widgetMetadata.description,
3592
+ inputs: mod.widgetMetadata.inputs?.shape || {}
3593
+ };
3594
+ }
3595
+ await new Promise((resolve) => setTimeout(resolve, 50));
3596
+ } catch (error) {
3597
+ console.warn(
3598
+ source_default.yellow(` \u26A0 Could not extract metadata for ${widgetName}`)
3599
+ );
3600
+ } finally {
3601
+ await metadataServer.close();
3602
+ try {
3603
+ await fs9.rm(metadataTempDir, { recursive: true, force: true });
3604
+ } catch {
3605
+ }
3606
+ }
3607
+ } catch (error) {
3608
+ }
3609
+ try {
3610
+ const buildNodeStubsPlugin = {
3611
+ name: "node-stubs-build",
3612
+ enforce: "pre",
3613
+ resolveId(id) {
3614
+ if (id === "posthog-node" || id.startsWith("posthog-node/")) {
3615
+ return "\0virtual:posthog-node-stub";
3616
+ }
3617
+ if (id === "path" || id === "node:path") {
3618
+ return "\0virtual:path-stub";
3619
+ }
3620
+ return null;
3621
+ },
3622
+ load(id) {
3623
+ if (id === "\0virtual:posthog-node-stub") {
3624
+ return `
3625
+ export class PostHog {
3626
+ constructor() {}
3627
+ capture() {}
3628
+ identify() {}
3629
+ alias() {}
3630
+ flush() { return Promise.resolve(); }
3631
+ shutdown() { return Promise.resolve(); }
3632
+ }
3633
+ export default PostHog;
3634
+ `;
3635
+ }
3636
+ if (id === "\0virtual:path-stub") {
3637
+ return `
3638
+ export function join(...paths) {
3639
+ return paths.filter(Boolean).join("/").replace(/\\/\\//g, "/").replace(/\\/$/, "");
3640
+ }
3641
+ export function resolve(...paths) {
3642
+ return join(...paths);
3643
+ }
3644
+ export function dirname(filepath) {
3645
+ const parts = filepath.split("/");
3646
+ parts.pop();
3647
+ return parts.join("/") || "/";
3648
+ }
3649
+ export function basename(filepath, ext) {
3650
+ const parts = filepath.split("/");
3651
+ let name = parts[parts.length - 1] || "";
3652
+ if (ext && name.endsWith(ext)) {
3653
+ name = name.slice(0, -ext.length);
3654
+ }
3655
+ return name;
3656
+ }
3657
+ export function extname(filepath) {
3658
+ const name = basename(filepath);
3659
+ const index = name.lastIndexOf(".");
3660
+ return index > 0 ? name.slice(index) : "";
3661
+ }
3662
+ export function normalize(filepath) {
3663
+ return filepath.replace(/\\/\\//g, "/");
3664
+ }
3665
+ export function isAbsolute(filepath) {
3666
+ return filepath.startsWith("/");
3667
+ }
3668
+ export const sep = "/";
3669
+ export const delimiter = ":";
3670
+ export const posix = {
3671
+ join,
3672
+ resolve,
3673
+ dirname,
3674
+ basename,
3675
+ extname,
3676
+ normalize,
3677
+ isAbsolute,
3678
+ sep,
3679
+ delimiter,
3680
+ };
3681
+ export default {
3682
+ join,
3683
+ resolve,
3684
+ dirname,
3685
+ basename,
3686
+ extname,
3687
+ normalize,
3688
+ isAbsolute,
3689
+ sep,
3690
+ delimiter,
3691
+ posix,
3692
+ };
3693
+ `;
3694
+ }
3695
+ return null;
3696
+ }
3697
+ };
3698
+ await build({
3699
+ root: tempDir,
3700
+ base: baseUrl,
3701
+ plugins: [buildNodeStubsPlugin, tailwindcss(), react()],
3702
+ experimental: {
3703
+ renderBuiltUrl: (filename, { hostType }) => {
3704
+ if (["js", "css"].includes(hostType)) {
3705
+ return {
3706
+ runtime: `window.__getFile(${JSON.stringify(filename)})`
3707
+ };
3708
+ } else {
3709
+ return { relative: true };
3710
+ }
3711
+ }
3712
+ },
3713
+ resolve: {
3714
+ alias: {
3715
+ "@": resourcesDir
3716
+ }
3717
+ },
3718
+ optimizeDeps: {
3719
+ // Exclude Node.js-only packages from browser bundling
3720
+ exclude: ["posthog-node"]
3721
+ },
3722
+ build: {
3723
+ outDir,
3724
+ emptyOutDir: true,
3725
+ rollupOptions: {
3726
+ input: import_node_path5.default.join(tempDir, "index.html"),
3727
+ external: (id) => {
3728
+ return false;
3729
+ }
3730
+ }
3731
+ }
3732
+ });
3733
+ const mcpServerUrl = process.env.MCP_SERVER_URL;
3734
+ if (mcpServerUrl) {
3735
+ try {
3736
+ const htmlPath = import_node_path5.default.join(outDir, "index.html");
3737
+ let html = await fs9.readFile(htmlPath, "utf8");
3738
+ const injectionScript = `<script>window.__getFile = (filename) => { return "${mcpUrl}/${widgetName}/"+filename }; window.__mcpPublicUrl = "${mcpServerUrl}/mcp-use/public"; window.__mcpPublicAssetsUrl = "${mcpUrl}/public";</script>`;
3739
+ if (!html.includes("window.__mcpPublicUrl")) {
3740
+ html = html.replace(
3741
+ /<head[^>]*>/i,
3742
+ `<head>
3743
+ ${injectionScript}`
3744
+ );
3745
+ }
3746
+ if (/<base\s+[^>]*\/?>/i.test(html)) {
3747
+ html = html.replace(
3748
+ /<base\s+[^>]*\/?>/i,
3749
+ `<base href="${mcpServerUrl}">`
3750
+ );
3751
+ } else {
3752
+ html = html.replace(
3753
+ injectionScript,
3754
+ `${injectionScript}
3755
+ <base href="${mcpServerUrl}">`
3756
+ );
3757
+ }
3758
+ await fs9.writeFile(htmlPath, html, "utf8");
3759
+ console.log(
3760
+ source_default.gray(` \u2192 Injected MCP_SERVER_URL into ${widgetName}`)
3761
+ );
3762
+ } catch (error) {
3763
+ console.warn(
3764
+ source_default.yellow(
3765
+ ` \u26A0 Failed to post-process HTML for ${widgetName}:`,
3766
+ error
3767
+ )
3768
+ );
3769
+ }
3770
+ }
3771
+ builtWidgets.push({
3772
+ name: widgetName,
3773
+ metadata: widgetMetadata
3774
+ });
3775
+ console.log(source_default.green(` \u2713 Built ${widgetName}`));
3776
+ } catch (error) {
3777
+ console.error(source_default.red(` \u2717 Failed to build ${widgetName}:`), error);
3778
+ }
3779
+ }
3780
+ return builtWidgets;
3781
+ }
3782
+ program.command("build").description("Build TypeScript and MCP UI widgets").option("-p, --path <path>", "Path to project directory", process.cwd()).option("--with-inspector", "Include inspector in production build").action(async (options) => {
3783
+ try {
3784
+ const projectPath = import_node_path5.default.resolve(options.path);
3785
+ const { promises: fs9 } = await import("fs");
3786
+ console.log(source_default.cyan.bold(`mcp-use v${packageJson.version}`));
3787
+ const builtWidgets = await buildWidgets(projectPath);
3788
+ console.log(source_default.gray("Building TypeScript..."));
3789
+ await runCommand("npx", ["tsc"], projectPath);
3790
+ console.log(source_default.green("\u2713 TypeScript build complete!"));
3791
+ const publicDir = import_node_path5.default.join(projectPath, "public");
3792
+ try {
3793
+ await fs9.access(publicDir);
3794
+ console.log(source_default.gray("Copying public assets..."));
3795
+ await fs9.cp(publicDir, import_node_path5.default.join(projectPath, "dist", "public"), {
3796
+ recursive: true
3797
+ });
3798
+ console.log(source_default.green("\u2713 Public assets copied"));
3799
+ } catch {
3800
+ }
3801
+ const manifestPath = import_node_path5.default.join(projectPath, "dist", "mcp-use.json");
3802
+ let existingManifest = {};
3803
+ try {
3804
+ const existingContent = await fs9.readFile(manifestPath, "utf-8");
3805
+ existingManifest = JSON.parse(existingContent);
3806
+ } catch {
3807
+ }
3808
+ const widgetsData = {};
3809
+ for (const widget of builtWidgets) {
3810
+ widgetsData[widget.name] = widget.metadata;
3811
+ }
3812
+ const includeInspector = !!options.withInspector;
3813
+ const buildTime = (/* @__PURE__ */ new Date()).toISOString();
3814
+ const { createHash } = await import("crypto");
3815
+ const buildId = createHash("sha256").update(buildTime + Math.random().toString()).digest("hex").substring(0, 16);
3816
+ const manifest = {
3817
+ ...existingManifest,
3818
+ // Preserve existing fields like tunnel
3819
+ includeInspector,
3820
+ buildTime,
3821
+ buildId,
3822
+ widgets: widgetsData
3823
+ };
3824
+ await fs9.mkdir(import_node_path5.default.dirname(manifestPath), { recursive: true });
3825
+ await fs9.writeFile(
3826
+ manifestPath,
3827
+ JSON.stringify(manifest, null, 2),
3828
+ "utf8"
3829
+ );
3830
+ console.log(source_default.green("\u2713 Build manifest created"));
3831
+ console.log(source_default.green.bold(`
3832
+ \u2713 Build complete!`));
3833
+ if (builtWidgets.length > 0) {
3834
+ console.log(source_default.gray(` ${builtWidgets.length} widget(s) built`));
3835
+ }
3836
+ if (options.withInspector) {
3837
+ console.log(source_default.gray(" Inspector included"));
3838
+ }
3839
+ } catch (error) {
3840
+ console.error(source_default.red("Build failed:"), error);
3841
+ process.exit(1);
3842
+ }
3843
+ });
3844
+ program.command("dev").description("Run development server with auto-reload and inspector").option("-p, --path <path>", "Path to project directory", process.cwd()).option("--port <port>", "Server port", "3000").option("--host <host>", "Server host", "localhost").option("--no-open", "Do not auto-open inspector").action(async (options) => {
3845
+ try {
3846
+ const projectPath = import_node_path5.default.resolve(options.path);
3847
+ let port = parseInt(options.port, 10);
3848
+ const host = options.host;
3849
+ console.log(source_default.cyan.bold(`mcp-use v${packageJson.version}`));
3850
+ if (!await isPortAvailable(port, host)) {
3851
+ console.log(source_default.yellow.bold(`\u26A0\uFE0F Port ${port} is already in use`));
3852
+ const availablePort = await findAvailablePort2(port, host);
3853
+ console.log(source_default.green.bold(`\u2713 Using port ${availablePort} instead`));
3854
+ port = availablePort;
3855
+ }
3856
+ const serverFile = await findServerFile(projectPath);
3857
+ const processes = [];
3858
+ const env2 = {
3859
+ PORT: String(port),
3860
+ HOST: host,
3861
+ NODE_ENV: "development"
3862
+ };
3863
+ const serverCommand = runCommand(
3864
+ "npx",
3865
+ ["tsx", "watch", serverFile],
3866
+ projectPath,
3867
+ env2,
3868
+ true
3869
+ );
3870
+ processes.push(serverCommand.process);
3871
+ if (options.open !== false) {
3872
+ const startTime = Date.now();
3873
+ const ready = await waitForServer(port, host);
3874
+ if (ready) {
3875
+ const mcpEndpoint = `http://${host}:${port}/mcp`;
3876
+ const inspectorUrl = `http://${host}:${port}/inspector?autoConnect=${encodeURIComponent(mcpEndpoint)}`;
3877
+ const readyTime = Date.now() - startTime;
3878
+ console.log(source_default.green.bold(`\u2713 Ready in ${readyTime}ms`));
3879
+ console.log(source_default.whiteBright(`Local: http://${host}:${port}`));
3880
+ console.log(source_default.whiteBright(`Network: http://${host}:${port}`));
3881
+ console.log(source_default.whiteBright(`MCP: ${mcpEndpoint}`));
3882
+ console.log(source_default.whiteBright(`Inspector: ${inspectorUrl}
3883
+ `));
3884
+ await open_default(inspectorUrl);
3885
+ }
3886
+ }
3887
+ const cleanup = () => {
3888
+ console.log(source_default.gray("\n\nShutting down..."));
3889
+ const processesToKill = processes.length;
3890
+ let killedCount = 0;
3891
+ const checkAndExit = () => {
3892
+ killedCount++;
3893
+ if (killedCount >= processesToKill) {
3894
+ process.exit(0);
3895
+ }
3896
+ };
3897
+ processes.forEach((proc) => {
3898
+ if (proc && typeof proc.kill === "function") {
3899
+ proc.on("exit", checkAndExit);
3900
+ proc.kill("SIGINT");
3901
+ } else {
3902
+ checkAndExit();
3903
+ }
3904
+ });
3905
+ setTimeout(() => {
3906
+ processes.forEach((proc) => {
3907
+ if (proc && typeof proc.kill === "function" && proc.exitCode === null) {
3908
+ proc.kill("SIGKILL");
3909
+ }
3910
+ });
3911
+ process.exit(0);
3912
+ }, 1e3);
3913
+ };
3914
+ process.on("SIGINT", cleanup);
3915
+ process.on("SIGTERM", cleanup);
3916
+ await new Promise(() => {
3917
+ });
3918
+ } catch (error) {
3919
+ console.error(source_default.red("Dev mode failed:"), error);
3920
+ process.exit(1);
3921
+ }
3922
+ });
3923
+ program.command("start").description("Start production server").option("-p, --path <path>", "Path to project directory", process.cwd()).option("--port <port>", "Server port", "3000").option("--tunnel", "Expose server through a tunnel").action(async (options) => {
3924
+ try {
3925
+ const projectPath = import_node_path5.default.resolve(options.path);
3926
+ const port = parseInt(options.port, 10);
3927
+ console.log(
3928
+ `\x1B[36m\x1B[1mmcp-use\x1B[0m \x1B[90mVersion: ${packageJson.version}\x1B[0m
3929
+ `
3930
+ );
3931
+ let mcpUrl;
3932
+ let tunnelProcess = void 0;
3933
+ let tunnelSubdomain = void 0;
3934
+ if (options.tunnel) {
3935
+ try {
3936
+ const manifestPath = import_node_path5.default.join(projectPath, "dist", "mcp-use.json");
3937
+ let existingSubdomain;
3938
+ try {
3939
+ const manifestContent = await (0, import_promises5.readFile)(manifestPath, "utf-8");
3940
+ const manifest = JSON.parse(manifestContent);
3941
+ existingSubdomain = manifest.tunnel?.subdomain;
3942
+ if (existingSubdomain) {
3943
+ console.log(
3944
+ source_default.gray(`Found existing subdomain: ${existingSubdomain}`)
3945
+ );
3946
+ }
3947
+ } catch (error) {
3948
+ console.debug(
3949
+ source_default.gray(
3950
+ `Debug: Failed to read or parse mcp-use.json: ${error instanceof Error ? error.message : String(error)}`
3951
+ )
3952
+ );
3953
+ }
3954
+ const tunnelInfo = await startTunnel(port, existingSubdomain);
3955
+ mcpUrl = tunnelInfo.url;
3956
+ tunnelProcess = tunnelInfo.process;
3957
+ const subdomain = tunnelInfo.subdomain;
3958
+ tunnelSubdomain = subdomain;
3959
+ try {
3960
+ let manifest = {};
3961
+ try {
3962
+ const manifestContent = await (0, import_promises5.readFile)(manifestPath, "utf-8");
3963
+ manifest = JSON.parse(manifestContent);
3964
+ } catch {
3965
+ }
3966
+ if (!manifest.tunnel) {
3967
+ manifest.tunnel = {};
3968
+ }
3969
+ manifest.tunnel.subdomain = subdomain;
3970
+ await (0, import_promises5.mkdir)(import_node_path5.default.dirname(manifestPath), { recursive: true });
3971
+ await (0, import_promises5.writeFile)(
3972
+ manifestPath,
3973
+ JSON.stringify(manifest, null, 2),
3974
+ "utf-8"
3975
+ );
3976
+ } catch (error) {
3977
+ console.warn(
3978
+ source_default.yellow(
3979
+ `\u26A0\uFE0F Failed to save subdomain to mcp-use.json: ${error instanceof Error ? error.message : "Unknown error"}`
3980
+ )
3981
+ );
3982
+ }
3983
+ } catch (error) {
3984
+ console.error(source_default.red("Failed to start tunnel:"), error);
3985
+ process.exit(1);
3986
+ }
3987
+ }
3988
+ let serverFile = "dist/index.js";
3989
+ try {
3990
+ await (0, import_promises5.access)(import_node_path5.default.join(projectPath, serverFile));
3991
+ } catch {
3992
+ serverFile = "dist/server.js";
3993
+ }
3994
+ console.log("Starting production server...");
3995
+ const env2 = {
3996
+ ...process.env,
3997
+ PORT: String(port),
3998
+ NODE_ENV: "production"
3999
+ };
4000
+ if (mcpUrl) {
4001
+ env2.MCP_URL = mcpUrl;
4002
+ console.log(source_default.whiteBright(`Tunnel: ${mcpUrl}/mcp`));
4003
+ }
4004
+ const serverProc = (0, import_node_child_process10.spawn)("node", [serverFile], {
4005
+ cwd: projectPath,
4006
+ stdio: "inherit",
4007
+ env: env2
4008
+ });
4009
+ let cleanupInProgress = false;
4010
+ const cleanup = async () => {
4011
+ if (cleanupInProgress) {
4012
+ return;
4013
+ }
4014
+ cleanupInProgress = true;
4015
+ console.log(source_default.gray("\n\nShutting down..."));
4016
+ if (tunnelProcess && typeof tunnelProcess.markShutdown === "function") {
4017
+ tunnelProcess.markShutdown();
4018
+ }
4019
+ if (tunnelSubdomain) {
4020
+ try {
4021
+ const apiBase = process.env.MCP_USE_API || "https://local.mcp-use.run";
4022
+ await fetch(`${apiBase}/api/tunnels/${tunnelSubdomain}`, {
4023
+ method: "DELETE"
4024
+ });
4025
+ } catch (err) {
4026
+ }
4027
+ }
4028
+ const processesToKill = 1 + (tunnelProcess ? 1 : 0);
4029
+ let killedCount = 0;
4030
+ const checkAndExit = () => {
4031
+ killedCount++;
4032
+ if (killedCount >= processesToKill) {
4033
+ process.exit(0);
4034
+ }
4035
+ };
4036
+ serverProc.on("exit", checkAndExit);
4037
+ serverProc.kill("SIGTERM");
4038
+ if (tunnelProcess && typeof tunnelProcess.kill === "function") {
4039
+ tunnelProcess.on("exit", checkAndExit);
4040
+ tunnelProcess.kill("SIGINT");
4041
+ } else {
4042
+ checkAndExit();
4043
+ }
4044
+ setTimeout(() => {
4045
+ if (serverProc.exitCode === null) {
4046
+ serverProc.kill("SIGKILL");
4047
+ }
4048
+ if (tunnelProcess && tunnelProcess.exitCode === null) {
4049
+ tunnelProcess.kill("SIGKILL");
4050
+ }
4051
+ process.exit(0);
4052
+ }, 2e3);
4053
+ };
4054
+ process.on("SIGINT", cleanup);
4055
+ process.on("SIGTERM", cleanup);
4056
+ serverProc.on("exit", (code) => {
4057
+ process.exit(code || 0);
4058
+ });
4059
+ } catch (error) {
4060
+ console.error("Start failed:", error);
4061
+ process.exit(1);
4062
+ }
4063
+ });
4064
+ program.command("login").description("Login to mcp-use cloud").action(async () => {
4065
+ await loginCommand();
4066
+ });
4067
+ program.command("logout").description("Logout from mcp-use cloud").action(async () => {
4068
+ await logoutCommand();
4069
+ });
4070
+ program.command("whoami").description("Show current user information").action(async () => {
4071
+ await whoamiCommand();
4072
+ });
4073
+ program.command("deploy").description("Deploy MCP server to mcp-use cloud").option("--open", "Open deployment in browser after successful deploy").option("--name <name>", "Custom deployment name").option("--port <port>", "Server port", "3000").option("--runtime <runtime>", "Runtime (node or python)").option(
4074
+ "--from-source",
4075
+ "Deploy from local source code (even for GitHub repos)"
4076
+ ).action(async (options) => {
4077
+ await deployCommand({
4078
+ open: options.open,
4079
+ name: options.name,
4080
+ port: options.port ? parseInt(options.port, 10) : void 0,
4081
+ runtime: options.runtime,
4082
+ fromSource: options.fromSource
4083
+ });
4084
+ });
4085
+ program.addCommand(createClientCommand());
4086
+ program.parse();
4087
+ //# sourceMappingURL=index.cjs.map