mcp-use 1.2.2-canary.0 → 1.2.2
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-VPPILX7B.js → chunk-3RJENWH4.js} +15 -6
- package/dist/{chunk-UVUM35MV.js → chunk-7UX634PO.js} +307 -112
- package/dist/{chunk-CPV4QNHD.js → chunk-KLIBVJ3Z.js} +145 -79
- package/dist/{chunk-EYAIJPBH.js → chunk-MZLETWQQ.js} +55 -17
- package/dist/{chunk-C3SRZK7H.js → chunk-RSGKBEHH.js} +144 -72
- package/dist/index.cjs +719 -300
- package/dist/index.d.ts +24 -24
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +86 -28
- package/dist/{langfuse-MO3AMDBE.js → langfuse-LCJ6VJEP.js} +2 -2
- package/dist/src/adapters/base.d.ts +2 -2
- package/dist/src/adapters/base.d.ts.map +1 -1
- package/dist/src/adapters/index.d.ts +2 -2
- package/dist/src/adapters/index.d.ts.map +1 -1
- package/dist/src/adapters/langchain_adapter.d.ts +4 -4
- package/dist/src/adapters/langchain_adapter.d.ts.map +1 -1
- package/dist/src/agents/base.d.ts +1 -1
- package/dist/src/agents/base.d.ts.map +1 -1
- package/dist/src/agents/index.d.ts +3 -3
- package/dist/src/agents/index.d.ts.map +1 -1
- package/dist/src/agents/mcp_agent.d.ts +12 -12
- package/dist/src/agents/mcp_agent.d.ts.map +1 -1
- package/dist/src/agents/prompts/system_prompt_builder.d.ts +2 -2
- package/dist/src/agents/prompts/system_prompt_builder.d.ts.map +1 -1
- package/dist/src/agents/prompts/templates.d.ts.map +1 -1
- package/dist/src/agents/remote.d.ts +2 -2
- package/dist/src/agents/remote.d.ts.map +1 -1
- package/dist/src/agents/types.d.ts +1 -1
- package/dist/src/agents/types.d.ts.map +1 -1
- package/dist/src/agents/utils/ai_sdk.d.ts +1 -1
- package/dist/src/agents/utils/ai_sdk.d.ts.map +1 -1
- package/dist/src/agents/utils/index.d.ts +1 -1
- package/dist/src/agents/utils/index.d.ts.map +1 -1
- package/dist/src/auth/browser-provider.d.ts +2 -2
- package/dist/src/auth/browser-provider.d.ts.map +1 -1
- package/dist/src/auth/callback.d.ts.map +1 -1
- package/dist/src/auth/index.d.ts +3 -3
- package/dist/src/auth/index.d.ts.map +1 -1
- package/dist/src/auth/types.d.ts +1 -1
- package/dist/src/auth/types.d.ts.map +1 -1
- package/dist/src/browser.cjs +508 -201
- package/dist/src/browser.d.ts +17 -17
- package/dist/src/browser.d.ts.map +1 -1
- package/dist/src/browser.js +11 -5
- package/dist/src/client/base.d.ts +2 -2
- package/dist/src/client/base.d.ts.map +1 -1
- package/dist/src/client/browser.d.ts +2 -2
- package/dist/src/client/browser.d.ts.map +1 -1
- package/dist/src/client.d.ts +2 -2
- package/dist/src/client.d.ts.map +1 -1
- package/dist/src/config.d.ts +1 -1
- package/dist/src/config.d.ts.map +1 -1
- package/dist/src/connectors/base.d.ts +5 -5
- package/dist/src/connectors/base.d.ts.map +1 -1
- package/dist/src/connectors/http.d.ts +3 -3
- package/dist/src/connectors/http.d.ts.map +1 -1
- package/dist/src/connectors/index.d.ts +4 -4
- package/dist/src/connectors/index.d.ts.map +1 -1
- package/dist/src/connectors/stdio.d.ts +3 -3
- package/dist/src/connectors/stdio.d.ts.map +1 -1
- package/dist/src/connectors/websocket.d.ts +3 -3
- package/dist/src/connectors/websocket.d.ts.map +1 -1
- package/dist/src/logging.d.ts +4 -4
- package/dist/src/logging.d.ts.map +1 -1
- package/dist/src/managers/index.d.ts +2 -2
- package/dist/src/managers/index.d.ts.map +1 -1
- package/dist/src/managers/server_manager.d.ts +4 -4
- package/dist/src/managers/server_manager.d.ts.map +1 -1
- package/dist/src/managers/tools/acquire_active_mcp_server.d.ts +3 -3
- package/dist/src/managers/tools/acquire_active_mcp_server.d.ts.map +1 -1
- package/dist/src/managers/tools/add_server_from_config.d.ts +3 -3
- package/dist/src/managers/tools/add_server_from_config.d.ts.map +1 -1
- package/dist/src/managers/tools/base.d.ts +6 -6
- package/dist/src/managers/tools/base.d.ts.map +1 -1
- package/dist/src/managers/tools/connect_mcp_server.d.ts +4 -4
- package/dist/src/managers/tools/connect_mcp_server.d.ts.map +1 -1
- package/dist/src/managers/tools/index.d.ts +5 -5
- package/dist/src/managers/tools/index.d.ts.map +1 -1
- package/dist/src/managers/tools/list_mcp_servers.d.ts +3 -3
- package/dist/src/managers/tools/list_mcp_servers.d.ts.map +1 -1
- package/dist/src/managers/tools/release_mcp_server_connection.d.ts +3 -3
- package/dist/src/managers/tools/release_mcp_server_connection.d.ts.map +1 -1
- package/dist/src/managers/types.d.ts +3 -3
- package/dist/src/managers/types.d.ts.map +1 -1
- package/dist/src/oauth-helper.d.ts.map +1 -1
- package/dist/src/observability/index.d.ts +3 -3
- package/dist/src/observability/index.d.ts.map +1 -1
- package/dist/src/observability/langfuse.d.ts +1 -1
- package/dist/src/observability/langfuse.d.ts.map +1 -1
- package/dist/src/observability/manager.d.ts +1 -1
- package/dist/src/observability/manager.d.ts.map +1 -1
- package/dist/src/observability/types.d.ts +1 -1
- package/dist/src/observability/types.d.ts.map +1 -1
- package/dist/src/react/index.cjs +295 -154
- package/dist/src/react/index.d.ts +6 -6
- package/dist/src/react/index.d.ts.map +1 -1
- package/dist/src/react/index.js +3 -3
- package/dist/src/react/types.d.ts +6 -6
- package/dist/src/react/types.d.ts.map +1 -1
- package/dist/src/react/useMcp.d.ts +1 -1
- package/dist/src/react/useMcp.d.ts.map +1 -1
- package/dist/src/react/useWidget.d.ts +5 -2
- package/dist/src/react/useWidget.d.ts.map +1 -1
- package/dist/src/react/widget-types.d.ts +3 -3
- package/dist/src/react/widget-types.d.ts.map +1 -1
- package/dist/src/server/adapters/mcp-ui-adapter.d.ts +3 -3
- package/dist/src/server/adapters/mcp-ui-adapter.d.ts.map +1 -1
- package/dist/src/server/index.cjs +170 -50
- package/dist/src/server/index.d.ts +4 -4
- package/dist/src/server/index.d.ts.map +1 -1
- package/dist/src/server/index.js +174 -51
- package/dist/src/server/logging.d.ts +1 -1
- package/dist/src/server/logging.d.ts.map +1 -1
- package/dist/src/server/mcp-server.d.ts +29 -29
- package/dist/src/server/mcp-server.d.ts.map +1 -1
- package/dist/src/server/types/common.d.ts +2 -2
- package/dist/src/server/types/common.d.ts.map +1 -1
- package/dist/src/server/types/index.d.ts +4 -4
- package/dist/src/server/types/index.d.ts.map +1 -1
- package/dist/src/server/types/prompt.d.ts +2 -2
- package/dist/src/server/types/prompt.d.ts.map +1 -1
- package/dist/src/server/types/resource.d.ts +24 -24
- package/dist/src/server/types/resource.d.ts.map +1 -1
- package/dist/src/server/types/tool.d.ts +3 -3
- package/dist/src/server/types/tool.d.ts.map +1 -1
- package/dist/src/server/types/widget.d.ts +1 -1
- package/dist/src/server/types.d.ts +1 -1
- package/dist/src/server/types.d.ts.map +1 -1
- package/dist/src/session.d.ts +1 -1
- package/dist/src/session.d.ts.map +1 -1
- package/dist/src/task_managers/base.d.ts.map +1 -1
- package/dist/src/task_managers/index.d.ts +5 -5
- package/dist/src/task_managers/index.d.ts.map +1 -1
- package/dist/src/task_managers/sse.d.ts +3 -3
- package/dist/src/task_managers/sse.d.ts.map +1 -1
- package/dist/src/task_managers/stdio.d.ts +4 -4
- package/dist/src/task_managers/stdio.d.ts.map +1 -1
- package/dist/src/task_managers/streamable_http.d.ts +3 -3
- package/dist/src/task_managers/streamable_http.d.ts.map +1 -1
- package/dist/src/task_managers/websocket.d.ts +2 -2
- package/dist/src/task_managers/websocket.d.ts.map +1 -1
- package/dist/src/telemetry/events.d.ts.map +1 -1
- package/dist/src/telemetry/index.d.ts +4 -4
- package/dist/src/telemetry/index.d.ts.map +1 -1
- package/dist/src/telemetry/telemetry.d.ts +1 -1
- package/dist/src/telemetry/telemetry.d.ts.map +1 -1
- package/dist/src/telemetry/utils.d.ts +1 -1
- package/dist/src/telemetry/utils.d.ts.map +1 -1
- package/dist/tsup.config.d.ts.map +1 -1
- package/dist/vitest.config.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/src/browser.cjs
CHANGED
|
@@ -90,7 +90,15 @@ var init_logging = __esm({
|
|
|
90
90
|
this._level = level;
|
|
91
91
|
}
|
|
92
92
|
shouldLog(level) {
|
|
93
|
-
const levels = [
|
|
93
|
+
const levels = [
|
|
94
|
+
"error",
|
|
95
|
+
"warn",
|
|
96
|
+
"info",
|
|
97
|
+
"http",
|
|
98
|
+
"verbose",
|
|
99
|
+
"debug",
|
|
100
|
+
"silly"
|
|
101
|
+
];
|
|
94
102
|
const currentIndex = levels.indexOf(this._level);
|
|
95
103
|
const messageIndex = levels.indexOf(level);
|
|
96
104
|
return messageIndex <= currentIndex;
|
|
@@ -163,7 +171,10 @@ var init_logging = __esm({
|
|
|
163
171
|
if (!isNodeJSEnvironment()) {
|
|
164
172
|
if (!this.simpleInstances[name]) {
|
|
165
173
|
const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || void 0;
|
|
166
|
-
this.simpleInstances[name] = new SimpleConsoleLogger(
|
|
174
|
+
this.simpleInstances[name] = new SimpleConsoleLogger(
|
|
175
|
+
name,
|
|
176
|
+
resolveLevel(debugEnv)
|
|
177
|
+
);
|
|
167
178
|
}
|
|
168
179
|
return this.simpleInstances[name];
|
|
169
180
|
}
|
|
@@ -237,10 +248,8 @@ var init_logging = __esm({
|
|
|
237
248
|
}
|
|
238
249
|
static setDebug(enabled) {
|
|
239
250
|
let level;
|
|
240
|
-
if (enabled === 2 || enabled === true)
|
|
241
|
-
|
|
242
|
-
else if (enabled === 1)
|
|
243
|
-
level = "info";
|
|
251
|
+
if (enabled === 2 || enabled === true) level = "debug";
|
|
252
|
+
else if (enabled === 1) level = "info";
|
|
244
253
|
else level = "info";
|
|
245
254
|
Object.values(this.simpleInstances).forEach((logger2) => {
|
|
246
255
|
logger2.level = level;
|
|
@@ -280,7 +289,9 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
|
|
|
280
289
|
try {
|
|
281
290
|
const langfuseModule = await import("langfuse-langchain").catch(() => null);
|
|
282
291
|
if (!langfuseModule) {
|
|
283
|
-
logger.debug(
|
|
292
|
+
logger.debug(
|
|
293
|
+
"Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain"
|
|
294
|
+
);
|
|
284
295
|
return;
|
|
285
296
|
}
|
|
286
297
|
const { CallbackHandler } = langfuseModule;
|
|
@@ -309,10 +320,23 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
|
|
|
309
320
|
const enhancedTags = [...tags || [], ...customTags];
|
|
310
321
|
const enhancedMetadata = { ...metadata2 || {}, ...metadataToAdd };
|
|
311
322
|
if (this.verbose) {
|
|
312
|
-
logger.debug(
|
|
313
|
-
|
|
323
|
+
logger.debug(
|
|
324
|
+
`Langfuse: Chain start with custom tags: ${JSON.stringify(enhancedTags)}`
|
|
325
|
+
);
|
|
326
|
+
logger.debug(
|
|
327
|
+
`Langfuse: Chain start with metadata: ${JSON.stringify(enhancedMetadata)}`
|
|
328
|
+
);
|
|
314
329
|
}
|
|
315
|
-
return super.handleChainStart(
|
|
330
|
+
return super.handleChainStart(
|
|
331
|
+
chain,
|
|
332
|
+
inputs,
|
|
333
|
+
runId,
|
|
334
|
+
parentRunId,
|
|
335
|
+
enhancedTags,
|
|
336
|
+
enhancedMetadata,
|
|
337
|
+
name,
|
|
338
|
+
kwargs
|
|
339
|
+
);
|
|
316
340
|
}
|
|
317
341
|
// Get custom tags based on environment and agent configuration
|
|
318
342
|
getCustomTags() {
|
|
@@ -388,7 +412,9 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
|
|
|
388
412
|
async handleRetrieverStart(...args) {
|
|
389
413
|
logger.debug("Langfuse: Retriever start intercepted");
|
|
390
414
|
if (this.verbose) {
|
|
391
|
-
logger.debug(
|
|
415
|
+
logger.debug(
|
|
416
|
+
`Langfuse: Retriever start args: ${JSON.stringify(args)}`
|
|
417
|
+
);
|
|
392
418
|
}
|
|
393
419
|
return super.handleRetrieverStart(...args);
|
|
394
420
|
}
|
|
@@ -414,9 +440,13 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
|
|
|
414
440
|
secretKey: process.env.LANGFUSE_SECRET_KEY,
|
|
415
441
|
baseUrl: process.env.LANGFUSE_HOST || process.env.LANGFUSE_BASEURL || "https://cloud.langfuse.com",
|
|
416
442
|
flushAt: Number.parseInt(process.env.LANGFUSE_FLUSH_AT || "15"),
|
|
417
|
-
flushInterval: Number.parseInt(
|
|
443
|
+
flushInterval: Number.parseInt(
|
|
444
|
+
process.env.LANGFUSE_FLUSH_INTERVAL || "10000"
|
|
445
|
+
),
|
|
418
446
|
release: process.env.LANGFUSE_RELEASE,
|
|
419
|
-
requestTimeout: Number.parseInt(
|
|
447
|
+
requestTimeout: Number.parseInt(
|
|
448
|
+
process.env.LANGFUSE_REQUEST_TIMEOUT || "10000"
|
|
449
|
+
),
|
|
420
450
|
enabled: process.env.LANGFUSE_ENABLED !== "false",
|
|
421
451
|
// Set trace name - can be customized via metadata.trace_name or defaults to 'mcp-use-agent'
|
|
422
452
|
traceName: initialMetadata.trace_name || process.env.LANGFUSE_TRACE_NAME || "mcp-use-agent",
|
|
@@ -426,14 +456,29 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
|
|
|
426
456
|
tags: initialTags.length > 0 ? initialTags : void 0,
|
|
427
457
|
metadata: initialMetadata || void 0
|
|
428
458
|
};
|
|
429
|
-
logger.debug(
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
459
|
+
logger.debug(
|
|
460
|
+
"Langfuse handler config:",
|
|
461
|
+
JSON.stringify(
|
|
462
|
+
{
|
|
463
|
+
traceName: config2.traceName,
|
|
464
|
+
sessionId: config2.sessionId,
|
|
465
|
+
userId: config2.userId,
|
|
466
|
+
tags: config2.tags
|
|
467
|
+
},
|
|
468
|
+
null,
|
|
469
|
+
2
|
|
470
|
+
)
|
|
471
|
+
);
|
|
472
|
+
langfuseState.handler = new LoggingCallbackHandler(
|
|
473
|
+
config2,
|
|
474
|
+
agentId,
|
|
475
|
+
metadata,
|
|
476
|
+
metadataProvider,
|
|
477
|
+
tagsProvider
|
|
478
|
+
);
|
|
479
|
+
logger.debug(
|
|
480
|
+
"Langfuse observability initialized successfully with logging enabled"
|
|
481
|
+
);
|
|
437
482
|
try {
|
|
438
483
|
const langfuseCore = await import("langfuse").catch(() => null);
|
|
439
484
|
if (langfuseCore) {
|
|
@@ -467,7 +512,9 @@ var init_langfuse = __esm({
|
|
|
467
512
|
};
|
|
468
513
|
__name(initializeLangfuse, "initializeLangfuse");
|
|
469
514
|
if (langfuseDisabled) {
|
|
470
|
-
logger.debug(
|
|
515
|
+
logger.debug(
|
|
516
|
+
"Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"
|
|
517
|
+
);
|
|
471
518
|
} else if (!process.env.LANGFUSE_PUBLIC_KEY || !process.env.LANGFUSE_SECRET_KEY) {
|
|
472
519
|
logger.debug(
|
|
473
520
|
"Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"
|
|
@@ -605,7 +652,9 @@ var ConnectionManager = class {
|
|
|
605
652
|
try {
|
|
606
653
|
await this.closeConnection(this._connection);
|
|
607
654
|
} catch (closeErr) {
|
|
608
|
-
logger.warn(
|
|
655
|
+
logger.warn(
|
|
656
|
+
`Error closing connection in ${this.constructor.name}: ${closeErr}`
|
|
657
|
+
);
|
|
609
658
|
}
|
|
610
659
|
this._connection = null;
|
|
611
660
|
}
|
|
@@ -773,7 +822,10 @@ var BaseConnector = class {
|
|
|
773
822
|
logger.debug("Caching server capabilities & tools");
|
|
774
823
|
const capabilities = this.client.getServerCapabilities();
|
|
775
824
|
this.capabilitiesCache = capabilities;
|
|
776
|
-
const listToolsRes = await this.client.listTools(
|
|
825
|
+
const listToolsRes = await this.client.listTools(
|
|
826
|
+
void 0,
|
|
827
|
+
defaultRequestOptions
|
|
828
|
+
);
|
|
777
829
|
this.toolsCache = listToolsRes.tools ?? [];
|
|
778
830
|
logger.debug(`Fetched ${this.toolsCache.length} tools from server`);
|
|
779
831
|
logger.debug("Server capabilities:", capabilities);
|
|
@@ -792,7 +844,11 @@ var BaseConnector = class {
|
|
|
792
844
|
throw new Error("MCP client is not connected");
|
|
793
845
|
}
|
|
794
846
|
logger.debug(`Calling tool '${name}' with args`, args);
|
|
795
|
-
const res = await this.client.callTool(
|
|
847
|
+
const res = await this.client.callTool(
|
|
848
|
+
{ name, arguments: args },
|
|
849
|
+
void 0,
|
|
850
|
+
options
|
|
851
|
+
);
|
|
796
852
|
logger.debug(`Tool '${name}' returned`, res);
|
|
797
853
|
return res;
|
|
798
854
|
}
|
|
@@ -922,7 +978,11 @@ var BaseConnector = class {
|
|
|
922
978
|
throw new Error("MCP client is not connected");
|
|
923
979
|
}
|
|
924
980
|
logger.debug(`Sending raw request '${method}' with params`, params);
|
|
925
|
-
return await this.client.request(
|
|
981
|
+
return await this.client.request(
|
|
982
|
+
{ method, params: params ?? {} },
|
|
983
|
+
void 0,
|
|
984
|
+
options
|
|
985
|
+
);
|
|
926
986
|
}
|
|
927
987
|
/**
|
|
928
988
|
* Helper to tear down the client & connection manager safely.
|
|
@@ -981,7 +1041,10 @@ var HttpConnector = class extends BaseConnector {
|
|
|
981
1041
|
}
|
|
982
1042
|
this.timeout = opts.timeout ?? 3e4;
|
|
983
1043
|
this.sseReadTimeout = opts.sseReadTimeout ?? 3e5;
|
|
984
|
-
this.clientInfo = opts.clientInfo ?? {
|
|
1044
|
+
this.clientInfo = opts.clientInfo ?? {
|
|
1045
|
+
name: "http-connector",
|
|
1046
|
+
version: "1.0.0"
|
|
1047
|
+
};
|
|
985
1048
|
this.preferSse = opts.preferSse ?? false;
|
|
986
1049
|
}
|
|
987
1050
|
/** Establish connection to the MCP implementation via HTTP (streamable or SSE). */
|
|
@@ -1052,29 +1115,28 @@ var HttpConnector = class extends BaseConnector {
|
|
|
1052
1115
|
authError.code = 401;
|
|
1053
1116
|
throw authError;
|
|
1054
1117
|
}
|
|
1055
|
-
throw new Error(
|
|
1118
|
+
throw new Error(
|
|
1119
|
+
"Could not connect to server with any available transport"
|
|
1120
|
+
);
|
|
1056
1121
|
}
|
|
1057
1122
|
}
|
|
1058
1123
|
}
|
|
1059
1124
|
async connectWithStreamableHttp(baseUrl) {
|
|
1060
1125
|
try {
|
|
1061
|
-
this.connectionManager = new StreamableHttpConnectionManager(
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
reconnectionDelayGrowFactor: 1.5,
|
|
1074
|
-
maxRetries: 2
|
|
1075
|
-
}
|
|
1126
|
+
this.connectionManager = new StreamableHttpConnectionManager(baseUrl, {
|
|
1127
|
+
authProvider: this.opts.authProvider,
|
|
1128
|
+
// ← Pass OAuth provider to SDK
|
|
1129
|
+
requestInit: {
|
|
1130
|
+
headers: this.headers
|
|
1131
|
+
},
|
|
1132
|
+
// Pass through timeout and other options
|
|
1133
|
+
reconnectionOptions: {
|
|
1134
|
+
maxReconnectionDelay: 3e4,
|
|
1135
|
+
initialReconnectionDelay: 1e3,
|
|
1136
|
+
reconnectionDelayGrowFactor: 1.5,
|
|
1137
|
+
maxRetries: 2
|
|
1076
1138
|
}
|
|
1077
|
-
);
|
|
1139
|
+
});
|
|
1078
1140
|
const transport = await this.connectionManager.start();
|
|
1079
1141
|
this.client = new import_client.Client(this.clientInfo, this.opts.clientOptions);
|
|
1080
1142
|
try {
|
|
@@ -1083,7 +1145,9 @@ var HttpConnector = class extends BaseConnector {
|
|
|
1083
1145
|
if (connectErr instanceof Error) {
|
|
1084
1146
|
const errMsg = connectErr.message || connectErr.toString();
|
|
1085
1147
|
if (errMsg.includes("Missing session ID") || errMsg.includes("Bad Request: Missing session ID")) {
|
|
1086
|
-
const wrappedError = new Error(
|
|
1148
|
+
const wrappedError = new Error(
|
|
1149
|
+
`FastMCP session ID error: ${errMsg}`
|
|
1150
|
+
);
|
|
1087
1151
|
wrappedError.cause = connectErr;
|
|
1088
1152
|
throw wrappedError;
|
|
1089
1153
|
}
|
|
@@ -1092,7 +1156,9 @@ var HttpConnector = class extends BaseConnector {
|
|
|
1092
1156
|
}
|
|
1093
1157
|
this.connected = true;
|
|
1094
1158
|
this.transportType = "streamable-http";
|
|
1095
|
-
logger.debug(
|
|
1159
|
+
logger.debug(
|
|
1160
|
+
`Successfully connected to MCP implementation via streamable HTTP: ${baseUrl}`
|
|
1161
|
+
);
|
|
1096
1162
|
} catch (err) {
|
|
1097
1163
|
await this.cleanupResources();
|
|
1098
1164
|
throw err;
|
|
@@ -1100,20 +1166,19 @@ var HttpConnector = class extends BaseConnector {
|
|
|
1100
1166
|
}
|
|
1101
1167
|
async connectWithSse(baseUrl) {
|
|
1102
1168
|
try {
|
|
1103
|
-
this.connectionManager = new SseConnectionManager(
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
requestInit: {
|
|
1107
|
-
headers: this.headers
|
|
1108
|
-
}
|
|
1169
|
+
this.connectionManager = new SseConnectionManager(baseUrl, {
|
|
1170
|
+
requestInit: {
|
|
1171
|
+
headers: this.headers
|
|
1109
1172
|
}
|
|
1110
|
-
);
|
|
1173
|
+
});
|
|
1111
1174
|
const transport = await this.connectionManager.start();
|
|
1112
1175
|
this.client = new import_client.Client(this.clientInfo, this.opts.clientOptions);
|
|
1113
1176
|
await this.client.connect(transport);
|
|
1114
1177
|
this.connected = true;
|
|
1115
1178
|
this.transportType = "sse";
|
|
1116
|
-
logger.debug(
|
|
1179
|
+
logger.debug(
|
|
1180
|
+
`Successfully connected to MCP implementation via HTTP/SSE: ${baseUrl}`
|
|
1181
|
+
);
|
|
1117
1182
|
} catch (err) {
|
|
1118
1183
|
await this.cleanupResources();
|
|
1119
1184
|
throw err;
|
|
@@ -1161,7 +1226,9 @@ var WebSocketConnectionManager = class extends ConnectionManager {
|
|
|
1161
1226
|
async establishConnection() {
|
|
1162
1227
|
logger.debug(`Connecting to WebSocket: ${this.url}`);
|
|
1163
1228
|
return new Promise((resolve, reject) => {
|
|
1164
|
-
const ws = new import_ws.default(this.url, {
|
|
1229
|
+
const ws = new import_ws.default(this.url, {
|
|
1230
|
+
headers: this.headers
|
|
1231
|
+
});
|
|
1165
1232
|
this._ws = ws;
|
|
1166
1233
|
const onOpen = /* @__PURE__ */ __name(() => {
|
|
1167
1234
|
cleanup();
|
|
@@ -1221,8 +1288,7 @@ var WebSocketConnector = class extends BaseConnector {
|
|
|
1221
1288
|
super();
|
|
1222
1289
|
this.url = url;
|
|
1223
1290
|
this.headers = { ...opts.headers ?? {} };
|
|
1224
|
-
if (opts.authToken)
|
|
1225
|
-
this.headers.Authorization = `Bearer ${opts.authToken}`;
|
|
1291
|
+
if (opts.authToken) this.headers.Authorization = `Bearer ${opts.authToken}`;
|
|
1226
1292
|
}
|
|
1227
1293
|
async connect() {
|
|
1228
1294
|
if (this.connected) {
|
|
@@ -1231,7 +1297,10 @@ var WebSocketConnector = class extends BaseConnector {
|
|
|
1231
1297
|
}
|
|
1232
1298
|
logger.debug(`Connecting via WebSocket: ${this.url}`);
|
|
1233
1299
|
try {
|
|
1234
|
-
this.connectionManager = new WebSocketConnectionManager(
|
|
1300
|
+
this.connectionManager = new WebSocketConnectionManager(
|
|
1301
|
+
this.url,
|
|
1302
|
+
this.headers
|
|
1303
|
+
);
|
|
1235
1304
|
this.ws = await this.connectionManager.start();
|
|
1236
1305
|
this.receiverTask = this.receiveLoop();
|
|
1237
1306
|
this.connected = true;
|
|
@@ -1252,8 +1321,7 @@ var WebSocketConnector = class extends BaseConnector {
|
|
|
1252
1321
|
this.connected = false;
|
|
1253
1322
|
}
|
|
1254
1323
|
sendRequest(method, params = null) {
|
|
1255
|
-
if (!this.ws)
|
|
1256
|
-
throw new Error("WebSocket is not connected");
|
|
1324
|
+
if (!this.ws) throw new Error("WebSocket is not connected");
|
|
1257
1325
|
const id = (0, import_uuid.v4)();
|
|
1258
1326
|
const payload = JSON.stringify({ id, method, params: params ?? {} });
|
|
1259
1327
|
return new Promise((resolve, reject) => {
|
|
@@ -1267,8 +1335,7 @@ var WebSocketConnector = class extends BaseConnector {
|
|
|
1267
1335
|
});
|
|
1268
1336
|
}
|
|
1269
1337
|
async receiveLoop() {
|
|
1270
|
-
if (!this.ws)
|
|
1271
|
-
return;
|
|
1338
|
+
if (!this.ws) return;
|
|
1272
1339
|
const socket = this.ws;
|
|
1273
1340
|
const onMessage = /* @__PURE__ */ __name((msg) => {
|
|
1274
1341
|
let data;
|
|
@@ -1282,10 +1349,8 @@ var WebSocketConnector = class extends BaseConnector {
|
|
|
1282
1349
|
if (id && this.pending.has(id)) {
|
|
1283
1350
|
const { resolve, reject } = this.pending.get(id);
|
|
1284
1351
|
this.pending.delete(id);
|
|
1285
|
-
if ("result" in data)
|
|
1286
|
-
|
|
1287
|
-
else if ("error" in data)
|
|
1288
|
-
reject(data.error);
|
|
1352
|
+
if ("result" in data) resolve(data.result);
|
|
1353
|
+
else if ("error" in data) reject(data.error);
|
|
1289
1354
|
} else {
|
|
1290
1355
|
logger.debug("Received unsolicited message", data);
|
|
1291
1356
|
}
|
|
@@ -1343,14 +1408,12 @@ var WebSocketConnector = class extends BaseConnector {
|
|
|
1343
1408
|
return await this.sendRequest(method, params);
|
|
1344
1409
|
}
|
|
1345
1410
|
get tools() {
|
|
1346
|
-
if (!this.toolsCache)
|
|
1347
|
-
throw new Error("MCP client is not initialized");
|
|
1411
|
+
if (!this.toolsCache) throw new Error("MCP client is not initialized");
|
|
1348
1412
|
return this.toolsCache;
|
|
1349
1413
|
}
|
|
1350
1414
|
async cleanupResources() {
|
|
1351
|
-
if (this.receiverTask)
|
|
1352
|
-
|
|
1353
|
-
});
|
|
1415
|
+
if (this.receiverTask) await this.receiverTask.catch(() => {
|
|
1416
|
+
});
|
|
1354
1417
|
this.receiverTask = null;
|
|
1355
1418
|
this.rejectAll(new Error("WebSocket disconnected"));
|
|
1356
1419
|
if (this.connectionManager) {
|
|
@@ -1478,7 +1541,9 @@ var BaseMCPClient = class {
|
|
|
1478
1541
|
async closeSession(serverName) {
|
|
1479
1542
|
const session = this.sessions[serverName];
|
|
1480
1543
|
if (!session) {
|
|
1481
|
-
logger.warn(
|
|
1544
|
+
logger.warn(
|
|
1545
|
+
`No session exists for server ${serverName}, nothing to close`
|
|
1546
|
+
);
|
|
1482
1547
|
return;
|
|
1483
1548
|
}
|
|
1484
1549
|
try {
|
|
@@ -1505,7 +1570,9 @@ var BaseMCPClient = class {
|
|
|
1505
1570
|
}
|
|
1506
1571
|
}
|
|
1507
1572
|
if (errors.length) {
|
|
1508
|
-
logger.error(
|
|
1573
|
+
logger.error(
|
|
1574
|
+
`Encountered ${errors.length} errors while closing sessions`
|
|
1575
|
+
);
|
|
1509
1576
|
} else {
|
|
1510
1577
|
logger.debug("All sessions closed successfully");
|
|
1511
1578
|
}
|
|
@@ -1703,9 +1770,14 @@ var LangChainAdapter = class extends BaseAdapter {
|
|
|
1703
1770
|
// Blank is acceptable but discouraged.
|
|
1704
1771
|
schema: argsSchema,
|
|
1705
1772
|
func: /* @__PURE__ */ __name(async (input) => {
|
|
1706
|
-
logger.debug(
|
|
1773
|
+
logger.debug(
|
|
1774
|
+
`MCP tool "${mcpTool.name}" received input: ${JSON.stringify(input)}`
|
|
1775
|
+
);
|
|
1707
1776
|
try {
|
|
1708
|
-
const result = await connector.callTool(
|
|
1777
|
+
const result = await connector.callTool(
|
|
1778
|
+
mcpTool.name,
|
|
1779
|
+
input
|
|
1780
|
+
);
|
|
1709
1781
|
return JSON.stringify(result);
|
|
1710
1782
|
} catch (err) {
|
|
1711
1783
|
logger.error(`Error executing MCP tool: ${err.message}`);
|
|
@@ -1865,7 +1937,9 @@ var ConnectMCPServerTool = class extends MCPServerTool {
|
|
|
1865
1937
|
const numTools = serverTools.length;
|
|
1866
1938
|
return `Connected to MCP server '${serverName}'. ${numTools} tools are now available.`;
|
|
1867
1939
|
} catch (error) {
|
|
1868
|
-
logger.error(
|
|
1940
|
+
logger.error(
|
|
1941
|
+
`Error connecting to server '${serverName}': ${String(error)}`
|
|
1942
|
+
);
|
|
1869
1943
|
return `Failed to connect to server '${serverName}': ${String(error)}`;
|
|
1870
1944
|
}
|
|
1871
1945
|
}
|
|
@@ -1901,7 +1975,9 @@ var ListMCPServersTool = class extends MCPServerTool {
|
|
|
1901
1975
|
outputLines.push(`${numberOfTools} tools available for this server
|
|
1902
1976
|
`);
|
|
1903
1977
|
} catch (error) {
|
|
1904
|
-
logger.error(
|
|
1978
|
+
logger.error(
|
|
1979
|
+
`Unexpected error listing tools for server '${serverName}': ${String(error)}`
|
|
1980
|
+
);
|
|
1905
1981
|
}
|
|
1906
1982
|
}
|
|
1907
1983
|
return outputLines.join("\n");
|
|
@@ -1962,10 +2038,10 @@ var ServerManager = class {
|
|
|
1962
2038
|
}
|
|
1963
2039
|
const tableData = allServerNames.map((name) => ({
|
|
1964
2040
|
"Server Name": name,
|
|
1965
|
-
|
|
1966
|
-
|
|
2041
|
+
Connected: activeSessionNames.includes(name) ? "\u2705" : "\u274C",
|
|
2042
|
+
Initialized: this.initializedServers[name] ? "\u2705" : "\u274C",
|
|
1967
2043
|
"Tool Count": this.serverTools[name]?.length ?? 0,
|
|
1968
|
-
|
|
2044
|
+
Active: this.activeServer === name ? "\u2705" : "\u274C"
|
|
1969
2045
|
}));
|
|
1970
2046
|
logger.info(`Server Manager State: [${context}]`);
|
|
1971
2047
|
console.table(tableData);
|
|
@@ -1982,13 +2058,19 @@ var ServerManager = class {
|
|
|
1982
2058
|
try {
|
|
1983
2059
|
let session = null;
|
|
1984
2060
|
session = this.client.getSession(serverName);
|
|
1985
|
-
logger.debug(
|
|
2061
|
+
logger.debug(
|
|
2062
|
+
`Using existing session for server '${serverName}' to prefetch tools.`
|
|
2063
|
+
);
|
|
1986
2064
|
if (!session) {
|
|
1987
2065
|
session = await this.client.createSession(serverName).catch((createSessionError) => {
|
|
1988
|
-
logger.warn(
|
|
2066
|
+
logger.warn(
|
|
2067
|
+
`Could not create session for '${serverName}' during prefetch: ${createSessionError}`
|
|
2068
|
+
);
|
|
1989
2069
|
return null;
|
|
1990
2070
|
});
|
|
1991
|
-
logger.debug(
|
|
2071
|
+
logger.debug(
|
|
2072
|
+
`Temporarily created session for '${serverName}' to prefetch tools.`
|
|
2073
|
+
);
|
|
1992
2074
|
}
|
|
1993
2075
|
if (session) {
|
|
1994
2076
|
const connector = session.connector;
|
|
@@ -1996,7 +2078,9 @@ var ServerManager = class {
|
|
|
1996
2078
|
try {
|
|
1997
2079
|
tools = await this.adapter.createToolsFromConnectors([connector]);
|
|
1998
2080
|
} catch (toolFetchError) {
|
|
1999
|
-
logger.error(
|
|
2081
|
+
logger.error(
|
|
2082
|
+
`Failed to create tools from connector for server '${serverName}': ${toolFetchError}`
|
|
2083
|
+
);
|
|
2000
2084
|
continue;
|
|
2001
2085
|
}
|
|
2002
2086
|
const cachedTools = this.serverTools[serverName];
|
|
@@ -2004,7 +2088,9 @@ var ServerManager = class {
|
|
|
2004
2088
|
if (toolsChanged) {
|
|
2005
2089
|
this.serverTools[serverName] = tools;
|
|
2006
2090
|
this.initializedServers[serverName] = true;
|
|
2007
|
-
logger.debug(
|
|
2091
|
+
logger.debug(
|
|
2092
|
+
`Prefetched ${tools.length} tools for server '${serverName}'.`
|
|
2093
|
+
);
|
|
2008
2094
|
} else {
|
|
2009
2095
|
logger.debug(
|
|
2010
2096
|
`Tools for server '${serverName}' unchanged, using cached version.`
|
|
@@ -2012,7 +2098,9 @@ var ServerManager = class {
|
|
|
2012
2098
|
}
|
|
2013
2099
|
}
|
|
2014
2100
|
} catch (outerError) {
|
|
2015
|
-
logger.error(
|
|
2101
|
+
logger.error(
|
|
2102
|
+
`Error prefetching tools for server '${serverName}': ${outerError}`
|
|
2103
|
+
);
|
|
2016
2104
|
}
|
|
2017
2105
|
}
|
|
2018
2106
|
}
|
|
@@ -2078,8 +2166,15 @@ var ObservabilityManager = class {
|
|
|
2078
2166
|
const { langfuseHandler: langfuseHandler2, langfuseInitPromise: langfuseInitPromise2 } = await Promise.resolve().then(() => (init_langfuse(), langfuse_exports));
|
|
2079
2167
|
if (this.agentId || this.metadata || this.metadataProvider || this.tagsProvider) {
|
|
2080
2168
|
const { initializeLangfuse: initializeLangfuse2 } = await Promise.resolve().then(() => (init_langfuse(), langfuse_exports));
|
|
2081
|
-
await initializeLangfuse2(
|
|
2082
|
-
|
|
2169
|
+
await initializeLangfuse2(
|
|
2170
|
+
this.agentId,
|
|
2171
|
+
this.metadata,
|
|
2172
|
+
this.metadataProvider,
|
|
2173
|
+
this.tagsProvider
|
|
2174
|
+
);
|
|
2175
|
+
logger.debug(
|
|
2176
|
+
`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`
|
|
2177
|
+
);
|
|
2083
2178
|
} else {
|
|
2084
2179
|
const initPromise = langfuseInitPromise2();
|
|
2085
2180
|
if (initPromise) {
|
|
@@ -2103,16 +2198,22 @@ var ObservabilityManager = class {
|
|
|
2103
2198
|
*/
|
|
2104
2199
|
async getCallbacks() {
|
|
2105
2200
|
if (!this.observe) {
|
|
2106
|
-
logger.debug(
|
|
2201
|
+
logger.debug(
|
|
2202
|
+
"ObservabilityManager: Observability disabled via observe=false"
|
|
2203
|
+
);
|
|
2107
2204
|
return [];
|
|
2108
2205
|
}
|
|
2109
2206
|
if (this.customCallbacks) {
|
|
2110
|
-
logger.debug(
|
|
2207
|
+
logger.debug(
|
|
2208
|
+
`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`
|
|
2209
|
+
);
|
|
2111
2210
|
return this.customCallbacks;
|
|
2112
2211
|
}
|
|
2113
2212
|
await this.collectAvailableHandlers();
|
|
2114
2213
|
if (this.availableHandlers.length > 0) {
|
|
2115
|
-
logger.debug(
|
|
2214
|
+
logger.debug(
|
|
2215
|
+
`ObservabilityManager: Using ${this.availableHandlers.length} handlers`
|
|
2216
|
+
);
|
|
2116
2217
|
} else {
|
|
2117
2218
|
logger.debug("ObservabilityManager: No callbacks configured");
|
|
2118
2219
|
}
|
|
@@ -2169,7 +2270,9 @@ var ObservabilityManager = class {
|
|
|
2169
2270
|
this.customCallbacks = [];
|
|
2170
2271
|
}
|
|
2171
2272
|
this.customCallbacks.push(callback);
|
|
2172
|
-
logger.debug(
|
|
2273
|
+
logger.debug(
|
|
2274
|
+
`ObservabilityManager: Added custom callback: ${callback.constructor.name}`
|
|
2275
|
+
);
|
|
2173
2276
|
}
|
|
2174
2277
|
/**
|
|
2175
2278
|
* Clear all custom callbacks.
|
|
@@ -2301,7 +2404,15 @@ function getModelName(llm) {
|
|
|
2301
2404
|
if ("_identifyingParams" in llm) {
|
|
2302
2405
|
const identifyingParams = llm._identifyingParams;
|
|
2303
2406
|
if (typeof identifyingParams === "object" && identifyingParams !== null) {
|
|
2304
|
-
for (const key of [
|
|
2407
|
+
for (const key of [
|
|
2408
|
+
"model",
|
|
2409
|
+
"modelName",
|
|
2410
|
+
"model_name",
|
|
2411
|
+
"modelId",
|
|
2412
|
+
"model_id",
|
|
2413
|
+
"deploymentName",
|
|
2414
|
+
"deployment_name"
|
|
2415
|
+
]) {
|
|
2305
2416
|
if (key in identifyingParams) {
|
|
2306
2417
|
return String(identifyingParams[key]);
|
|
2307
2418
|
}
|
|
@@ -2392,8 +2503,16 @@ var Telemetry = class _Telemetry {
|
|
|
2392
2503
|
__name(this, "Telemetry");
|
|
2393
2504
|
}
|
|
2394
2505
|
static instance = null;
|
|
2395
|
-
USER_ID_PATH = path2.join(
|
|
2396
|
-
|
|
2506
|
+
USER_ID_PATH = path2.join(
|
|
2507
|
+
getCacheHome(),
|
|
2508
|
+
"mcp_use_3",
|
|
2509
|
+
"telemetry_user_id"
|
|
2510
|
+
);
|
|
2511
|
+
VERSION_DOWNLOAD_PATH = path2.join(
|
|
2512
|
+
getCacheHome(),
|
|
2513
|
+
"mcp_use",
|
|
2514
|
+
"download_version"
|
|
2515
|
+
);
|
|
2397
2516
|
PROJECT_API_KEY = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
|
|
2398
2517
|
HOST = "https://eu.i.posthog.com";
|
|
2399
2518
|
SCARF_GATEWAY_URL = "https://mcpuse.gateway.scarf.sh/events-ts";
|
|
@@ -2413,17 +2532,18 @@ var Telemetry = class _Telemetry {
|
|
|
2413
2532
|
} else if (!isNodeJS) {
|
|
2414
2533
|
this._posthogClient = null;
|
|
2415
2534
|
this._scarfClient = null;
|
|
2416
|
-
logger.debug(
|
|
2535
|
+
logger.debug(
|
|
2536
|
+
"Telemetry disabled - non-Node.js environment detected (e.g., Cloudflare Workers)"
|
|
2537
|
+
);
|
|
2417
2538
|
} else {
|
|
2418
|
-
logger.info(
|
|
2539
|
+
logger.info(
|
|
2540
|
+
"Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."
|
|
2541
|
+
);
|
|
2419
2542
|
try {
|
|
2420
|
-
this._posthogClient = new import_posthog_node.PostHog(
|
|
2421
|
-
this.
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
disableGeoip: false
|
|
2425
|
-
}
|
|
2426
|
-
);
|
|
2543
|
+
this._posthogClient = new import_posthog_node.PostHog(this.PROJECT_API_KEY, {
|
|
2544
|
+
host: this.HOST,
|
|
2545
|
+
disableGeoip: false
|
|
2546
|
+
});
|
|
2427
2547
|
} catch (e) {
|
|
2428
2548
|
logger.warn(`Failed to initialize PostHog telemetry: ${e}`);
|
|
2429
2549
|
this._posthogClient = null;
|
|
@@ -2533,7 +2653,9 @@ var Telemetry = class _Telemetry {
|
|
|
2533
2653
|
if (!fs2.existsSync(this.VERSION_DOWNLOAD_PATH)) {
|
|
2534
2654
|
shouldTrack = true;
|
|
2535
2655
|
firstDownload = true;
|
|
2536
|
-
fs2.mkdirSync(path2.dirname(this.VERSION_DOWNLOAD_PATH), {
|
|
2656
|
+
fs2.mkdirSync(path2.dirname(this.VERSION_DOWNLOAD_PATH), {
|
|
2657
|
+
recursive: true
|
|
2658
|
+
});
|
|
2537
2659
|
fs2.writeFileSync(this.VERSION_DOWNLOAD_PATH, currentVersion);
|
|
2538
2660
|
} else {
|
|
2539
2661
|
const savedVersion = fs2.readFileSync(this.VERSION_DOWNLOAD_PATH, "utf-8").trim();
|
|
@@ -2544,7 +2666,9 @@ var Telemetry = class _Telemetry {
|
|
|
2544
2666
|
}
|
|
2545
2667
|
}
|
|
2546
2668
|
if (shouldTrack) {
|
|
2547
|
-
logger.debug(
|
|
2669
|
+
logger.debug(
|
|
2670
|
+
`Tracking package download event with properties: ${JSON.stringify(properties)}`
|
|
2671
|
+
);
|
|
2548
2672
|
const eventProperties = { ...properties || {} };
|
|
2549
2673
|
eventProperties.mcp_use_version = currentVersion;
|
|
2550
2674
|
eventProperties.user_id = this.userId;
|
|
@@ -2596,8 +2720,7 @@ function generateToolDescriptions(tools, disallowedTools) {
|
|
|
2596
2720
|
const disallowedSet = new Set(disallowedTools ?? []);
|
|
2597
2721
|
const descriptions = [];
|
|
2598
2722
|
for (const tool of tools) {
|
|
2599
|
-
if (disallowedSet.has(tool.name))
|
|
2600
|
-
continue;
|
|
2723
|
+
if (disallowedSet.has(tool.name)) continue;
|
|
2601
2724
|
const escaped = tool.description.replace(/\{/g, "{{").replace(/\}/g, "}}");
|
|
2602
2725
|
descriptions.push(`- ${tool.name}: ${escaped}`);
|
|
2603
2726
|
}
|
|
@@ -2610,7 +2733,9 @@ function buildSystemPromptContent(template, toolDescriptionLines, additionalInst
|
|
|
2610
2733
|
if (template.includes("{tool_descriptions}")) {
|
|
2611
2734
|
content = template.replace("{tool_descriptions}", block);
|
|
2612
2735
|
} else {
|
|
2613
|
-
console.warn(
|
|
2736
|
+
console.warn(
|
|
2737
|
+
"`{tool_descriptions}` placeholder not found; appending at end."
|
|
2738
|
+
);
|
|
2614
2739
|
content = `${template}
|
|
2615
2740
|
|
|
2616
2741
|
Available tools:
|
|
@@ -2766,7 +2891,9 @@ var RemoteAgent = class {
|
|
|
2766
2891
|
`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`
|
|
2767
2892
|
);
|
|
2768
2893
|
}
|
|
2769
|
-
throw new Error(
|
|
2894
|
+
throw new Error(
|
|
2895
|
+
`Failed to create chat session: ${statusCode} - ${responseText}`
|
|
2896
|
+
);
|
|
2770
2897
|
}
|
|
2771
2898
|
const chatData = await response.json();
|
|
2772
2899
|
const chatId = chatData.id;
|
|
@@ -2839,8 +2966,12 @@ var RemoteAgent = class {
|
|
|
2839
2966
|
"Internal server error occurred during agent execution. Please try again later or contact support if the issue persists."
|
|
2840
2967
|
);
|
|
2841
2968
|
} else {
|
|
2842
|
-
logger.error(
|
|
2843
|
-
|
|
2969
|
+
logger.error(
|
|
2970
|
+
`\u274C Remote execution failed with status ${statusCode}: ${responseText}`
|
|
2971
|
+
);
|
|
2972
|
+
throw new Error(
|
|
2973
|
+
`Remote agent execution failed: ${statusCode} - ${responseText}`
|
|
2974
|
+
);
|
|
2844
2975
|
}
|
|
2845
2976
|
}
|
|
2846
2977
|
const result = await response.json();
|
|
@@ -2891,7 +3022,13 @@ Raw error: ${result}`
|
|
|
2891
3022
|
}
|
|
2892
3023
|
// eslint-disable-next-line require-yield
|
|
2893
3024
|
async *stream(query, maxSteps, manageConnector, externalHistory, outputSchema) {
|
|
2894
|
-
const result = await this.run(
|
|
3025
|
+
const result = await this.run(
|
|
3026
|
+
query,
|
|
3027
|
+
maxSteps,
|
|
3028
|
+
manageConnector,
|
|
3029
|
+
externalHistory,
|
|
3030
|
+
outputSchema
|
|
3031
|
+
);
|
|
2895
3032
|
return result;
|
|
2896
3033
|
}
|
|
2897
3034
|
async close() {
|
|
@@ -2967,7 +3104,9 @@ var MCPAgent = class {
|
|
|
2967
3104
|
return;
|
|
2968
3105
|
}
|
|
2969
3106
|
if (!options.llm) {
|
|
2970
|
-
throw new Error(
|
|
3107
|
+
throw new Error(
|
|
3108
|
+
"llm is required for local execution. For remote execution, provide agentId instead."
|
|
3109
|
+
);
|
|
2971
3110
|
}
|
|
2972
3111
|
this.llm = options.llm;
|
|
2973
3112
|
this.client = options.client;
|
|
@@ -2985,11 +3124,15 @@ var MCPAgent = class {
|
|
|
2985
3124
|
this.verbose = options.verbose ?? false;
|
|
2986
3125
|
this.observe = options.observe ?? true;
|
|
2987
3126
|
if (!this.client && this.connectors.length === 0) {
|
|
2988
|
-
throw new Error(
|
|
3127
|
+
throw new Error(
|
|
3128
|
+
"Either 'client' or at least one 'connector' must be provided."
|
|
3129
|
+
);
|
|
2989
3130
|
}
|
|
2990
3131
|
if (this.useServerManager) {
|
|
2991
3132
|
if (!this.client) {
|
|
2992
|
-
throw new Error(
|
|
3133
|
+
throw new Error(
|
|
3134
|
+
"'client' must be provided when 'useServerManager' is true."
|
|
3135
|
+
);
|
|
2993
3136
|
}
|
|
2994
3137
|
this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
|
|
2995
3138
|
this.serverManager = options.serverManagerFactory?.(this.client) ?? new ServerManager(this.client, this.adapter);
|
|
@@ -3049,25 +3192,37 @@ var MCPAgent = class {
|
|
|
3049
3192
|
} else {
|
|
3050
3193
|
if (this.client) {
|
|
3051
3194
|
this.sessions = this.client.getAllActiveSessions();
|
|
3052
|
-
logger.info(
|
|
3195
|
+
logger.info(
|
|
3196
|
+
`\u{1F50C} Found ${Object.keys(this.sessions).length} existing sessions`
|
|
3197
|
+
);
|
|
3053
3198
|
if (Object.keys(this.sessions).length === 0) {
|
|
3054
3199
|
logger.info("\u{1F504} No active sessions found, creating new ones...");
|
|
3055
3200
|
this.sessions = await this.client.createAllSessions();
|
|
3056
|
-
logger.info(
|
|
3201
|
+
logger.info(
|
|
3202
|
+
`\u2705 Created ${Object.keys(this.sessions).length} new sessions`
|
|
3203
|
+
);
|
|
3057
3204
|
}
|
|
3058
3205
|
this._tools = await LangChainAdapter.createTools(this.client);
|
|
3059
3206
|
this._tools.push(...this.additionalTools);
|
|
3060
|
-
logger.info(
|
|
3207
|
+
logger.info(
|
|
3208
|
+
`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain tools from client`
|
|
3209
|
+
);
|
|
3061
3210
|
} else {
|
|
3062
|
-
logger.info(
|
|
3211
|
+
logger.info(
|
|
3212
|
+
`\u{1F517} Connecting to ${this.connectors.length} direct connectors...`
|
|
3213
|
+
);
|
|
3063
3214
|
for (const connector of this.connectors) {
|
|
3064
3215
|
if (!connector.isClientConnected) {
|
|
3065
3216
|
await connector.connect();
|
|
3066
3217
|
}
|
|
3067
3218
|
}
|
|
3068
|
-
this._tools = await this.adapter.createToolsFromConnectors(
|
|
3219
|
+
this._tools = await this.adapter.createToolsFromConnectors(
|
|
3220
|
+
this.connectors
|
|
3221
|
+
);
|
|
3069
3222
|
this._tools.push(...this.additionalTools);
|
|
3070
|
-
logger.info(
|
|
3223
|
+
logger.info(
|
|
3224
|
+
`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain tools from connectors`
|
|
3225
|
+
);
|
|
3071
3226
|
}
|
|
3072
3227
|
logger.info(`\u{1F9F0} Found ${this._tools.length} tools across all connectors`);
|
|
3073
3228
|
await this.createSystemMessageFromTools(this._tools);
|
|
@@ -3077,7 +3232,9 @@ var MCPAgent = class {
|
|
|
3077
3232
|
const mcpServerInfo = this.getMCPServerInfo();
|
|
3078
3233
|
if (Object.keys(mcpServerInfo).length > 0) {
|
|
3079
3234
|
this.setMetadata(mcpServerInfo);
|
|
3080
|
-
logger.debug(
|
|
3235
|
+
logger.debug(
|
|
3236
|
+
`MCP server info added to metadata: ${JSON.stringify(mcpServerInfo)}`
|
|
3237
|
+
);
|
|
3081
3238
|
}
|
|
3082
3239
|
logger.info("\u2728 Agent initialization complete");
|
|
3083
3240
|
}
|
|
@@ -3095,7 +3252,9 @@ var MCPAgent = class {
|
|
|
3095
3252
|
if (this.memoryEnabled) {
|
|
3096
3253
|
this.conversationHistory = [
|
|
3097
3254
|
this.systemMessage,
|
|
3098
|
-
...this.conversationHistory.filter(
|
|
3255
|
+
...this.conversationHistory.filter(
|
|
3256
|
+
(m) => !(m instanceof import_langchain2.SystemMessage)
|
|
3257
|
+
)
|
|
3099
3258
|
];
|
|
3100
3259
|
}
|
|
3101
3260
|
}
|
|
@@ -3113,7 +3272,9 @@ var MCPAgent = class {
|
|
|
3113
3272
|
systemPrompt: systemContent,
|
|
3114
3273
|
middleware
|
|
3115
3274
|
});
|
|
3116
|
-
logger.debug(
|
|
3275
|
+
logger.debug(
|
|
3276
|
+
`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`
|
|
3277
|
+
);
|
|
3117
3278
|
return agent;
|
|
3118
3279
|
}
|
|
3119
3280
|
getConversationHistory() {
|
|
@@ -3123,8 +3284,7 @@ var MCPAgent = class {
|
|
|
3123
3284
|
this.conversationHistory = this.memoryEnabled && this.systemMessage ? [this.systemMessage] : [];
|
|
3124
3285
|
}
|
|
3125
3286
|
addToHistory(message) {
|
|
3126
|
-
if (this.memoryEnabled)
|
|
3127
|
-
this.conversationHistory.push(message);
|
|
3287
|
+
if (this.memoryEnabled) this.conversationHistory.push(message);
|
|
3128
3288
|
}
|
|
3129
3289
|
getSystemMessage() {
|
|
3130
3290
|
return this.systemMessage;
|
|
@@ -3132,7 +3292,9 @@ var MCPAgent = class {
|
|
|
3132
3292
|
setSystemMessage(message) {
|
|
3133
3293
|
this.systemMessage = new import_langchain2.SystemMessage(message);
|
|
3134
3294
|
if (this.memoryEnabled) {
|
|
3135
|
-
this.conversationHistory = this.conversationHistory.filter(
|
|
3295
|
+
this.conversationHistory = this.conversationHistory.filter(
|
|
3296
|
+
(m) => !(m instanceof import_langchain2.SystemMessage)
|
|
3297
|
+
);
|
|
3136
3298
|
this.conversationHistory.unshift(this.systemMessage);
|
|
3137
3299
|
}
|
|
3138
3300
|
if (this._initialized && this._tools.length) {
|
|
@@ -3144,7 +3306,9 @@ var MCPAgent = class {
|
|
|
3144
3306
|
this.disallowedTools = disallowedTools;
|
|
3145
3307
|
this.adapter = new LangChainAdapter(this.disallowedTools);
|
|
3146
3308
|
if (this._initialized) {
|
|
3147
|
-
logger.debug(
|
|
3309
|
+
logger.debug(
|
|
3310
|
+
"Agent already initialized. Changes will take effect on next initialization."
|
|
3311
|
+
);
|
|
3148
3312
|
}
|
|
3149
3313
|
}
|
|
3150
3314
|
getDisallowedTools() {
|
|
@@ -3210,16 +3374,22 @@ var MCPAgent = class {
|
|
|
3210
3374
|
try {
|
|
3211
3375
|
const serialized = JSON.stringify(value);
|
|
3212
3376
|
if (serialized.length > 1e3) {
|
|
3213
|
-
logger.warn(
|
|
3377
|
+
logger.warn(
|
|
3378
|
+
`Metadata value for key '${sanitizedKey}' is too large. Truncating.`
|
|
3379
|
+
);
|
|
3214
3380
|
sanitized[sanitizedKey] = `${serialized.substring(0, 1e3)}...`;
|
|
3215
3381
|
} else {
|
|
3216
3382
|
sanitized[sanitizedKey] = value;
|
|
3217
3383
|
}
|
|
3218
3384
|
} catch (error) {
|
|
3219
|
-
logger.warn(
|
|
3385
|
+
logger.warn(
|
|
3386
|
+
`Failed to serialize metadata value for key '${sanitizedKey}': ${error}. Skipping.`
|
|
3387
|
+
);
|
|
3220
3388
|
}
|
|
3221
3389
|
} else {
|
|
3222
|
-
logger.warn(
|
|
3390
|
+
logger.warn(
|
|
3391
|
+
`Unsupported metadata value type for key '${sanitizedKey}': ${typeof value}. Skipping.`
|
|
3392
|
+
);
|
|
3223
3393
|
}
|
|
3224
3394
|
}
|
|
3225
3395
|
return sanitized;
|
|
@@ -3266,15 +3436,24 @@ var MCPAgent = class {
|
|
|
3266
3436
|
};
|
|
3267
3437
|
}
|
|
3268
3438
|
} catch (error) {
|
|
3269
|
-
logger.warn(
|
|
3270
|
-
|
|
3439
|
+
logger.warn(
|
|
3440
|
+
`Failed to get config for server '${serverName}': ${error}`
|
|
3441
|
+
);
|
|
3442
|
+
serverConfigs[serverName] = {
|
|
3443
|
+
type: "error",
|
|
3444
|
+
error: "config_unavailable"
|
|
3445
|
+
};
|
|
3271
3446
|
}
|
|
3272
3447
|
}
|
|
3273
3448
|
serverInfo.mcp_server_configs = serverConfigs;
|
|
3274
3449
|
} else if (this.connectors && this.connectors.length > 0) {
|
|
3275
3450
|
serverInfo.mcp_servers_count = this.connectors.length;
|
|
3276
|
-
serverInfo.mcp_server_names = this.connectors.map(
|
|
3277
|
-
|
|
3451
|
+
serverInfo.mcp_server_names = this.connectors.map(
|
|
3452
|
+
(c) => c.publicIdentifier
|
|
3453
|
+
);
|
|
3454
|
+
serverInfo.mcp_server_types = this.connectors.map(
|
|
3455
|
+
(c) => c.constructor.name
|
|
3456
|
+
);
|
|
3278
3457
|
}
|
|
3279
3458
|
} catch (error) {
|
|
3280
3459
|
logger.warn(`Failed to collect MCP server info: ${error}`);
|
|
@@ -3328,7 +3507,13 @@ var MCPAgent = class {
|
|
|
3328
3507
|
}
|
|
3329
3508
|
async run(query, maxSteps, manageConnector, externalHistory, outputSchema) {
|
|
3330
3509
|
if (this.isRemote && this.remoteAgent) {
|
|
3331
|
-
return this.remoteAgent.run(
|
|
3510
|
+
return this.remoteAgent.run(
|
|
3511
|
+
query,
|
|
3512
|
+
maxSteps,
|
|
3513
|
+
manageConnector,
|
|
3514
|
+
externalHistory,
|
|
3515
|
+
outputSchema
|
|
3516
|
+
);
|
|
3332
3517
|
}
|
|
3333
3518
|
const generator = this.stream(
|
|
3334
3519
|
query,
|
|
@@ -3341,7 +3526,13 @@ var MCPAgent = class {
|
|
|
3341
3526
|
}
|
|
3342
3527
|
async *stream(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
|
|
3343
3528
|
if (this.isRemote && this.remoteAgent) {
|
|
3344
|
-
const result = await this.remoteAgent.run(
|
|
3529
|
+
const result = await this.remoteAgent.run(
|
|
3530
|
+
query,
|
|
3531
|
+
maxSteps,
|
|
3532
|
+
manageConnector,
|
|
3533
|
+
externalHistory,
|
|
3534
|
+
outputSchema
|
|
3535
|
+
);
|
|
3345
3536
|
return result;
|
|
3346
3537
|
}
|
|
3347
3538
|
let initializedHere = false;
|
|
@@ -3386,27 +3577,31 @@ var MCPAgent = class {
|
|
|
3386
3577
|
logger.info("\u{1F3C1} Starting agent execution");
|
|
3387
3578
|
const maxRestarts = 3;
|
|
3388
3579
|
let restartCount = 0;
|
|
3389
|
-
const accumulatedMessages = [
|
|
3580
|
+
const accumulatedMessages = [
|
|
3581
|
+
...langchainHistory,
|
|
3582
|
+
new import_langchain2.HumanMessage(query)
|
|
3583
|
+
];
|
|
3390
3584
|
while (restartCount <= maxRestarts) {
|
|
3391
3585
|
const inputs = { messages: accumulatedMessages };
|
|
3392
3586
|
let shouldRestart = false;
|
|
3393
|
-
const stream = await this._agentExecutor.stream(
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3399
|
-
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
...this.metadata.session_id && { sessionId: this.metadata.session_id }
|
|
3587
|
+
const stream = await this._agentExecutor.stream(inputs, {
|
|
3588
|
+
streamMode: "updates",
|
|
3589
|
+
// Get updates as they happen
|
|
3590
|
+
callbacks: this.callbacks,
|
|
3591
|
+
metadata: this.getMetadata(),
|
|
3592
|
+
tags: this.getTags(),
|
|
3593
|
+
// Set trace name for LangChain/Langfuse
|
|
3594
|
+
runName: this.metadata.trace_name || "mcp-use-agent",
|
|
3595
|
+
// Pass sessionId for Langfuse if present in metadata
|
|
3596
|
+
...this.metadata.session_id && {
|
|
3597
|
+
sessionId: this.metadata.session_id
|
|
3405
3598
|
}
|
|
3406
|
-
);
|
|
3599
|
+
});
|
|
3407
3600
|
for await (const chunk of stream) {
|
|
3408
3601
|
for (const [nodeName, nodeOutput] of Object.entries(chunk)) {
|
|
3409
|
-
logger.debug(
|
|
3602
|
+
logger.debug(
|
|
3603
|
+
`\u{1F4E6} Node '${nodeName}' output: ${JSON.stringify(nodeOutput)}`
|
|
3604
|
+
);
|
|
3410
3605
|
if (nodeOutput && typeof nodeOutput === "object" && "messages" in nodeOutput) {
|
|
3411
3606
|
let messages = nodeOutput.messages;
|
|
3412
3607
|
if (!Array.isArray(messages)) {
|
|
@@ -3428,7 +3623,9 @@ var MCPAgent = class {
|
|
|
3428
3623
|
if (toolInputStr.length > 100) {
|
|
3429
3624
|
toolInputStr = `${toolInputStr.slice(0, 97)}...`;
|
|
3430
3625
|
}
|
|
3431
|
-
logger.info(
|
|
3626
|
+
logger.info(
|
|
3627
|
+
`\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`
|
|
3628
|
+
);
|
|
3432
3629
|
yield {
|
|
3433
3630
|
action: {
|
|
3434
3631
|
tool: toolName,
|
|
@@ -3450,9 +3647,15 @@ var MCPAgent = class {
|
|
|
3450
3647
|
logger.info(`\u{1F4C4} Tool result: ${observationStr}`);
|
|
3451
3648
|
if (this.useServerManager && this.serverManager) {
|
|
3452
3649
|
const currentTools = this.serverManager.tools;
|
|
3453
|
-
const currentToolNames = new Set(
|
|
3454
|
-
|
|
3455
|
-
|
|
3650
|
+
const currentToolNames = new Set(
|
|
3651
|
+
currentTools.map((t) => t.name)
|
|
3652
|
+
);
|
|
3653
|
+
const existingToolNames = new Set(
|
|
3654
|
+
this._tools.map((t) => t.name)
|
|
3655
|
+
);
|
|
3656
|
+
if (currentToolNames.size !== existingToolNames.size || [...currentToolNames].some(
|
|
3657
|
+
(n) => !existingToolNames.has(n)
|
|
3658
|
+
)) {
|
|
3456
3659
|
logger.info(
|
|
3457
3660
|
`\u{1F504} Tools changed during execution. New tools: ${[...currentToolNames].join(", ")}`
|
|
3458
3661
|
);
|
|
@@ -3487,7 +3690,9 @@ var MCPAgent = class {
|
|
|
3487
3690
|
break;
|
|
3488
3691
|
}
|
|
3489
3692
|
if (restartCount > maxRestarts) {
|
|
3490
|
-
logger.warn(
|
|
3693
|
+
logger.warn(
|
|
3694
|
+
`\u26A0\uFE0F Max restarts (${maxRestarts}) reached. Continuing with current tools.`
|
|
3695
|
+
);
|
|
3491
3696
|
break;
|
|
3492
3697
|
}
|
|
3493
3698
|
}
|
|
@@ -3506,17 +3711,25 @@ var MCPAgent = class {
|
|
|
3506
3711
|
outputSchema
|
|
3507
3712
|
);
|
|
3508
3713
|
if (this.memoryEnabled) {
|
|
3509
|
-
this.addToHistory(
|
|
3714
|
+
this.addToHistory(
|
|
3715
|
+
new import_langchain2.AIMessage(
|
|
3716
|
+
`Structured result: ${JSON.stringify(structuredResult)}`
|
|
3717
|
+
)
|
|
3718
|
+
);
|
|
3510
3719
|
}
|
|
3511
3720
|
logger.info("\u2705 Structured output successful");
|
|
3512
3721
|
success = true;
|
|
3513
3722
|
return structuredResult;
|
|
3514
3723
|
} catch (e) {
|
|
3515
3724
|
logger.error(`\u274C Structured output failed: ${e}`);
|
|
3516
|
-
throw new Error(
|
|
3725
|
+
throw new Error(
|
|
3726
|
+
`Failed to generate structured output: ${e instanceof Error ? e.message : String(e)}`
|
|
3727
|
+
);
|
|
3517
3728
|
}
|
|
3518
3729
|
}
|
|
3519
|
-
logger.info(
|
|
3730
|
+
logger.info(
|
|
3731
|
+
`\u{1F389} Agent execution complete in ${((Date.now() - startTime) / 1e3).toFixed(2)} seconds`
|
|
3732
|
+
);
|
|
3520
3733
|
success = true;
|
|
3521
3734
|
return finalOutput || "No output generated";
|
|
3522
3735
|
} catch (e) {
|
|
@@ -3543,7 +3756,9 @@ var MCPAgent = class {
|
|
|
3543
3756
|
modelProvider: this.modelProvider,
|
|
3544
3757
|
modelName: this.modelName,
|
|
3545
3758
|
serverCount,
|
|
3546
|
-
serverIdentifiers: this.connectors.map(
|
|
3759
|
+
serverIdentifiers: this.connectors.map(
|
|
3760
|
+
(connector) => connector.publicIdentifier
|
|
3761
|
+
),
|
|
3547
3762
|
totalToolsAvailable: toolsAvailable.length,
|
|
3548
3763
|
toolsAvailableNames: toolsAvailable.map((t) => t.name),
|
|
3549
3764
|
maxStepsConfigured: this.maxSteps,
|
|
@@ -3647,7 +3862,10 @@ var MCPAgent = class {
|
|
|
3647
3862
|
logger.info(`\u26A0\uFE0F Skipped message of type: ${msg.constructor.name}`);
|
|
3648
3863
|
}
|
|
3649
3864
|
}
|
|
3650
|
-
const inputs = [
|
|
3865
|
+
const inputs = [
|
|
3866
|
+
...langchainHistory,
|
|
3867
|
+
new import_langchain2.HumanMessage(query)
|
|
3868
|
+
];
|
|
3651
3869
|
logger.info("callbacks", this.callbacks);
|
|
3652
3870
|
const eventStream = agentExecutor.streamEvents(
|
|
3653
3871
|
{ messages: inputs },
|
|
@@ -3660,7 +3878,9 @@ var MCPAgent = class {
|
|
|
3660
3878
|
// Set trace name for LangChain/Langfuse
|
|
3661
3879
|
runName: this.metadata.trace_name || "mcp-use-agent",
|
|
3662
3880
|
// Pass sessionId for Langfuse if present in metadata
|
|
3663
|
-
...this.metadata.session_id && {
|
|
3881
|
+
...this.metadata.session_id && {
|
|
3882
|
+
sessionId: this.metadata.session_id
|
|
3883
|
+
}
|
|
3664
3884
|
}
|
|
3665
3885
|
);
|
|
3666
3886
|
for await (const event of eventStream) {
|
|
@@ -3679,7 +3899,9 @@ var MCPAgent = class {
|
|
|
3679
3899
|
}
|
|
3680
3900
|
const normalizedContent = this._normalizeOutput(chunk.content);
|
|
3681
3901
|
finalResponse += normalizedContent;
|
|
3682
|
-
logger.debug(
|
|
3902
|
+
logger.debug(
|
|
3903
|
+
`\u{1F4DD} Accumulated response length: ${finalResponse.length}`
|
|
3904
|
+
);
|
|
3683
3905
|
}
|
|
3684
3906
|
}
|
|
3685
3907
|
yield event;
|
|
@@ -3736,7 +3958,11 @@ var MCPAgent = class {
|
|
|
3736
3958
|
data: { output: conversionResult }
|
|
3737
3959
|
};
|
|
3738
3960
|
if (this.memoryEnabled) {
|
|
3739
|
-
this.addToHistory(
|
|
3961
|
+
this.addToHistory(
|
|
3962
|
+
new import_langchain2.AIMessage(
|
|
3963
|
+
`Structured result: ${JSON.stringify(conversionResult)}`
|
|
3964
|
+
)
|
|
3965
|
+
);
|
|
3740
3966
|
}
|
|
3741
3967
|
logger.info("\u2705 Structured output successful");
|
|
3742
3968
|
}
|
|
@@ -3755,7 +3981,9 @@ var MCPAgent = class {
|
|
|
3755
3981
|
} catch (e) {
|
|
3756
3982
|
logger.error(`\u274C Error during streamEvents: ${e}`);
|
|
3757
3983
|
if (initializedHere && manageConnector) {
|
|
3758
|
-
logger.info(
|
|
3984
|
+
logger.info(
|
|
3985
|
+
"\u{1F9F9} Cleaning up resources after initialization error in streamEvents"
|
|
3986
|
+
);
|
|
3759
3987
|
await this.close();
|
|
3760
3988
|
}
|
|
3761
3989
|
throw e;
|
|
@@ -3775,7 +4003,9 @@ var MCPAgent = class {
|
|
|
3775
4003
|
modelProvider: this.modelProvider,
|
|
3776
4004
|
modelName: this.modelName,
|
|
3777
4005
|
serverCount,
|
|
3778
|
-
serverIdentifiers: this.connectors.map(
|
|
4006
|
+
serverIdentifiers: this.connectors.map(
|
|
4007
|
+
(connector) => connector.publicIdentifier
|
|
4008
|
+
),
|
|
3779
4009
|
totalToolsAvailable: this._tools.length,
|
|
3780
4010
|
toolsAvailableNames: this._tools.map((t) => t.name),
|
|
3781
4011
|
maxStepsConfigured: this.maxSteps,
|
|
@@ -3803,11 +4033,15 @@ var MCPAgent = class {
|
|
|
3803
4033
|
* @param outputSchema - The Zod schema to validate against
|
|
3804
4034
|
*/
|
|
3805
4035
|
async _attemptStructuredOutput(rawResult, llm, outputSchema) {
|
|
3806
|
-
logger.info(
|
|
4036
|
+
logger.info(
|
|
4037
|
+
`\u{1F504} Attempting structured output with schema: ${JSON.stringify(outputSchema, null, 2)}`
|
|
4038
|
+
);
|
|
3807
4039
|
logger.info(`\u{1F504} Raw result: ${JSON.stringify(rawResult, null, 2)}`);
|
|
3808
4040
|
let structuredLlm = null;
|
|
3809
4041
|
let schemaDescription = "";
|
|
3810
|
-
logger.debug(
|
|
4042
|
+
logger.debug(
|
|
4043
|
+
`\u{1F504} Structured output requested, schema: ${JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2)}`
|
|
4044
|
+
);
|
|
3811
4045
|
if (llm && "withStructuredOutput" in llm && typeof llm.withStructuredOutput === "function") {
|
|
3812
4046
|
structuredLlm = llm.withStructuredOutput(outputSchema);
|
|
3813
4047
|
} else if (llm) {
|
|
@@ -3859,11 +4093,17 @@ var MCPAgent = class {
|
|
|
3859
4093
|
`;
|
|
3860
4094
|
}
|
|
3861
4095
|
try {
|
|
3862
|
-
logger.info(
|
|
4096
|
+
logger.info(
|
|
4097
|
+
`\u{1F504} Structured output attempt ${attempt} - using streaming approach`
|
|
4098
|
+
);
|
|
3863
4099
|
const contentPreview = textContent.length > 300 ? `${textContent.slice(0, 300)}...` : textContent;
|
|
3864
|
-
logger.info(
|
|
3865
|
-
|
|
3866
|
-
|
|
4100
|
+
logger.info(
|
|
4101
|
+
`\u{1F504} Content being formatted (${textContent.length} chars): ${contentPreview}`
|
|
4102
|
+
);
|
|
4103
|
+
logger.info(
|
|
4104
|
+
`\u{1F504} Full format prompt (${formatPrompt.length} chars):
|
|
4105
|
+
${formatPrompt}`
|
|
4106
|
+
);
|
|
3867
4107
|
const stream = await structuredLlm.stream(formatPrompt);
|
|
3868
4108
|
let structuredResult = null;
|
|
3869
4109
|
let chunkCount = 0;
|
|
@@ -3889,19 +4129,30 @@ ${formatPrompt}`);
|
|
|
3889
4129
|
logger.info(`\u{1F504} Structured output streaming: ${chunkCount} chunks`);
|
|
3890
4130
|
}
|
|
3891
4131
|
}
|
|
3892
|
-
logger.info(
|
|
4132
|
+
logger.info(
|
|
4133
|
+
`\u{1F504} Structured result attempt ${attempt}: ${JSON.stringify(structuredResult, null, 2)}`
|
|
4134
|
+
);
|
|
3893
4135
|
if (!structuredResult) {
|
|
3894
4136
|
throw new Error("No structured result received from stream");
|
|
3895
4137
|
}
|
|
3896
|
-
const validatedResult = this._validateStructuredResult(
|
|
4138
|
+
const validatedResult = this._validateStructuredResult(
|
|
4139
|
+
structuredResult,
|
|
4140
|
+
outputSchema
|
|
4141
|
+
);
|
|
3897
4142
|
logger.info(`\u2705 Structured output successful on attempt ${attempt}`);
|
|
3898
4143
|
return validatedResult;
|
|
3899
4144
|
} catch (e) {
|
|
3900
4145
|
lastError = e instanceof Error ? e.message : String(e);
|
|
3901
|
-
logger.warn(
|
|
4146
|
+
logger.warn(
|
|
4147
|
+
`\u26A0\uFE0F Structured output attempt ${attempt} failed: ${lastError}`
|
|
4148
|
+
);
|
|
3902
4149
|
if (attempt === maxRetries) {
|
|
3903
|
-
logger.error(
|
|
3904
|
-
|
|
4150
|
+
logger.error(
|
|
4151
|
+
`\u274C All ${maxRetries} structured output attempts failed`
|
|
4152
|
+
);
|
|
4153
|
+
throw new Error(
|
|
4154
|
+
`Failed to generate valid structured output after ${maxRetries} attempts. Last error: ${lastError}`
|
|
4155
|
+
);
|
|
3905
4156
|
}
|
|
3906
4157
|
continue;
|
|
3907
4158
|
}
|
|
@@ -3916,14 +4167,18 @@ ${formatPrompt}`);
|
|
|
3916
4167
|
const validatedResult = outputSchema.parse(structuredResult);
|
|
3917
4168
|
const schemaType = outputSchema;
|
|
3918
4169
|
if (schemaType._def && schemaType._def.shape) {
|
|
3919
|
-
for (const [fieldName, fieldSchema] of Object.entries(
|
|
4170
|
+
for (const [fieldName, fieldSchema] of Object.entries(
|
|
4171
|
+
schemaType._def.shape
|
|
4172
|
+
)) {
|
|
3920
4173
|
const field = fieldSchema;
|
|
3921
4174
|
const isOptional = field.isOptional?.() ?? field._def?.typeName === "ZodOptional";
|
|
3922
4175
|
const isNullable = field.isNullable?.() ?? field._def?.typeName === "ZodNullable";
|
|
3923
4176
|
if (!isOptional && !isNullable) {
|
|
3924
4177
|
const value = validatedResult[fieldName];
|
|
3925
4178
|
if (value === null || value === void 0 || typeof value === "string" && !value.trim() || Array.isArray(value) && value.length === 0) {
|
|
3926
|
-
throw new Error(
|
|
4179
|
+
throw new Error(
|
|
4180
|
+
`Required field '${fieldName}' is missing or empty`
|
|
4181
|
+
);
|
|
3927
4182
|
}
|
|
3928
4183
|
}
|
|
3929
4184
|
}
|
|
@@ -4009,7 +4264,10 @@ var BrowserOAuthClientProvider = class {
|
|
|
4009
4264
|
try {
|
|
4010
4265
|
return JSON.parse(data);
|
|
4011
4266
|
} catch (e) {
|
|
4012
|
-
console.warn(
|
|
4267
|
+
console.warn(
|
|
4268
|
+
`[${this.storageKeyPrefix}] Failed to parse client information:`,
|
|
4269
|
+
e
|
|
4270
|
+
);
|
|
4013
4271
|
localStorage.removeItem(key);
|
|
4014
4272
|
return void 0;
|
|
4015
4273
|
}
|
|
@@ -4091,7 +4349,11 @@ var BrowserOAuthClientProvider = class {
|
|
|
4091
4349
|
const sanitizedAuthUrl = await this.prepareAuthorizationUrl(authorizationUrl);
|
|
4092
4350
|
const popupFeatures = "width=600,height=700,resizable=yes,scrollbars=yes,status=yes";
|
|
4093
4351
|
try {
|
|
4094
|
-
const popup = window.open(
|
|
4352
|
+
const popup = window.open(
|
|
4353
|
+
sanitizedAuthUrl,
|
|
4354
|
+
`mcp_auth_${this.serverUrlHash}`,
|
|
4355
|
+
popupFeatures
|
|
4356
|
+
);
|
|
4095
4357
|
if (this.onPopupWindow) {
|
|
4096
4358
|
this.onPopupWindow(sanitizedAuthUrl, popupFeatures, popup);
|
|
4097
4359
|
}
|
|
@@ -4101,10 +4363,15 @@ var BrowserOAuthClientProvider = class {
|
|
|
4101
4363
|
);
|
|
4102
4364
|
} else {
|
|
4103
4365
|
popup.focus();
|
|
4104
|
-
console.info(
|
|
4366
|
+
console.info(
|
|
4367
|
+
`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`
|
|
4368
|
+
);
|
|
4105
4369
|
}
|
|
4106
4370
|
} catch (e) {
|
|
4107
|
-
console.error(
|
|
4371
|
+
console.error(
|
|
4372
|
+
`[${this.storageKeyPrefix}] Error opening popup window:`,
|
|
4373
|
+
e
|
|
4374
|
+
);
|
|
4108
4375
|
}
|
|
4109
4376
|
}
|
|
4110
4377
|
// --- Helper Methods ---
|
|
@@ -4135,7 +4402,10 @@ var BrowserOAuthClientProvider = class {
|
|
|
4135
4402
|
}
|
|
4136
4403
|
}
|
|
4137
4404
|
} catch (e) {
|
|
4138
|
-
console.warn(
|
|
4405
|
+
console.warn(
|
|
4406
|
+
`[${this.storageKeyPrefix}] Error parsing state key ${key} during clearStorage:`,
|
|
4407
|
+
e
|
|
4408
|
+
);
|
|
4139
4409
|
}
|
|
4140
4410
|
}
|
|
4141
4411
|
}
|
|
@@ -4169,23 +4439,36 @@ async function onMcpAuthorization() {
|
|
|
4169
4439
|
const error = queryParams.get("error");
|
|
4170
4440
|
const errorDescription = queryParams.get("error_description");
|
|
4171
4441
|
const logPrefix = "[mcp-callback]";
|
|
4172
|
-
console.log(`${logPrefix} Handling callback...`, {
|
|
4442
|
+
console.log(`${logPrefix} Handling callback...`, {
|
|
4443
|
+
code,
|
|
4444
|
+
state,
|
|
4445
|
+
error,
|
|
4446
|
+
errorDescription
|
|
4447
|
+
});
|
|
4173
4448
|
let provider = null;
|
|
4174
4449
|
let storedStateData = null;
|
|
4175
4450
|
const stateKey = state ? `mcp:auth:state_${state}` : null;
|
|
4176
4451
|
try {
|
|
4177
4452
|
if (error) {
|
|
4178
|
-
throw new Error(
|
|
4453
|
+
throw new Error(
|
|
4454
|
+
`OAuth error: ${error} - ${errorDescription || "No description provided."}`
|
|
4455
|
+
);
|
|
4179
4456
|
}
|
|
4180
4457
|
if (!code) {
|
|
4181
|
-
throw new Error(
|
|
4458
|
+
throw new Error(
|
|
4459
|
+
"Authorization code not found in callback query parameters."
|
|
4460
|
+
);
|
|
4182
4461
|
}
|
|
4183
4462
|
if (!state || !stateKey) {
|
|
4184
|
-
throw new Error(
|
|
4463
|
+
throw new Error(
|
|
4464
|
+
"State parameter not found or invalid in callback query parameters."
|
|
4465
|
+
);
|
|
4185
4466
|
}
|
|
4186
4467
|
const storedStateJSON = localStorage.getItem(stateKey);
|
|
4187
4468
|
if (!storedStateJSON) {
|
|
4188
|
-
throw new Error(
|
|
4469
|
+
throw new Error(
|
|
4470
|
+
`Invalid or expired state parameter "${state}". No matching state found in storage.`
|
|
4471
|
+
);
|
|
4189
4472
|
}
|
|
4190
4473
|
try {
|
|
4191
4474
|
storedStateData = JSON.parse(storedStateJSON);
|
|
@@ -4194,38 +4477,59 @@ async function onMcpAuthorization() {
|
|
|
4194
4477
|
}
|
|
4195
4478
|
if (!storedStateData.expiry || storedStateData.expiry < Date.now()) {
|
|
4196
4479
|
localStorage.removeItem(stateKey);
|
|
4197
|
-
throw new Error(
|
|
4480
|
+
throw new Error(
|
|
4481
|
+
"OAuth state has expired. Please try initiating authentication again."
|
|
4482
|
+
);
|
|
4198
4483
|
}
|
|
4199
4484
|
if (!storedStateData.providerOptions) {
|
|
4200
4485
|
throw new Error("Stored state is missing required provider options.");
|
|
4201
4486
|
}
|
|
4202
4487
|
const { serverUrl, ...providerOptions } = storedStateData.providerOptions;
|
|
4203
|
-
console.log(
|
|
4488
|
+
console.log(
|
|
4489
|
+
`${logPrefix} Re-instantiating provider for server: ${serverUrl}`
|
|
4490
|
+
);
|
|
4204
4491
|
provider = new BrowserOAuthClientProvider(serverUrl, providerOptions);
|
|
4205
4492
|
console.log(`${logPrefix} Calling SDK auth() to exchange code...`);
|
|
4206
4493
|
const baseUrl = new URL(serverUrl).origin;
|
|
4207
|
-
const authResult = await (0, import_auth.auth)(provider, {
|
|
4494
|
+
const authResult = await (0, import_auth.auth)(provider, {
|
|
4495
|
+
serverUrl: baseUrl,
|
|
4496
|
+
authorizationCode: code
|
|
4497
|
+
});
|
|
4208
4498
|
if (authResult === "AUTHORIZED") {
|
|
4209
|
-
console.log(
|
|
4499
|
+
console.log(
|
|
4500
|
+
`${logPrefix} Authorization successful via SDK auth(). Notifying opener...`
|
|
4501
|
+
);
|
|
4210
4502
|
if (window.opener && !window.opener.closed) {
|
|
4211
|
-
window.opener.postMessage(
|
|
4503
|
+
window.opener.postMessage(
|
|
4504
|
+
{ type: "mcp_auth_callback", success: true },
|
|
4505
|
+
window.location.origin
|
|
4506
|
+
);
|
|
4212
4507
|
window.close();
|
|
4213
4508
|
} else {
|
|
4214
|
-
console.warn(
|
|
4509
|
+
console.warn(
|
|
4510
|
+
`${logPrefix} No opener window detected. Redirecting to root.`
|
|
4511
|
+
);
|
|
4215
4512
|
const pathParts = window.location.pathname.split("/").filter(Boolean);
|
|
4216
4513
|
const basePath = pathParts.length > 0 && pathParts[pathParts.length - 1] === "callback" ? "/" + pathParts.slice(0, -2).join("/") : "/";
|
|
4217
4514
|
window.location.href = basePath || "/";
|
|
4218
4515
|
}
|
|
4219
4516
|
localStorage.removeItem(stateKey);
|
|
4220
4517
|
} else {
|
|
4221
|
-
console.warn(
|
|
4222
|
-
|
|
4518
|
+
console.warn(
|
|
4519
|
+
`${logPrefix} SDK auth() returned unexpected status: ${authResult}`
|
|
4520
|
+
);
|
|
4521
|
+
throw new Error(
|
|
4522
|
+
`Unexpected result from authentication library: ${authResult}`
|
|
4523
|
+
);
|
|
4223
4524
|
}
|
|
4224
4525
|
} catch (err) {
|
|
4225
4526
|
console.error(`${logPrefix} Error during OAuth callback handling:`, err);
|
|
4226
4527
|
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
4227
4528
|
if (window.opener && !window.opener.closed) {
|
|
4228
|
-
window.opener.postMessage(
|
|
4529
|
+
window.opener.postMessage(
|
|
4530
|
+
{ type: "mcp_auth_callback", success: false, error: errorMessage },
|
|
4531
|
+
window.location.origin
|
|
4532
|
+
);
|
|
4229
4533
|
}
|
|
4230
4534
|
try {
|
|
4231
4535
|
document.body.innerHTML = `
|
|
@@ -4239,7 +4543,10 @@ async function onMcpAuthorization() {
|
|
|
4239
4543
|
</div>
|
|
4240
4544
|
`;
|
|
4241
4545
|
} catch (displayError) {
|
|
4242
|
-
console.error(
|
|
4546
|
+
console.error(
|
|
4547
|
+
`${logPrefix} Could not display error in callback window:`,
|
|
4548
|
+
displayError
|
|
4549
|
+
);
|
|
4243
4550
|
}
|
|
4244
4551
|
if (stateKey) {
|
|
4245
4552
|
localStorage.removeItem(stateKey);
|