mcp-use 1.11.0-canary.7 → 1.11.0-canary.9
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/.tsbuildinfo +1 -1
- package/dist/{chunk-REYY7LSD.js → chunk-5QFJZ7H3.js} +2 -2
- package/dist/chunk-D3CNYAYE.js +1055 -0
- package/dist/{chunk-OD6B7KGQ.js → chunk-ESMOFYJ6.js} +27 -2100
- package/dist/{chunk-WTGUJLTR.js → chunk-F3BZFJCD.js} +167 -7
- package/dist/chunk-GXNAXUDI.js +0 -0
- package/dist/{chunk-QP7MQ2UJ.js → chunk-HU2DGJ5J.js} +175 -133
- package/dist/{chunk-REX2YTWF.js → chunk-M7WATKYM.js} +1 -1
- package/dist/chunk-MFSO5PUW.js +1049 -0
- package/dist/{chunk-5LBXMCKC.js → chunk-N3DO4P2L.js} +27 -2100
- package/dist/{chunk-M7CHBY4S.js → chunk-OWPXM4QQ.js} +1 -1
- package/dist/{chunk-3QVRNWW7.js → chunk-Q5LZL6BH.js} +1 -1
- package/dist/{chunk-ZN3MKSKM.js → chunk-UCPSHMNO.js} +1 -1
- package/dist/chunk-UWWLWLS2.js +62 -0
- package/dist/chunk-WW3A2EKQ.js +1055 -0
- package/dist/{chunk-CHHWJQVC.js → chunk-XEFWIBQF.js} +1 -1
- package/dist/index.cjs +211 -10
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +31 -28
- package/dist/notifications-FLGIFS56.js +9 -0
- package/dist/src/adapters/index.cjs +1346 -0
- package/dist/src/adapters/index.js +11 -0
- package/dist/src/agents/index.cjs +46 -4
- package/dist/src/agents/index.js +8 -6
- package/dist/src/browser.cjs +46 -5
- package/dist/src/browser.d.ts +1 -1
- package/dist/src/browser.d.ts.map +1 -1
- package/dist/src/browser.js +15 -13
- package/dist/src/client/prompts.js +4 -4
- package/dist/src/client.cjs +3787 -0
- package/dist/src/client.js +20 -0
- package/dist/src/react/index.cjs +211 -9
- package/dist/src/react/index.js +5 -5
- package/dist/src/react/types.d.ts +41 -1
- package/dist/src/react/types.d.ts.map +1 -1
- package/dist/src/react/useMcp.d.ts.map +1 -1
- package/dist/src/react/useWidget.d.ts +11 -7
- package/dist/src/react/useWidget.d.ts.map +1 -1
- package/dist/src/react/widget-types.d.ts +6 -2
- package/dist/src/react/widget-types.d.ts.map +1 -1
- package/dist/src/server/endpoints/mount-mcp.d.ts.map +1 -1
- package/dist/src/server/index.cjs +1269 -144
- package/dist/src/server/index.d.ts +2 -0
- package/dist/src/server/index.d.ts.map +1 -1
- package/dist/src/server/index.js +1158 -100
- package/dist/src/server/mcp-server.d.ts +5 -1
- package/dist/src/server/mcp-server.d.ts.map +1 -1
- package/dist/src/server/notifications/index.d.ts +1 -1
- package/dist/src/server/notifications/index.d.ts.map +1 -1
- package/dist/src/server/notifications/notification-registration.d.ts +51 -0
- package/dist/src/server/notifications/notification-registration.d.ts.map +1 -1
- package/dist/src/server/sessions/index.d.ts +3 -1
- package/dist/src/server/sessions/index.d.ts.map +1 -1
- package/dist/src/server/sessions/session-manager.d.ts +30 -16
- package/dist/src/server/sessions/session-manager.d.ts.map +1 -1
- package/dist/src/server/sessions/stores/filesystem.d.ts +121 -0
- package/dist/src/server/sessions/stores/filesystem.d.ts.map +1 -0
- package/dist/src/server/sessions/stores/index.d.ts +94 -0
- package/dist/src/server/sessions/stores/index.d.ts.map +1 -0
- package/dist/src/server/sessions/stores/memory.d.ts +82 -0
- package/dist/src/server/sessions/stores/memory.d.ts.map +1 -0
- package/dist/src/server/sessions/stores/redis.d.ts +164 -0
- package/dist/src/server/sessions/stores/redis.d.ts.map +1 -0
- package/dist/src/server/sessions/streams/index.d.ts +77 -0
- package/dist/src/server/sessions/streams/index.d.ts.map +1 -0
- package/dist/src/server/sessions/streams/memory.d.ts +76 -0
- package/dist/src/server/sessions/streams/memory.d.ts.map +1 -0
- package/dist/src/server/sessions/streams/redis.d.ts +146 -0
- package/dist/src/server/sessions/streams/redis.d.ts.map +1 -0
- package/dist/src/server/types/common.d.ts +105 -28
- package/dist/src/server/types/common.d.ts.map +1 -1
- package/dist/src/server/types/resource.d.ts +16 -0
- package/dist/src/server/types/resource.d.ts.map +1 -1
- package/dist/src/server/types/widget.d.ts +21 -2
- package/dist/src/server/types/widget.d.ts.map +1 -1
- package/dist/src/server/utils/response-helpers.d.ts +12 -6
- package/dist/src/server/utils/response-helpers.d.ts.map +1 -1
- package/dist/src/server/widgets/index.d.ts +1 -1
- package/dist/src/server/widgets/index.d.ts.map +1 -1
- package/dist/src/server/widgets/mount-widgets-dev.d.ts.map +1 -1
- package/dist/src/server/widgets/setup-widget-routes.d.ts.map +1 -1
- package/dist/src/server/widgets/ui-resource-registration.d.ts.map +1 -1
- package/dist/src/server/widgets/widget-helpers.d.ts +22 -0
- package/dist/src/server/widgets/widget-helpers.d.ts.map +1 -1
- package/dist/src/server/widgets/widget-types.d.ts +2 -0
- package/dist/src/server/widgets/widget-types.d.ts.map +1 -1
- package/dist/src/task_managers/index.d.ts +10 -0
- package/dist/src/task_managers/index.d.ts.map +1 -1
- package/dist/src/task_managers/sse.d.ts +34 -1
- package/dist/src/task_managers/sse.d.ts.map +1 -1
- package/dist/src/task_managers/streamable_http.d.ts +8 -2
- package/dist/src/task_managers/streamable_http.d.ts.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/{tool-execution-helpers-PAFGGAGL.js → tool-execution-helpers-MXVN6YNU.js} +2 -2
- package/dist/tsup.config.d.ts.map +1 -1
- package/package.json +29 -5
- /package/dist/{chunk-H4BZVTGK.js → chunk-LGDFGYRL.js} +0 -0
|
@@ -0,0 +1,3787 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
9
|
+
var __export = (target, all) => {
|
|
10
|
+
for (var name in all)
|
|
11
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
12
|
+
};
|
|
13
|
+
var __copyProps = (to, from, except, desc) => {
|
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
15
|
+
for (let key of __getOwnPropNames(from))
|
|
16
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
17
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
18
|
+
}
|
|
19
|
+
return to;
|
|
20
|
+
};
|
|
21
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
22
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
23
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
24
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
25
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
26
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
27
|
+
mod
|
|
28
|
+
));
|
|
29
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
30
|
+
|
|
31
|
+
// src/client.ts
|
|
32
|
+
var client_exports = {};
|
|
33
|
+
__export(client_exports, {
|
|
34
|
+
BaseCodeExecutor: () => BaseCodeExecutor,
|
|
35
|
+
E2BCodeExecutor: () => E2BCodeExecutor,
|
|
36
|
+
MCPClient: () => MCPClient,
|
|
37
|
+
VMCodeExecutor: () => VMCodeExecutor,
|
|
38
|
+
isVMAvailable: () => isVMAvailable
|
|
39
|
+
});
|
|
40
|
+
module.exports = __toCommonJS(client_exports);
|
|
41
|
+
var import_node_fs2 = __toESM(require("fs"), 1);
|
|
42
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
43
|
+
|
|
44
|
+
// src/logging.ts
|
|
45
|
+
async function getNodeModules() {
|
|
46
|
+
if (typeof process !== "undefined" && process.platform) {
|
|
47
|
+
try {
|
|
48
|
+
const fs2 = await import("fs");
|
|
49
|
+
const path2 = await import("path");
|
|
50
|
+
return { fs: fs2.default, path: path2.default };
|
|
51
|
+
} catch {
|
|
52
|
+
return { fs: null, path: null };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return { fs: null, path: null };
|
|
56
|
+
}
|
|
57
|
+
__name(getNodeModules, "getNodeModules");
|
|
58
|
+
var winston = null;
|
|
59
|
+
function loadWinstonSync() {
|
|
60
|
+
if (typeof require !== "undefined") {
|
|
61
|
+
try {
|
|
62
|
+
winston = require("winston");
|
|
63
|
+
} catch {
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
__name(loadWinstonSync, "loadWinstonSync");
|
|
68
|
+
async function getWinston() {
|
|
69
|
+
if (!winston) {
|
|
70
|
+
winston = await import("winston");
|
|
71
|
+
}
|
|
72
|
+
return winston;
|
|
73
|
+
}
|
|
74
|
+
__name(getWinston, "getWinston");
|
|
75
|
+
var DEFAULT_LOGGER_NAME = "mcp-use";
|
|
76
|
+
function isNodeJSEnvironment() {
|
|
77
|
+
try {
|
|
78
|
+
if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
if (typeof globalThis.EdgeRuntime !== "undefined" || typeof globalThis.Deno !== "undefined") {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
const hasNodeGlobals = typeof process !== "undefined" && typeof process.platform !== "undefined" && typeof __dirname !== "undefined";
|
|
85
|
+
return hasNodeGlobals;
|
|
86
|
+
} catch {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
__name(isNodeJSEnvironment, "isNodeJSEnvironment");
|
|
91
|
+
var SimpleConsoleLogger = class {
|
|
92
|
+
static {
|
|
93
|
+
__name(this, "SimpleConsoleLogger");
|
|
94
|
+
}
|
|
95
|
+
_level;
|
|
96
|
+
name;
|
|
97
|
+
constructor(name = DEFAULT_LOGGER_NAME, level = "info") {
|
|
98
|
+
this.name = name;
|
|
99
|
+
this._level = level;
|
|
100
|
+
}
|
|
101
|
+
shouldLog(level) {
|
|
102
|
+
const levels = [
|
|
103
|
+
"error",
|
|
104
|
+
"warn",
|
|
105
|
+
"info",
|
|
106
|
+
"http",
|
|
107
|
+
"verbose",
|
|
108
|
+
"debug",
|
|
109
|
+
"silly"
|
|
110
|
+
];
|
|
111
|
+
const currentIndex = levels.indexOf(this._level);
|
|
112
|
+
const messageIndex = levels.indexOf(level);
|
|
113
|
+
return messageIndex <= currentIndex;
|
|
114
|
+
}
|
|
115
|
+
formatMessage(level, message) {
|
|
116
|
+
const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", { hour12: false });
|
|
117
|
+
return `${timestamp} [${this.name}] ${level}: ${message}`;
|
|
118
|
+
}
|
|
119
|
+
error(message) {
|
|
120
|
+
if (this.shouldLog("error")) {
|
|
121
|
+
console.error(this.formatMessage("error", message));
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
warn(message) {
|
|
125
|
+
if (this.shouldLog("warn")) {
|
|
126
|
+
console.warn(this.formatMessage("warn", message));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
info(message) {
|
|
130
|
+
if (this.shouldLog("info")) {
|
|
131
|
+
console.info(this.formatMessage("info", message));
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
debug(message) {
|
|
135
|
+
if (this.shouldLog("debug")) {
|
|
136
|
+
console.debug(this.formatMessage("debug", message));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
http(message) {
|
|
140
|
+
if (this.shouldLog("http")) {
|
|
141
|
+
console.log(this.formatMessage("http", message));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
verbose(message) {
|
|
145
|
+
if (this.shouldLog("verbose")) {
|
|
146
|
+
console.log(this.formatMessage("verbose", message));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
silly(message) {
|
|
150
|
+
if (this.shouldLog("silly")) {
|
|
151
|
+
console.log(this.formatMessage("silly", message));
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
// Make it compatible with Winston interface
|
|
155
|
+
get level() {
|
|
156
|
+
return this._level;
|
|
157
|
+
}
|
|
158
|
+
set level(newLevel) {
|
|
159
|
+
this._level = newLevel;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
function resolveLevel(env) {
|
|
163
|
+
const envValue = typeof process !== "undefined" && process.env ? env : void 0;
|
|
164
|
+
switch (envValue?.trim()) {
|
|
165
|
+
case "2":
|
|
166
|
+
return "debug";
|
|
167
|
+
case "1":
|
|
168
|
+
return "info";
|
|
169
|
+
default:
|
|
170
|
+
return "info";
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
__name(resolveLevel, "resolveLevel");
|
|
174
|
+
var Logger = class {
|
|
175
|
+
static {
|
|
176
|
+
__name(this, "Logger");
|
|
177
|
+
}
|
|
178
|
+
static instances = {};
|
|
179
|
+
static simpleInstances = {};
|
|
180
|
+
static currentFormat = "minimal";
|
|
181
|
+
static get(name = DEFAULT_LOGGER_NAME) {
|
|
182
|
+
if (!isNodeJSEnvironment()) {
|
|
183
|
+
if (!this.simpleInstances[name]) {
|
|
184
|
+
const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || void 0;
|
|
185
|
+
this.simpleInstances[name] = new SimpleConsoleLogger(
|
|
186
|
+
name,
|
|
187
|
+
resolveLevel(debugEnv)
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
return this.simpleInstances[name];
|
|
191
|
+
}
|
|
192
|
+
if (!this.instances[name]) {
|
|
193
|
+
if (!winston) {
|
|
194
|
+
throw new Error("Winston not loaded - call Logger.configure() first");
|
|
195
|
+
}
|
|
196
|
+
const { createLogger, format } = winston;
|
|
197
|
+
const { combine, timestamp, label, colorize, splat } = format;
|
|
198
|
+
this.instances[name] = createLogger({
|
|
199
|
+
level: resolveLevel(process.env.DEBUG),
|
|
200
|
+
format: combine(
|
|
201
|
+
colorize(),
|
|
202
|
+
splat(),
|
|
203
|
+
label({ label: name }),
|
|
204
|
+
timestamp({ format: "HH:mm:ss" }),
|
|
205
|
+
this.getFormatter()
|
|
206
|
+
),
|
|
207
|
+
transports: [new winston.transports.Console()]
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
return this.instances[name];
|
|
211
|
+
}
|
|
212
|
+
static getFormatter() {
|
|
213
|
+
if (!winston) {
|
|
214
|
+
throw new Error("Winston not loaded");
|
|
215
|
+
}
|
|
216
|
+
const { format } = winston;
|
|
217
|
+
const { printf } = format;
|
|
218
|
+
const minimalFormatter = printf(({ level, message, label, timestamp }) => {
|
|
219
|
+
return `${timestamp} [${label}] ${level}: ${message}`;
|
|
220
|
+
});
|
|
221
|
+
const detailedFormatter = printf(({ level, message, label, timestamp }) => {
|
|
222
|
+
return `${timestamp} [${label}] ${level.toUpperCase()}: ${message}`;
|
|
223
|
+
});
|
|
224
|
+
const emojiFormatter = printf(({ level, message, label, timestamp }) => {
|
|
225
|
+
return `${timestamp} [${label}] ${level.toUpperCase()}: ${message}`;
|
|
226
|
+
});
|
|
227
|
+
switch (this.currentFormat) {
|
|
228
|
+
case "minimal":
|
|
229
|
+
return minimalFormatter;
|
|
230
|
+
case "detailed":
|
|
231
|
+
return detailedFormatter;
|
|
232
|
+
case "emoji":
|
|
233
|
+
return emojiFormatter;
|
|
234
|
+
default:
|
|
235
|
+
return minimalFormatter;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
static async configure(options = {}) {
|
|
239
|
+
const { level, console: console2 = true, file, format = "minimal" } = options;
|
|
240
|
+
const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || void 0;
|
|
241
|
+
const resolvedLevel = level ?? resolveLevel(debugEnv);
|
|
242
|
+
this.currentFormat = format;
|
|
243
|
+
if (!isNodeJSEnvironment()) {
|
|
244
|
+
Object.values(this.simpleInstances).forEach((logger2) => {
|
|
245
|
+
logger2.level = resolvedLevel;
|
|
246
|
+
});
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
await getWinston();
|
|
250
|
+
if (!winston) {
|
|
251
|
+
throw new Error("Failed to load winston");
|
|
252
|
+
}
|
|
253
|
+
const root = this.get();
|
|
254
|
+
root.level = resolvedLevel;
|
|
255
|
+
const winstonRoot = root;
|
|
256
|
+
winstonRoot.clear();
|
|
257
|
+
if (console2) {
|
|
258
|
+
winstonRoot.add(new winston.transports.Console());
|
|
259
|
+
}
|
|
260
|
+
if (file) {
|
|
261
|
+
const { fs: nodeFs, path: nodePath } = await getNodeModules();
|
|
262
|
+
if (nodeFs && nodePath) {
|
|
263
|
+
const dir = nodePath.dirname(nodePath.resolve(file));
|
|
264
|
+
if (!nodeFs.existsSync(dir)) {
|
|
265
|
+
nodeFs.mkdirSync(dir, { recursive: true });
|
|
266
|
+
}
|
|
267
|
+
winstonRoot.add(new winston.transports.File({ filename: file }));
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const { format: winstonFormat } = winston;
|
|
271
|
+
const { combine, timestamp, label, colorize, splat } = winstonFormat;
|
|
272
|
+
Object.values(this.instances).forEach((logger2) => {
|
|
273
|
+
if (logger2 && "format" in logger2) {
|
|
274
|
+
logger2.level = resolvedLevel;
|
|
275
|
+
logger2.format = combine(
|
|
276
|
+
colorize(),
|
|
277
|
+
splat(),
|
|
278
|
+
label({ label: DEFAULT_LOGGER_NAME }),
|
|
279
|
+
timestamp({ format: "HH:mm:ss" }),
|
|
280
|
+
this.getFormatter()
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
static setDebug(enabled) {
|
|
286
|
+
let level;
|
|
287
|
+
if (enabled === 2 || enabled === true) level = "debug";
|
|
288
|
+
else if (enabled === 1) level = "info";
|
|
289
|
+
else level = "info";
|
|
290
|
+
Object.values(this.simpleInstances).forEach((logger2) => {
|
|
291
|
+
logger2.level = level;
|
|
292
|
+
});
|
|
293
|
+
Object.values(this.instances).forEach((logger2) => {
|
|
294
|
+
if (logger2) {
|
|
295
|
+
logger2.level = level;
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
if (typeof process !== "undefined" && process.env) {
|
|
299
|
+
process.env.DEBUG = enabled ? enabled === true ? "2" : String(enabled) : "0";
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
static setFormat(format) {
|
|
303
|
+
this.currentFormat = format;
|
|
304
|
+
this.configure({ format });
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
if (isNodeJSEnvironment()) {
|
|
308
|
+
loadWinstonSync();
|
|
309
|
+
if (winston) {
|
|
310
|
+
Logger.configure();
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
var logger = Logger.get();
|
|
314
|
+
|
|
315
|
+
// src/session.ts
|
|
316
|
+
var MCPSession = class {
|
|
317
|
+
static {
|
|
318
|
+
__name(this, "MCPSession");
|
|
319
|
+
}
|
|
320
|
+
connector;
|
|
321
|
+
autoConnect;
|
|
322
|
+
constructor(connector, autoConnect = true) {
|
|
323
|
+
this.connector = connector;
|
|
324
|
+
this.autoConnect = autoConnect;
|
|
325
|
+
}
|
|
326
|
+
async connect() {
|
|
327
|
+
await this.connector.connect();
|
|
328
|
+
}
|
|
329
|
+
async disconnect() {
|
|
330
|
+
await this.connector.disconnect();
|
|
331
|
+
}
|
|
332
|
+
async initialize() {
|
|
333
|
+
if (!this.isConnected && this.autoConnect) {
|
|
334
|
+
await this.connect();
|
|
335
|
+
}
|
|
336
|
+
await this.connector.initialize();
|
|
337
|
+
}
|
|
338
|
+
get isConnected() {
|
|
339
|
+
return this.connector && this.connector.isClientConnected;
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Register an event handler for session events
|
|
343
|
+
*
|
|
344
|
+
* @param event - The event type to listen for
|
|
345
|
+
* @param handler - The handler function to call when the event occurs
|
|
346
|
+
*
|
|
347
|
+
* @example
|
|
348
|
+
* ```typescript
|
|
349
|
+
* session.on("notification", async (notification) => {
|
|
350
|
+
* console.log(`Received: ${notification.method}`, notification.params);
|
|
351
|
+
*
|
|
352
|
+
* if (notification.method === "notifications/tools/list_changed") {
|
|
353
|
+
* // Refresh tools list
|
|
354
|
+
* }
|
|
355
|
+
* });
|
|
356
|
+
* ```
|
|
357
|
+
*/
|
|
358
|
+
on(event, handler) {
|
|
359
|
+
if (event === "notification") {
|
|
360
|
+
this.connector.onNotification(handler);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Set roots and notify the server.
|
|
365
|
+
* Roots represent directories or files that the client has access to.
|
|
366
|
+
*
|
|
367
|
+
* @param roots - Array of Root objects with `uri` (must start with "file://") and optional `name`
|
|
368
|
+
*
|
|
369
|
+
* @example
|
|
370
|
+
* ```typescript
|
|
371
|
+
* await session.setRoots([
|
|
372
|
+
* { uri: "file:///home/user/project", name: "My Project" },
|
|
373
|
+
* { uri: "file:///home/user/data" }
|
|
374
|
+
* ]);
|
|
375
|
+
* ```
|
|
376
|
+
*/
|
|
377
|
+
async setRoots(roots) {
|
|
378
|
+
return this.connector.setRoots(roots);
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Get the current roots.
|
|
382
|
+
*/
|
|
383
|
+
getRoots() {
|
|
384
|
+
return this.connector.getRoots();
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Get the cached list of tools from the server.
|
|
388
|
+
*
|
|
389
|
+
* @returns Array of available tools
|
|
390
|
+
*
|
|
391
|
+
* @example
|
|
392
|
+
* ```typescript
|
|
393
|
+
* const tools = session.tools;
|
|
394
|
+
* console.log(`Available tools: ${tools.map(t => t.name).join(", ")}`);
|
|
395
|
+
* ```
|
|
396
|
+
*/
|
|
397
|
+
get tools() {
|
|
398
|
+
return this.connector.tools;
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* List all available tools from the MCP server.
|
|
402
|
+
* This method fetches fresh tools from the server, unlike the `tools` getter which returns cached tools.
|
|
403
|
+
*
|
|
404
|
+
* @param options - Optional request options
|
|
405
|
+
* @returns Array of available tools
|
|
406
|
+
*
|
|
407
|
+
* @example
|
|
408
|
+
* ```typescript
|
|
409
|
+
* const tools = await session.listTools();
|
|
410
|
+
* console.log(`Available tools: ${tools.map(t => t.name).join(", ")}`);
|
|
411
|
+
* ```
|
|
412
|
+
*/
|
|
413
|
+
async listTools(options) {
|
|
414
|
+
return this.connector.listTools(options);
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Get the server capabilities advertised during initialization.
|
|
418
|
+
*
|
|
419
|
+
* @returns Server capabilities object
|
|
420
|
+
*/
|
|
421
|
+
get serverCapabilities() {
|
|
422
|
+
return this.connector.serverCapabilities;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Get the server information (name and version).
|
|
426
|
+
*
|
|
427
|
+
* @returns Server info object or null if not available
|
|
428
|
+
*/
|
|
429
|
+
get serverInfo() {
|
|
430
|
+
return this.connector.serverInfo;
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Call a tool on the server.
|
|
434
|
+
*
|
|
435
|
+
* @param name - Name of the tool to call
|
|
436
|
+
* @param args - Arguments to pass to the tool (defaults to empty object)
|
|
437
|
+
* @param options - Optional request options (timeout, progress handlers, etc.)
|
|
438
|
+
* @returns Result from the tool execution
|
|
439
|
+
*
|
|
440
|
+
* @example
|
|
441
|
+
* ```typescript
|
|
442
|
+
* const result = await session.callTool("add", { a: 5, b: 3 });
|
|
443
|
+
* console.log(`Result: ${result.content[0].text}`);
|
|
444
|
+
* ```
|
|
445
|
+
*/
|
|
446
|
+
async callTool(name, args = {}, options) {
|
|
447
|
+
return this.connector.callTool(name, args, options);
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* List resources from the server with optional pagination.
|
|
451
|
+
*
|
|
452
|
+
* @param cursor - Optional cursor for pagination
|
|
453
|
+
* @param options - Request options
|
|
454
|
+
* @returns Resource list with optional nextCursor for pagination
|
|
455
|
+
*
|
|
456
|
+
* @example
|
|
457
|
+
* ```typescript
|
|
458
|
+
* const result = await session.listResources();
|
|
459
|
+
* console.log(`Found ${result.resources.length} resources`);
|
|
460
|
+
* ```
|
|
461
|
+
*/
|
|
462
|
+
async listResources(cursor, options) {
|
|
463
|
+
return this.connector.listResources(cursor, options);
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* List all resources from the server, automatically handling pagination.
|
|
467
|
+
*
|
|
468
|
+
* @param options - Request options
|
|
469
|
+
* @returns Complete list of all resources
|
|
470
|
+
*
|
|
471
|
+
* @example
|
|
472
|
+
* ```typescript
|
|
473
|
+
* const result = await session.listAllResources();
|
|
474
|
+
* console.log(`Total resources: ${result.resources.length}`);
|
|
475
|
+
* ```
|
|
476
|
+
*/
|
|
477
|
+
async listAllResources(options) {
|
|
478
|
+
return this.connector.listAllResources(options);
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* List resource templates from the server.
|
|
482
|
+
*
|
|
483
|
+
* @param options - Request options
|
|
484
|
+
* @returns List of available resource templates
|
|
485
|
+
*
|
|
486
|
+
* @example
|
|
487
|
+
* ```typescript
|
|
488
|
+
* const result = await session.listResourceTemplates();
|
|
489
|
+
* console.log(`Available templates: ${result.resourceTemplates.length}`);
|
|
490
|
+
* ```
|
|
491
|
+
*/
|
|
492
|
+
async listResourceTemplates(options) {
|
|
493
|
+
return this.connector.listResourceTemplates(options);
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Read a resource by URI.
|
|
497
|
+
*
|
|
498
|
+
* @param uri - URI of the resource to read
|
|
499
|
+
* @param options - Request options
|
|
500
|
+
* @returns Resource content
|
|
501
|
+
*
|
|
502
|
+
* @example
|
|
503
|
+
* ```typescript
|
|
504
|
+
* const resource = await session.readResource("file:///path/to/file.txt");
|
|
505
|
+
* console.log(resource.contents);
|
|
506
|
+
* ```
|
|
507
|
+
*/
|
|
508
|
+
async readResource(uri, options) {
|
|
509
|
+
return this.connector.readResource(uri, options);
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Subscribe to resource updates.
|
|
513
|
+
*
|
|
514
|
+
* @param uri - URI of the resource to subscribe to
|
|
515
|
+
* @param options - Request options
|
|
516
|
+
*
|
|
517
|
+
* @example
|
|
518
|
+
* ```typescript
|
|
519
|
+
* await session.subscribeToResource("file:///path/to/file.txt");
|
|
520
|
+
* // Now you'll receive notifications when this resource changes
|
|
521
|
+
* ```
|
|
522
|
+
*/
|
|
523
|
+
async subscribeToResource(uri, options) {
|
|
524
|
+
return this.connector.subscribeToResource(uri, options);
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Unsubscribe from resource updates.
|
|
528
|
+
*
|
|
529
|
+
* @param uri - URI of the resource to unsubscribe from
|
|
530
|
+
* @param options - Request options
|
|
531
|
+
*
|
|
532
|
+
* @example
|
|
533
|
+
* ```typescript
|
|
534
|
+
* await session.unsubscribeFromResource("file:///path/to/file.txt");
|
|
535
|
+
* ```
|
|
536
|
+
*/
|
|
537
|
+
async unsubscribeFromResource(uri, options) {
|
|
538
|
+
return this.connector.unsubscribeFromResource(uri, options);
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* List available prompts from the server.
|
|
542
|
+
*
|
|
543
|
+
* @returns List of available prompts
|
|
544
|
+
*
|
|
545
|
+
* @example
|
|
546
|
+
* ```typescript
|
|
547
|
+
* const result = await session.listPrompts();
|
|
548
|
+
* console.log(`Available prompts: ${result.prompts.length}`);
|
|
549
|
+
* ```
|
|
550
|
+
*/
|
|
551
|
+
async listPrompts() {
|
|
552
|
+
return this.connector.listPrompts();
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Get a specific prompt with arguments.
|
|
556
|
+
*
|
|
557
|
+
* @param name - Name of the prompt to get
|
|
558
|
+
* @param args - Arguments for the prompt
|
|
559
|
+
* @returns Prompt result
|
|
560
|
+
*
|
|
561
|
+
* @example
|
|
562
|
+
* ```typescript
|
|
563
|
+
* const prompt = await session.getPrompt("greeting", { name: "Alice" });
|
|
564
|
+
* console.log(prompt.messages);
|
|
565
|
+
* ```
|
|
566
|
+
*/
|
|
567
|
+
async getPrompt(name, args) {
|
|
568
|
+
return this.connector.getPrompt(name, args);
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Send a raw request through the client.
|
|
572
|
+
*
|
|
573
|
+
* @param method - MCP method name
|
|
574
|
+
* @param params - Request parameters
|
|
575
|
+
* @param options - Request options
|
|
576
|
+
* @returns Response from the server
|
|
577
|
+
*
|
|
578
|
+
* @example
|
|
579
|
+
* ```typescript
|
|
580
|
+
* const result = await session.request("custom/method", { key: "value" });
|
|
581
|
+
* ```
|
|
582
|
+
*/
|
|
583
|
+
async request(method, params = null, options) {
|
|
584
|
+
return this.connector.request(method, params, options);
|
|
585
|
+
}
|
|
586
|
+
};
|
|
587
|
+
|
|
588
|
+
// src/telemetry/events.ts
|
|
589
|
+
var BaseTelemetryEvent = class {
|
|
590
|
+
static {
|
|
591
|
+
__name(this, "BaseTelemetryEvent");
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
var MCPAgentExecutionEvent = class extends BaseTelemetryEvent {
|
|
595
|
+
constructor(data) {
|
|
596
|
+
super();
|
|
597
|
+
this.data = data;
|
|
598
|
+
}
|
|
599
|
+
static {
|
|
600
|
+
__name(this, "MCPAgentExecutionEvent");
|
|
601
|
+
}
|
|
602
|
+
get name() {
|
|
603
|
+
return "mcp_agent_execution";
|
|
604
|
+
}
|
|
605
|
+
get properties() {
|
|
606
|
+
return {
|
|
607
|
+
// Core execution info
|
|
608
|
+
execution_method: this.data.executionMethod,
|
|
609
|
+
query: this.data.query,
|
|
610
|
+
query_length: this.data.query.length,
|
|
611
|
+
success: this.data.success,
|
|
612
|
+
// Agent configuration
|
|
613
|
+
model_provider: this.data.modelProvider,
|
|
614
|
+
model_name: this.data.modelName,
|
|
615
|
+
server_count: this.data.serverCount,
|
|
616
|
+
server_identifiers: this.data.serverIdentifiers,
|
|
617
|
+
total_tools_available: this.data.totalToolsAvailable,
|
|
618
|
+
tools_available_names: this.data.toolsAvailableNames,
|
|
619
|
+
max_steps_configured: this.data.maxStepsConfigured,
|
|
620
|
+
memory_enabled: this.data.memoryEnabled,
|
|
621
|
+
use_server_manager: this.data.useServerManager,
|
|
622
|
+
// Execution parameters (always include, even if null)
|
|
623
|
+
max_steps_used: this.data.maxStepsUsed,
|
|
624
|
+
manage_connector: this.data.manageConnector,
|
|
625
|
+
external_history_used: this.data.externalHistoryUsed,
|
|
626
|
+
// Execution results (always include, even if null)
|
|
627
|
+
steps_taken: this.data.stepsTaken ?? null,
|
|
628
|
+
tools_used_count: this.data.toolsUsedCount ?? null,
|
|
629
|
+
tools_used_names: this.data.toolsUsedNames ?? null,
|
|
630
|
+
response: this.data.response ?? null,
|
|
631
|
+
response_length: this.data.response ? this.data.response.length : null,
|
|
632
|
+
execution_time_ms: this.data.executionTimeMs ?? null,
|
|
633
|
+
error_type: this.data.errorType ?? null,
|
|
634
|
+
conversation_history_length: this.data.conversationHistoryLength ?? null
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
function createServerRunEventData(server, transport) {
|
|
639
|
+
const toolRegistrations = Array.from(server.registrations.tools.values());
|
|
640
|
+
const promptRegistrations = Array.from(server.registrations.prompts.values());
|
|
641
|
+
const resourceRegistrations = Array.from(
|
|
642
|
+
server.registrations.resources.values()
|
|
643
|
+
);
|
|
644
|
+
const templateRegistrations = Array.from(
|
|
645
|
+
server.registrations.resourceTemplates.values()
|
|
646
|
+
);
|
|
647
|
+
const allResources = resourceRegistrations.map((r) => ({
|
|
648
|
+
name: r.config.name,
|
|
649
|
+
title: r.config.title ?? null,
|
|
650
|
+
description: r.config.description ?? null,
|
|
651
|
+
uri: r.config.uri ?? null,
|
|
652
|
+
mime_type: r.config.mimeType ?? null
|
|
653
|
+
}));
|
|
654
|
+
const appsSdkResources = allResources.filter(
|
|
655
|
+
(r) => r.mime_type === "text/html+skybridge"
|
|
656
|
+
);
|
|
657
|
+
const mcpUiResources = allResources.filter(
|
|
658
|
+
(r) => r.mime_type === "text/uri-list" || r.mime_type === "text/html"
|
|
659
|
+
);
|
|
660
|
+
const mcpAppsResources = allResources.filter(
|
|
661
|
+
(r) => r.mime_type === "text/html+mcp"
|
|
662
|
+
);
|
|
663
|
+
return {
|
|
664
|
+
transport,
|
|
665
|
+
toolsNumber: server.registeredTools.length,
|
|
666
|
+
resourcesNumber: server.registeredResources.length,
|
|
667
|
+
promptsNumber: server.registeredPrompts.length,
|
|
668
|
+
auth: !!server.oauthProvider,
|
|
669
|
+
name: server.config.name,
|
|
670
|
+
description: server.config.description ?? null,
|
|
671
|
+
baseUrl: server.serverBaseUrl ?? null,
|
|
672
|
+
toolNames: server.registeredTools.length > 0 ? server.registeredTools : null,
|
|
673
|
+
resourceNames: server.registeredResources.length > 0 ? server.registeredResources : null,
|
|
674
|
+
promptNames: server.registeredPrompts.length > 0 ? server.registeredPrompts : null,
|
|
675
|
+
tools: toolRegistrations.length > 0 ? toolRegistrations.map((r) => ({
|
|
676
|
+
name: r.config.name,
|
|
677
|
+
title: r.config.title ?? null,
|
|
678
|
+
description: r.config.description ?? null,
|
|
679
|
+
input_schema: r.config.schema ? JSON.stringify(r.config.schema) : null,
|
|
680
|
+
output_schema: r.config.outputSchema ? JSON.stringify(r.config.outputSchema) : null
|
|
681
|
+
})) : null,
|
|
682
|
+
resources: allResources.length > 0 ? allResources : null,
|
|
683
|
+
prompts: promptRegistrations.length > 0 ? promptRegistrations.map((r) => ({
|
|
684
|
+
name: r.config.name,
|
|
685
|
+
title: r.config.title ?? null,
|
|
686
|
+
description: r.config.description ?? null,
|
|
687
|
+
args: r.config.args ? JSON.stringify(r.config.args) : null
|
|
688
|
+
})) : null,
|
|
689
|
+
templates: templateRegistrations.length > 0 ? templateRegistrations.map((r) => ({
|
|
690
|
+
name: r.config.name,
|
|
691
|
+
title: r.config.title ?? null,
|
|
692
|
+
description: r.config.description ?? null
|
|
693
|
+
})) : null,
|
|
694
|
+
capabilities: {
|
|
695
|
+
logging: true,
|
|
696
|
+
resources: { subscribe: true, listChanged: true }
|
|
697
|
+
},
|
|
698
|
+
appsSdkResources: appsSdkResources.length > 0 ? appsSdkResources : null,
|
|
699
|
+
appsSdkResourcesNumber: appsSdkResources.length,
|
|
700
|
+
mcpUiResources: mcpUiResources.length > 0 ? mcpUiResources : null,
|
|
701
|
+
mcpUiResourcesNumber: mcpUiResources.length,
|
|
702
|
+
mcpAppsResources: mcpAppsResources.length > 0 ? mcpAppsResources : null,
|
|
703
|
+
mcpAppsResourcesNumber: mcpAppsResources.length
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
__name(createServerRunEventData, "createServerRunEventData");
|
|
707
|
+
var ServerRunEvent = class extends BaseTelemetryEvent {
|
|
708
|
+
constructor(data) {
|
|
709
|
+
super();
|
|
710
|
+
this.data = data;
|
|
711
|
+
}
|
|
712
|
+
static {
|
|
713
|
+
__name(this, "ServerRunEvent");
|
|
714
|
+
}
|
|
715
|
+
get name() {
|
|
716
|
+
return "server_run";
|
|
717
|
+
}
|
|
718
|
+
get properties() {
|
|
719
|
+
return {
|
|
720
|
+
transport: this.data.transport,
|
|
721
|
+
tools_number: this.data.toolsNumber,
|
|
722
|
+
resources_number: this.data.resourcesNumber,
|
|
723
|
+
prompts_number: this.data.promptsNumber,
|
|
724
|
+
auth: this.data.auth,
|
|
725
|
+
name: this.data.name,
|
|
726
|
+
description: this.data.description ?? null,
|
|
727
|
+
base_url: this.data.baseUrl ?? null,
|
|
728
|
+
tool_names: this.data.toolNames ?? null,
|
|
729
|
+
resource_names: this.data.resourceNames ?? null,
|
|
730
|
+
prompt_names: this.data.promptNames ?? null,
|
|
731
|
+
tools: this.data.tools ?? null,
|
|
732
|
+
resources: this.data.resources ?? null,
|
|
733
|
+
prompts: this.data.prompts ?? null,
|
|
734
|
+
templates: this.data.templates ?? null,
|
|
735
|
+
capabilities: this.data.capabilities ? JSON.stringify(this.data.capabilities) : null,
|
|
736
|
+
apps_sdk_resources: this.data.appsSdkResources ? JSON.stringify(this.data.appsSdkResources) : null,
|
|
737
|
+
apps_sdk_resources_number: this.data.appsSdkResourcesNumber ?? 0,
|
|
738
|
+
mcp_ui_resources: this.data.mcpUiResources ? JSON.stringify(this.data.mcpUiResources) : null,
|
|
739
|
+
mcp_ui_resources_number: this.data.mcpUiResourcesNumber ?? 0,
|
|
740
|
+
mcp_apps_resources: this.data.mcpAppsResources ? JSON.stringify(this.data.mcpAppsResources) : null,
|
|
741
|
+
mcp_apps_resources_number: this.data.mcpAppsResourcesNumber ?? 0
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
};
|
|
745
|
+
var ServerInitializeEvent = class extends BaseTelemetryEvent {
|
|
746
|
+
constructor(data) {
|
|
747
|
+
super();
|
|
748
|
+
this.data = data;
|
|
749
|
+
}
|
|
750
|
+
static {
|
|
751
|
+
__name(this, "ServerInitializeEvent");
|
|
752
|
+
}
|
|
753
|
+
get name() {
|
|
754
|
+
return "server_initialize_call";
|
|
755
|
+
}
|
|
756
|
+
get properties() {
|
|
757
|
+
return {
|
|
758
|
+
protocol_version: this.data.protocolVersion,
|
|
759
|
+
client_info: JSON.stringify(this.data.clientInfo),
|
|
760
|
+
client_capabilities: JSON.stringify(this.data.clientCapabilities),
|
|
761
|
+
session_id: this.data.sessionId ?? null
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
};
|
|
765
|
+
var ServerToolCallEvent = class extends BaseTelemetryEvent {
|
|
766
|
+
constructor(data) {
|
|
767
|
+
super();
|
|
768
|
+
this.data = data;
|
|
769
|
+
}
|
|
770
|
+
static {
|
|
771
|
+
__name(this, "ServerToolCallEvent");
|
|
772
|
+
}
|
|
773
|
+
get name() {
|
|
774
|
+
return "server_tool_call";
|
|
775
|
+
}
|
|
776
|
+
get properties() {
|
|
777
|
+
return {
|
|
778
|
+
tool_name: this.data.toolName,
|
|
779
|
+
length_input_argument: this.data.lengthInputArgument,
|
|
780
|
+
success: this.data.success,
|
|
781
|
+
error_type: this.data.errorType ?? null,
|
|
782
|
+
execution_time_ms: this.data.executionTimeMs ?? null
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
var ServerResourceCallEvent = class extends BaseTelemetryEvent {
|
|
787
|
+
constructor(data) {
|
|
788
|
+
super();
|
|
789
|
+
this.data = data;
|
|
790
|
+
}
|
|
791
|
+
static {
|
|
792
|
+
__name(this, "ServerResourceCallEvent");
|
|
793
|
+
}
|
|
794
|
+
get name() {
|
|
795
|
+
return "server_resource_call";
|
|
796
|
+
}
|
|
797
|
+
get properties() {
|
|
798
|
+
return {
|
|
799
|
+
name: this.data.name,
|
|
800
|
+
description: this.data.description,
|
|
801
|
+
contents: this.data.contents,
|
|
802
|
+
success: this.data.success,
|
|
803
|
+
error_type: this.data.errorType ?? null
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
};
|
|
807
|
+
var ServerPromptCallEvent = class extends BaseTelemetryEvent {
|
|
808
|
+
constructor(data) {
|
|
809
|
+
super();
|
|
810
|
+
this.data = data;
|
|
811
|
+
}
|
|
812
|
+
static {
|
|
813
|
+
__name(this, "ServerPromptCallEvent");
|
|
814
|
+
}
|
|
815
|
+
get name() {
|
|
816
|
+
return "server_prompt_call";
|
|
817
|
+
}
|
|
818
|
+
get properties() {
|
|
819
|
+
return {
|
|
820
|
+
name: this.data.name,
|
|
821
|
+
description: this.data.description,
|
|
822
|
+
success: this.data.success,
|
|
823
|
+
error_type: this.data.errorType ?? null
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
};
|
|
827
|
+
var ServerContextEvent = class extends BaseTelemetryEvent {
|
|
828
|
+
constructor(data) {
|
|
829
|
+
super();
|
|
830
|
+
this.data = data;
|
|
831
|
+
}
|
|
832
|
+
static {
|
|
833
|
+
__name(this, "ServerContextEvent");
|
|
834
|
+
}
|
|
835
|
+
get name() {
|
|
836
|
+
return `server_context_${this.data.contextType}`;
|
|
837
|
+
}
|
|
838
|
+
get properties() {
|
|
839
|
+
return {
|
|
840
|
+
context_type: this.data.contextType,
|
|
841
|
+
notification_type: this.data.notificationType ?? null
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
};
|
|
845
|
+
var MCPClientInitEvent = class extends BaseTelemetryEvent {
|
|
846
|
+
constructor(data) {
|
|
847
|
+
super();
|
|
848
|
+
this.data = data;
|
|
849
|
+
}
|
|
850
|
+
static {
|
|
851
|
+
__name(this, "MCPClientInitEvent");
|
|
852
|
+
}
|
|
853
|
+
get name() {
|
|
854
|
+
return "mcpclient_init";
|
|
855
|
+
}
|
|
856
|
+
get properties() {
|
|
857
|
+
return {
|
|
858
|
+
code_mode: this.data.codeMode,
|
|
859
|
+
sandbox: this.data.sandbox,
|
|
860
|
+
all_callbacks: this.data.allCallbacks,
|
|
861
|
+
verify: this.data.verify,
|
|
862
|
+
servers: this.data.servers,
|
|
863
|
+
num_servers: this.data.numServers,
|
|
864
|
+
is_browser: this.data.isBrowser
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
};
|
|
868
|
+
var ConnectorInitEvent = class extends BaseTelemetryEvent {
|
|
869
|
+
constructor(data) {
|
|
870
|
+
super();
|
|
871
|
+
this.data = data;
|
|
872
|
+
}
|
|
873
|
+
static {
|
|
874
|
+
__name(this, "ConnectorInitEvent");
|
|
875
|
+
}
|
|
876
|
+
get name() {
|
|
877
|
+
return "connector_init";
|
|
878
|
+
}
|
|
879
|
+
get properties() {
|
|
880
|
+
return {
|
|
881
|
+
connector_type: this.data.connectorType,
|
|
882
|
+
server_command: this.data.serverCommand ?? null,
|
|
883
|
+
server_args: this.data.serverArgs ?? null,
|
|
884
|
+
server_url: this.data.serverUrl ?? null,
|
|
885
|
+
public_identifier: this.data.publicIdentifier ?? null
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
};
|
|
889
|
+
var ClientAddServerEvent = class extends BaseTelemetryEvent {
|
|
890
|
+
constructor(data) {
|
|
891
|
+
super();
|
|
892
|
+
this.data = data;
|
|
893
|
+
}
|
|
894
|
+
static {
|
|
895
|
+
__name(this, "ClientAddServerEvent");
|
|
896
|
+
}
|
|
897
|
+
get name() {
|
|
898
|
+
return "client_add_server";
|
|
899
|
+
}
|
|
900
|
+
get properties() {
|
|
901
|
+
const { serverName, serverConfig } = this.data;
|
|
902
|
+
const url = serverConfig.url;
|
|
903
|
+
return {
|
|
904
|
+
server_name: serverName,
|
|
905
|
+
server_url_domain: url ? this._extractHostname(url) : null,
|
|
906
|
+
transport: serverConfig.transport ?? null,
|
|
907
|
+
has_auth: !!(serverConfig.authToken || serverConfig.authProvider)
|
|
908
|
+
};
|
|
909
|
+
}
|
|
910
|
+
_extractHostname(url) {
|
|
911
|
+
try {
|
|
912
|
+
return new URL(url).hostname;
|
|
913
|
+
} catch {
|
|
914
|
+
return null;
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
};
|
|
918
|
+
var ClientRemoveServerEvent = class extends BaseTelemetryEvent {
|
|
919
|
+
constructor(data) {
|
|
920
|
+
super();
|
|
921
|
+
this.data = data;
|
|
922
|
+
}
|
|
923
|
+
static {
|
|
924
|
+
__name(this, "ClientRemoveServerEvent");
|
|
925
|
+
}
|
|
926
|
+
get name() {
|
|
927
|
+
return "client_remove_server";
|
|
928
|
+
}
|
|
929
|
+
get properties() {
|
|
930
|
+
return {
|
|
931
|
+
server_name: this.data.serverName
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
};
|
|
935
|
+
|
|
936
|
+
// src/server/utils/runtime.ts
|
|
937
|
+
var isDeno = typeof globalThis.Deno !== "undefined";
|
|
938
|
+
function generateUUID() {
|
|
939
|
+
return globalThis.crypto.randomUUID();
|
|
940
|
+
}
|
|
941
|
+
__name(generateUUID, "generateUUID");
|
|
942
|
+
|
|
943
|
+
// src/version.ts
|
|
944
|
+
var VERSION = "1.11.0-canary.9";
|
|
945
|
+
function getPackageVersion() {
|
|
946
|
+
return VERSION;
|
|
947
|
+
}
|
|
948
|
+
__name(getPackageVersion, "getPackageVersion");
|
|
949
|
+
|
|
950
|
+
// src/telemetry/telemetry.ts
|
|
951
|
+
var USER_ID_STORAGE_KEY = "mcp_use_user_id";
|
|
952
|
+
function detectRuntimeEnvironment() {
|
|
953
|
+
try {
|
|
954
|
+
if (typeof globalThis.Bun !== "undefined") {
|
|
955
|
+
return "bun";
|
|
956
|
+
}
|
|
957
|
+
if (typeof globalThis.Deno !== "undefined") {
|
|
958
|
+
return "deno";
|
|
959
|
+
}
|
|
960
|
+
if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
|
|
961
|
+
return "cloudflare-workers";
|
|
962
|
+
}
|
|
963
|
+
if (typeof globalThis.EdgeRuntime !== "undefined") {
|
|
964
|
+
return "edge";
|
|
965
|
+
}
|
|
966
|
+
if (typeof window !== "undefined" && typeof document !== "undefined") {
|
|
967
|
+
return "browser";
|
|
968
|
+
}
|
|
969
|
+
if (typeof process !== "undefined" && typeof process.versions?.node !== "undefined") {
|
|
970
|
+
return "node";
|
|
971
|
+
}
|
|
972
|
+
return "unknown";
|
|
973
|
+
} catch {
|
|
974
|
+
return "unknown";
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
__name(detectRuntimeEnvironment, "detectRuntimeEnvironment");
|
|
978
|
+
function getStorageCapability(env) {
|
|
979
|
+
switch (env) {
|
|
980
|
+
case "node":
|
|
981
|
+
case "bun":
|
|
982
|
+
return "filesystem";
|
|
983
|
+
case "browser":
|
|
984
|
+
try {
|
|
985
|
+
if (typeof localStorage !== "undefined") {
|
|
986
|
+
localStorage.setItem("__mcp_use_test__", "1");
|
|
987
|
+
localStorage.removeItem("__mcp_use_test__");
|
|
988
|
+
return "localStorage";
|
|
989
|
+
}
|
|
990
|
+
} catch {
|
|
991
|
+
}
|
|
992
|
+
return "session-only";
|
|
993
|
+
case "deno":
|
|
994
|
+
return "session-only";
|
|
995
|
+
default:
|
|
996
|
+
return "session-only";
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
__name(getStorageCapability, "getStorageCapability");
|
|
1000
|
+
var cachedEnvironment = null;
|
|
1001
|
+
function getRuntimeEnvironment() {
|
|
1002
|
+
if (cachedEnvironment === null) {
|
|
1003
|
+
cachedEnvironment = detectRuntimeEnvironment();
|
|
1004
|
+
}
|
|
1005
|
+
return cachedEnvironment;
|
|
1006
|
+
}
|
|
1007
|
+
__name(getRuntimeEnvironment, "getRuntimeEnvironment");
|
|
1008
|
+
var ScarfEventLogger = class {
|
|
1009
|
+
static {
|
|
1010
|
+
__name(this, "ScarfEventLogger");
|
|
1011
|
+
}
|
|
1012
|
+
endpoint;
|
|
1013
|
+
timeout;
|
|
1014
|
+
constructor(endpoint, timeout = 3e3) {
|
|
1015
|
+
this.endpoint = endpoint;
|
|
1016
|
+
this.timeout = timeout;
|
|
1017
|
+
}
|
|
1018
|
+
async logEvent(properties) {
|
|
1019
|
+
try {
|
|
1020
|
+
const controller = new AbortController();
|
|
1021
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
1022
|
+
const response = await fetch(this.endpoint, {
|
|
1023
|
+
method: "POST",
|
|
1024
|
+
headers: {
|
|
1025
|
+
"Content-Type": "application/json"
|
|
1026
|
+
},
|
|
1027
|
+
body: JSON.stringify(properties),
|
|
1028
|
+
signal: controller.signal
|
|
1029
|
+
});
|
|
1030
|
+
clearTimeout(timeoutId);
|
|
1031
|
+
if (!response.ok) {
|
|
1032
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
1033
|
+
}
|
|
1034
|
+
} catch (error) {
|
|
1035
|
+
logger.debug(`Failed to send Scarf event: ${error}`);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
};
|
|
1039
|
+
var Telemetry = class _Telemetry {
|
|
1040
|
+
static {
|
|
1041
|
+
__name(this, "Telemetry");
|
|
1042
|
+
}
|
|
1043
|
+
static instance = null;
|
|
1044
|
+
PROJECT_API_KEY = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
|
|
1045
|
+
HOST = "https://eu.i.posthog.com";
|
|
1046
|
+
SCARF_GATEWAY_URL = "https://mcpuse.gateway.scarf.sh/events-ts";
|
|
1047
|
+
UNKNOWN_USER_ID = "UNKNOWN_USER_ID";
|
|
1048
|
+
_currUserId = null;
|
|
1049
|
+
_posthogNodeClient = null;
|
|
1050
|
+
_posthogBrowserClient = null;
|
|
1051
|
+
_posthogLoading = null;
|
|
1052
|
+
_scarfClient = null;
|
|
1053
|
+
_runtimeEnvironment;
|
|
1054
|
+
_storageCapability;
|
|
1055
|
+
_source;
|
|
1056
|
+
// Node.js specific paths (lazily computed)
|
|
1057
|
+
_userIdPath = null;
|
|
1058
|
+
_versionDownloadPath = null;
|
|
1059
|
+
constructor() {
|
|
1060
|
+
this._runtimeEnvironment = getRuntimeEnvironment();
|
|
1061
|
+
this._storageCapability = getStorageCapability(this._runtimeEnvironment);
|
|
1062
|
+
this._source = typeof process !== "undefined" && process.env?.MCP_USE_TELEMETRY_SOURCE || this._runtimeEnvironment;
|
|
1063
|
+
const telemetryDisabled = this._checkTelemetryDisabled();
|
|
1064
|
+
const canSupportTelemetry = this._runtimeEnvironment !== "unknown";
|
|
1065
|
+
if (telemetryDisabled) {
|
|
1066
|
+
this._posthogNodeClient = null;
|
|
1067
|
+
this._posthogBrowserClient = null;
|
|
1068
|
+
this._scarfClient = null;
|
|
1069
|
+
logger.debug("Telemetry disabled via environment/localStorage");
|
|
1070
|
+
} else if (!canSupportTelemetry) {
|
|
1071
|
+
this._posthogNodeClient = null;
|
|
1072
|
+
this._posthogBrowserClient = null;
|
|
1073
|
+
this._scarfClient = null;
|
|
1074
|
+
logger.debug(
|
|
1075
|
+
`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`
|
|
1076
|
+
);
|
|
1077
|
+
} else {
|
|
1078
|
+
logger.info(
|
|
1079
|
+
"Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."
|
|
1080
|
+
);
|
|
1081
|
+
this._posthogLoading = this._initPostHog();
|
|
1082
|
+
try {
|
|
1083
|
+
this._scarfClient = new ScarfEventLogger(this.SCARF_GATEWAY_URL, 3e3);
|
|
1084
|
+
} catch (e) {
|
|
1085
|
+
logger.warn(`Failed to initialize Scarf telemetry: ${e}`);
|
|
1086
|
+
this._scarfClient = null;
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
_checkTelemetryDisabled() {
|
|
1091
|
+
if (typeof process !== "undefined" && process.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === "false") {
|
|
1092
|
+
return true;
|
|
1093
|
+
}
|
|
1094
|
+
if (typeof localStorage !== "undefined" && localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY") === "false") {
|
|
1095
|
+
return true;
|
|
1096
|
+
}
|
|
1097
|
+
return false;
|
|
1098
|
+
}
|
|
1099
|
+
async _initPostHog() {
|
|
1100
|
+
const isBrowser = this._runtimeEnvironment === "browser";
|
|
1101
|
+
if (isBrowser) {
|
|
1102
|
+
await this._initPostHogBrowser();
|
|
1103
|
+
} else {
|
|
1104
|
+
await this._initPostHogNode();
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
async _initPostHogBrowser() {
|
|
1108
|
+
try {
|
|
1109
|
+
const posthogModule = await import("posthog-js");
|
|
1110
|
+
const posthog = posthogModule.default || posthogModule.posthog;
|
|
1111
|
+
if (!posthog || typeof posthog.init !== "function") {
|
|
1112
|
+
throw new Error("posthog-js module did not export expected interface");
|
|
1113
|
+
}
|
|
1114
|
+
posthog.init(this.PROJECT_API_KEY, {
|
|
1115
|
+
api_host: this.HOST,
|
|
1116
|
+
persistence: "localStorage",
|
|
1117
|
+
autocapture: false,
|
|
1118
|
+
// We only want explicit captures
|
|
1119
|
+
capture_pageview: false,
|
|
1120
|
+
// We don't want automatic pageview tracking
|
|
1121
|
+
disable_session_recording: true,
|
|
1122
|
+
// No session recording
|
|
1123
|
+
loaded: /* @__PURE__ */ __name(() => {
|
|
1124
|
+
logger.debug("PostHog browser client initialized");
|
|
1125
|
+
}, "loaded")
|
|
1126
|
+
});
|
|
1127
|
+
this._posthogBrowserClient = posthog;
|
|
1128
|
+
} catch (e) {
|
|
1129
|
+
logger.warn(`Failed to initialize PostHog browser telemetry: ${e}`);
|
|
1130
|
+
this._posthogBrowserClient = null;
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
async _initPostHogNode() {
|
|
1134
|
+
try {
|
|
1135
|
+
const { PostHog } = await import("posthog-node");
|
|
1136
|
+
const isServerlessEnvironment = [
|
|
1137
|
+
"cloudflare-workers",
|
|
1138
|
+
"edge",
|
|
1139
|
+
"deno"
|
|
1140
|
+
].includes(this._runtimeEnvironment);
|
|
1141
|
+
const posthogOptions = {
|
|
1142
|
+
host: this.HOST,
|
|
1143
|
+
disableGeoip: false
|
|
1144
|
+
};
|
|
1145
|
+
if (isServerlessEnvironment) {
|
|
1146
|
+
posthogOptions.flushAt = 1;
|
|
1147
|
+
posthogOptions.flushInterval = 0;
|
|
1148
|
+
}
|
|
1149
|
+
this._posthogNodeClient = new PostHog(
|
|
1150
|
+
this.PROJECT_API_KEY,
|
|
1151
|
+
posthogOptions
|
|
1152
|
+
);
|
|
1153
|
+
logger.debug("PostHog Node.js client initialized");
|
|
1154
|
+
} catch (e) {
|
|
1155
|
+
logger.warn(`Failed to initialize PostHog Node.js telemetry: ${e}`);
|
|
1156
|
+
this._posthogNodeClient = null;
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Get the detected runtime environment
|
|
1161
|
+
*/
|
|
1162
|
+
get runtimeEnvironment() {
|
|
1163
|
+
return this._runtimeEnvironment;
|
|
1164
|
+
}
|
|
1165
|
+
/**
|
|
1166
|
+
* Get the storage capability for this environment
|
|
1167
|
+
*/
|
|
1168
|
+
get storageCapability() {
|
|
1169
|
+
return this._storageCapability;
|
|
1170
|
+
}
|
|
1171
|
+
static getInstance() {
|
|
1172
|
+
if (!_Telemetry.instance) {
|
|
1173
|
+
_Telemetry.instance = new _Telemetry();
|
|
1174
|
+
}
|
|
1175
|
+
return _Telemetry.instance;
|
|
1176
|
+
}
|
|
1177
|
+
/**
|
|
1178
|
+
* Set the source identifier for telemetry events.
|
|
1179
|
+
* This allows tracking usage from different applications.
|
|
1180
|
+
* @param source - The source identifier (e.g., "my-app", "cli", "vs-code-extension")
|
|
1181
|
+
*/
|
|
1182
|
+
setSource(source) {
|
|
1183
|
+
this._source = source;
|
|
1184
|
+
logger.debug(`Telemetry source set to: ${source}`);
|
|
1185
|
+
}
|
|
1186
|
+
/**
|
|
1187
|
+
* Get the current source identifier.
|
|
1188
|
+
*/
|
|
1189
|
+
getSource() {
|
|
1190
|
+
return this._source;
|
|
1191
|
+
}
|
|
1192
|
+
/**
|
|
1193
|
+
* Check if telemetry is enabled.
|
|
1194
|
+
*/
|
|
1195
|
+
get isEnabled() {
|
|
1196
|
+
return this._posthogNodeClient !== null || this._posthogBrowserClient !== null || this._scarfClient !== null;
|
|
1197
|
+
}
|
|
1198
|
+
get userId() {
|
|
1199
|
+
if (this._currUserId) {
|
|
1200
|
+
return this._currUserId;
|
|
1201
|
+
}
|
|
1202
|
+
try {
|
|
1203
|
+
switch (this._storageCapability) {
|
|
1204
|
+
case "filesystem":
|
|
1205
|
+
this._currUserId = this._getUserIdFromFilesystem();
|
|
1206
|
+
break;
|
|
1207
|
+
case "localStorage":
|
|
1208
|
+
this._currUserId = this._getUserIdFromLocalStorage();
|
|
1209
|
+
break;
|
|
1210
|
+
case "session-only":
|
|
1211
|
+
default:
|
|
1212
|
+
this._currUserId = `session-${generateUUID()}`;
|
|
1213
|
+
logger.debug(
|
|
1214
|
+
`Using session-based user ID (${this._runtimeEnvironment} environment)`
|
|
1215
|
+
);
|
|
1216
|
+
break;
|
|
1217
|
+
}
|
|
1218
|
+
if (this._storageCapability === "filesystem" && this._currUserId) {
|
|
1219
|
+
this._trackPackageDownloadInternal(this._currUserId, {
|
|
1220
|
+
triggered_by: "user_id_property"
|
|
1221
|
+
}).catch((e) => logger.debug(`Failed to track package download: ${e}`));
|
|
1222
|
+
}
|
|
1223
|
+
} catch (e) {
|
|
1224
|
+
logger.debug(`Failed to get/create user ID: ${e}`);
|
|
1225
|
+
this._currUserId = this.UNKNOWN_USER_ID;
|
|
1226
|
+
}
|
|
1227
|
+
return this._currUserId;
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Get or create user ID from filesystem (Node.js/Bun)
|
|
1231
|
+
*/
|
|
1232
|
+
_getUserIdFromFilesystem() {
|
|
1233
|
+
const fs2 = require("fs");
|
|
1234
|
+
const os = require("os");
|
|
1235
|
+
const path2 = require("path");
|
|
1236
|
+
if (!this._userIdPath) {
|
|
1237
|
+
this._userIdPath = path2.join(
|
|
1238
|
+
this._getCacheHome(os, path2),
|
|
1239
|
+
"mcp_use_3",
|
|
1240
|
+
"telemetry_user_id"
|
|
1241
|
+
);
|
|
1242
|
+
}
|
|
1243
|
+
const isFirstTime = !fs2.existsSync(this._userIdPath);
|
|
1244
|
+
if (isFirstTime) {
|
|
1245
|
+
logger.debug(`Creating user ID path: ${this._userIdPath}`);
|
|
1246
|
+
fs2.mkdirSync(path2.dirname(this._userIdPath), { recursive: true });
|
|
1247
|
+
const newUserId = generateUUID();
|
|
1248
|
+
fs2.writeFileSync(this._userIdPath, newUserId);
|
|
1249
|
+
logger.debug(`User ID path created: ${this._userIdPath}`);
|
|
1250
|
+
return newUserId;
|
|
1251
|
+
}
|
|
1252
|
+
return fs2.readFileSync(this._userIdPath, "utf-8").trim();
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* Get or create user ID from localStorage (Browser)
|
|
1256
|
+
*/
|
|
1257
|
+
_getUserIdFromLocalStorage() {
|
|
1258
|
+
try {
|
|
1259
|
+
let userId = localStorage.getItem(USER_ID_STORAGE_KEY);
|
|
1260
|
+
if (!userId) {
|
|
1261
|
+
userId = generateUUID();
|
|
1262
|
+
localStorage.setItem(USER_ID_STORAGE_KEY, userId);
|
|
1263
|
+
logger.debug(`Created new browser user ID`);
|
|
1264
|
+
}
|
|
1265
|
+
return userId;
|
|
1266
|
+
} catch (e) {
|
|
1267
|
+
logger.debug(`localStorage access failed: ${e}`);
|
|
1268
|
+
return `session-${generateUUID()}`;
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
_getCacheHome(os, path2) {
|
|
1272
|
+
const envVar = process.env.XDG_CACHE_HOME;
|
|
1273
|
+
if (envVar && path2.isAbsolute(envVar)) {
|
|
1274
|
+
return envVar;
|
|
1275
|
+
}
|
|
1276
|
+
const platform = process.platform;
|
|
1277
|
+
const homeDir = os.homedir();
|
|
1278
|
+
if (platform === "win32") {
|
|
1279
|
+
const appdata = process.env.LOCALAPPDATA || process.env.APPDATA;
|
|
1280
|
+
if (appdata) {
|
|
1281
|
+
return appdata;
|
|
1282
|
+
}
|
|
1283
|
+
return path2.join(homeDir, "AppData", "Local");
|
|
1284
|
+
} else if (platform === "darwin") {
|
|
1285
|
+
return path2.join(homeDir, "Library", "Caches");
|
|
1286
|
+
} else {
|
|
1287
|
+
return path2.join(homeDir, ".cache");
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
async capture(event) {
|
|
1291
|
+
if (this._posthogLoading) {
|
|
1292
|
+
await this._posthogLoading;
|
|
1293
|
+
}
|
|
1294
|
+
if (!this._posthogNodeClient && !this._posthogBrowserClient && !this._scarfClient) {
|
|
1295
|
+
return;
|
|
1296
|
+
}
|
|
1297
|
+
const properties = { ...event.properties };
|
|
1298
|
+
properties.mcp_use_version = getPackageVersion();
|
|
1299
|
+
properties.language = "typescript";
|
|
1300
|
+
properties.source = this._source;
|
|
1301
|
+
properties.runtime = this._runtimeEnvironment;
|
|
1302
|
+
if (this._posthogNodeClient) {
|
|
1303
|
+
try {
|
|
1304
|
+
logger.debug(`CAPTURE: PostHog Node Event ${event.name}`);
|
|
1305
|
+
this._posthogNodeClient.capture({
|
|
1306
|
+
distinctId: this.userId,
|
|
1307
|
+
event: event.name,
|
|
1308
|
+
properties
|
|
1309
|
+
});
|
|
1310
|
+
} catch (e) {
|
|
1311
|
+
logger.debug(`Failed to track PostHog Node event ${event.name}: ${e}`);
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
if (this._posthogBrowserClient) {
|
|
1315
|
+
try {
|
|
1316
|
+
logger.debug(`CAPTURE: PostHog Browser Event ${event.name}`);
|
|
1317
|
+
this._posthogBrowserClient.capture(event.name, {
|
|
1318
|
+
...properties,
|
|
1319
|
+
distinct_id: this.userId
|
|
1320
|
+
});
|
|
1321
|
+
} catch (e) {
|
|
1322
|
+
logger.debug(
|
|
1323
|
+
`Failed to track PostHog Browser event ${event.name}: ${e}`
|
|
1324
|
+
);
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
if (this._scarfClient) {
|
|
1328
|
+
try {
|
|
1329
|
+
const scarfProperties = {
|
|
1330
|
+
...properties,
|
|
1331
|
+
user_id: this.userId,
|
|
1332
|
+
event: event.name
|
|
1333
|
+
};
|
|
1334
|
+
await this._scarfClient.logEvent(scarfProperties);
|
|
1335
|
+
} catch (e) {
|
|
1336
|
+
logger.debug(`Failed to track Scarf event ${event.name}: ${e}`);
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
// ============================================================================
|
|
1341
|
+
// Package Download Tracking (Node.js only)
|
|
1342
|
+
// ============================================================================
|
|
1343
|
+
/**
|
|
1344
|
+
* Track package download event.
|
|
1345
|
+
* This is a public wrapper that safely accesses userId.
|
|
1346
|
+
*/
|
|
1347
|
+
async trackPackageDownload(properties) {
|
|
1348
|
+
return this._trackPackageDownloadInternal(this.userId, properties);
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Internal method to track package download with explicit userId.
|
|
1352
|
+
*/
|
|
1353
|
+
async _trackPackageDownloadInternal(userId, properties) {
|
|
1354
|
+
if (!this._scarfClient) {
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
if (this._storageCapability !== "filesystem") {
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
try {
|
|
1361
|
+
const fs2 = require("fs");
|
|
1362
|
+
const path2 = require("path");
|
|
1363
|
+
const os = require("os");
|
|
1364
|
+
if (!this._versionDownloadPath) {
|
|
1365
|
+
this._versionDownloadPath = path2.join(
|
|
1366
|
+
this._getCacheHome(os, path2),
|
|
1367
|
+
"mcp_use",
|
|
1368
|
+
"download_version"
|
|
1369
|
+
);
|
|
1370
|
+
}
|
|
1371
|
+
const currentVersion = getPackageVersion();
|
|
1372
|
+
let shouldTrack = false;
|
|
1373
|
+
let firstDownload = false;
|
|
1374
|
+
if (!fs2.existsSync(this._versionDownloadPath)) {
|
|
1375
|
+
shouldTrack = true;
|
|
1376
|
+
firstDownload = true;
|
|
1377
|
+
fs2.mkdirSync(path2.dirname(this._versionDownloadPath), {
|
|
1378
|
+
recursive: true
|
|
1379
|
+
});
|
|
1380
|
+
fs2.writeFileSync(this._versionDownloadPath, currentVersion);
|
|
1381
|
+
} else {
|
|
1382
|
+
const savedVersion = fs2.readFileSync(this._versionDownloadPath, "utf-8").trim();
|
|
1383
|
+
if (currentVersion > savedVersion) {
|
|
1384
|
+
shouldTrack = true;
|
|
1385
|
+
firstDownload = false;
|
|
1386
|
+
fs2.writeFileSync(this._versionDownloadPath, currentVersion);
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
if (shouldTrack) {
|
|
1390
|
+
logger.debug(
|
|
1391
|
+
`Tracking package download event with properties: ${JSON.stringify(properties)}`
|
|
1392
|
+
);
|
|
1393
|
+
const eventProperties = { ...properties || {} };
|
|
1394
|
+
eventProperties.mcp_use_version = currentVersion;
|
|
1395
|
+
eventProperties.user_id = userId;
|
|
1396
|
+
eventProperties.event = "package_download";
|
|
1397
|
+
eventProperties.first_download = firstDownload;
|
|
1398
|
+
eventProperties.language = "typescript";
|
|
1399
|
+
eventProperties.source = this._source;
|
|
1400
|
+
eventProperties.runtime = this._runtimeEnvironment;
|
|
1401
|
+
await this._scarfClient.logEvent(eventProperties);
|
|
1402
|
+
}
|
|
1403
|
+
} catch (e) {
|
|
1404
|
+
logger.debug(`Failed to track Scarf package_download event: ${e}`);
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
// ============================================================================
|
|
1408
|
+
// Agent Events
|
|
1409
|
+
// ============================================================================
|
|
1410
|
+
async trackAgentExecution(data) {
|
|
1411
|
+
if (!this.isEnabled) return;
|
|
1412
|
+
const event = new MCPAgentExecutionEvent(data);
|
|
1413
|
+
await this.capture(event);
|
|
1414
|
+
}
|
|
1415
|
+
// ============================================================================
|
|
1416
|
+
// Server Events
|
|
1417
|
+
// ============================================================================
|
|
1418
|
+
/**
|
|
1419
|
+
* Track server run event directly from an MCPServer instance.
|
|
1420
|
+
*/
|
|
1421
|
+
async trackServerRunFromServer(server, transport) {
|
|
1422
|
+
if (!this.isEnabled) return;
|
|
1423
|
+
const data = createServerRunEventData(server, transport);
|
|
1424
|
+
const event = new ServerRunEvent(data);
|
|
1425
|
+
await this.capture(event);
|
|
1426
|
+
}
|
|
1427
|
+
async trackServerInitialize(data) {
|
|
1428
|
+
if (!this.isEnabled) return;
|
|
1429
|
+
const event = new ServerInitializeEvent(data);
|
|
1430
|
+
await this.capture(event);
|
|
1431
|
+
}
|
|
1432
|
+
async trackServerToolCall(data) {
|
|
1433
|
+
if (!this.isEnabled) return;
|
|
1434
|
+
const event = new ServerToolCallEvent(data);
|
|
1435
|
+
await this.capture(event);
|
|
1436
|
+
}
|
|
1437
|
+
async trackServerResourceCall(data) {
|
|
1438
|
+
if (!this.isEnabled) return;
|
|
1439
|
+
const event = new ServerResourceCallEvent(data);
|
|
1440
|
+
await this.capture(event);
|
|
1441
|
+
}
|
|
1442
|
+
async trackServerPromptCall(data) {
|
|
1443
|
+
if (!this.isEnabled) return;
|
|
1444
|
+
const event = new ServerPromptCallEvent(data);
|
|
1445
|
+
await this.capture(event);
|
|
1446
|
+
}
|
|
1447
|
+
async trackServerContext(data) {
|
|
1448
|
+
if (!this.isEnabled) return;
|
|
1449
|
+
const event = new ServerContextEvent(data);
|
|
1450
|
+
await this.capture(event);
|
|
1451
|
+
}
|
|
1452
|
+
// ============================================================================
|
|
1453
|
+
// Client Events
|
|
1454
|
+
// ============================================================================
|
|
1455
|
+
async trackMCPClientInit(data) {
|
|
1456
|
+
if (!this.isEnabled) return;
|
|
1457
|
+
const event = new MCPClientInitEvent(data);
|
|
1458
|
+
await this.capture(event);
|
|
1459
|
+
}
|
|
1460
|
+
async trackConnectorInit(data) {
|
|
1461
|
+
if (!this.isEnabled) return;
|
|
1462
|
+
const event = new ConnectorInitEvent(data);
|
|
1463
|
+
await this.capture(event);
|
|
1464
|
+
}
|
|
1465
|
+
async trackClientAddServer(serverName, serverConfig) {
|
|
1466
|
+
if (!this.isEnabled) return;
|
|
1467
|
+
const event = new ClientAddServerEvent({ serverName, serverConfig });
|
|
1468
|
+
await this.capture(event);
|
|
1469
|
+
}
|
|
1470
|
+
async trackClientRemoveServer(serverName) {
|
|
1471
|
+
if (!this.isEnabled) return;
|
|
1472
|
+
const event = new ClientRemoveServerEvent({ serverName });
|
|
1473
|
+
await this.capture(event);
|
|
1474
|
+
}
|
|
1475
|
+
// ============================================================================
|
|
1476
|
+
// React Hook / Browser specific events
|
|
1477
|
+
// ============================================================================
|
|
1478
|
+
async trackUseMcpConnection(data) {
|
|
1479
|
+
if (!this.isEnabled) return;
|
|
1480
|
+
await this.capture({
|
|
1481
|
+
name: "usemcp_connection",
|
|
1482
|
+
properties: {
|
|
1483
|
+
url_domain: new URL(data.url).hostname,
|
|
1484
|
+
// Only domain for privacy
|
|
1485
|
+
transport_type: data.transportType,
|
|
1486
|
+
success: data.success,
|
|
1487
|
+
error_type: data.errorType ?? null,
|
|
1488
|
+
connection_time_ms: data.connectionTimeMs ?? null,
|
|
1489
|
+
has_oauth: data.hasOAuth,
|
|
1490
|
+
has_sampling: data.hasSampling,
|
|
1491
|
+
has_elicitation: data.hasElicitation
|
|
1492
|
+
}
|
|
1493
|
+
});
|
|
1494
|
+
}
|
|
1495
|
+
async trackUseMcpToolCall(data) {
|
|
1496
|
+
if (!this.isEnabled) return;
|
|
1497
|
+
await this.capture({
|
|
1498
|
+
name: "usemcp_tool_call",
|
|
1499
|
+
properties: {
|
|
1500
|
+
tool_name: data.toolName,
|
|
1501
|
+
success: data.success,
|
|
1502
|
+
error_type: data.errorType ?? null,
|
|
1503
|
+
execution_time_ms: data.executionTimeMs ?? null
|
|
1504
|
+
}
|
|
1505
|
+
});
|
|
1506
|
+
}
|
|
1507
|
+
async trackUseMcpResourceRead(data) {
|
|
1508
|
+
if (!this.isEnabled) return;
|
|
1509
|
+
await this.capture({
|
|
1510
|
+
name: "usemcp_resource_read",
|
|
1511
|
+
properties: {
|
|
1512
|
+
resource_uri_scheme: data.resourceUri.split(":")[0],
|
|
1513
|
+
// Only scheme for privacy
|
|
1514
|
+
success: data.success,
|
|
1515
|
+
error_type: data.errorType ?? null
|
|
1516
|
+
}
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
// ============================================================================
|
|
1520
|
+
// Browser-specific Methods
|
|
1521
|
+
// ============================================================================
|
|
1522
|
+
/**
|
|
1523
|
+
* Identify the current user (useful for linking sessions)
|
|
1524
|
+
* Browser only - no-op in Node.js
|
|
1525
|
+
*/
|
|
1526
|
+
identify(userId, properties) {
|
|
1527
|
+
if (this._posthogBrowserClient) {
|
|
1528
|
+
try {
|
|
1529
|
+
this._posthogBrowserClient.identify(userId, properties);
|
|
1530
|
+
} catch (e) {
|
|
1531
|
+
logger.debug(`Failed to identify user: ${e}`);
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
/**
|
|
1536
|
+
* Reset the user identity (useful for logout)
|
|
1537
|
+
* Browser only - no-op in Node.js
|
|
1538
|
+
*/
|
|
1539
|
+
reset() {
|
|
1540
|
+
if (this._posthogBrowserClient) {
|
|
1541
|
+
try {
|
|
1542
|
+
this._posthogBrowserClient.reset();
|
|
1543
|
+
} catch (e) {
|
|
1544
|
+
logger.debug(`Failed to reset user: ${e}`);
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
this._currUserId = null;
|
|
1548
|
+
}
|
|
1549
|
+
// ============================================================================
|
|
1550
|
+
// Node.js-specific Methods
|
|
1551
|
+
// ============================================================================
|
|
1552
|
+
/**
|
|
1553
|
+
* Flush the telemetry queue (Node.js only)
|
|
1554
|
+
*/
|
|
1555
|
+
flush() {
|
|
1556
|
+
if (this._posthogNodeClient) {
|
|
1557
|
+
try {
|
|
1558
|
+
this._posthogNodeClient.flush();
|
|
1559
|
+
logger.debug("PostHog client telemetry queue flushed");
|
|
1560
|
+
} catch (e) {
|
|
1561
|
+
logger.debug(`Failed to flush PostHog client: ${e}`);
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* Shutdown the telemetry client (Node.js only)
|
|
1567
|
+
*/
|
|
1568
|
+
shutdown() {
|
|
1569
|
+
if (this._posthogNodeClient) {
|
|
1570
|
+
try {
|
|
1571
|
+
this._posthogNodeClient.shutdown();
|
|
1572
|
+
logger.debug("PostHog client shutdown successfully");
|
|
1573
|
+
} catch (e) {
|
|
1574
|
+
logger.debug(`Error shutting down PostHog client: ${e}`);
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
};
|
|
1579
|
+
var Tel = Telemetry;
|
|
1580
|
+
|
|
1581
|
+
// src/client/base.ts
|
|
1582
|
+
var BaseMCPClient = class {
|
|
1583
|
+
static {
|
|
1584
|
+
__name(this, "BaseMCPClient");
|
|
1585
|
+
}
|
|
1586
|
+
config = {};
|
|
1587
|
+
sessions = {};
|
|
1588
|
+
activeSessions = [];
|
|
1589
|
+
constructor(config) {
|
|
1590
|
+
if (config) {
|
|
1591
|
+
this.config = config;
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
static fromDict(_cfg) {
|
|
1595
|
+
throw new Error("fromDict must be implemented by concrete class");
|
|
1596
|
+
}
|
|
1597
|
+
addServer(name, serverConfig) {
|
|
1598
|
+
this.config.mcpServers = this.config.mcpServers || {};
|
|
1599
|
+
this.config.mcpServers[name] = serverConfig;
|
|
1600
|
+
Tel.getInstance().trackClientAddServer(name, serverConfig);
|
|
1601
|
+
}
|
|
1602
|
+
removeServer(name) {
|
|
1603
|
+
if (this.config.mcpServers?.[name]) {
|
|
1604
|
+
delete this.config.mcpServers[name];
|
|
1605
|
+
this.activeSessions = this.activeSessions.filter((n) => n !== name);
|
|
1606
|
+
Tel.getInstance().trackClientRemoveServer(name);
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
getServerNames() {
|
|
1610
|
+
return Object.keys(this.config.mcpServers ?? {});
|
|
1611
|
+
}
|
|
1612
|
+
getServerConfig(name) {
|
|
1613
|
+
return this.config.mcpServers?.[name];
|
|
1614
|
+
}
|
|
1615
|
+
getConfig() {
|
|
1616
|
+
return this.config ?? {};
|
|
1617
|
+
}
|
|
1618
|
+
async createSession(serverName, autoInitialize = true) {
|
|
1619
|
+
const servers = this.config.mcpServers ?? {};
|
|
1620
|
+
if (Object.keys(servers).length === 0) {
|
|
1621
|
+
logger.warn("No MCP servers defined in config");
|
|
1622
|
+
}
|
|
1623
|
+
if (!servers[serverName]) {
|
|
1624
|
+
throw new Error(`Server '${serverName}' not found in config`);
|
|
1625
|
+
}
|
|
1626
|
+
const connector = this.createConnectorFromConfig(servers[serverName]);
|
|
1627
|
+
const session = new MCPSession(connector);
|
|
1628
|
+
if (autoInitialize) {
|
|
1629
|
+
await session.initialize();
|
|
1630
|
+
}
|
|
1631
|
+
this.sessions[serverName] = session;
|
|
1632
|
+
if (!this.activeSessions.includes(serverName)) {
|
|
1633
|
+
this.activeSessions.push(serverName);
|
|
1634
|
+
}
|
|
1635
|
+
return session;
|
|
1636
|
+
}
|
|
1637
|
+
async createAllSessions(autoInitialize = true) {
|
|
1638
|
+
const servers = this.config.mcpServers ?? {};
|
|
1639
|
+
if (Object.keys(servers).length === 0) {
|
|
1640
|
+
logger.warn("No MCP servers defined in config");
|
|
1641
|
+
}
|
|
1642
|
+
for (const name of Object.keys(servers)) {
|
|
1643
|
+
await this.createSession(name, autoInitialize);
|
|
1644
|
+
}
|
|
1645
|
+
return this.sessions;
|
|
1646
|
+
}
|
|
1647
|
+
getSession(serverName) {
|
|
1648
|
+
const session = this.sessions[serverName];
|
|
1649
|
+
if (!session) {
|
|
1650
|
+
return null;
|
|
1651
|
+
}
|
|
1652
|
+
return session;
|
|
1653
|
+
}
|
|
1654
|
+
requireSession(serverName) {
|
|
1655
|
+
const session = this.sessions[serverName];
|
|
1656
|
+
if (!session) {
|
|
1657
|
+
throw new Error(
|
|
1658
|
+
`Session '${serverName}' not found. Available sessions: ${this.activeSessions.join(", ") || "none"}`
|
|
1659
|
+
);
|
|
1660
|
+
}
|
|
1661
|
+
return session;
|
|
1662
|
+
}
|
|
1663
|
+
getAllActiveSessions() {
|
|
1664
|
+
return Object.fromEntries(
|
|
1665
|
+
this.activeSessions.map((n) => [n, this.sessions[n]])
|
|
1666
|
+
);
|
|
1667
|
+
}
|
|
1668
|
+
async closeSession(serverName) {
|
|
1669
|
+
const session = this.sessions[serverName];
|
|
1670
|
+
if (!session) {
|
|
1671
|
+
logger.warn(
|
|
1672
|
+
`No session exists for server ${serverName}, nothing to close`
|
|
1673
|
+
);
|
|
1674
|
+
return;
|
|
1675
|
+
}
|
|
1676
|
+
try {
|
|
1677
|
+
logger.debug(`Closing session for server ${serverName}`);
|
|
1678
|
+
await session.disconnect();
|
|
1679
|
+
} catch (e) {
|
|
1680
|
+
logger.error(`Error closing session for server '${serverName}': ${e}`);
|
|
1681
|
+
} finally {
|
|
1682
|
+
delete this.sessions[serverName];
|
|
1683
|
+
this.activeSessions = this.activeSessions.filter((n) => n !== serverName);
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
async closeAllSessions() {
|
|
1687
|
+
const serverNames = Object.keys(this.sessions);
|
|
1688
|
+
const errors = [];
|
|
1689
|
+
for (const serverName of serverNames) {
|
|
1690
|
+
try {
|
|
1691
|
+
logger.debug(`Closing session for server ${serverName}`);
|
|
1692
|
+
await this.closeSession(serverName);
|
|
1693
|
+
} catch (e) {
|
|
1694
|
+
const errorMsg = `Failed to close session for server '${serverName}': ${e}`;
|
|
1695
|
+
logger.error(errorMsg);
|
|
1696
|
+
errors.push(errorMsg);
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
if (errors.length) {
|
|
1700
|
+
logger.error(
|
|
1701
|
+
`Encountered ${errors.length} errors while closing sessions`
|
|
1702
|
+
);
|
|
1703
|
+
} else {
|
|
1704
|
+
logger.debug("All sessions closed successfully");
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
};
|
|
1708
|
+
|
|
1709
|
+
// src/client/executors/base.ts
|
|
1710
|
+
var BaseCodeExecutor = class {
|
|
1711
|
+
static {
|
|
1712
|
+
__name(this, "BaseCodeExecutor");
|
|
1713
|
+
}
|
|
1714
|
+
client;
|
|
1715
|
+
_connecting = false;
|
|
1716
|
+
constructor(client) {
|
|
1717
|
+
this.client = client;
|
|
1718
|
+
}
|
|
1719
|
+
/**
|
|
1720
|
+
* Ensure all configured MCP servers are connected before execution.
|
|
1721
|
+
* Prevents race conditions with a connection lock.
|
|
1722
|
+
*/
|
|
1723
|
+
async ensureServersConnected() {
|
|
1724
|
+
const configuredServers = this.client.getServerNames();
|
|
1725
|
+
const activeSessions = Object.keys(this.client.getAllActiveSessions());
|
|
1726
|
+
const missingServers = configuredServers.filter(
|
|
1727
|
+
(s) => !activeSessions.includes(s)
|
|
1728
|
+
);
|
|
1729
|
+
if (missingServers.length > 0 && !this._connecting) {
|
|
1730
|
+
this._connecting = true;
|
|
1731
|
+
try {
|
|
1732
|
+
logger.debug(
|
|
1733
|
+
`Connecting to configured servers for code execution: ${missingServers.join(", ")}`
|
|
1734
|
+
);
|
|
1735
|
+
await this.client.createAllSessions();
|
|
1736
|
+
} finally {
|
|
1737
|
+
this._connecting = false;
|
|
1738
|
+
}
|
|
1739
|
+
} else if (missingServers.length > 0 && this._connecting) {
|
|
1740
|
+
logger.debug("Waiting for ongoing server connection...");
|
|
1741
|
+
const startWait = Date.now();
|
|
1742
|
+
while (this._connecting && Date.now() - startWait < 5e3) {
|
|
1743
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
/**
|
|
1748
|
+
* Get tool namespace information from all active MCP sessions.
|
|
1749
|
+
* Filters out the internal code_mode server.
|
|
1750
|
+
*/
|
|
1751
|
+
getToolNamespaces() {
|
|
1752
|
+
const namespaces = [];
|
|
1753
|
+
const activeSessions = this.client.getAllActiveSessions();
|
|
1754
|
+
for (const [serverName, session] of Object.entries(activeSessions)) {
|
|
1755
|
+
if (serverName === "code_mode") continue;
|
|
1756
|
+
try {
|
|
1757
|
+
const connector = session.connector;
|
|
1758
|
+
let tools;
|
|
1759
|
+
try {
|
|
1760
|
+
tools = connector.tools;
|
|
1761
|
+
} catch (e) {
|
|
1762
|
+
logger.warn(`Tools not available for server ${serverName}: ${e}`);
|
|
1763
|
+
continue;
|
|
1764
|
+
}
|
|
1765
|
+
if (!tools || tools.length === 0) continue;
|
|
1766
|
+
namespaces.push({ serverName, tools, session });
|
|
1767
|
+
} catch (e) {
|
|
1768
|
+
logger.warn(`Failed to load tools for server ${serverName}: ${e}`);
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
return namespaces;
|
|
1772
|
+
}
|
|
1773
|
+
/**
|
|
1774
|
+
* Create a search function for discovering available MCP tools.
|
|
1775
|
+
* Used by code execution environments to find tools at runtime.
|
|
1776
|
+
*/
|
|
1777
|
+
createSearchToolsFunction() {
|
|
1778
|
+
return async (query = "", detailLevel = "full") => {
|
|
1779
|
+
const allTools = [];
|
|
1780
|
+
const allNamespaces = /* @__PURE__ */ new Set();
|
|
1781
|
+
const queryLower = query.toLowerCase();
|
|
1782
|
+
const activeSessions = this.client.getAllActiveSessions();
|
|
1783
|
+
for (const [serverName, session] of Object.entries(activeSessions)) {
|
|
1784
|
+
if (serverName === "code_mode") continue;
|
|
1785
|
+
try {
|
|
1786
|
+
const tools = session.connector.tools;
|
|
1787
|
+
if (tools && tools.length > 0) {
|
|
1788
|
+
allNamespaces.add(serverName);
|
|
1789
|
+
}
|
|
1790
|
+
for (const tool of tools) {
|
|
1791
|
+
if (detailLevel === "names") {
|
|
1792
|
+
allTools.push({ name: tool.name, server: serverName });
|
|
1793
|
+
} else if (detailLevel === "descriptions") {
|
|
1794
|
+
allTools.push({
|
|
1795
|
+
name: tool.name,
|
|
1796
|
+
server: serverName,
|
|
1797
|
+
description: tool.description
|
|
1798
|
+
});
|
|
1799
|
+
} else {
|
|
1800
|
+
allTools.push({
|
|
1801
|
+
name: tool.name,
|
|
1802
|
+
server: serverName,
|
|
1803
|
+
description: tool.description,
|
|
1804
|
+
input_schema: tool.inputSchema
|
|
1805
|
+
});
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
} catch (e) {
|
|
1809
|
+
logger.warn(`Failed to search tools in server ${serverName}: ${e}`);
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
let filteredTools = allTools;
|
|
1813
|
+
if (query) {
|
|
1814
|
+
filteredTools = allTools.filter((tool) => {
|
|
1815
|
+
const nameMatch = tool.name.toLowerCase().includes(queryLower);
|
|
1816
|
+
const descMatch = tool.description?.toLowerCase().includes(queryLower);
|
|
1817
|
+
const serverMatch = tool.server.toLowerCase().includes(queryLower);
|
|
1818
|
+
return nameMatch || descMatch || serverMatch;
|
|
1819
|
+
});
|
|
1820
|
+
}
|
|
1821
|
+
return {
|
|
1822
|
+
meta: {
|
|
1823
|
+
total_tools: allTools.length,
|
|
1824
|
+
namespaces: Array.from(allNamespaces).sort(),
|
|
1825
|
+
result_count: filteredTools.length
|
|
1826
|
+
},
|
|
1827
|
+
results: filteredTools
|
|
1828
|
+
};
|
|
1829
|
+
};
|
|
1830
|
+
}
|
|
1831
|
+
};
|
|
1832
|
+
|
|
1833
|
+
// src/client/executors/e2b.ts
|
|
1834
|
+
var E2BCodeExecutor = class extends BaseCodeExecutor {
|
|
1835
|
+
static {
|
|
1836
|
+
__name(this, "E2BCodeExecutor");
|
|
1837
|
+
}
|
|
1838
|
+
e2bApiKey;
|
|
1839
|
+
codeExecSandbox = null;
|
|
1840
|
+
SandboxClass = null;
|
|
1841
|
+
timeoutMs;
|
|
1842
|
+
constructor(client, options) {
|
|
1843
|
+
super(client);
|
|
1844
|
+
this.e2bApiKey = options.apiKey;
|
|
1845
|
+
this.timeoutMs = options.timeoutMs ?? 3e5;
|
|
1846
|
+
}
|
|
1847
|
+
/**
|
|
1848
|
+
* Lazy load E2B Sandbox class.
|
|
1849
|
+
* This allows the library to work without E2B installed.
|
|
1850
|
+
*/
|
|
1851
|
+
async ensureSandboxClass() {
|
|
1852
|
+
if (this.SandboxClass) return;
|
|
1853
|
+
try {
|
|
1854
|
+
const e2b = await import("@e2b/code-interpreter");
|
|
1855
|
+
this.SandboxClass = e2b.Sandbox;
|
|
1856
|
+
} catch (error) {
|
|
1857
|
+
throw new Error(
|
|
1858
|
+
"@e2b/code-interpreter is not installed. The E2B code executor requires this optional dependency. Install it with: yarn add @e2b/code-interpreter"
|
|
1859
|
+
);
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
/**
|
|
1863
|
+
* Get or create a dedicated sandbox for code execution.
|
|
1864
|
+
*/
|
|
1865
|
+
async getOrCreateCodeExecSandbox() {
|
|
1866
|
+
if (this.codeExecSandbox) return this.codeExecSandbox;
|
|
1867
|
+
await this.ensureSandboxClass();
|
|
1868
|
+
logger.debug("Starting E2B sandbox for code execution...");
|
|
1869
|
+
this.codeExecSandbox = await this.SandboxClass.create("base", {
|
|
1870
|
+
apiKey: this.e2bApiKey,
|
|
1871
|
+
timeoutMs: this.timeoutMs
|
|
1872
|
+
});
|
|
1873
|
+
return this.codeExecSandbox;
|
|
1874
|
+
}
|
|
1875
|
+
/**
|
|
1876
|
+
* Generate the shim code that exposes tools to the sandbox environment.
|
|
1877
|
+
* Creates a bridge that intercepts tool calls and sends them back to host.
|
|
1878
|
+
*/
|
|
1879
|
+
generateShim(tools) {
|
|
1880
|
+
let shim = `
|
|
1881
|
+
// MCP Bridge Shim
|
|
1882
|
+
global.__callMcpTool = async (server, tool, args) => {
|
|
1883
|
+
const id = Math.random().toString(36).substring(7);
|
|
1884
|
+
console.log(JSON.stringify({
|
|
1885
|
+
type: '__MCP_TOOL_CALL__',
|
|
1886
|
+
id,
|
|
1887
|
+
server,
|
|
1888
|
+
tool,
|
|
1889
|
+
args
|
|
1890
|
+
}));
|
|
1891
|
+
|
|
1892
|
+
const resultPath = \`/tmp/mcp_result_\${id}.json\`;
|
|
1893
|
+
const fs = require('fs');
|
|
1894
|
+
|
|
1895
|
+
// Poll for result file
|
|
1896
|
+
let attempts = 0;
|
|
1897
|
+
while (attempts < 300) { // 30 seconds timeout
|
|
1898
|
+
if (fs.existsSync(resultPath)) {
|
|
1899
|
+
const content = fs.readFileSync(resultPath, 'utf8');
|
|
1900
|
+
const result = JSON.parse(content);
|
|
1901
|
+
fs.unlinkSync(resultPath); // Clean up
|
|
1902
|
+
|
|
1903
|
+
if (result.error) {
|
|
1904
|
+
throw new Error(result.error);
|
|
1905
|
+
}
|
|
1906
|
+
return result.data;
|
|
1907
|
+
}
|
|
1908
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
1909
|
+
attempts++;
|
|
1910
|
+
}
|
|
1911
|
+
throw new Error('Tool execution timed out');
|
|
1912
|
+
};
|
|
1913
|
+
|
|
1914
|
+
// Global search_tools helper
|
|
1915
|
+
global.search_tools = async (query, detailLevel = 'full') => {
|
|
1916
|
+
const allTools = ${JSON.stringify(
|
|
1917
|
+
Object.entries(tools).flatMap(
|
|
1918
|
+
([server, serverTools]) => serverTools.map((tool) => ({
|
|
1919
|
+
name: tool.name,
|
|
1920
|
+
description: tool.description,
|
|
1921
|
+
server,
|
|
1922
|
+
input_schema: tool.inputSchema
|
|
1923
|
+
}))
|
|
1924
|
+
)
|
|
1925
|
+
)};
|
|
1926
|
+
|
|
1927
|
+
const filtered = allTools.filter(tool => {
|
|
1928
|
+
if (!query) return true;
|
|
1929
|
+
const q = query.toLowerCase();
|
|
1930
|
+
return tool.name.toLowerCase().includes(q) ||
|
|
1931
|
+
(tool.description && tool.description.toLowerCase().includes(q));
|
|
1932
|
+
});
|
|
1933
|
+
|
|
1934
|
+
if (detailLevel === 'names') {
|
|
1935
|
+
return filtered.map(t => ({ name: t.name, server: t.server }));
|
|
1936
|
+
} else if (detailLevel === 'descriptions') {
|
|
1937
|
+
return filtered.map(t => ({ name: t.name, server: t.server, description: t.description }));
|
|
1938
|
+
}
|
|
1939
|
+
return filtered;
|
|
1940
|
+
};
|
|
1941
|
+
`;
|
|
1942
|
+
for (const [serverName, serverTools] of Object.entries(tools)) {
|
|
1943
|
+
if (!serverTools || serverTools.length === 0) continue;
|
|
1944
|
+
const safeServerName = serverName.replace(/[^a-zA-Z0-9_]/g, "_");
|
|
1945
|
+
shim += `
|
|
1946
|
+
global['${serverName}'] = {`;
|
|
1947
|
+
for (const tool of serverTools) {
|
|
1948
|
+
shim += `
|
|
1949
|
+
'${tool.name}': async (args) => await global.__callMcpTool('${serverName}', '${tool.name}', args),`;
|
|
1950
|
+
}
|
|
1951
|
+
shim += `
|
|
1952
|
+
};
|
|
1953
|
+
|
|
1954
|
+
// Also expose as safe name if different
|
|
1955
|
+
if ('${safeServerName}' !== '${serverName}') {
|
|
1956
|
+
global['${safeServerName}'] = global['${serverName}'];
|
|
1957
|
+
}
|
|
1958
|
+
`;
|
|
1959
|
+
}
|
|
1960
|
+
return shim;
|
|
1961
|
+
}
|
|
1962
|
+
/**
|
|
1963
|
+
* Build the tool catalog for the shim.
|
|
1964
|
+
* Returns a map of server names to their available tools.
|
|
1965
|
+
*/
|
|
1966
|
+
buildToolCatalog() {
|
|
1967
|
+
const catalog = {};
|
|
1968
|
+
const namespaces = this.getToolNamespaces();
|
|
1969
|
+
for (const { serverName, tools } of namespaces) {
|
|
1970
|
+
catalog[serverName] = tools;
|
|
1971
|
+
}
|
|
1972
|
+
return catalog;
|
|
1973
|
+
}
|
|
1974
|
+
/**
|
|
1975
|
+
* Execute JavaScript/TypeScript code in an E2B sandbox with MCP tool access.
|
|
1976
|
+
* Tool calls are proxied back to the host via the bridge pattern.
|
|
1977
|
+
*
|
|
1978
|
+
* @param code - Code to execute
|
|
1979
|
+
* @param timeout - Execution timeout in milliseconds (default: 30000)
|
|
1980
|
+
*/
|
|
1981
|
+
async execute(code, timeout = 3e4) {
|
|
1982
|
+
const startTime = Date.now();
|
|
1983
|
+
let result = null;
|
|
1984
|
+
let error = null;
|
|
1985
|
+
let logs = [];
|
|
1986
|
+
try {
|
|
1987
|
+
await this.ensureServersConnected();
|
|
1988
|
+
const sandbox = await this.getOrCreateCodeExecSandbox();
|
|
1989
|
+
const toolCatalog = this.buildToolCatalog();
|
|
1990
|
+
const shim = this.generateShim(toolCatalog);
|
|
1991
|
+
const wrappedCode = `
|
|
1992
|
+
${shim}
|
|
1993
|
+
|
|
1994
|
+
(async () => {
|
|
1995
|
+
try {
|
|
1996
|
+
const func = async () => {
|
|
1997
|
+
${code}
|
|
1998
|
+
};
|
|
1999
|
+
const result = await func();
|
|
2000
|
+
console.log('__MCP_RESULT_START__');
|
|
2001
|
+
console.log(JSON.stringify(result));
|
|
2002
|
+
console.log('__MCP_RESULT_END__');
|
|
2003
|
+
} catch (e) {
|
|
2004
|
+
console.error(e);
|
|
2005
|
+
process.exit(1);
|
|
2006
|
+
}
|
|
2007
|
+
})();
|
|
2008
|
+
`;
|
|
2009
|
+
const filename = `exec_${Date.now()}.js`;
|
|
2010
|
+
await sandbox.files.write(filename, wrappedCode);
|
|
2011
|
+
const execution = await sandbox.commands.run(`node ${filename}`, {
|
|
2012
|
+
timeoutMs: timeout,
|
|
2013
|
+
onStdout: /* @__PURE__ */ __name(async (data) => {
|
|
2014
|
+
try {
|
|
2015
|
+
const lines = data.split("\n");
|
|
2016
|
+
for (const line of lines) {
|
|
2017
|
+
if (line.trim().startsWith('{"type":"__MCP_TOOL_CALL__"')) {
|
|
2018
|
+
const call = JSON.parse(line);
|
|
2019
|
+
if (call.type === "__MCP_TOOL_CALL__") {
|
|
2020
|
+
try {
|
|
2021
|
+
logger.debug(
|
|
2022
|
+
`[E2B Bridge] Calling tool ${call.server}.${call.tool}`
|
|
2023
|
+
);
|
|
2024
|
+
const activeSessions = this.client.getAllActiveSessions();
|
|
2025
|
+
const session = activeSessions[call.server];
|
|
2026
|
+
if (!session) {
|
|
2027
|
+
throw new Error(`Server ${call.server} not found`);
|
|
2028
|
+
}
|
|
2029
|
+
const toolResult = await session.connector.callTool(
|
|
2030
|
+
call.tool,
|
|
2031
|
+
call.args
|
|
2032
|
+
);
|
|
2033
|
+
let extractedResult = toolResult;
|
|
2034
|
+
if (toolResult.content && toolResult.content.length > 0) {
|
|
2035
|
+
const item = toolResult.content[0];
|
|
2036
|
+
if (item.type === "text") {
|
|
2037
|
+
try {
|
|
2038
|
+
extractedResult = JSON.parse(item.text);
|
|
2039
|
+
} catch {
|
|
2040
|
+
extractedResult = item.text;
|
|
2041
|
+
}
|
|
2042
|
+
} else {
|
|
2043
|
+
extractedResult = item;
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
const resultPath = `/tmp/mcp_result_${call.id}.json`;
|
|
2047
|
+
await sandbox.files.write(
|
|
2048
|
+
resultPath,
|
|
2049
|
+
JSON.stringify({ data: extractedResult })
|
|
2050
|
+
);
|
|
2051
|
+
} catch (err) {
|
|
2052
|
+
logger.error(
|
|
2053
|
+
`[E2B Bridge] Tool execution failed: ${err.message}`
|
|
2054
|
+
);
|
|
2055
|
+
const resultPath = `/tmp/mcp_result_${call.id}.json`;
|
|
2056
|
+
await sandbox.files.write(
|
|
2057
|
+
resultPath,
|
|
2058
|
+
JSON.stringify({
|
|
2059
|
+
error: err.message || String(err)
|
|
2060
|
+
})
|
|
2061
|
+
);
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
}
|
|
2066
|
+
} catch (e) {
|
|
2067
|
+
}
|
|
2068
|
+
}, "onStdout")
|
|
2069
|
+
});
|
|
2070
|
+
logs = [execution.stdout, execution.stderr].filter(Boolean);
|
|
2071
|
+
if (execution.exitCode !== 0) {
|
|
2072
|
+
error = execution.stderr || "Execution failed";
|
|
2073
|
+
} else {
|
|
2074
|
+
const stdout = execution.stdout;
|
|
2075
|
+
const startMarker = "__MCP_RESULT_START__";
|
|
2076
|
+
const endMarker = "__MCP_RESULT_END__";
|
|
2077
|
+
const startIndex = stdout.indexOf(startMarker);
|
|
2078
|
+
const endIndex = stdout.indexOf(endMarker);
|
|
2079
|
+
if (startIndex !== -1 && endIndex !== -1) {
|
|
2080
|
+
const jsonStr = stdout.substring(startIndex + startMarker.length, endIndex).trim();
|
|
2081
|
+
try {
|
|
2082
|
+
result = JSON.parse(jsonStr);
|
|
2083
|
+
} catch (e) {
|
|
2084
|
+
result = jsonStr;
|
|
2085
|
+
}
|
|
2086
|
+
logs = logs.map((log) => {
|
|
2087
|
+
let cleaned = log.replace(
|
|
2088
|
+
new RegExp(startMarker + "[\\s\\S]*?" + endMarker),
|
|
2089
|
+
"[Result captured]"
|
|
2090
|
+
);
|
|
2091
|
+
cleaned = cleaned.split("\n").filter((l) => !l.includes("__MCP_TOOL_CALL__")).join("\n");
|
|
2092
|
+
return cleaned;
|
|
2093
|
+
});
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
} catch (e) {
|
|
2097
|
+
error = e.message || String(e);
|
|
2098
|
+
if (error && (error.includes("timeout") || error.includes("timed out"))) {
|
|
2099
|
+
error = "Script execution timed out";
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
return {
|
|
2103
|
+
result,
|
|
2104
|
+
logs,
|
|
2105
|
+
error,
|
|
2106
|
+
execution_time: (Date.now() - startTime) / 1e3
|
|
2107
|
+
};
|
|
2108
|
+
}
|
|
2109
|
+
/**
|
|
2110
|
+
* Clean up the E2B sandbox.
|
|
2111
|
+
* Should be called when the executor is no longer needed.
|
|
2112
|
+
*/
|
|
2113
|
+
async cleanup() {
|
|
2114
|
+
if (this.codeExecSandbox) {
|
|
2115
|
+
try {
|
|
2116
|
+
await this.codeExecSandbox.kill();
|
|
2117
|
+
this.codeExecSandbox = null;
|
|
2118
|
+
logger.debug("E2B code execution sandbox stopped");
|
|
2119
|
+
} catch (error) {
|
|
2120
|
+
logger.error("Failed to stop E2B code execution sandbox:", error);
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
};
|
|
2125
|
+
|
|
2126
|
+
// src/client/executors/vm.ts
|
|
2127
|
+
var vm = null;
|
|
2128
|
+
var vmCheckAttempted = false;
|
|
2129
|
+
function getVMModuleName() {
|
|
2130
|
+
return ["node", "vm"].join(":");
|
|
2131
|
+
}
|
|
2132
|
+
__name(getVMModuleName, "getVMModuleName");
|
|
2133
|
+
function tryLoadVM() {
|
|
2134
|
+
if (vmCheckAttempted) {
|
|
2135
|
+
return vm !== null;
|
|
2136
|
+
}
|
|
2137
|
+
vmCheckAttempted = true;
|
|
2138
|
+
try {
|
|
2139
|
+
const nodeRequire = typeof require !== "undefined" ? require : null;
|
|
2140
|
+
if (nodeRequire) {
|
|
2141
|
+
vm = nodeRequire(getVMModuleName());
|
|
2142
|
+
return true;
|
|
2143
|
+
}
|
|
2144
|
+
} catch (error) {
|
|
2145
|
+
logger.debug("node:vm module not available via require");
|
|
2146
|
+
}
|
|
2147
|
+
return false;
|
|
2148
|
+
}
|
|
2149
|
+
__name(tryLoadVM, "tryLoadVM");
|
|
2150
|
+
async function tryLoadVMAsync() {
|
|
2151
|
+
if (vm !== null) {
|
|
2152
|
+
return true;
|
|
2153
|
+
}
|
|
2154
|
+
if (!vmCheckAttempted) {
|
|
2155
|
+
if (tryLoadVM()) {
|
|
2156
|
+
return true;
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
try {
|
|
2160
|
+
vm = await import(
|
|
2161
|
+
/* @vite-ignore */
|
|
2162
|
+
getVMModuleName()
|
|
2163
|
+
);
|
|
2164
|
+
return true;
|
|
2165
|
+
} catch (error) {
|
|
2166
|
+
logger.debug(
|
|
2167
|
+
"node:vm module not available in this environment (e.g., Deno)"
|
|
2168
|
+
);
|
|
2169
|
+
return false;
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
__name(tryLoadVMAsync, "tryLoadVMAsync");
|
|
2173
|
+
function isVMAvailable() {
|
|
2174
|
+
tryLoadVM();
|
|
2175
|
+
return vm !== null;
|
|
2176
|
+
}
|
|
2177
|
+
__name(isVMAvailable, "isVMAvailable");
|
|
2178
|
+
var VMCodeExecutor = class extends BaseCodeExecutor {
|
|
2179
|
+
static {
|
|
2180
|
+
__name(this, "VMCodeExecutor");
|
|
2181
|
+
}
|
|
2182
|
+
defaultTimeout;
|
|
2183
|
+
memoryLimitMb;
|
|
2184
|
+
constructor(client, options) {
|
|
2185
|
+
super(client);
|
|
2186
|
+
this.defaultTimeout = options?.timeoutMs ?? 3e4;
|
|
2187
|
+
this.memoryLimitMb = options?.memoryLimitMb;
|
|
2188
|
+
tryLoadVM();
|
|
2189
|
+
}
|
|
2190
|
+
/**
|
|
2191
|
+
* Ensure VM module is loaded before execution
|
|
2192
|
+
*/
|
|
2193
|
+
async ensureVMLoaded() {
|
|
2194
|
+
if (vm !== null) {
|
|
2195
|
+
return;
|
|
2196
|
+
}
|
|
2197
|
+
const loaded = await tryLoadVMAsync();
|
|
2198
|
+
if (!loaded) {
|
|
2199
|
+
throw new Error(
|
|
2200
|
+
"node:vm module is not available in this environment. Please use E2B executor instead or run in a Node.js environment."
|
|
2201
|
+
);
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
/**
|
|
2205
|
+
* Execute JavaScript/TypeScript code with access to MCP tools.
|
|
2206
|
+
*
|
|
2207
|
+
* @param code - Code to execute
|
|
2208
|
+
* @param timeout - Execution timeout in milliseconds (default: configured timeout or 30000)
|
|
2209
|
+
*/
|
|
2210
|
+
async execute(code, timeout) {
|
|
2211
|
+
const effectiveTimeout = timeout ?? this.defaultTimeout;
|
|
2212
|
+
await this.ensureVMLoaded();
|
|
2213
|
+
await this.ensureServersConnected();
|
|
2214
|
+
const logs = [];
|
|
2215
|
+
const startTime = Date.now();
|
|
2216
|
+
let result = null;
|
|
2217
|
+
let error = null;
|
|
2218
|
+
try {
|
|
2219
|
+
const context = await this._buildContext(logs);
|
|
2220
|
+
const wrappedCode = `
|
|
2221
|
+
(async () => {
|
|
2222
|
+
try {
|
|
2223
|
+
${code}
|
|
2224
|
+
} catch (e) {
|
|
2225
|
+
throw e;
|
|
2226
|
+
}
|
|
2227
|
+
})()
|
|
2228
|
+
`;
|
|
2229
|
+
const script = new vm.Script(wrappedCode, {
|
|
2230
|
+
filename: "agent_code.js"
|
|
2231
|
+
});
|
|
2232
|
+
const promise = script.runInNewContext(context, {
|
|
2233
|
+
timeout: effectiveTimeout,
|
|
2234
|
+
displayErrors: true
|
|
2235
|
+
});
|
|
2236
|
+
result = await promise;
|
|
2237
|
+
} catch (e) {
|
|
2238
|
+
error = e.message || String(e);
|
|
2239
|
+
if (e.code === "ERR_SCRIPT_EXECUTION_TIMEOUT" || e.message === "Script execution timed out." || typeof error === "string" && (error.includes("timed out") || error.includes("timeout"))) {
|
|
2240
|
+
error = "Script execution timed out";
|
|
2241
|
+
}
|
|
2242
|
+
if (e.stack) {
|
|
2243
|
+
logger.debug(`Code execution error stack: ${e.stack}`);
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
const executionTime = (Date.now() - startTime) / 1e3;
|
|
2247
|
+
return {
|
|
2248
|
+
result,
|
|
2249
|
+
logs,
|
|
2250
|
+
error,
|
|
2251
|
+
execution_time: executionTime
|
|
2252
|
+
};
|
|
2253
|
+
}
|
|
2254
|
+
/**
|
|
2255
|
+
* Build the VM execution context with MCP tools and standard globals.
|
|
2256
|
+
*
|
|
2257
|
+
* @param logs - Array to capture console output
|
|
2258
|
+
*/
|
|
2259
|
+
async _buildContext(logs) {
|
|
2260
|
+
const logHandler = /* @__PURE__ */ __name((...args) => {
|
|
2261
|
+
logs.push(
|
|
2262
|
+
args.map(
|
|
2263
|
+
(arg) => typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)
|
|
2264
|
+
).join(" ")
|
|
2265
|
+
);
|
|
2266
|
+
}, "logHandler");
|
|
2267
|
+
const sandbox = {
|
|
2268
|
+
console: {
|
|
2269
|
+
log: logHandler,
|
|
2270
|
+
error: /* @__PURE__ */ __name((...args) => {
|
|
2271
|
+
logHandler("[ERROR]", ...args);
|
|
2272
|
+
}, "error"),
|
|
2273
|
+
warn: /* @__PURE__ */ __name((...args) => {
|
|
2274
|
+
logHandler("[WARN]", ...args);
|
|
2275
|
+
}, "warn"),
|
|
2276
|
+
info: logHandler,
|
|
2277
|
+
debug: logHandler
|
|
2278
|
+
},
|
|
2279
|
+
// Standard globals
|
|
2280
|
+
Object,
|
|
2281
|
+
Array,
|
|
2282
|
+
String,
|
|
2283
|
+
Number,
|
|
2284
|
+
Boolean,
|
|
2285
|
+
Date,
|
|
2286
|
+
Math,
|
|
2287
|
+
JSON,
|
|
2288
|
+
RegExp,
|
|
2289
|
+
Map,
|
|
2290
|
+
Set,
|
|
2291
|
+
Promise,
|
|
2292
|
+
parseInt,
|
|
2293
|
+
parseFloat,
|
|
2294
|
+
isNaN,
|
|
2295
|
+
isFinite,
|
|
2296
|
+
encodeURI,
|
|
2297
|
+
decodeURI,
|
|
2298
|
+
encodeURIComponent,
|
|
2299
|
+
decodeURIComponent,
|
|
2300
|
+
setTimeout,
|
|
2301
|
+
clearTimeout,
|
|
2302
|
+
// Helper for tools
|
|
2303
|
+
search_tools: this.createSearchToolsFunction(),
|
|
2304
|
+
__tool_namespaces: []
|
|
2305
|
+
};
|
|
2306
|
+
const toolNamespaces = {};
|
|
2307
|
+
const namespaceInfos = this.getToolNamespaces();
|
|
2308
|
+
for (const { serverName, tools, session } of namespaceInfos) {
|
|
2309
|
+
const serverNamespace = {};
|
|
2310
|
+
for (const tool of tools) {
|
|
2311
|
+
const toolName = tool.name;
|
|
2312
|
+
serverNamespace[toolName] = async (args) => {
|
|
2313
|
+
const result = await session.connector.callTool(toolName, args || {});
|
|
2314
|
+
if (result.content && result.content.length > 0) {
|
|
2315
|
+
const item = result.content[0];
|
|
2316
|
+
if (item.type === "text") {
|
|
2317
|
+
try {
|
|
2318
|
+
return JSON.parse(item.text);
|
|
2319
|
+
} catch {
|
|
2320
|
+
return item.text;
|
|
2321
|
+
}
|
|
2322
|
+
}
|
|
2323
|
+
return item;
|
|
2324
|
+
}
|
|
2325
|
+
return result;
|
|
2326
|
+
};
|
|
2327
|
+
}
|
|
2328
|
+
sandbox[serverName] = serverNamespace;
|
|
2329
|
+
toolNamespaces[serverName] = true;
|
|
2330
|
+
}
|
|
2331
|
+
sandbox.__tool_namespaces = Object.keys(toolNamespaces);
|
|
2332
|
+
return vm.createContext(sandbox);
|
|
2333
|
+
}
|
|
2334
|
+
/**
|
|
2335
|
+
* Clean up resources.
|
|
2336
|
+
* VM executor doesn't need cleanup, but method kept for interface consistency.
|
|
2337
|
+
*/
|
|
2338
|
+
async cleanup() {
|
|
2339
|
+
}
|
|
2340
|
+
};
|
|
2341
|
+
|
|
2342
|
+
// src/connectors/base.ts
|
|
2343
|
+
var import_types = require("@mcp-use/modelcontextprotocol-sdk/types.js");
|
|
2344
|
+
var BaseConnector = class {
|
|
2345
|
+
static {
|
|
2346
|
+
__name(this, "BaseConnector");
|
|
2347
|
+
}
|
|
2348
|
+
client = null;
|
|
2349
|
+
connectionManager = null;
|
|
2350
|
+
toolsCache = null;
|
|
2351
|
+
capabilitiesCache = null;
|
|
2352
|
+
serverInfoCache = null;
|
|
2353
|
+
connected = false;
|
|
2354
|
+
opts;
|
|
2355
|
+
notificationHandlers = [];
|
|
2356
|
+
rootsCache = [];
|
|
2357
|
+
constructor(opts = {}) {
|
|
2358
|
+
this.opts = opts;
|
|
2359
|
+
if (opts.roots) {
|
|
2360
|
+
this.rootsCache = [...opts.roots];
|
|
2361
|
+
}
|
|
2362
|
+
}
|
|
2363
|
+
/**
|
|
2364
|
+
* Track connector initialization event
|
|
2365
|
+
* Should be called by subclasses after successful connection
|
|
2366
|
+
*/
|
|
2367
|
+
trackConnectorInit(data) {
|
|
2368
|
+
const connectorType = this.constructor.name;
|
|
2369
|
+
Telemetry.getInstance().trackConnectorInit({
|
|
2370
|
+
connectorType,
|
|
2371
|
+
...data
|
|
2372
|
+
}).catch((e) => logger.debug(`Failed to track connector init: ${e}`));
|
|
2373
|
+
}
|
|
2374
|
+
/**
|
|
2375
|
+
* Register a handler for server notifications
|
|
2376
|
+
*
|
|
2377
|
+
* @param handler - Function to call when a notification is received
|
|
2378
|
+
*
|
|
2379
|
+
* @example
|
|
2380
|
+
* ```typescript
|
|
2381
|
+
* connector.onNotification((notification) => {
|
|
2382
|
+
* console.log(`Received: ${notification.method}`, notification.params);
|
|
2383
|
+
* });
|
|
2384
|
+
* ```
|
|
2385
|
+
*/
|
|
2386
|
+
onNotification(handler) {
|
|
2387
|
+
this.notificationHandlers.push(handler);
|
|
2388
|
+
if (this.client) {
|
|
2389
|
+
this.setupNotificationHandler();
|
|
2390
|
+
}
|
|
2391
|
+
}
|
|
2392
|
+
/**
|
|
2393
|
+
* Internal: wire notification handlers to the SDK client
|
|
2394
|
+
* Includes automatic handling for list_changed notifications per MCP spec
|
|
2395
|
+
*/
|
|
2396
|
+
setupNotificationHandler() {
|
|
2397
|
+
if (!this.client) return;
|
|
2398
|
+
this.client.fallbackNotificationHandler = async (notification) => {
|
|
2399
|
+
switch (notification.method) {
|
|
2400
|
+
case "notifications/tools/list_changed":
|
|
2401
|
+
await this.refreshToolsCache();
|
|
2402
|
+
break;
|
|
2403
|
+
case "notifications/resources/list_changed":
|
|
2404
|
+
await this.onResourcesListChanged();
|
|
2405
|
+
break;
|
|
2406
|
+
case "notifications/prompts/list_changed":
|
|
2407
|
+
await this.onPromptsListChanged();
|
|
2408
|
+
break;
|
|
2409
|
+
default:
|
|
2410
|
+
break;
|
|
2411
|
+
}
|
|
2412
|
+
for (const handler of this.notificationHandlers) {
|
|
2413
|
+
try {
|
|
2414
|
+
await handler(notification);
|
|
2415
|
+
} catch (err) {
|
|
2416
|
+
logger.error("Error in notification handler:", err);
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
};
|
|
2420
|
+
}
|
|
2421
|
+
/**
|
|
2422
|
+
* Auto-refresh tools cache when server sends tools/list_changed notification
|
|
2423
|
+
*/
|
|
2424
|
+
async refreshToolsCache() {
|
|
2425
|
+
if (!this.client) return;
|
|
2426
|
+
try {
|
|
2427
|
+
logger.debug(
|
|
2428
|
+
"[Auto] Refreshing tools cache due to list_changed notification"
|
|
2429
|
+
);
|
|
2430
|
+
const result = await this.client.listTools();
|
|
2431
|
+
this.toolsCache = result.tools ?? [];
|
|
2432
|
+
logger.debug(
|
|
2433
|
+
`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`
|
|
2434
|
+
);
|
|
2435
|
+
} catch (err) {
|
|
2436
|
+
logger.warn("[Auto] Failed to refresh tools cache:", err);
|
|
2437
|
+
}
|
|
2438
|
+
}
|
|
2439
|
+
/**
|
|
2440
|
+
* Called when server sends resources/list_changed notification
|
|
2441
|
+
* Resources aren't cached by default, but we log for user awareness
|
|
2442
|
+
*/
|
|
2443
|
+
async onResourcesListChanged() {
|
|
2444
|
+
logger.debug(
|
|
2445
|
+
"[Auto] Resources list changed - clients should re-fetch if needed"
|
|
2446
|
+
);
|
|
2447
|
+
}
|
|
2448
|
+
/**
|
|
2449
|
+
* Called when server sends prompts/list_changed notification
|
|
2450
|
+
* Prompts aren't cached by default, but we log for user awareness
|
|
2451
|
+
*/
|
|
2452
|
+
async onPromptsListChanged() {
|
|
2453
|
+
logger.debug(
|
|
2454
|
+
"[Auto] Prompts list changed - clients should re-fetch if needed"
|
|
2455
|
+
);
|
|
2456
|
+
}
|
|
2457
|
+
/**
|
|
2458
|
+
* Set roots and notify the server.
|
|
2459
|
+
* Roots represent directories or files that the client has access to.
|
|
2460
|
+
*
|
|
2461
|
+
* @param roots - Array of Root objects with `uri` (must start with "file://") and optional `name`
|
|
2462
|
+
*
|
|
2463
|
+
* @example
|
|
2464
|
+
* ```typescript
|
|
2465
|
+
* await connector.setRoots([
|
|
2466
|
+
* { uri: "file:///home/user/project", name: "My Project" },
|
|
2467
|
+
* { uri: "file:///home/user/data" }
|
|
2468
|
+
* ]);
|
|
2469
|
+
* ```
|
|
2470
|
+
*/
|
|
2471
|
+
async setRoots(roots) {
|
|
2472
|
+
this.rootsCache = [...roots];
|
|
2473
|
+
if (this.client) {
|
|
2474
|
+
logger.debug(
|
|
2475
|
+
`Sending roots/list_changed notification with ${roots.length} root(s)`
|
|
2476
|
+
);
|
|
2477
|
+
await this.client.sendRootsListChanged();
|
|
2478
|
+
}
|
|
2479
|
+
}
|
|
2480
|
+
/**
|
|
2481
|
+
* Get the current roots.
|
|
2482
|
+
*/
|
|
2483
|
+
getRoots() {
|
|
2484
|
+
return [...this.rootsCache];
|
|
2485
|
+
}
|
|
2486
|
+
/**
|
|
2487
|
+
* Internal: set up roots/list request handler.
|
|
2488
|
+
* This is called after the client connects to register the handler for server requests.
|
|
2489
|
+
*/
|
|
2490
|
+
setupRootsHandler() {
|
|
2491
|
+
if (!this.client) return;
|
|
2492
|
+
this.client.setRequestHandler(
|
|
2493
|
+
import_types.ListRootsRequestSchema,
|
|
2494
|
+
async (_request, _extra) => {
|
|
2495
|
+
logger.debug(
|
|
2496
|
+
`Server requested roots list, returning ${this.rootsCache.length} root(s)`
|
|
2497
|
+
);
|
|
2498
|
+
return { roots: this.rootsCache };
|
|
2499
|
+
}
|
|
2500
|
+
);
|
|
2501
|
+
}
|
|
2502
|
+
/**
|
|
2503
|
+
* Internal: set up sampling/createMessage request handler.
|
|
2504
|
+
* This is called after the client connects to register the handler for sampling requests.
|
|
2505
|
+
*/
|
|
2506
|
+
setupSamplingHandler() {
|
|
2507
|
+
if (!this.client) {
|
|
2508
|
+
logger.debug("setupSamplingHandler: No client available");
|
|
2509
|
+
return;
|
|
2510
|
+
}
|
|
2511
|
+
if (!this.opts.samplingCallback) {
|
|
2512
|
+
logger.debug("setupSamplingHandler: No sampling callback provided");
|
|
2513
|
+
return;
|
|
2514
|
+
}
|
|
2515
|
+
logger.debug("setupSamplingHandler: Setting up sampling request handler");
|
|
2516
|
+
this.client.setRequestHandler(
|
|
2517
|
+
import_types.CreateMessageRequestSchema,
|
|
2518
|
+
async (request, _extra) => {
|
|
2519
|
+
logger.debug("Server requested sampling, forwarding to callback");
|
|
2520
|
+
return await this.opts.samplingCallback(request.params);
|
|
2521
|
+
}
|
|
2522
|
+
);
|
|
2523
|
+
logger.debug(
|
|
2524
|
+
"setupSamplingHandler: Sampling handler registered successfully"
|
|
2525
|
+
);
|
|
2526
|
+
}
|
|
2527
|
+
/**
|
|
2528
|
+
* Internal: set up elicitation/create request handler.
|
|
2529
|
+
* This is called after the client connects to register the handler for elicitation requests.
|
|
2530
|
+
*/
|
|
2531
|
+
setupElicitationHandler() {
|
|
2532
|
+
if (!this.client) {
|
|
2533
|
+
logger.debug("setupElicitationHandler: No client available");
|
|
2534
|
+
return;
|
|
2535
|
+
}
|
|
2536
|
+
if (!this.opts.elicitationCallback) {
|
|
2537
|
+
logger.debug("setupElicitationHandler: No elicitation callback provided");
|
|
2538
|
+
return;
|
|
2539
|
+
}
|
|
2540
|
+
logger.debug(
|
|
2541
|
+
"setupElicitationHandler: Setting up elicitation request handler"
|
|
2542
|
+
);
|
|
2543
|
+
this.client.setRequestHandler(
|
|
2544
|
+
import_types.ElicitRequestSchema,
|
|
2545
|
+
async (request, _extra) => {
|
|
2546
|
+
logger.debug("Server requested elicitation, forwarding to callback");
|
|
2547
|
+
return await this.opts.elicitationCallback(request.params);
|
|
2548
|
+
}
|
|
2549
|
+
);
|
|
2550
|
+
logger.debug(
|
|
2551
|
+
"setupElicitationHandler: Elicitation handler registered successfully"
|
|
2552
|
+
);
|
|
2553
|
+
}
|
|
2554
|
+
/** Disconnect and release resources. */
|
|
2555
|
+
async disconnect() {
|
|
2556
|
+
if (!this.connected) {
|
|
2557
|
+
logger.debug("Not connected to MCP implementation");
|
|
2558
|
+
return;
|
|
2559
|
+
}
|
|
2560
|
+
logger.debug("Disconnecting from MCP implementation");
|
|
2561
|
+
await this.cleanupResources();
|
|
2562
|
+
this.connected = false;
|
|
2563
|
+
logger.debug("Disconnected from MCP implementation");
|
|
2564
|
+
}
|
|
2565
|
+
/** Check if the client is connected */
|
|
2566
|
+
get isClientConnected() {
|
|
2567
|
+
return this.client != null;
|
|
2568
|
+
}
|
|
2569
|
+
/**
|
|
2570
|
+
* Initialise the MCP session **after** `connect()` has succeeded.
|
|
2571
|
+
*
|
|
2572
|
+
* In the SDK, `Client.connect(transport)` automatically performs the
|
|
2573
|
+
* protocol‑level `initialize` handshake, so we only need to cache the list of
|
|
2574
|
+
* tools and expose some server info.
|
|
2575
|
+
*/
|
|
2576
|
+
async initialize(defaultRequestOptions = this.opts.defaultRequestOptions ?? {}) {
|
|
2577
|
+
if (!this.client) {
|
|
2578
|
+
throw new Error("MCP client is not connected");
|
|
2579
|
+
}
|
|
2580
|
+
logger.debug("Caching server capabilities & tools");
|
|
2581
|
+
const capabilities = this.client.getServerCapabilities();
|
|
2582
|
+
this.capabilitiesCache = capabilities || null;
|
|
2583
|
+
const serverInfo = this.client.getServerVersion();
|
|
2584
|
+
this.serverInfoCache = serverInfo || null;
|
|
2585
|
+
const listToolsRes = await this.client.listTools(
|
|
2586
|
+
void 0,
|
|
2587
|
+
defaultRequestOptions
|
|
2588
|
+
);
|
|
2589
|
+
this.toolsCache = listToolsRes.tools ?? [];
|
|
2590
|
+
logger.debug(`Fetched ${this.toolsCache.length} tools from server`);
|
|
2591
|
+
logger.debug("Server capabilities:", capabilities);
|
|
2592
|
+
logger.debug("Server info:", serverInfo);
|
|
2593
|
+
return capabilities;
|
|
2594
|
+
}
|
|
2595
|
+
/** Lazily expose the cached tools list. */
|
|
2596
|
+
get tools() {
|
|
2597
|
+
if (!this.toolsCache) {
|
|
2598
|
+
throw new Error("MCP client is not initialized; call initialize() first");
|
|
2599
|
+
}
|
|
2600
|
+
return this.toolsCache;
|
|
2601
|
+
}
|
|
2602
|
+
/** Expose cached server capabilities. */
|
|
2603
|
+
get serverCapabilities() {
|
|
2604
|
+
return this.capabilitiesCache || {};
|
|
2605
|
+
}
|
|
2606
|
+
/** Expose cached server info. */
|
|
2607
|
+
get serverInfo() {
|
|
2608
|
+
return this.serverInfoCache;
|
|
2609
|
+
}
|
|
2610
|
+
/** Call a tool on the server. */
|
|
2611
|
+
async callTool(name, args, options) {
|
|
2612
|
+
if (!this.client) {
|
|
2613
|
+
throw new Error("MCP client is not connected");
|
|
2614
|
+
}
|
|
2615
|
+
const enhancedOptions = options ? { ...options } : void 0;
|
|
2616
|
+
if (enhancedOptions?.resetTimeoutOnProgress && !enhancedOptions.onprogress) {
|
|
2617
|
+
enhancedOptions.onprogress = () => {
|
|
2618
|
+
};
|
|
2619
|
+
logger.debug(
|
|
2620
|
+
`[BaseConnector] Added onprogress callback for tool '${name}' to enable progressToken`
|
|
2621
|
+
);
|
|
2622
|
+
}
|
|
2623
|
+
logger.debug(`Calling tool '${name}' with args`, args);
|
|
2624
|
+
const res = await this.client.callTool(
|
|
2625
|
+
{ name, arguments: args },
|
|
2626
|
+
void 0,
|
|
2627
|
+
enhancedOptions
|
|
2628
|
+
);
|
|
2629
|
+
logger.debug(`Tool '${name}' returned`, res);
|
|
2630
|
+
return res;
|
|
2631
|
+
}
|
|
2632
|
+
/**
|
|
2633
|
+
* List all available tools from the MCP server.
|
|
2634
|
+
* This method fetches fresh tools from the server, unlike the `tools` getter which returns cached tools.
|
|
2635
|
+
*
|
|
2636
|
+
* @param options - Optional request options
|
|
2637
|
+
* @returns Array of available tools
|
|
2638
|
+
*/
|
|
2639
|
+
async listTools(options) {
|
|
2640
|
+
if (!this.client) {
|
|
2641
|
+
throw new Error("MCP client is not connected");
|
|
2642
|
+
}
|
|
2643
|
+
const result = await this.client.listTools(void 0, options);
|
|
2644
|
+
return result.tools ?? [];
|
|
2645
|
+
}
|
|
2646
|
+
/**
|
|
2647
|
+
* List resources from the server with optional pagination
|
|
2648
|
+
*
|
|
2649
|
+
* @param cursor - Optional cursor for pagination
|
|
2650
|
+
* @param options - Request options
|
|
2651
|
+
* @returns Resource list with optional nextCursor for pagination
|
|
2652
|
+
*/
|
|
2653
|
+
async listResources(cursor, options) {
|
|
2654
|
+
if (!this.client) {
|
|
2655
|
+
throw new Error("MCP client is not connected");
|
|
2656
|
+
}
|
|
2657
|
+
logger.debug("Listing resources", cursor ? `with cursor: ${cursor}` : "");
|
|
2658
|
+
return await this.client.listResources({ cursor }, options);
|
|
2659
|
+
}
|
|
2660
|
+
/**
|
|
2661
|
+
* List all resources from the server, automatically handling pagination
|
|
2662
|
+
*
|
|
2663
|
+
* @param options - Request options
|
|
2664
|
+
* @returns Complete list of all resources
|
|
2665
|
+
*/
|
|
2666
|
+
async listAllResources(options) {
|
|
2667
|
+
if (!this.client) {
|
|
2668
|
+
throw new Error("MCP client is not connected");
|
|
2669
|
+
}
|
|
2670
|
+
if (!this.capabilitiesCache?.resources) {
|
|
2671
|
+
logger.debug("Server does not advertise resources capability, skipping");
|
|
2672
|
+
return { resources: [] };
|
|
2673
|
+
}
|
|
2674
|
+
try {
|
|
2675
|
+
logger.debug("Listing all resources (with auto-pagination)");
|
|
2676
|
+
const allResources = [];
|
|
2677
|
+
let cursor = void 0;
|
|
2678
|
+
do {
|
|
2679
|
+
const result = await this.client.listResources({ cursor }, options);
|
|
2680
|
+
allResources.push(...result.resources || []);
|
|
2681
|
+
cursor = result.nextCursor;
|
|
2682
|
+
} while (cursor);
|
|
2683
|
+
return { resources: allResources };
|
|
2684
|
+
} catch (err) {
|
|
2685
|
+
const error = err;
|
|
2686
|
+
if (error.code === -32601) {
|
|
2687
|
+
logger.debug("Server advertised resources but method not found");
|
|
2688
|
+
return { resources: [] };
|
|
2689
|
+
}
|
|
2690
|
+
throw err;
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
/**
|
|
2694
|
+
* List resource templates from the server
|
|
2695
|
+
*
|
|
2696
|
+
* @param options - Request options
|
|
2697
|
+
* @returns List of available resource templates
|
|
2698
|
+
*/
|
|
2699
|
+
async listResourceTemplates(options) {
|
|
2700
|
+
if (!this.client) {
|
|
2701
|
+
throw new Error("MCP client is not connected");
|
|
2702
|
+
}
|
|
2703
|
+
logger.debug("Listing resource templates");
|
|
2704
|
+
return await this.client.listResourceTemplates(void 0, options);
|
|
2705
|
+
}
|
|
2706
|
+
/** Read a resource by URI. */
|
|
2707
|
+
async readResource(uri, options) {
|
|
2708
|
+
if (!this.client) {
|
|
2709
|
+
throw new Error("MCP client is not connected");
|
|
2710
|
+
}
|
|
2711
|
+
logger.debug(`Reading resource ${uri}`);
|
|
2712
|
+
const res = await this.client.readResource({ uri }, options);
|
|
2713
|
+
return res;
|
|
2714
|
+
}
|
|
2715
|
+
/**
|
|
2716
|
+
* Subscribe to resource updates
|
|
2717
|
+
*
|
|
2718
|
+
* @param uri - URI of the resource to subscribe to
|
|
2719
|
+
* @param options - Request options
|
|
2720
|
+
*/
|
|
2721
|
+
async subscribeToResource(uri, options) {
|
|
2722
|
+
if (!this.client) {
|
|
2723
|
+
throw new Error("MCP client is not connected");
|
|
2724
|
+
}
|
|
2725
|
+
logger.debug(`Subscribing to resource: ${uri}`);
|
|
2726
|
+
return await this.client.subscribeResource({ uri }, options);
|
|
2727
|
+
}
|
|
2728
|
+
/**
|
|
2729
|
+
* Unsubscribe from resource updates
|
|
2730
|
+
*
|
|
2731
|
+
* @param uri - URI of the resource to unsubscribe from
|
|
2732
|
+
* @param options - Request options
|
|
2733
|
+
*/
|
|
2734
|
+
async unsubscribeFromResource(uri, options) {
|
|
2735
|
+
if (!this.client) {
|
|
2736
|
+
throw new Error("MCP client is not connected");
|
|
2737
|
+
}
|
|
2738
|
+
logger.debug(`Unsubscribing from resource: ${uri}`);
|
|
2739
|
+
return await this.client.unsubscribeResource({ uri }, options);
|
|
2740
|
+
}
|
|
2741
|
+
async listPrompts() {
|
|
2742
|
+
if (!this.client) {
|
|
2743
|
+
throw new Error("MCP client is not connected");
|
|
2744
|
+
}
|
|
2745
|
+
if (!this.capabilitiesCache?.prompts) {
|
|
2746
|
+
logger.debug("Server does not advertise prompts capability, skipping");
|
|
2747
|
+
return { prompts: [] };
|
|
2748
|
+
}
|
|
2749
|
+
try {
|
|
2750
|
+
logger.debug("Listing prompts");
|
|
2751
|
+
return await this.client.listPrompts();
|
|
2752
|
+
} catch (err) {
|
|
2753
|
+
const error = err;
|
|
2754
|
+
if (error.code === -32601) {
|
|
2755
|
+
logger.debug("Server advertised prompts but method not found");
|
|
2756
|
+
return { prompts: [] };
|
|
2757
|
+
}
|
|
2758
|
+
throw err;
|
|
2759
|
+
}
|
|
2760
|
+
}
|
|
2761
|
+
async getPrompt(name, args) {
|
|
2762
|
+
if (!this.client) {
|
|
2763
|
+
throw new Error("MCP client is not connected");
|
|
2764
|
+
}
|
|
2765
|
+
logger.debug(`Getting prompt ${name}`);
|
|
2766
|
+
return await this.client.getPrompt({ name, arguments: args });
|
|
2767
|
+
}
|
|
2768
|
+
/** Send a raw request through the client. */
|
|
2769
|
+
async request(method, params = null, options) {
|
|
2770
|
+
if (!this.client) {
|
|
2771
|
+
throw new Error("MCP client is not connected");
|
|
2772
|
+
}
|
|
2773
|
+
logger.debug(`Sending raw request '${method}' with params`, params);
|
|
2774
|
+
return await this.client.request(
|
|
2775
|
+
{ method, params: params ?? {} },
|
|
2776
|
+
void 0,
|
|
2777
|
+
options
|
|
2778
|
+
);
|
|
2779
|
+
}
|
|
2780
|
+
/**
|
|
2781
|
+
* Helper to tear down the client & connection manager safely.
|
|
2782
|
+
*/
|
|
2783
|
+
async cleanupResources() {
|
|
2784
|
+
const issues = [];
|
|
2785
|
+
if (this.client) {
|
|
2786
|
+
try {
|
|
2787
|
+
if (typeof this.client.close === "function") {
|
|
2788
|
+
await this.client.close();
|
|
2789
|
+
}
|
|
2790
|
+
} catch (e) {
|
|
2791
|
+
const msg = `Error closing client: ${e}`;
|
|
2792
|
+
logger.warn(msg);
|
|
2793
|
+
issues.push(msg);
|
|
2794
|
+
} finally {
|
|
2795
|
+
this.client = null;
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
if (this.connectionManager) {
|
|
2799
|
+
try {
|
|
2800
|
+
await this.connectionManager.stop();
|
|
2801
|
+
} catch (e) {
|
|
2802
|
+
const msg = `Error stopping connection manager: ${e}`;
|
|
2803
|
+
logger.warn(msg);
|
|
2804
|
+
issues.push(msg);
|
|
2805
|
+
} finally {
|
|
2806
|
+
this.connectionManager = null;
|
|
2807
|
+
}
|
|
2808
|
+
}
|
|
2809
|
+
this.toolsCache = null;
|
|
2810
|
+
if (issues.length) {
|
|
2811
|
+
logger.warn(`Resource cleanup finished with ${issues.length} issue(s)`);
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
};
|
|
2815
|
+
|
|
2816
|
+
// src/client/connectors/codeMode.ts
|
|
2817
|
+
var CodeModeConnector = class extends BaseConnector {
|
|
2818
|
+
static {
|
|
2819
|
+
__name(this, "CodeModeConnector");
|
|
2820
|
+
}
|
|
2821
|
+
mcpClient;
|
|
2822
|
+
_tools;
|
|
2823
|
+
constructor(client) {
|
|
2824
|
+
super();
|
|
2825
|
+
this.mcpClient = client;
|
|
2826
|
+
this.connected = true;
|
|
2827
|
+
this._tools = this._createToolsList();
|
|
2828
|
+
}
|
|
2829
|
+
async connect() {
|
|
2830
|
+
this.connected = true;
|
|
2831
|
+
}
|
|
2832
|
+
async disconnect() {
|
|
2833
|
+
this.connected = false;
|
|
2834
|
+
}
|
|
2835
|
+
get publicIdentifier() {
|
|
2836
|
+
return { name: "code_mode", version: "1.0.0" };
|
|
2837
|
+
}
|
|
2838
|
+
_createToolsList() {
|
|
2839
|
+
return [
|
|
2840
|
+
{
|
|
2841
|
+
name: "execute_code",
|
|
2842
|
+
description: "Execute JavaScript/TypeScript code with access to MCP tools. This is the PRIMARY way to interact with MCP servers in code mode. Write code that discovers tools using search_tools(), calls tools as async functions (e.g., await github.get_pull_request(...)), processes data efficiently, and returns results. Use 'await' for async operations and 'return' to return values. Available in code: search_tools(), __tool_namespaces, and server.tool_name() functions.",
|
|
2843
|
+
inputSchema: {
|
|
2844
|
+
type: "object",
|
|
2845
|
+
properties: {
|
|
2846
|
+
code: {
|
|
2847
|
+
type: "string",
|
|
2848
|
+
description: "JavaScript/TypeScript code to execute. Use 'await' for async operations. Use 'return' to return a value. Available: search_tools(), server.tool_name(), __tool_namespaces"
|
|
2849
|
+
},
|
|
2850
|
+
timeout: {
|
|
2851
|
+
type: "number",
|
|
2852
|
+
description: "Execution timeout in milliseconds",
|
|
2853
|
+
default: 3e4
|
|
2854
|
+
}
|
|
2855
|
+
},
|
|
2856
|
+
required: ["code"]
|
|
2857
|
+
}
|
|
2858
|
+
},
|
|
2859
|
+
{
|
|
2860
|
+
name: "search_tools",
|
|
2861
|
+
description: "Search and discover available MCP tools across all servers. Use this to find out what tools are available before writing code. Returns tool information including names, descriptions, and schemas. Can filter by query and control detail level.",
|
|
2862
|
+
inputSchema: {
|
|
2863
|
+
type: "object",
|
|
2864
|
+
properties: {
|
|
2865
|
+
query: {
|
|
2866
|
+
type: "string",
|
|
2867
|
+
description: "Search query to filter tools by name or description",
|
|
2868
|
+
default: ""
|
|
2869
|
+
},
|
|
2870
|
+
detail_level: {
|
|
2871
|
+
type: "string",
|
|
2872
|
+
description: "Detail level: 'names', 'descriptions', or 'full'",
|
|
2873
|
+
enum: ["names", "descriptions", "full"],
|
|
2874
|
+
default: "full"
|
|
2875
|
+
}
|
|
2876
|
+
}
|
|
2877
|
+
}
|
|
2878
|
+
}
|
|
2879
|
+
];
|
|
2880
|
+
}
|
|
2881
|
+
// Override tools getter to return static list immediately
|
|
2882
|
+
get tools() {
|
|
2883
|
+
return this._tools;
|
|
2884
|
+
}
|
|
2885
|
+
async initialize() {
|
|
2886
|
+
this.toolsCache = this._tools;
|
|
2887
|
+
return { capabilities: {}, version: "1.0.0" };
|
|
2888
|
+
}
|
|
2889
|
+
async callTool(name, args) {
|
|
2890
|
+
if (name === "execute_code") {
|
|
2891
|
+
const code = args.code;
|
|
2892
|
+
const timeout = args.timeout || 3e4;
|
|
2893
|
+
const result = await this.mcpClient.executeCode(code, timeout);
|
|
2894
|
+
return {
|
|
2895
|
+
content: [
|
|
2896
|
+
{
|
|
2897
|
+
type: "text",
|
|
2898
|
+
text: JSON.stringify(result)
|
|
2899
|
+
}
|
|
2900
|
+
]
|
|
2901
|
+
};
|
|
2902
|
+
} else if (name === "search_tools") {
|
|
2903
|
+
const query = args.query || "";
|
|
2904
|
+
const detailLevel = args.detail_level;
|
|
2905
|
+
const result = await this.mcpClient.searchTools(
|
|
2906
|
+
query,
|
|
2907
|
+
detailLevel && detailLevel in ["names", "descriptions", "full"] ? detailLevel : "full"
|
|
2908
|
+
);
|
|
2909
|
+
return {
|
|
2910
|
+
content: [
|
|
2911
|
+
{
|
|
2912
|
+
type: "text",
|
|
2913
|
+
text: JSON.stringify(result)
|
|
2914
|
+
}
|
|
2915
|
+
]
|
|
2916
|
+
};
|
|
2917
|
+
}
|
|
2918
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
2919
|
+
}
|
|
2920
|
+
};
|
|
2921
|
+
|
|
2922
|
+
// src/config.ts
|
|
2923
|
+
var import_node_fs = require("fs");
|
|
2924
|
+
|
|
2925
|
+
// src/connectors/http.ts
|
|
2926
|
+
var import_client = require("@mcp-use/modelcontextprotocol-sdk/client/index.js");
|
|
2927
|
+
var import_streamableHttp = require("@mcp-use/modelcontextprotocol-sdk/client/streamableHttp.js");
|
|
2928
|
+
|
|
2929
|
+
// src/task_managers/sse.ts
|
|
2930
|
+
var import_sse = require("@mcp-use/modelcontextprotocol-sdk/client/sse.js");
|
|
2931
|
+
|
|
2932
|
+
// src/task_managers/base.ts
|
|
2933
|
+
var ConnectionManager = class {
|
|
2934
|
+
static {
|
|
2935
|
+
__name(this, "ConnectionManager");
|
|
2936
|
+
}
|
|
2937
|
+
_readyPromise;
|
|
2938
|
+
_readyResolver;
|
|
2939
|
+
_donePromise;
|
|
2940
|
+
_doneResolver;
|
|
2941
|
+
_exception = null;
|
|
2942
|
+
_connection = null;
|
|
2943
|
+
_task = null;
|
|
2944
|
+
_abortController = null;
|
|
2945
|
+
constructor() {
|
|
2946
|
+
this.reset();
|
|
2947
|
+
}
|
|
2948
|
+
/**
|
|
2949
|
+
* Start the connection manager and establish a connection.
|
|
2950
|
+
*
|
|
2951
|
+
* @returns The established connection.
|
|
2952
|
+
* @throws If the connection cannot be established.
|
|
2953
|
+
*/
|
|
2954
|
+
async start() {
|
|
2955
|
+
this.reset();
|
|
2956
|
+
logger.debug(`Starting ${this.constructor.name}`);
|
|
2957
|
+
this._task = this.connectionTask();
|
|
2958
|
+
await this._readyPromise;
|
|
2959
|
+
if (this._exception) {
|
|
2960
|
+
throw this._exception;
|
|
2961
|
+
}
|
|
2962
|
+
if (this._connection === null) {
|
|
2963
|
+
throw new Error("Connection was not established");
|
|
2964
|
+
}
|
|
2965
|
+
return this._connection;
|
|
2966
|
+
}
|
|
2967
|
+
/**
|
|
2968
|
+
* Stop the connection manager and close the connection.
|
|
2969
|
+
*/
|
|
2970
|
+
async stop() {
|
|
2971
|
+
if (this._task && this._abortController) {
|
|
2972
|
+
logger.debug(`Cancelling ${this.constructor.name} task`);
|
|
2973
|
+
this._abortController.abort();
|
|
2974
|
+
try {
|
|
2975
|
+
await this._task;
|
|
2976
|
+
} catch (e) {
|
|
2977
|
+
if (e instanceof Error && e.name === "AbortError") {
|
|
2978
|
+
logger.debug(`${this.constructor.name} task aborted successfully`);
|
|
2979
|
+
} else {
|
|
2980
|
+
logger.warn(`Error stopping ${this.constructor.name} task: ${e}`);
|
|
2981
|
+
}
|
|
2982
|
+
}
|
|
2983
|
+
}
|
|
2984
|
+
await this._donePromise;
|
|
2985
|
+
logger.debug(`${this.constructor.name} task completed`);
|
|
2986
|
+
}
|
|
2987
|
+
/**
|
|
2988
|
+
* Reset all internal state.
|
|
2989
|
+
*/
|
|
2990
|
+
reset() {
|
|
2991
|
+
this._readyPromise = new Promise((res) => this._readyResolver = res);
|
|
2992
|
+
this._donePromise = new Promise((res) => this._doneResolver = res);
|
|
2993
|
+
this._exception = null;
|
|
2994
|
+
this._connection = null;
|
|
2995
|
+
this._task = null;
|
|
2996
|
+
this._abortController = new AbortController();
|
|
2997
|
+
}
|
|
2998
|
+
/**
|
|
2999
|
+
* The background task responsible for establishing and maintaining the
|
|
3000
|
+
* connection until it is cancelled.
|
|
3001
|
+
*/
|
|
3002
|
+
async connectionTask() {
|
|
3003
|
+
logger.debug(`Running ${this.constructor.name} task`);
|
|
3004
|
+
try {
|
|
3005
|
+
this._connection = await this.establishConnection();
|
|
3006
|
+
logger.debug(`${this.constructor.name} connected successfully`);
|
|
3007
|
+
this._readyResolver();
|
|
3008
|
+
await this.waitForAbort();
|
|
3009
|
+
} catch (err) {
|
|
3010
|
+
this._exception = err;
|
|
3011
|
+
logger.error(`Error in ${this.constructor.name} task: ${err}`);
|
|
3012
|
+
this._readyResolver();
|
|
3013
|
+
} finally {
|
|
3014
|
+
if (this._connection !== null) {
|
|
3015
|
+
try {
|
|
3016
|
+
await this.closeConnection(this._connection);
|
|
3017
|
+
} catch (closeErr) {
|
|
3018
|
+
logger.warn(
|
|
3019
|
+
`Error closing connection in ${this.constructor.name}: ${closeErr}`
|
|
3020
|
+
);
|
|
3021
|
+
}
|
|
3022
|
+
this._connection = null;
|
|
3023
|
+
}
|
|
3024
|
+
this._doneResolver();
|
|
3025
|
+
}
|
|
3026
|
+
}
|
|
3027
|
+
/**
|
|
3028
|
+
* Helper that returns a promise which resolves when the abort signal fires.
|
|
3029
|
+
*/
|
|
3030
|
+
async waitForAbort() {
|
|
3031
|
+
return new Promise((_resolve, _reject) => {
|
|
3032
|
+
if (!this._abortController) {
|
|
3033
|
+
return;
|
|
3034
|
+
}
|
|
3035
|
+
const signal = this._abortController.signal;
|
|
3036
|
+
if (signal.aborted) {
|
|
3037
|
+
_resolve();
|
|
3038
|
+
return;
|
|
3039
|
+
}
|
|
3040
|
+
const onAbort = /* @__PURE__ */ __name(() => {
|
|
3041
|
+
signal.removeEventListener("abort", onAbort);
|
|
3042
|
+
_resolve();
|
|
3043
|
+
}, "onAbort");
|
|
3044
|
+
signal.addEventListener("abort", onAbort);
|
|
3045
|
+
});
|
|
3046
|
+
}
|
|
3047
|
+
};
|
|
3048
|
+
|
|
3049
|
+
// src/task_managers/sse.ts
|
|
3050
|
+
var SseConnectionManager = class extends ConnectionManager {
|
|
3051
|
+
static {
|
|
3052
|
+
__name(this, "SseConnectionManager");
|
|
3053
|
+
}
|
|
3054
|
+
url;
|
|
3055
|
+
opts;
|
|
3056
|
+
_transport = null;
|
|
3057
|
+
reinitializing = false;
|
|
3058
|
+
/**
|
|
3059
|
+
* Create an SSE connection manager.
|
|
3060
|
+
*
|
|
3061
|
+
* @param url The SSE endpoint URL.
|
|
3062
|
+
* @param opts Optional transport options (auth, headers, etc.).
|
|
3063
|
+
*/
|
|
3064
|
+
constructor(url, opts) {
|
|
3065
|
+
super();
|
|
3066
|
+
this.url = typeof url === "string" ? new URL(url) : url;
|
|
3067
|
+
this.opts = opts;
|
|
3068
|
+
}
|
|
3069
|
+
/**
|
|
3070
|
+
* Spawn a new `SSEClientTransport` and wrap it with 404 handling.
|
|
3071
|
+
* Per MCP spec, clients MUST re-initialize when receiving 404 for stale sessions.
|
|
3072
|
+
*/
|
|
3073
|
+
async establishConnection() {
|
|
3074
|
+
const transport = new import_sse.SSEClientTransport(this.url, this.opts);
|
|
3075
|
+
const originalSend = transport.send.bind(transport);
|
|
3076
|
+
transport.send = async (message) => {
|
|
3077
|
+
const sendMessage = /* @__PURE__ */ __name(async (msg) => {
|
|
3078
|
+
if (Array.isArray(msg)) {
|
|
3079
|
+
for (const singleMsg of msg) {
|
|
3080
|
+
await originalSend(singleMsg);
|
|
3081
|
+
}
|
|
3082
|
+
} else {
|
|
3083
|
+
await originalSend(msg);
|
|
3084
|
+
}
|
|
3085
|
+
}, "sendMessage");
|
|
3086
|
+
try {
|
|
3087
|
+
await sendMessage(message);
|
|
3088
|
+
} catch (error) {
|
|
3089
|
+
if (error?.code === 404 && transport.sessionId && !this.reinitializing) {
|
|
3090
|
+
logger.warn(
|
|
3091
|
+
`[SSE] Session not found (404), re-initializing per MCP spec...`
|
|
3092
|
+
);
|
|
3093
|
+
this.reinitializing = true;
|
|
3094
|
+
try {
|
|
3095
|
+
transport.sessionId = void 0;
|
|
3096
|
+
await this.reinitialize(transport);
|
|
3097
|
+
logger.info(`[SSE] Re-initialization successful, retrying request`);
|
|
3098
|
+
await sendMessage(message);
|
|
3099
|
+
} finally {
|
|
3100
|
+
this.reinitializing = false;
|
|
3101
|
+
}
|
|
3102
|
+
} else {
|
|
3103
|
+
throw error;
|
|
3104
|
+
}
|
|
3105
|
+
}
|
|
3106
|
+
};
|
|
3107
|
+
this._transport = transport;
|
|
3108
|
+
logger.debug(`${this.constructor.name} connected successfully`);
|
|
3109
|
+
return transport;
|
|
3110
|
+
}
|
|
3111
|
+
/**
|
|
3112
|
+
* Re-initialize the transport with a new session
|
|
3113
|
+
* This is called when the server returns 404 for a stale session
|
|
3114
|
+
*/
|
|
3115
|
+
async reinitialize(transport) {
|
|
3116
|
+
logger.debug(`[SSE] Re-initialization triggered`);
|
|
3117
|
+
}
|
|
3118
|
+
/**
|
|
3119
|
+
* Close the underlying transport and clean up resources.
|
|
3120
|
+
*/
|
|
3121
|
+
async closeConnection(_connection) {
|
|
3122
|
+
if (this._transport) {
|
|
3123
|
+
try {
|
|
3124
|
+
await this._transport.close();
|
|
3125
|
+
} catch (e) {
|
|
3126
|
+
logger.warn(`Error closing SSE transport: ${e}`);
|
|
3127
|
+
} finally {
|
|
3128
|
+
this._transport = null;
|
|
3129
|
+
}
|
|
3130
|
+
}
|
|
3131
|
+
}
|
|
3132
|
+
};
|
|
3133
|
+
|
|
3134
|
+
// src/connectors/http.ts
|
|
3135
|
+
var HttpConnector = class extends BaseConnector {
|
|
3136
|
+
static {
|
|
3137
|
+
__name(this, "HttpConnector");
|
|
3138
|
+
}
|
|
3139
|
+
baseUrl;
|
|
3140
|
+
headers;
|
|
3141
|
+
timeout;
|
|
3142
|
+
sseReadTimeout;
|
|
3143
|
+
clientInfo;
|
|
3144
|
+
preferSse;
|
|
3145
|
+
transportType = null;
|
|
3146
|
+
streamableTransport = null;
|
|
3147
|
+
constructor(baseUrl, opts = {}) {
|
|
3148
|
+
super(opts);
|
|
3149
|
+
this.baseUrl = baseUrl.replace(/\/$/, "");
|
|
3150
|
+
this.headers = { ...opts.headers ?? {} };
|
|
3151
|
+
if (opts.authToken) {
|
|
3152
|
+
this.headers.Authorization = `Bearer ${opts.authToken}`;
|
|
3153
|
+
}
|
|
3154
|
+
this.timeout = opts.timeout ?? 3e4;
|
|
3155
|
+
this.sseReadTimeout = opts.sseReadTimeout ?? 3e5;
|
|
3156
|
+
this.clientInfo = opts.clientInfo ?? {
|
|
3157
|
+
name: "http-connector",
|
|
3158
|
+
version: "1.0.0"
|
|
3159
|
+
};
|
|
3160
|
+
this.preferSse = opts.preferSse ?? false;
|
|
3161
|
+
}
|
|
3162
|
+
/** Establish connection to the MCP implementation via HTTP (streamable or SSE). */
|
|
3163
|
+
async connect() {
|
|
3164
|
+
if (this.connected) {
|
|
3165
|
+
logger.debug("Already connected to MCP implementation");
|
|
3166
|
+
return;
|
|
3167
|
+
}
|
|
3168
|
+
const baseUrl = this.baseUrl;
|
|
3169
|
+
if (this.preferSse) {
|
|
3170
|
+
logger.debug(`Connecting to MCP implementation via HTTP/SSE: ${baseUrl}`);
|
|
3171
|
+
await this.connectWithSse(baseUrl);
|
|
3172
|
+
return;
|
|
3173
|
+
}
|
|
3174
|
+
logger.debug(`Connecting to MCP implementation via HTTP: ${baseUrl}`);
|
|
3175
|
+
try {
|
|
3176
|
+
logger.info("\u{1F504} Attempting streamable HTTP transport...");
|
|
3177
|
+
await this.connectWithStreamableHttp(baseUrl);
|
|
3178
|
+
logger.info("\u2705 Successfully connected via streamable HTTP");
|
|
3179
|
+
} catch (err) {
|
|
3180
|
+
let fallbackReason = "Unknown error";
|
|
3181
|
+
let is401Error = false;
|
|
3182
|
+
if (err instanceof import_streamableHttp.StreamableHTTPError) {
|
|
3183
|
+
const streamableErr = err;
|
|
3184
|
+
is401Error = streamableErr.code === 401;
|
|
3185
|
+
if (streamableErr.code === 400 && streamableErr.message.includes("Missing session ID")) {
|
|
3186
|
+
fallbackReason = "Server requires session ID (FastMCP compatibility) - using SSE transport";
|
|
3187
|
+
logger.warn(`\u26A0\uFE0F ${fallbackReason}`);
|
|
3188
|
+
} else if (streamableErr.code === 404 || streamableErr.code === 405) {
|
|
3189
|
+
fallbackReason = `Server returned ${streamableErr.code} - server likely doesn't support streamable HTTP`;
|
|
3190
|
+
logger.debug(fallbackReason);
|
|
3191
|
+
} else {
|
|
3192
|
+
fallbackReason = `Server returned ${streamableErr.code}: ${streamableErr.message}`;
|
|
3193
|
+
logger.debug(fallbackReason);
|
|
3194
|
+
}
|
|
3195
|
+
} else if (err instanceof Error) {
|
|
3196
|
+
const errorStr = err.toString();
|
|
3197
|
+
const errorMsg = err.message || "";
|
|
3198
|
+
is401Error = errorStr.includes("401") || errorMsg.includes("Unauthorized");
|
|
3199
|
+
if (errorStr.includes("Missing session ID") || errorStr.includes("Bad Request: Missing session ID") || errorMsg.includes("FastMCP session ID error")) {
|
|
3200
|
+
fallbackReason = "Server requires session ID (FastMCP compatibility) - using SSE transport";
|
|
3201
|
+
logger.warn(`\u26A0\uFE0F ${fallbackReason}`);
|
|
3202
|
+
} else if (errorStr.includes("405 Method Not Allowed") || errorStr.includes("404 Not Found")) {
|
|
3203
|
+
fallbackReason = "Server doesn't support streamable HTTP (405/404)";
|
|
3204
|
+
logger.debug(fallbackReason);
|
|
3205
|
+
} else {
|
|
3206
|
+
fallbackReason = `Streamable HTTP failed: ${err.message}`;
|
|
3207
|
+
logger.debug(fallbackReason);
|
|
3208
|
+
}
|
|
3209
|
+
}
|
|
3210
|
+
if (is401Error) {
|
|
3211
|
+
logger.info("Authentication required - skipping SSE fallback");
|
|
3212
|
+
await this.cleanupResources();
|
|
3213
|
+
const authError = new Error("Authentication required");
|
|
3214
|
+
authError.code = 401;
|
|
3215
|
+
throw authError;
|
|
3216
|
+
}
|
|
3217
|
+
logger.info("\u{1F504} Falling back to SSE transport...");
|
|
3218
|
+
try {
|
|
3219
|
+
await this.connectWithSse(baseUrl);
|
|
3220
|
+
} catch (sseErr) {
|
|
3221
|
+
logger.error(`Failed to connect with both transports:`);
|
|
3222
|
+
logger.error(` Streamable HTTP: ${fallbackReason}`);
|
|
3223
|
+
logger.error(` SSE: ${sseErr}`);
|
|
3224
|
+
await this.cleanupResources();
|
|
3225
|
+
const sseIs401 = sseErr?.message?.includes("401") || sseErr?.message?.includes("Unauthorized");
|
|
3226
|
+
if (sseIs401) {
|
|
3227
|
+
const authError = new Error("Authentication required");
|
|
3228
|
+
authError.code = 401;
|
|
3229
|
+
throw authError;
|
|
3230
|
+
}
|
|
3231
|
+
throw new Error(
|
|
3232
|
+
"Could not connect to server with any available transport"
|
|
3233
|
+
);
|
|
3234
|
+
}
|
|
3235
|
+
}
|
|
3236
|
+
}
|
|
3237
|
+
async connectWithStreamableHttp(baseUrl) {
|
|
3238
|
+
try {
|
|
3239
|
+
const streamableTransport = new import_streamableHttp.StreamableHTTPClientTransport(
|
|
3240
|
+
new URL(baseUrl),
|
|
3241
|
+
{
|
|
3242
|
+
authProvider: this.opts.authProvider,
|
|
3243
|
+
// ← Pass OAuth provider to SDK
|
|
3244
|
+
requestInit: {
|
|
3245
|
+
headers: this.headers
|
|
3246
|
+
},
|
|
3247
|
+
// Pass through reconnection options
|
|
3248
|
+
reconnectionOptions: {
|
|
3249
|
+
maxReconnectionDelay: 3e4,
|
|
3250
|
+
initialReconnectionDelay: 1e3,
|
|
3251
|
+
reconnectionDelayGrowFactor: 1.5,
|
|
3252
|
+
maxRetries: 2
|
|
3253
|
+
}
|
|
3254
|
+
// Don't pass sessionId - let the SDK generate it automatically during connect()
|
|
3255
|
+
}
|
|
3256
|
+
);
|
|
3257
|
+
let transport = streamableTransport;
|
|
3258
|
+
if (this.opts.wrapTransport) {
|
|
3259
|
+
const serverId = this.baseUrl;
|
|
3260
|
+
transport = this.opts.wrapTransport(
|
|
3261
|
+
transport,
|
|
3262
|
+
serverId
|
|
3263
|
+
);
|
|
3264
|
+
}
|
|
3265
|
+
const clientOptions = {
|
|
3266
|
+
...this.opts.clientOptions || {},
|
|
3267
|
+
capabilities: {
|
|
3268
|
+
...this.opts.clientOptions?.capabilities || {},
|
|
3269
|
+
roots: { listChanged: true },
|
|
3270
|
+
// Always advertise roots capability
|
|
3271
|
+
// Add sampling capability if callback is provided
|
|
3272
|
+
...this.opts.samplingCallback ? { sampling: {} } : {},
|
|
3273
|
+
// Add elicitation capability if callback is provided
|
|
3274
|
+
...this.opts.elicitationCallback ? { elicitation: { form: {}, url: {} } } : {}
|
|
3275
|
+
}
|
|
3276
|
+
};
|
|
3277
|
+
logger.debug(
|
|
3278
|
+
`Creating Client with capabilities:`,
|
|
3279
|
+
JSON.stringify(clientOptions.capabilities, null, 2)
|
|
3280
|
+
);
|
|
3281
|
+
this.client = new import_client.Client(this.clientInfo, clientOptions);
|
|
3282
|
+
this.setupRootsHandler();
|
|
3283
|
+
logger.debug("Roots handler registered before connect");
|
|
3284
|
+
try {
|
|
3285
|
+
await this.client.connect(transport, {
|
|
3286
|
+
timeout: Math.min(this.timeout, 3e3)
|
|
3287
|
+
});
|
|
3288
|
+
const sessionId = streamableTransport.sessionId;
|
|
3289
|
+
if (sessionId) {
|
|
3290
|
+
logger.debug(`Session ID obtained: ${sessionId}`);
|
|
3291
|
+
} else {
|
|
3292
|
+
logger.warn(
|
|
3293
|
+
"Session ID not available after connect - this may cause issues with SSE stream"
|
|
3294
|
+
);
|
|
3295
|
+
}
|
|
3296
|
+
} catch (connectErr) {
|
|
3297
|
+
if (connectErr instanceof Error) {
|
|
3298
|
+
const errMsg = connectErr.message || connectErr.toString();
|
|
3299
|
+
if (errMsg.includes("Missing session ID") || errMsg.includes("Bad Request: Missing session ID") || errMsg.includes("Mcp-Session-Id header is required")) {
|
|
3300
|
+
const wrappedError = new Error(
|
|
3301
|
+
`Session ID error: ${errMsg}. The SDK should automatically extract session ID from initialize response.`
|
|
3302
|
+
);
|
|
3303
|
+
wrappedError.cause = connectErr;
|
|
3304
|
+
throw wrappedError;
|
|
3305
|
+
}
|
|
3306
|
+
}
|
|
3307
|
+
throw connectErr;
|
|
3308
|
+
}
|
|
3309
|
+
this.streamableTransport = streamableTransport;
|
|
3310
|
+
this.connectionManager = {
|
|
3311
|
+
stop: /* @__PURE__ */ __name(async () => {
|
|
3312
|
+
if (this.streamableTransport) {
|
|
3313
|
+
try {
|
|
3314
|
+
await this.streamableTransport.terminateSession();
|
|
3315
|
+
await this.streamableTransport.close();
|
|
3316
|
+
} catch (e) {
|
|
3317
|
+
logger.warn(`Error closing Streamable HTTP transport: ${e}`);
|
|
3318
|
+
} finally {
|
|
3319
|
+
this.streamableTransport = null;
|
|
3320
|
+
}
|
|
3321
|
+
}
|
|
3322
|
+
}, "stop")
|
|
3323
|
+
};
|
|
3324
|
+
this.connected = true;
|
|
3325
|
+
this.transportType = "streamable-http";
|
|
3326
|
+
this.setupNotificationHandler();
|
|
3327
|
+
this.setupSamplingHandler();
|
|
3328
|
+
this.setupElicitationHandler();
|
|
3329
|
+
logger.debug(
|
|
3330
|
+
`Successfully connected to MCP implementation via streamable HTTP: ${baseUrl}`
|
|
3331
|
+
);
|
|
3332
|
+
this.trackConnectorInit({
|
|
3333
|
+
serverUrl: this.baseUrl,
|
|
3334
|
+
publicIdentifier: `${this.baseUrl} (streamable-http)`
|
|
3335
|
+
});
|
|
3336
|
+
} catch (err) {
|
|
3337
|
+
await this.cleanupResources();
|
|
3338
|
+
throw err;
|
|
3339
|
+
}
|
|
3340
|
+
}
|
|
3341
|
+
async connectWithSse(baseUrl) {
|
|
3342
|
+
try {
|
|
3343
|
+
this.connectionManager = new SseConnectionManager(baseUrl, {
|
|
3344
|
+
authProvider: this.opts.authProvider,
|
|
3345
|
+
// ← Pass OAuth provider to SDK (same as streamable HTTP)
|
|
3346
|
+
requestInit: {
|
|
3347
|
+
headers: this.headers
|
|
3348
|
+
}
|
|
3349
|
+
});
|
|
3350
|
+
let transport = await this.connectionManager.start();
|
|
3351
|
+
if (this.opts.wrapTransport) {
|
|
3352
|
+
const serverId = this.baseUrl;
|
|
3353
|
+
transport = this.opts.wrapTransport(transport, serverId);
|
|
3354
|
+
}
|
|
3355
|
+
const clientOptions = {
|
|
3356
|
+
...this.opts.clientOptions || {},
|
|
3357
|
+
capabilities: {
|
|
3358
|
+
...this.opts.clientOptions?.capabilities || {},
|
|
3359
|
+
roots: { listChanged: true },
|
|
3360
|
+
// Always advertise roots capability
|
|
3361
|
+
// Add sampling capability if callback is provided
|
|
3362
|
+
...this.opts.samplingCallback ? { sampling: {} } : {},
|
|
3363
|
+
// Add elicitation capability if callback is provided
|
|
3364
|
+
...this.opts.elicitationCallback ? { elicitation: { form: {}, url: {} } } : {}
|
|
3365
|
+
}
|
|
3366
|
+
};
|
|
3367
|
+
logger.debug(
|
|
3368
|
+
`Creating Client with capabilities (SSE):`,
|
|
3369
|
+
JSON.stringify(clientOptions.capabilities, null, 2)
|
|
3370
|
+
);
|
|
3371
|
+
this.client = new import_client.Client(this.clientInfo, clientOptions);
|
|
3372
|
+
this.setupRootsHandler();
|
|
3373
|
+
logger.debug("Roots handler registered before connect (SSE)");
|
|
3374
|
+
await this.client.connect(transport);
|
|
3375
|
+
this.connected = true;
|
|
3376
|
+
this.transportType = "sse";
|
|
3377
|
+
this.setupNotificationHandler();
|
|
3378
|
+
this.setupSamplingHandler();
|
|
3379
|
+
this.setupElicitationHandler();
|
|
3380
|
+
logger.debug(
|
|
3381
|
+
`Successfully connected to MCP implementation via HTTP/SSE: ${baseUrl}`
|
|
3382
|
+
);
|
|
3383
|
+
this.trackConnectorInit({
|
|
3384
|
+
serverUrl: this.baseUrl,
|
|
3385
|
+
publicIdentifier: `${this.baseUrl} (sse)`
|
|
3386
|
+
});
|
|
3387
|
+
} catch (err) {
|
|
3388
|
+
await this.cleanupResources();
|
|
3389
|
+
throw err;
|
|
3390
|
+
}
|
|
3391
|
+
}
|
|
3392
|
+
get publicIdentifier() {
|
|
3393
|
+
return {
|
|
3394
|
+
type: "http",
|
|
3395
|
+
url: this.baseUrl,
|
|
3396
|
+
transport: this.transportType || "unknown"
|
|
3397
|
+
};
|
|
3398
|
+
}
|
|
3399
|
+
/**
|
|
3400
|
+
* Get the transport type being used (streamable-http or sse)
|
|
3401
|
+
*/
|
|
3402
|
+
getTransportType() {
|
|
3403
|
+
return this.transportType;
|
|
3404
|
+
}
|
|
3405
|
+
};
|
|
3406
|
+
|
|
3407
|
+
// src/connectors/stdio.ts
|
|
3408
|
+
var import_node_process = __toESM(require("process"), 1);
|
|
3409
|
+
var import_client2 = require("@mcp-use/modelcontextprotocol-sdk/client/index.js");
|
|
3410
|
+
|
|
3411
|
+
// src/task_managers/stdio.ts
|
|
3412
|
+
var import_stdio = require("@mcp-use/modelcontextprotocol-sdk/client/stdio.js");
|
|
3413
|
+
var StdioConnectionManager = class extends ConnectionManager {
|
|
3414
|
+
static {
|
|
3415
|
+
__name(this, "StdioConnectionManager");
|
|
3416
|
+
}
|
|
3417
|
+
serverParams;
|
|
3418
|
+
errlog;
|
|
3419
|
+
_transport = null;
|
|
3420
|
+
/**
|
|
3421
|
+
* Create a new stdio connection manager.
|
|
3422
|
+
*
|
|
3423
|
+
* @param serverParams Parameters for the stdio server process.
|
|
3424
|
+
* @param errlog Stream to which the server's stderr should be piped.
|
|
3425
|
+
* Defaults to `process.stderr`.
|
|
3426
|
+
*/
|
|
3427
|
+
constructor(serverParams, errlog = process.stderr) {
|
|
3428
|
+
super();
|
|
3429
|
+
this.serverParams = serverParams;
|
|
3430
|
+
this.errlog = errlog;
|
|
3431
|
+
}
|
|
3432
|
+
/**
|
|
3433
|
+
* Establish the stdio connection by spawning the server process and starting
|
|
3434
|
+
* the SDK's transport. Returns the live `StdioClientTransport` instance.
|
|
3435
|
+
*/
|
|
3436
|
+
async establishConnection() {
|
|
3437
|
+
this._transport = new import_stdio.StdioClientTransport(this.serverParams);
|
|
3438
|
+
if (this._transport.stderr && typeof this._transport.stderr.pipe === "function") {
|
|
3439
|
+
this._transport.stderr.pipe(
|
|
3440
|
+
this.errlog
|
|
3441
|
+
);
|
|
3442
|
+
}
|
|
3443
|
+
logger.debug(`${this.constructor.name} connected successfully`);
|
|
3444
|
+
return this._transport;
|
|
3445
|
+
}
|
|
3446
|
+
/**
|
|
3447
|
+
* Close the stdio connection, making sure the transport cleans up the child
|
|
3448
|
+
* process and associated resources.
|
|
3449
|
+
*/
|
|
3450
|
+
async closeConnection(_connection) {
|
|
3451
|
+
if (this._transport) {
|
|
3452
|
+
try {
|
|
3453
|
+
await this._transport.close();
|
|
3454
|
+
} catch (e) {
|
|
3455
|
+
logger.warn(`Error closing stdio transport: ${e}`);
|
|
3456
|
+
} finally {
|
|
3457
|
+
this._transport = null;
|
|
3458
|
+
}
|
|
3459
|
+
}
|
|
3460
|
+
}
|
|
3461
|
+
};
|
|
3462
|
+
|
|
3463
|
+
// src/connectors/stdio.ts
|
|
3464
|
+
var StdioConnector = class extends BaseConnector {
|
|
3465
|
+
static {
|
|
3466
|
+
__name(this, "StdioConnector");
|
|
3467
|
+
}
|
|
3468
|
+
command;
|
|
3469
|
+
args;
|
|
3470
|
+
env;
|
|
3471
|
+
errlog;
|
|
3472
|
+
clientInfo;
|
|
3473
|
+
constructor({
|
|
3474
|
+
command = "npx",
|
|
3475
|
+
args = [],
|
|
3476
|
+
env,
|
|
3477
|
+
errlog = import_node_process.default.stderr,
|
|
3478
|
+
...rest
|
|
3479
|
+
} = {}) {
|
|
3480
|
+
super(rest);
|
|
3481
|
+
this.command = command;
|
|
3482
|
+
this.args = args;
|
|
3483
|
+
this.env = env;
|
|
3484
|
+
this.errlog = errlog;
|
|
3485
|
+
this.clientInfo = rest.clientInfo ?? {
|
|
3486
|
+
name: "stdio-connector",
|
|
3487
|
+
version: "1.0.0"
|
|
3488
|
+
};
|
|
3489
|
+
}
|
|
3490
|
+
/** Establish connection to the MCP implementation. */
|
|
3491
|
+
async connect() {
|
|
3492
|
+
if (this.connected) {
|
|
3493
|
+
logger.debug("Already connected to MCP implementation");
|
|
3494
|
+
return;
|
|
3495
|
+
}
|
|
3496
|
+
logger.debug(`Connecting to MCP implementation via stdio: ${this.command}`);
|
|
3497
|
+
try {
|
|
3498
|
+
let mergedEnv;
|
|
3499
|
+
if (this.env) {
|
|
3500
|
+
mergedEnv = {};
|
|
3501
|
+
for (const [key, value] of Object.entries(import_node_process.default.env)) {
|
|
3502
|
+
if (value !== void 0) {
|
|
3503
|
+
mergedEnv[key] = value;
|
|
3504
|
+
}
|
|
3505
|
+
}
|
|
3506
|
+
Object.assign(mergedEnv, this.env);
|
|
3507
|
+
}
|
|
3508
|
+
const serverParams = {
|
|
3509
|
+
command: this.command,
|
|
3510
|
+
args: this.args,
|
|
3511
|
+
env: mergedEnv
|
|
3512
|
+
};
|
|
3513
|
+
this.connectionManager = new StdioConnectionManager(
|
|
3514
|
+
serverParams,
|
|
3515
|
+
this.errlog
|
|
3516
|
+
);
|
|
3517
|
+
const transport = await this.connectionManager.start();
|
|
3518
|
+
const clientOptions = {
|
|
3519
|
+
...this.opts.clientOptions || {},
|
|
3520
|
+
capabilities: {
|
|
3521
|
+
...this.opts.clientOptions?.capabilities || {},
|
|
3522
|
+
roots: { listChanged: true },
|
|
3523
|
+
// Always advertise roots capability
|
|
3524
|
+
// Add sampling capability if callback is provided
|
|
3525
|
+
...this.opts.samplingCallback ? { sampling: {} } : {},
|
|
3526
|
+
// Add elicitation capability if callback is provided
|
|
3527
|
+
...this.opts.elicitationCallback ? { elicitation: { form: {}, url: {} } } : {}
|
|
3528
|
+
}
|
|
3529
|
+
};
|
|
3530
|
+
this.client = new import_client2.Client(this.clientInfo, clientOptions);
|
|
3531
|
+
await this.client.connect(transport);
|
|
3532
|
+
this.connected = true;
|
|
3533
|
+
this.setupNotificationHandler();
|
|
3534
|
+
this.setupRootsHandler();
|
|
3535
|
+
this.setupSamplingHandler();
|
|
3536
|
+
this.setupElicitationHandler();
|
|
3537
|
+
logger.debug(
|
|
3538
|
+
`Successfully connected to MCP implementation: ${this.command}`
|
|
3539
|
+
);
|
|
3540
|
+
this.trackConnectorInit({
|
|
3541
|
+
serverCommand: this.command,
|
|
3542
|
+
serverArgs: this.args,
|
|
3543
|
+
publicIdentifier: `${this.command} ${this.args.join(" ")}`
|
|
3544
|
+
});
|
|
3545
|
+
} catch (err) {
|
|
3546
|
+
logger.error(`Failed to connect to MCP implementation: ${err}`);
|
|
3547
|
+
await this.cleanupResources();
|
|
3548
|
+
throw err;
|
|
3549
|
+
}
|
|
3550
|
+
}
|
|
3551
|
+
get publicIdentifier() {
|
|
3552
|
+
return {
|
|
3553
|
+
type: "stdio",
|
|
3554
|
+
"command&args": `${this.command} ${this.args.join(" ")}`
|
|
3555
|
+
};
|
|
3556
|
+
}
|
|
3557
|
+
};
|
|
3558
|
+
|
|
3559
|
+
// src/config.ts
|
|
3560
|
+
function loadConfigFile(filepath) {
|
|
3561
|
+
const raw = (0, import_node_fs.readFileSync)(filepath, "utf-8");
|
|
3562
|
+
return JSON.parse(raw);
|
|
3563
|
+
}
|
|
3564
|
+
__name(loadConfigFile, "loadConfigFile");
|
|
3565
|
+
function createConnectorFromConfig(serverConfig, connectorOptions) {
|
|
3566
|
+
if ("command" in serverConfig && "args" in serverConfig) {
|
|
3567
|
+
return new StdioConnector({
|
|
3568
|
+
command: serverConfig.command,
|
|
3569
|
+
args: serverConfig.args,
|
|
3570
|
+
env: serverConfig.env,
|
|
3571
|
+
...connectorOptions
|
|
3572
|
+
});
|
|
3573
|
+
}
|
|
3574
|
+
if ("url" in serverConfig) {
|
|
3575
|
+
const transport = serverConfig.transport || "http";
|
|
3576
|
+
return new HttpConnector(serverConfig.url, {
|
|
3577
|
+
headers: serverConfig.headers,
|
|
3578
|
+
authToken: serverConfig.auth_token || serverConfig.authToken,
|
|
3579
|
+
// Only force SSE if explicitly requested
|
|
3580
|
+
preferSse: serverConfig.preferSse || transport === "sse",
|
|
3581
|
+
...connectorOptions
|
|
3582
|
+
});
|
|
3583
|
+
}
|
|
3584
|
+
throw new Error("Cannot determine connector type from config");
|
|
3585
|
+
}
|
|
3586
|
+
__name(createConnectorFromConfig, "createConnectorFromConfig");
|
|
3587
|
+
|
|
3588
|
+
// src/client.ts
|
|
3589
|
+
var MCPClient = class _MCPClient extends BaseMCPClient {
|
|
3590
|
+
static {
|
|
3591
|
+
__name(this, "MCPClient");
|
|
3592
|
+
}
|
|
3593
|
+
/**
|
|
3594
|
+
* Get the mcp-use package version.
|
|
3595
|
+
* Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)
|
|
3596
|
+
*/
|
|
3597
|
+
static getPackageVersion() {
|
|
3598
|
+
return getPackageVersion();
|
|
3599
|
+
}
|
|
3600
|
+
codeMode = false;
|
|
3601
|
+
_codeExecutor = null;
|
|
3602
|
+
_customCodeExecutor = null;
|
|
3603
|
+
_codeExecutorConfig = "vm";
|
|
3604
|
+
_executorOptions;
|
|
3605
|
+
_samplingCallback;
|
|
3606
|
+
_elicitationCallback;
|
|
3607
|
+
constructor(config, options) {
|
|
3608
|
+
if (config) {
|
|
3609
|
+
if (typeof config === "string") {
|
|
3610
|
+
super(loadConfigFile(config));
|
|
3611
|
+
} else {
|
|
3612
|
+
super(config);
|
|
3613
|
+
}
|
|
3614
|
+
} else {
|
|
3615
|
+
super();
|
|
3616
|
+
}
|
|
3617
|
+
let codeModeEnabled = false;
|
|
3618
|
+
let executorConfig = "vm";
|
|
3619
|
+
let executorOptions;
|
|
3620
|
+
if (options?.codeMode) {
|
|
3621
|
+
if (typeof options.codeMode === "boolean") {
|
|
3622
|
+
codeModeEnabled = options.codeMode;
|
|
3623
|
+
} else {
|
|
3624
|
+
codeModeEnabled = options.codeMode.enabled;
|
|
3625
|
+
executorConfig = options.codeMode.executor ?? "vm";
|
|
3626
|
+
executorOptions = options.codeMode.executorOptions;
|
|
3627
|
+
}
|
|
3628
|
+
}
|
|
3629
|
+
this.codeMode = codeModeEnabled;
|
|
3630
|
+
this._codeExecutorConfig = executorConfig;
|
|
3631
|
+
this._executorOptions = executorOptions;
|
|
3632
|
+
this._samplingCallback = options?.samplingCallback;
|
|
3633
|
+
this._elicitationCallback = options?.elicitationCallback;
|
|
3634
|
+
if (this.codeMode) {
|
|
3635
|
+
this._setupCodeModeConnector();
|
|
3636
|
+
}
|
|
3637
|
+
this._trackClientInit();
|
|
3638
|
+
}
|
|
3639
|
+
_trackClientInit() {
|
|
3640
|
+
const servers = Object.keys(this.config.mcpServers ?? {});
|
|
3641
|
+
const hasSamplingCallback = !!this._samplingCallback;
|
|
3642
|
+
const hasElicitationCallback = !!this._elicitationCallback;
|
|
3643
|
+
Tel.getInstance().trackMCPClientInit({
|
|
3644
|
+
codeMode: this.codeMode,
|
|
3645
|
+
sandbox: false,
|
|
3646
|
+
// Sandbox not supported in TS yet
|
|
3647
|
+
allCallbacks: hasSamplingCallback && hasElicitationCallback,
|
|
3648
|
+
verify: false,
|
|
3649
|
+
// No verify option in TS client
|
|
3650
|
+
servers,
|
|
3651
|
+
numServers: servers.length,
|
|
3652
|
+
isBrowser: false
|
|
3653
|
+
// Node.js MCPClient
|
|
3654
|
+
}).catch((e) => logger.debug(`Failed to track MCPClient init: ${e}`));
|
|
3655
|
+
}
|
|
3656
|
+
static fromDict(cfg, options) {
|
|
3657
|
+
return new _MCPClient(cfg, options);
|
|
3658
|
+
}
|
|
3659
|
+
static fromConfigFile(path2, options) {
|
|
3660
|
+
return new _MCPClient(loadConfigFile(path2), options);
|
|
3661
|
+
}
|
|
3662
|
+
/**
|
|
3663
|
+
* Save configuration to a file (Node.js only)
|
|
3664
|
+
*/
|
|
3665
|
+
saveConfig(filepath) {
|
|
3666
|
+
const dir = import_node_path.default.dirname(filepath);
|
|
3667
|
+
if (!import_node_fs2.default.existsSync(dir)) {
|
|
3668
|
+
import_node_fs2.default.mkdirSync(dir, { recursive: true });
|
|
3669
|
+
}
|
|
3670
|
+
import_node_fs2.default.writeFileSync(filepath, JSON.stringify(this.config, null, 2), "utf-8");
|
|
3671
|
+
}
|
|
3672
|
+
/**
|
|
3673
|
+
* Create a connector from server configuration (Node.js version)
|
|
3674
|
+
* Supports all connector types including StdioConnector
|
|
3675
|
+
*/
|
|
3676
|
+
createConnectorFromConfig(serverConfig) {
|
|
3677
|
+
return createConnectorFromConfig(serverConfig, {
|
|
3678
|
+
samplingCallback: this._samplingCallback,
|
|
3679
|
+
elicitationCallback: this._elicitationCallback
|
|
3680
|
+
});
|
|
3681
|
+
}
|
|
3682
|
+
_setupCodeModeConnector() {
|
|
3683
|
+
logger.debug("Code mode connector initialized as internal meta server");
|
|
3684
|
+
const connector = new CodeModeConnector(this);
|
|
3685
|
+
const session = new MCPSession(connector);
|
|
3686
|
+
this.sessions["code_mode"] = session;
|
|
3687
|
+
this.activeSessions.push("code_mode");
|
|
3688
|
+
}
|
|
3689
|
+
_ensureCodeExecutor() {
|
|
3690
|
+
if (!this._codeExecutor) {
|
|
3691
|
+
const config = this._codeExecutorConfig;
|
|
3692
|
+
if (config instanceof BaseCodeExecutor) {
|
|
3693
|
+
this._codeExecutor = config;
|
|
3694
|
+
} else if (typeof config === "function") {
|
|
3695
|
+
this._customCodeExecutor = config;
|
|
3696
|
+
throw new Error(
|
|
3697
|
+
"Custom executor function should be handled in executeCode"
|
|
3698
|
+
);
|
|
3699
|
+
} else if (config === "e2b") {
|
|
3700
|
+
const opts = this._executorOptions;
|
|
3701
|
+
if (!opts?.apiKey) {
|
|
3702
|
+
logger.warn("E2B executor requires apiKey. Falling back to VM.");
|
|
3703
|
+
try {
|
|
3704
|
+
this._codeExecutor = new VMCodeExecutor(
|
|
3705
|
+
this,
|
|
3706
|
+
this._executorOptions
|
|
3707
|
+
);
|
|
3708
|
+
} catch (error) {
|
|
3709
|
+
throw new Error(
|
|
3710
|
+
"VM executor is not available in this environment and E2B API key is not provided. Please provide an E2B API key or run in a Node.js environment."
|
|
3711
|
+
);
|
|
3712
|
+
}
|
|
3713
|
+
} else {
|
|
3714
|
+
this._codeExecutor = new E2BCodeExecutor(this, opts);
|
|
3715
|
+
}
|
|
3716
|
+
} else {
|
|
3717
|
+
try {
|
|
3718
|
+
this._codeExecutor = new VMCodeExecutor(
|
|
3719
|
+
this,
|
|
3720
|
+
this._executorOptions
|
|
3721
|
+
);
|
|
3722
|
+
} catch (error) {
|
|
3723
|
+
const e2bOpts = this._executorOptions;
|
|
3724
|
+
const e2bApiKey = e2bOpts?.apiKey || process.env.E2B_API_KEY;
|
|
3725
|
+
if (e2bApiKey) {
|
|
3726
|
+
logger.info(
|
|
3727
|
+
"VM executor not available in this environment. Falling back to E2B."
|
|
3728
|
+
);
|
|
3729
|
+
this._codeExecutor = new E2BCodeExecutor(this, {
|
|
3730
|
+
...e2bOpts,
|
|
3731
|
+
apiKey: e2bApiKey
|
|
3732
|
+
});
|
|
3733
|
+
} else {
|
|
3734
|
+
throw new Error(
|
|
3735
|
+
"VM executor is not available in this environment. Please provide an E2B API key via executorOptions or E2B_API_KEY environment variable, or run in a Node.js environment."
|
|
3736
|
+
);
|
|
3737
|
+
}
|
|
3738
|
+
}
|
|
3739
|
+
}
|
|
3740
|
+
}
|
|
3741
|
+
return this._codeExecutor;
|
|
3742
|
+
}
|
|
3743
|
+
/**
|
|
3744
|
+
* Execute code in code mode
|
|
3745
|
+
*/
|
|
3746
|
+
async executeCode(code, timeout) {
|
|
3747
|
+
if (!this.codeMode) {
|
|
3748
|
+
throw new Error("Code execution mode is not enabled");
|
|
3749
|
+
}
|
|
3750
|
+
if (this._customCodeExecutor) {
|
|
3751
|
+
return this._customCodeExecutor(code, timeout);
|
|
3752
|
+
}
|
|
3753
|
+
return this._ensureCodeExecutor().execute(code, timeout);
|
|
3754
|
+
}
|
|
3755
|
+
/**
|
|
3756
|
+
* Search available tools (used by code mode)
|
|
3757
|
+
*/
|
|
3758
|
+
async searchTools(query = "", detailLevel = "full") {
|
|
3759
|
+
if (!this.codeMode) {
|
|
3760
|
+
throw new Error("Code execution mode is not enabled");
|
|
3761
|
+
}
|
|
3762
|
+
return this._ensureCodeExecutor().createSearchToolsFunction()(
|
|
3763
|
+
query,
|
|
3764
|
+
detailLevel
|
|
3765
|
+
);
|
|
3766
|
+
}
|
|
3767
|
+
/**
|
|
3768
|
+
* Override getServerNames to exclude internal code_mode server
|
|
3769
|
+
*/
|
|
3770
|
+
getServerNames() {
|
|
3771
|
+
const isCodeModeEnabled = this.codeMode;
|
|
3772
|
+
return super.getServerNames().filter((name) => {
|
|
3773
|
+
return !isCodeModeEnabled || name !== "code_mode";
|
|
3774
|
+
});
|
|
3775
|
+
}
|
|
3776
|
+
/**
|
|
3777
|
+
* Close the client and clean up resources including code executors.
|
|
3778
|
+
* This ensures E2B sandboxes and other resources are properly released.
|
|
3779
|
+
*/
|
|
3780
|
+
async close() {
|
|
3781
|
+
if (this._codeExecutor) {
|
|
3782
|
+
await this._codeExecutor.cleanup();
|
|
3783
|
+
this._codeExecutor = null;
|
|
3784
|
+
}
|
|
3785
|
+
await this.closeAllSessions();
|
|
3786
|
+
}
|
|
3787
|
+
};
|