mcp-use 1.1.8-canary.1 → 1.2.0-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/.tsbuildinfo +1 -0
- package/dist/{chunk-4SWVHFJH.js → chunk-ZD4Q56ZQ.js} +250 -197
- package/dist/{chunk-2HFIPY7C.js → chunk-ZUEQQ6YK.js} +17 -2
- package/dist/index.cjs +281 -209
- package/dist/index.js +2 -2
- package/dist/{langfuse-YA2S23SM.js → langfuse-6AJGHMAV.js} +1 -1
- package/dist/src/agents/mcp_agent.d.ts +30 -6
- package/dist/src/agents/mcp_agent.d.ts.map +1 -1
- package/dist/src/agents/prompts/system_prompt_builder.d.ts +1 -1
- package/dist/src/agents/prompts/system_prompt_builder.d.ts.map +1 -1
- package/dist/src/browser.cjs +281 -209
- package/dist/src/browser.js +2 -2
- package/dist/src/managers/server_manager.d.ts +2 -1
- package/dist/src/managers/server_manager.d.ts.map +1 -1
- package/dist/src/managers/tools/acquire_active_mcp_server.d.ts +2 -2
- 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 +3 -3
- package/dist/src/managers/tools/base.d.ts.map +1 -1
- package/dist/src/managers/tools/connect_mcp_server.d.ts +2 -2
- package/dist/src/managers/tools/connect_mcp_server.d.ts.map +1 -1
- package/dist/src/managers/tools/list_mcp_servers.d.ts +2 -2
- package/dist/src/managers/tools/list_mcp_servers.d.ts.map +1 -1
- package/dist/src/managers/tools/release_mcp_server_connection.d.ts +2 -2
- package/dist/src/managers/tools/release_mcp_server_connection.d.ts.map +1 -1
- package/dist/src/managers/types.d.ts +14 -0
- package/dist/src/managers/types.d.ts.map +1 -0
- package/dist/src/observability/langfuse.d.ts.map +1 -1
- package/dist/src/observability/manager.d.ts +11 -0
- package/dist/src/observability/manager.d.ts.map +1 -1
- package/dist/tsup.config.d.ts.map +1 -1
- package/package.json +33 -13
- package/dist/tests/ai_sdk_compatibility.test.d.ts +0 -13
- package/dist/tests/ai_sdk_compatibility.test.d.ts.map +0 -1
- package/dist/tests/helpers/widget-generators.d.ts +0 -24
- package/dist/tests/helpers/widget-generators.d.ts.map +0 -1
- package/dist/tests/mcp-ui-adapter.test.d.ts +0 -8
- package/dist/tests/mcp-ui-adapter.test.d.ts.map +0 -1
- package/dist/tests/stream_events.test.d.ts +0 -12
- package/dist/tests/stream_events.test.d.ts.map +0 -1
- package/dist/tests/stream_events_simple.test.d.ts +0 -7
- package/dist/tests/stream_events_simple.test.d.ts.map +0 -1
- package/dist/tsconfig.tsbuildinfo +0 -1
package/dist/src/browser.cjs
CHANGED
|
@@ -280,7 +280,7 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
|
|
|
280
280
|
try {
|
|
281
281
|
const langfuseModule = await import("langfuse-langchain").catch(() => null);
|
|
282
282
|
if (!langfuseModule) {
|
|
283
|
-
logger.debug("Langfuse package not installed - tracing disabled. Install with: npm install langfuse
|
|
283
|
+
logger.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");
|
|
284
284
|
return;
|
|
285
285
|
}
|
|
286
286
|
const { CallbackHandler } = langfuseModule;
|
|
@@ -407,6 +407,8 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
|
|
|
407
407
|
return super.handleAgentEnd(...args);
|
|
408
408
|
}
|
|
409
409
|
}
|
|
410
|
+
const initialMetadata = metadata || (metadataProvider ? metadataProvider() : {});
|
|
411
|
+
const initialTags = tagsProvider ? tagsProvider() : [];
|
|
410
412
|
const config2 = {
|
|
411
413
|
publicKey: process.env.LANGFUSE_PUBLIC_KEY,
|
|
412
414
|
secretKey: process.env.LANGFUSE_SECRET_KEY,
|
|
@@ -415,8 +417,21 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
|
|
|
415
417
|
flushInterval: Number.parseInt(process.env.LANGFUSE_FLUSH_INTERVAL || "10000"),
|
|
416
418
|
release: process.env.LANGFUSE_RELEASE,
|
|
417
419
|
requestTimeout: Number.parseInt(process.env.LANGFUSE_REQUEST_TIMEOUT || "10000"),
|
|
418
|
-
enabled: process.env.LANGFUSE_ENABLED !== "false"
|
|
420
|
+
enabled: process.env.LANGFUSE_ENABLED !== "false",
|
|
421
|
+
// Set trace name - can be customized via metadata.trace_name or defaults to 'mcp-use-agent'
|
|
422
|
+
traceName: initialMetadata.trace_name || process.env.LANGFUSE_TRACE_NAME || "mcp-use-agent",
|
|
423
|
+
// Pass sessionId, userId, and tags to the handler
|
|
424
|
+
sessionId: initialMetadata.session_id || void 0,
|
|
425
|
+
userId: initialMetadata.user_id || void 0,
|
|
426
|
+
tags: initialTags.length > 0 ? initialTags : void 0,
|
|
427
|
+
metadata: initialMetadata || void 0
|
|
419
428
|
};
|
|
429
|
+
logger.debug("Langfuse handler config:", JSON.stringify({
|
|
430
|
+
traceName: config2.traceName,
|
|
431
|
+
sessionId: config2.sessionId,
|
|
432
|
+
userId: config2.userId,
|
|
433
|
+
tags: config2.tags
|
|
434
|
+
}, null, 2));
|
|
420
435
|
langfuseState.handler = new LoggingCallbackHandler(config2, agentId, metadata, metadataProvider, tagsProvider);
|
|
421
436
|
logger.debug("Langfuse observability initialized successfully with logging enabled");
|
|
422
437
|
try {
|
|
@@ -469,13 +484,13 @@ var init_langfuse = __esm({
|
|
|
469
484
|
// src/browser.ts
|
|
470
485
|
var browser_exports = {};
|
|
471
486
|
__export(browser_exports, {
|
|
472
|
-
AIMessage: () =>
|
|
487
|
+
AIMessage: () => import_messages2.AIMessage,
|
|
473
488
|
BaseAdapter: () => BaseAdapter,
|
|
474
489
|
BaseConnector: () => BaseConnector,
|
|
475
|
-
BaseMessage: () =>
|
|
490
|
+
BaseMessage: () => import_messages2.BaseMessage,
|
|
476
491
|
BrowserOAuthClientProvider: () => BrowserOAuthClientProvider,
|
|
477
492
|
HttpConnector: () => HttpConnector,
|
|
478
|
-
HumanMessage: () =>
|
|
493
|
+
HumanMessage: () => import_messages2.HumanMessage,
|
|
479
494
|
LangChainAdapter: () => LangChainAdapter,
|
|
480
495
|
Logger: () => Logger,
|
|
481
496
|
MCPAgent: () => MCPAgent,
|
|
@@ -483,8 +498,8 @@ __export(browser_exports, {
|
|
|
483
498
|
MCPSession: () => MCPSession,
|
|
484
499
|
ObservabilityManager: () => ObservabilityManager,
|
|
485
500
|
RemoteAgent: () => RemoteAgent,
|
|
486
|
-
SystemMessage: () =>
|
|
487
|
-
ToolMessage: () =>
|
|
501
|
+
SystemMessage: () => import_messages2.SystemMessage,
|
|
502
|
+
ToolMessage: () => import_messages2.ToolMessage,
|
|
488
503
|
WebSocketConnector: () => WebSocketConnector,
|
|
489
504
|
createReadableStreamFromGenerator: () => createReadableStreamFromGenerator,
|
|
490
505
|
logger: () => logger,
|
|
@@ -1487,11 +1502,8 @@ var BrowserMCPClient = class _BrowserMCPClient extends BaseMCPClient {
|
|
|
1487
1502
|
};
|
|
1488
1503
|
|
|
1489
1504
|
// src/agents/mcp_agent.ts
|
|
1490
|
-
var
|
|
1491
|
-
var
|
|
1492
|
-
var import_output_parsers = require("@langchain/core/output_parsers");
|
|
1493
|
-
var import_prompts = require("@langchain/core/prompts");
|
|
1494
|
-
var import_agents = require("langchain/agents");
|
|
1505
|
+
var import_messages = require("@langchain/core/messages");
|
|
1506
|
+
var import_langchain2 = require("langchain");
|
|
1495
1507
|
var import_zod_to_json_schema2 = require("zod-to-json-schema");
|
|
1496
1508
|
|
|
1497
1509
|
// src/adapters/langchain_adapter.ts
|
|
@@ -1712,7 +1724,7 @@ var AcquireActiveMCPServerTool = class extends MCPServerTool {
|
|
|
1712
1724
|
};
|
|
1713
1725
|
|
|
1714
1726
|
// src/managers/tools/add_server_from_config.ts
|
|
1715
|
-
var import_tools3 = require("langchain/tools");
|
|
1727
|
+
var import_tools3 = require("@langchain/core/tools");
|
|
1716
1728
|
var import_zod3 = require("zod");
|
|
1717
1729
|
init_logging();
|
|
1718
1730
|
var AddMCPServerFromConfigTool = class extends import_tools3.StructuredTool {
|
|
@@ -2085,6 +2097,23 @@ var ObservabilityManager = class {
|
|
|
2085
2097
|
const callbacks = await this.getCallbacks();
|
|
2086
2098
|
return callbacks.length > 0;
|
|
2087
2099
|
}
|
|
2100
|
+
/**
|
|
2101
|
+
* Get the current observability status including metadata and tags.
|
|
2102
|
+
* @returns Object containing enabled status, callback count, handler names, metadata, and tags.
|
|
2103
|
+
*/
|
|
2104
|
+
async getStatus() {
|
|
2105
|
+
const callbacks = await this.getCallbacks();
|
|
2106
|
+
const handlerNames = await this.getHandlerNames();
|
|
2107
|
+
const currentMetadata = this.metadataProvider ? this.metadataProvider() : this.metadata || {};
|
|
2108
|
+
const currentTags = this.tagsProvider ? this.tagsProvider() : [];
|
|
2109
|
+
return {
|
|
2110
|
+
enabled: this.observe && callbacks.length > 0,
|
|
2111
|
+
callbackCount: callbacks.length,
|
|
2112
|
+
handlerNames,
|
|
2113
|
+
metadata: currentMetadata,
|
|
2114
|
+
tags: currentTags
|
|
2115
|
+
};
|
|
2116
|
+
}
|
|
2088
2117
|
/**
|
|
2089
2118
|
* Add a callback to the custom callbacks list.
|
|
2090
2119
|
* @param callback The callback to add.
|
|
@@ -2516,7 +2545,7 @@ var Telemetry = class _Telemetry {
|
|
|
2516
2545
|
};
|
|
2517
2546
|
|
|
2518
2547
|
// src/agents/prompts/system_prompt_builder.ts
|
|
2519
|
-
var
|
|
2548
|
+
var import_langchain = require("langchain");
|
|
2520
2549
|
function generateToolDescriptions(tools, disallowedTools) {
|
|
2521
2550
|
const disallowedSet = new Set(disallowedTools ?? []);
|
|
2522
2551
|
const descriptions = [];
|
|
@@ -2551,7 +2580,7 @@ ${additionalInstructions}`;
|
|
|
2551
2580
|
__name(buildSystemPromptContent, "buildSystemPromptContent");
|
|
2552
2581
|
function createSystemMessage(tools, systemPromptTemplate, serverManagerTemplate, useServerManager, disallowedTools, userProvidedPrompt, additionalInstructions) {
|
|
2553
2582
|
if (userProvidedPrompt) {
|
|
2554
|
-
return new
|
|
2583
|
+
return new import_langchain.SystemMessage({ content: userProvidedPrompt });
|
|
2555
2584
|
}
|
|
2556
2585
|
const template = useServerManager ? serverManagerTemplate : systemPromptTemplate;
|
|
2557
2586
|
const toolLines = generateToolDescriptions(tools, disallowedTools);
|
|
@@ -2560,7 +2589,7 @@ function createSystemMessage(tools, systemPromptTemplate, serverManagerTemplate,
|
|
|
2560
2589
|
toolLines,
|
|
2561
2590
|
additionalInstructions
|
|
2562
2591
|
);
|
|
2563
|
-
return new
|
|
2592
|
+
return new import_langchain.SystemMessage({ content: finalContent });
|
|
2564
2593
|
}
|
|
2565
2594
|
__name(createSystemMessage, "createSystemMessage");
|
|
2566
2595
|
|
|
@@ -2837,6 +2866,7 @@ var MCPAgent = class {
|
|
|
2837
2866
|
memoryEnabled;
|
|
2838
2867
|
disallowedTools;
|
|
2839
2868
|
additionalTools;
|
|
2869
|
+
toolsUsedNames = [];
|
|
2840
2870
|
useServerManager;
|
|
2841
2871
|
verbose;
|
|
2842
2872
|
observe;
|
|
@@ -2904,6 +2934,7 @@ var MCPAgent = class {
|
|
|
2904
2934
|
this.additionalInstructions = options.additionalInstructions ?? null;
|
|
2905
2935
|
this.disallowedTools = options.disallowedTools ?? [];
|
|
2906
2936
|
this.additionalTools = options.additionalTools ?? [];
|
|
2937
|
+
this.toolsUsedNames = options.toolsUsedNames ?? [];
|
|
2907
2938
|
this.useServerManager = options.useServerManager ?? false;
|
|
2908
2939
|
this.verbose = options.verbose ?? false;
|
|
2909
2940
|
this.observe = options.observe ?? true;
|
|
@@ -3018,7 +3049,7 @@ var MCPAgent = class {
|
|
|
3018
3049
|
if (this.memoryEnabled) {
|
|
3019
3050
|
this.conversationHistory = [
|
|
3020
3051
|
this.systemMessage,
|
|
3021
|
-
...this.conversationHistory.filter((m) => !(m instanceof
|
|
3052
|
+
...this.conversationHistory.filter((m) => !(m instanceof import_langchain2.SystemMessage))
|
|
3022
3053
|
];
|
|
3023
3054
|
}
|
|
3024
3055
|
}
|
|
@@ -3027,25 +3058,17 @@ var MCPAgent = class {
|
|
|
3027
3058
|
throw new Error("LLM is required to create agent");
|
|
3028
3059
|
}
|
|
3029
3060
|
const systemContent = this.systemMessage?.content ?? "You are a helpful assistant.";
|
|
3030
|
-
const
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
]);
|
|
3036
|
-
const agent = (0, import_agents.createToolCallingAgent)({
|
|
3037
|
-
llm: this.llm,
|
|
3038
|
-
tools: this._tools,
|
|
3039
|
-
prompt
|
|
3040
|
-
});
|
|
3041
|
-
return new import_agents.AgentExecutor({
|
|
3042
|
-
agent,
|
|
3061
|
+
const toolNames = this._tools.map((tool) => tool.name);
|
|
3062
|
+
logger.info(`\u{1F9E0} Agent ready with tools: ${toolNames.join(", ")}`);
|
|
3063
|
+
const middleware = [(0, import_langchain2.modelCallLimitMiddleware)({ runLimit: this.maxSteps })];
|
|
3064
|
+
const agent = (0, import_langchain2.createAgent)({
|
|
3065
|
+
model: this.llm,
|
|
3043
3066
|
tools: this._tools,
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
returnIntermediateSteps: true,
|
|
3047
|
-
callbacks: this.callbacks
|
|
3067
|
+
systemPrompt: systemContent,
|
|
3068
|
+
middleware
|
|
3048
3069
|
});
|
|
3070
|
+
logger.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`);
|
|
3071
|
+
return agent;
|
|
3049
3072
|
}
|
|
3050
3073
|
getConversationHistory() {
|
|
3051
3074
|
return [...this.conversationHistory];
|
|
@@ -3061,9 +3084,9 @@ var MCPAgent = class {
|
|
|
3061
3084
|
return this.systemMessage;
|
|
3062
3085
|
}
|
|
3063
3086
|
setSystemMessage(message) {
|
|
3064
|
-
this.systemMessage = new
|
|
3087
|
+
this.systemMessage = new import_langchain2.SystemMessage(message);
|
|
3065
3088
|
if (this.memoryEnabled) {
|
|
3066
|
-
this.conversationHistory = this.conversationHistory.filter((m) => !(m instanceof
|
|
3089
|
+
this.conversationHistory = this.conversationHistory.filter((m) => !(m instanceof import_langchain2.SystemMessage));
|
|
3067
3090
|
this.conversationHistory.unshift(this.systemMessage);
|
|
3068
3091
|
}
|
|
3069
3092
|
if (this._initialized && this._tools.length) {
|
|
@@ -3213,6 +3236,42 @@ var MCPAgent = class {
|
|
|
3213
3236
|
}
|
|
3214
3237
|
return serverInfo;
|
|
3215
3238
|
}
|
|
3239
|
+
_normalizeOutput(value) {
|
|
3240
|
+
try {
|
|
3241
|
+
if (typeof value === "string") {
|
|
3242
|
+
return value;
|
|
3243
|
+
}
|
|
3244
|
+
if (value && typeof value === "object" && "content" in value) {
|
|
3245
|
+
return this._normalizeOutput(value.content);
|
|
3246
|
+
}
|
|
3247
|
+
if (Array.isArray(value)) {
|
|
3248
|
+
const parts = [];
|
|
3249
|
+
for (const item of value) {
|
|
3250
|
+
if (typeof item === "object" && item !== null) {
|
|
3251
|
+
if ("text" in item && typeof item.text === "string") {
|
|
3252
|
+
parts.push(item.text);
|
|
3253
|
+
} else if ("content" in item) {
|
|
3254
|
+
parts.push(this._normalizeOutput(item.content));
|
|
3255
|
+
} else {
|
|
3256
|
+
parts.push(String(item));
|
|
3257
|
+
}
|
|
3258
|
+
} else {
|
|
3259
|
+
const partText = item && typeof item === "object" && "text" in item ? item.text : null;
|
|
3260
|
+
if (typeof partText === "string") {
|
|
3261
|
+
parts.push(partText);
|
|
3262
|
+
} else {
|
|
3263
|
+
const partContent = item && typeof item === "object" && "content" in item ? item.content : item;
|
|
3264
|
+
parts.push(this._normalizeOutput(partContent));
|
|
3265
|
+
}
|
|
3266
|
+
}
|
|
3267
|
+
}
|
|
3268
|
+
return parts.join("");
|
|
3269
|
+
}
|
|
3270
|
+
return String(value);
|
|
3271
|
+
} catch (error) {
|
|
3272
|
+
return String(value);
|
|
3273
|
+
}
|
|
3274
|
+
}
|
|
3216
3275
|
async _consumeAndReturn(generator) {
|
|
3217
3276
|
while (true) {
|
|
3218
3277
|
const { done, value } = await generator.next();
|
|
@@ -3234,36 +3293,16 @@ var MCPAgent = class {
|
|
|
3234
3293
|
);
|
|
3235
3294
|
return this._consumeAndReturn(generator);
|
|
3236
3295
|
}
|
|
3237
|
-
/**
|
|
3238
|
-
* Runs the agent and yields intermediate steps as an async generator.
|
|
3239
|
-
* If outputSchema is provided, returns structured output of type T.
|
|
3240
|
-
*/
|
|
3241
3296
|
async *stream(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
|
|
3242
3297
|
if (this.isRemote && this.remoteAgent) {
|
|
3243
|
-
const
|
|
3244
|
-
return
|
|
3298
|
+
const result = await this.remoteAgent.run(query, maxSteps, manageConnector, externalHistory, outputSchema);
|
|
3299
|
+
return result;
|
|
3245
3300
|
}
|
|
3246
|
-
let result = "";
|
|
3247
3301
|
let initializedHere = false;
|
|
3248
3302
|
const startTime = Date.now();
|
|
3249
|
-
|
|
3303
|
+
let success = false;
|
|
3304
|
+
let finalOutput = null;
|
|
3250
3305
|
let stepsTaken = 0;
|
|
3251
|
-
const structuredOutputSuccess = false;
|
|
3252
|
-
const structuredOutputSuccessRef = { value: structuredOutputSuccess };
|
|
3253
|
-
let structuredLlm = null;
|
|
3254
|
-
let schemaDescription = "";
|
|
3255
|
-
if (outputSchema) {
|
|
3256
|
-
query = this._enhanceQueryWithSchema(query, outputSchema);
|
|
3257
|
-
logger.debug(`\u{1F504} Structured output requested, schema: ${JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2)}`);
|
|
3258
|
-
if (this.llm && "withStructuredOutput" in this.llm && typeof this.llm.withStructuredOutput === "function") {
|
|
3259
|
-
structuredLlm = this.llm.withStructuredOutput(outputSchema);
|
|
3260
|
-
} else if (this.llm) {
|
|
3261
|
-
structuredLlm = this.llm;
|
|
3262
|
-
} else {
|
|
3263
|
-
throw new Error("LLM is required for structured output");
|
|
3264
|
-
}
|
|
3265
|
-
schemaDescription = JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2);
|
|
3266
|
-
}
|
|
3267
3306
|
try {
|
|
3268
3307
|
if (manageConnector && !this._initialized) {
|
|
3269
3308
|
await this.initialize();
|
|
@@ -3275,158 +3314,169 @@ var MCPAgent = class {
|
|
|
3275
3314
|
if (!this._agentExecutor) {
|
|
3276
3315
|
throw new Error("MCP agent failed to initialize");
|
|
3277
3316
|
}
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
|
|
3282
|
-
|
|
3283
|
-
|
|
3317
|
+
if (this.useServerManager && this.serverManager) {
|
|
3318
|
+
const currentTools = this.serverManager.tools;
|
|
3319
|
+
const currentToolNames = new Set(currentTools.map((t) => t.name));
|
|
3320
|
+
const existingToolNames = new Set(this._tools.map((t) => t.name));
|
|
3321
|
+
if (currentToolNames.size !== existingToolNames.size || [...currentToolNames].some((n) => !existingToolNames.has(n))) {
|
|
3322
|
+
logger.info(
|
|
3323
|
+
`\u{1F504} Tools changed before execution, updating agent. New tools: ${[...currentToolNames].join(", ")}`
|
|
3324
|
+
);
|
|
3325
|
+
this._tools = currentTools;
|
|
3326
|
+
this._tools.push(...this.additionalTools);
|
|
3327
|
+
await this.createSystemMessageFromTools(this._tools);
|
|
3328
|
+
this._agentExecutor = this.createAgent();
|
|
3329
|
+
}
|
|
3284
3330
|
}
|
|
3285
3331
|
const historyToUse = externalHistory ?? this.conversationHistory;
|
|
3286
3332
|
const langchainHistory = [];
|
|
3287
3333
|
for (const msg of historyToUse) {
|
|
3288
|
-
if (msg instanceof
|
|
3334
|
+
if (msg instanceof import_messages.HumanMessage || msg instanceof import_messages.AIMessage) {
|
|
3289
3335
|
langchainHistory.push(msg);
|
|
3290
3336
|
}
|
|
3291
3337
|
}
|
|
3292
|
-
const
|
|
3293
|
-
|
|
3294
|
-
|
|
3295
|
-
|
|
3296
|
-
let
|
|
3297
|
-
|
|
3298
|
-
|
|
3299
|
-
|
|
3300
|
-
|
|
3301
|
-
|
|
3302
|
-
|
|
3303
|
-
|
|
3304
|
-
|
|
3305
|
-
|
|
3306
|
-
|
|
3307
|
-
|
|
3308
|
-
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
|
|
3312
|
-
|
|
3313
|
-
const currentToolNames = new Set(currentTools.map((t) => t.name));
|
|
3314
|
-
const existingToolNames = new Set(this._tools.map((t) => t.name));
|
|
3315
|
-
const changed = currentTools.length !== this._tools.length || [...currentToolNames].some((n) => !existingToolNames.has(n));
|
|
3316
|
-
if (changed) {
|
|
3317
|
-
logger.info(
|
|
3318
|
-
`\u{1F504} Tools changed before step ${stepNum + 1}, updating agent. New tools: ${[...currentToolNames].join(", ")}`
|
|
3319
|
-
);
|
|
3320
|
-
this._tools = currentTools;
|
|
3321
|
-
this._tools.push(...this.additionalTools);
|
|
3322
|
-
await this.createSystemMessageFromTools(this._tools);
|
|
3323
|
-
this._agentExecutor = this.createAgent();
|
|
3324
|
-
this._agentExecutor.maxIterations = steps;
|
|
3325
|
-
nameToToolMap = Object.fromEntries(this._tools.map((t) => [t.name, t]));
|
|
3338
|
+
const displayQuery = query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, " ")}...` : query.replace(/\n/g, " ");
|
|
3339
|
+
logger.info(`\u{1F4AC} Received query: '${displayQuery}'`);
|
|
3340
|
+
logger.info("\u{1F3C1} Starting agent execution");
|
|
3341
|
+
const maxRestarts = 3;
|
|
3342
|
+
let restartCount = 0;
|
|
3343
|
+
const accumulatedMessages = [...langchainHistory, new import_messages.HumanMessage(query)];
|
|
3344
|
+
while (restartCount <= maxRestarts) {
|
|
3345
|
+
const inputs = { messages: accumulatedMessages };
|
|
3346
|
+
let shouldRestart = false;
|
|
3347
|
+
const stream = await this._agentExecutor.stream(
|
|
3348
|
+
inputs,
|
|
3349
|
+
{
|
|
3350
|
+
streamMode: "updates",
|
|
3351
|
+
// Get updates as they happen
|
|
3352
|
+
callbacks: this.callbacks,
|
|
3353
|
+
metadata: this.getMetadata(),
|
|
3354
|
+
tags: this.getTags(),
|
|
3355
|
+
// Set trace name for LangChain/Langfuse
|
|
3356
|
+
runName: this.metadata.trace_name || "mcp-use-agent",
|
|
3357
|
+
// Pass sessionId for Langfuse if present in metadata
|
|
3358
|
+
...this.metadata.session_id && { sessionId: this.metadata.session_id }
|
|
3326
3359
|
}
|
|
3327
|
-
|
|
3328
|
-
|
|
3329
|
-
|
|
3330
|
-
|
|
3331
|
-
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
result = nextStepOutput.returnValues?.output ?? "No output generated";
|
|
3340
|
-
runManager?.handleChainEnd({ output: result });
|
|
3341
|
-
if (outputSchema && structuredLlm) {
|
|
3342
|
-
logger.info("\u{1F527} Attempting structured output...");
|
|
3343
|
-
const currentResult = result;
|
|
3344
|
-
this._attemptStructuredOutput(
|
|
3345
|
-
currentResult,
|
|
3346
|
-
this.llm,
|
|
3347
|
-
outputSchema
|
|
3348
|
-
).then((structuredResult) => {
|
|
3349
|
-
if (this.memoryEnabled) {
|
|
3350
|
-
this.addToHistory(new import_messages2.AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
|
|
3360
|
+
);
|
|
3361
|
+
for await (const chunk of stream) {
|
|
3362
|
+
for (const [nodeName, nodeOutput] of Object.entries(chunk)) {
|
|
3363
|
+
logger.debug(`\u{1F4E6} Node '${nodeName}' output: ${JSON.stringify(nodeOutput)}`);
|
|
3364
|
+
if (nodeOutput && typeof nodeOutput === "object" && "messages" in nodeOutput) {
|
|
3365
|
+
let messages = nodeOutput.messages;
|
|
3366
|
+
if (!Array.isArray(messages)) {
|
|
3367
|
+
messages = [messages];
|
|
3368
|
+
}
|
|
3369
|
+
for (const msg of messages) {
|
|
3370
|
+
if (!accumulatedMessages.includes(msg)) {
|
|
3371
|
+
accumulatedMessages.push(msg);
|
|
3351
3372
|
}
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
|
|
3370
|
-
|
|
3373
|
+
}
|
|
3374
|
+
for (const message of messages) {
|
|
3375
|
+
if ("tool_calls" in message && Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {
|
|
3376
|
+
for (const toolCall of message.tool_calls) {
|
|
3377
|
+
const toolName = toolCall.name || "unknown";
|
|
3378
|
+
const toolInput = toolCall.args || {};
|
|
3379
|
+
this.toolsUsedNames.push(toolName);
|
|
3380
|
+
stepsTaken++;
|
|
3381
|
+
let toolInputStr = JSON.stringify(toolInput);
|
|
3382
|
+
if (toolInputStr.length > 100) {
|
|
3383
|
+
toolInputStr = `${toolInputStr.slice(0, 97)}...`;
|
|
3384
|
+
}
|
|
3385
|
+
logger.info(`\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`);
|
|
3386
|
+
yield {
|
|
3387
|
+
action: {
|
|
3388
|
+
tool: toolName,
|
|
3389
|
+
toolInput,
|
|
3390
|
+
log: `Calling tool ${toolName}`
|
|
3391
|
+
},
|
|
3392
|
+
observation: ""
|
|
3393
|
+
// Will be filled in by tool result
|
|
3394
|
+
};
|
|
3395
|
+
}
|
|
3371
3396
|
}
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
|
|
3377
|
-
|
|
3378
|
-
|
|
3379
|
-
|
|
3380
|
-
|
|
3381
|
-
|
|
3382
|
-
|
|
3383
|
-
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3399
|
-
|
|
3397
|
+
if (message instanceof import_messages.ToolMessage || message && "type" in message && message.type === "tool") {
|
|
3398
|
+
const observation = message.content;
|
|
3399
|
+
let observationStr = String(observation);
|
|
3400
|
+
if (observationStr.length > 100) {
|
|
3401
|
+
observationStr = `${observationStr.slice(0, 97)}...`;
|
|
3402
|
+
}
|
|
3403
|
+
observationStr = observationStr.replace(/\n/g, " ");
|
|
3404
|
+
logger.info(`\u{1F4C4} Tool result: ${observationStr}`);
|
|
3405
|
+
if (this.useServerManager && this.serverManager) {
|
|
3406
|
+
const currentTools = this.serverManager.tools;
|
|
3407
|
+
const currentToolNames = new Set(currentTools.map((t) => t.name));
|
|
3408
|
+
const existingToolNames = new Set(this._tools.map((t) => t.name));
|
|
3409
|
+
if (currentToolNames.size !== existingToolNames.size || [...currentToolNames].some((n) => !existingToolNames.has(n))) {
|
|
3410
|
+
logger.info(
|
|
3411
|
+
`\u{1F504} Tools changed during execution. New tools: ${[...currentToolNames].join(", ")}`
|
|
3412
|
+
);
|
|
3413
|
+
this._tools = currentTools;
|
|
3414
|
+
this._tools.push(...this.additionalTools);
|
|
3415
|
+
await this.createSystemMessageFromTools(this._tools);
|
|
3416
|
+
this._agentExecutor = this.createAgent();
|
|
3417
|
+
shouldRestart = true;
|
|
3418
|
+
restartCount++;
|
|
3419
|
+
logger.info(
|
|
3420
|
+
`\u{1F503} Restarting execution with updated tools (restart ${restartCount}/${maxRestarts})`
|
|
3421
|
+
);
|
|
3422
|
+
break;
|
|
3423
|
+
}
|
|
3424
|
+
}
|
|
3425
|
+
}
|
|
3426
|
+
if (message instanceof import_messages.AIMessage && !("tool_calls" in message && Array.isArray(message.tool_calls) && message.tool_calls.length > 0)) {
|
|
3427
|
+
finalOutput = this._normalizeOutput(message.content);
|
|
3428
|
+
logger.info("\u2705 Agent finished with output");
|
|
3429
|
+
}
|
|
3430
|
+
}
|
|
3431
|
+
if (shouldRestart) {
|
|
3400
3432
|
break;
|
|
3401
3433
|
}
|
|
3402
3434
|
}
|
|
3403
3435
|
}
|
|
3404
|
-
|
|
3405
|
-
if (e instanceof import_output_parsers.OutputParserException) {
|
|
3406
|
-
logger.error(`\u274C Output parsing error during step ${stepNum + 1}: ${e}`);
|
|
3407
|
-
result = `Agent stopped due to a parsing error: ${e}`;
|
|
3408
|
-
runManager?.handleChainError(result);
|
|
3436
|
+
if (shouldRestart) {
|
|
3409
3437
|
break;
|
|
3410
3438
|
}
|
|
3411
|
-
|
|
3412
|
-
|
|
3413
|
-
|
|
3414
|
-
|
|
3439
|
+
}
|
|
3440
|
+
if (!shouldRestart) {
|
|
3441
|
+
break;
|
|
3442
|
+
}
|
|
3443
|
+
if (restartCount > maxRestarts) {
|
|
3444
|
+
logger.warn(`\u26A0\uFE0F Max restarts (${maxRestarts}) reached. Continuing with current tools.`);
|
|
3415
3445
|
break;
|
|
3416
3446
|
}
|
|
3417
3447
|
}
|
|
3418
|
-
if (
|
|
3419
|
-
|
|
3420
|
-
|
|
3421
|
-
|
|
3448
|
+
if (this.memoryEnabled) {
|
|
3449
|
+
this.addToHistory(new import_messages.HumanMessage(query));
|
|
3450
|
+
if (finalOutput) {
|
|
3451
|
+
this.addToHistory(new import_messages.AIMessage(finalOutput));
|
|
3452
|
+
}
|
|
3422
3453
|
}
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
|
|
3454
|
+
if (outputSchema && finalOutput) {
|
|
3455
|
+
try {
|
|
3456
|
+
logger.info("\u{1F527} Attempting structured output...");
|
|
3457
|
+
const structuredResult = await this._attemptStructuredOutput(
|
|
3458
|
+
finalOutput,
|
|
3459
|
+
this.llm,
|
|
3460
|
+
outputSchema
|
|
3461
|
+
);
|
|
3462
|
+
if (this.memoryEnabled) {
|
|
3463
|
+
this.addToHistory(new import_messages.AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
|
|
3464
|
+
}
|
|
3465
|
+
logger.info("\u2705 Structured output successful");
|
|
3466
|
+
success = true;
|
|
3467
|
+
return structuredResult;
|
|
3468
|
+
} catch (e) {
|
|
3469
|
+
logger.error(`\u274C Structured output failed: ${e}`);
|
|
3470
|
+
throw new Error(`Failed to generate structured output: ${e instanceof Error ? e.message : String(e)}`);
|
|
3471
|
+
}
|
|
3472
|
+
}
|
|
3473
|
+
logger.info(`\u{1F389} Agent execution complete in ${((Date.now() - startTime) / 1e3).toFixed(2)} seconds`);
|
|
3474
|
+
success = true;
|
|
3475
|
+
return finalOutput || "No output generated";
|
|
3426
3476
|
} catch (e) {
|
|
3427
3477
|
logger.error(`\u274C Error running query: ${e}`);
|
|
3428
3478
|
if (initializedHere && manageConnector) {
|
|
3429
|
-
logger.info("\u{1F9F9} Cleaning up resources after
|
|
3479
|
+
logger.info("\u{1F9F9} Cleaning up resources after error");
|
|
3430
3480
|
await this.close();
|
|
3431
3481
|
}
|
|
3432
3482
|
throw e;
|
|
@@ -3439,16 +3489,17 @@ var MCPAgent = class {
|
|
|
3439
3489
|
serverCount = this.connectors.length;
|
|
3440
3490
|
}
|
|
3441
3491
|
const conversationHistoryLength = this.memoryEnabled ? this.conversationHistory.length : 0;
|
|
3492
|
+
const toolsAvailable = this._tools || [];
|
|
3442
3493
|
await this.telemetry.trackAgentExecution({
|
|
3443
3494
|
executionMethod: "stream",
|
|
3444
3495
|
query,
|
|
3445
|
-
success
|
|
3496
|
+
success,
|
|
3446
3497
|
modelProvider: this.modelProvider,
|
|
3447
3498
|
modelName: this.modelName,
|
|
3448
3499
|
serverCount,
|
|
3449
3500
|
serverIdentifiers: this.connectors.map((connector) => connector.publicIdentifier),
|
|
3450
|
-
totalToolsAvailable:
|
|
3451
|
-
toolsAvailableNames:
|
|
3501
|
+
totalToolsAvailable: toolsAvailable.length,
|
|
3502
|
+
toolsAvailableNames: toolsAvailable.map((t) => t.name),
|
|
3452
3503
|
maxStepsConfigured: this.maxSteps,
|
|
3453
3504
|
memoryEnabled: this.memoryEnabled,
|
|
3454
3505
|
useServerManager: this.useServerManager,
|
|
@@ -3456,19 +3507,30 @@ var MCPAgent = class {
|
|
|
3456
3507
|
manageConnector,
|
|
3457
3508
|
externalHistoryUsed: externalHistory !== void 0,
|
|
3458
3509
|
stepsTaken,
|
|
3459
|
-
toolsUsedCount: toolsUsedNames.length,
|
|
3460
|
-
toolsUsedNames,
|
|
3461
|
-
response:
|
|
3510
|
+
toolsUsedCount: this.toolsUsedNames.length,
|
|
3511
|
+
toolsUsedNames: this.toolsUsedNames,
|
|
3512
|
+
response: finalOutput || "",
|
|
3462
3513
|
executionTimeMs,
|
|
3463
|
-
errorType:
|
|
3514
|
+
errorType: success ? null : "execution_error",
|
|
3464
3515
|
conversationHistoryLength
|
|
3465
3516
|
});
|
|
3466
3517
|
if (manageConnector && !this.client && initializedHere) {
|
|
3467
|
-
logger.info("\u{1F9F9} Closing agent after
|
|
3518
|
+
logger.info("\u{1F9F9} Closing agent after stream completion");
|
|
3468
3519
|
await this.close();
|
|
3469
3520
|
}
|
|
3470
3521
|
}
|
|
3471
3522
|
}
|
|
3523
|
+
/**
|
|
3524
|
+
* Flush observability traces to the configured observability platform.
|
|
3525
|
+
* Important for serverless environments where traces need to be sent before function termination.
|
|
3526
|
+
*/
|
|
3527
|
+
async flush() {
|
|
3528
|
+
if (this.isRemote && this.remoteAgent) {
|
|
3529
|
+
return;
|
|
3530
|
+
}
|
|
3531
|
+
logger.debug("Flushing observability traces...");
|
|
3532
|
+
await this.observabilityManager.flush();
|
|
3533
|
+
}
|
|
3472
3534
|
async close() {
|
|
3473
3535
|
if (this.isRemote && this.remoteAgent) {
|
|
3474
3536
|
await this.remoteAgent.close();
|
|
@@ -3519,34 +3581,40 @@ var MCPAgent = class {
|
|
|
3519
3581
|
await this.initialize();
|
|
3520
3582
|
initializedHere = true;
|
|
3521
3583
|
}
|
|
3522
|
-
const agentExecutor = this.
|
|
3584
|
+
const agentExecutor = this._agentExecutor;
|
|
3523
3585
|
if (!agentExecutor) {
|
|
3524
3586
|
throw new Error("MCP agent failed to initialize");
|
|
3525
3587
|
}
|
|
3526
|
-
|
|
3527
|
-
agentExecutor.maxIterations = steps;
|
|
3588
|
+
this.maxSteps = maxSteps ?? this.maxSteps;
|
|
3528
3589
|
const display_query = query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, " ")}...` : query.replace(/\n/g, " ");
|
|
3529
3590
|
logger.info(`\u{1F4AC} Received query for streamEvents: '${display_query}'`);
|
|
3530
3591
|
if (this.memoryEnabled) {
|
|
3531
3592
|
logger.info(`\u{1F504} Adding user message to history: ${query}`);
|
|
3532
|
-
this.addToHistory(new
|
|
3593
|
+
this.addToHistory(new import_messages.HumanMessage(query));
|
|
3533
3594
|
}
|
|
3534
3595
|
const historyToUse = externalHistory ?? this.conversationHistory;
|
|
3535
3596
|
const langchainHistory = [];
|
|
3536
3597
|
for (const msg of historyToUse) {
|
|
3537
|
-
if (msg instanceof
|
|
3598
|
+
if (msg instanceof import_messages.HumanMessage || msg instanceof import_messages.AIMessage || msg instanceof import_messages.ToolMessage) {
|
|
3538
3599
|
langchainHistory.push(msg);
|
|
3539
3600
|
} else {
|
|
3540
3601
|
logger.info(`\u26A0\uFE0F Skipped message of type: ${msg.constructor.name}`);
|
|
3541
3602
|
}
|
|
3542
3603
|
}
|
|
3543
|
-
const inputs =
|
|
3604
|
+
const inputs = [...langchainHistory, new import_messages.HumanMessage(query)];
|
|
3544
3605
|
logger.info("callbacks", this.callbacks);
|
|
3545
3606
|
const eventStream = agentExecutor.streamEvents(
|
|
3546
|
-
inputs,
|
|
3607
|
+
{ messages: inputs },
|
|
3547
3608
|
{
|
|
3609
|
+
streamMode: "updates",
|
|
3548
3610
|
version: "v2",
|
|
3549
|
-
callbacks: this.callbacks
|
|
3611
|
+
callbacks: this.callbacks,
|
|
3612
|
+
metadata: this.getMetadata(),
|
|
3613
|
+
tags: this.getTags(),
|
|
3614
|
+
// Set trace name for LangChain/Langfuse
|
|
3615
|
+
runName: this.metadata.trace_name || "mcp-use-agent",
|
|
3616
|
+
// Pass sessionId for Langfuse if present in metadata
|
|
3617
|
+
...this.metadata.session_id && { sessionId: this.metadata.session_id }
|
|
3550
3618
|
}
|
|
3551
3619
|
);
|
|
3552
3620
|
for await (const event of eventStream) {
|
|
@@ -3575,7 +3643,7 @@ var MCPAgent = class {
|
|
|
3575
3643
|
let conversionCompleted = false;
|
|
3576
3644
|
let conversionResult = null;
|
|
3577
3645
|
let conversionError = null;
|
|
3578
|
-
|
|
3646
|
+
this._attemptStructuredOutput(
|
|
3579
3647
|
finalResponse,
|
|
3580
3648
|
this.llm,
|
|
3581
3649
|
outputSchema
|
|
@@ -3611,7 +3679,7 @@ var MCPAgent = class {
|
|
|
3611
3679
|
data: { output: conversionResult }
|
|
3612
3680
|
};
|
|
3613
3681
|
if (this.memoryEnabled) {
|
|
3614
|
-
this.addToHistory(new
|
|
3682
|
+
this.addToHistory(new import_messages.AIMessage(`Structured result: ${JSON.stringify(conversionResult)}`));
|
|
3615
3683
|
}
|
|
3616
3684
|
logger.info("\u2705 Structured output successful");
|
|
3617
3685
|
}
|
|
@@ -3623,7 +3691,7 @@ var MCPAgent = class {
|
|
|
3623
3691
|
};
|
|
3624
3692
|
}
|
|
3625
3693
|
} else if (this.memoryEnabled && finalResponse) {
|
|
3626
|
-
this.addToHistory(new
|
|
3694
|
+
this.addToHistory(new import_messages.AIMessage(finalResponse));
|
|
3627
3695
|
}
|
|
3628
3696
|
logger.info(`\u{1F389} StreamEvents complete - ${eventCount} events emitted`);
|
|
3629
3697
|
success = true;
|
|
@@ -3672,6 +3740,10 @@ var MCPAgent = class {
|
|
|
3672
3740
|
}
|
|
3673
3741
|
/**
|
|
3674
3742
|
* Attempt to create structured output from raw result with validation and retry logic.
|
|
3743
|
+
*
|
|
3744
|
+
* @param rawResult - The raw text result from the agent
|
|
3745
|
+
* @param llm - LLM to use for structured output
|
|
3746
|
+
* @param outputSchema - The Zod schema to validate against
|
|
3675
3747
|
*/
|
|
3676
3748
|
async _attemptStructuredOutput(rawResult, llm, outputSchema) {
|
|
3677
3749
|
logger.info(`\u{1F504} Attempting structured output with schema: ${outputSchema}`);
|
|
@@ -4171,7 +4243,7 @@ async function* streamEventsToAISDKWithTools(streamEvents) {
|
|
|
4171
4243
|
__name(streamEventsToAISDKWithTools, "streamEventsToAISDKWithTools");
|
|
4172
4244
|
|
|
4173
4245
|
// src/browser.ts
|
|
4174
|
-
var
|
|
4246
|
+
var import_messages2 = require("@langchain/core/messages");
|
|
4175
4247
|
// Annotate the CommonJS export names for ESM import in node:
|
|
4176
4248
|
0 && (module.exports = {
|
|
4177
4249
|
AIMessage,
|