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/index.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,16 +484,16 @@ var init_langfuse = __esm({
|
|
|
469
484
|
// index.ts
|
|
470
485
|
var index_exports = {};
|
|
471
486
|
__export(index_exports, {
|
|
472
|
-
AIMessage: () =>
|
|
487
|
+
AIMessage: () => import_messages2.AIMessage,
|
|
473
488
|
AcquireActiveMCPServerTool: () => AcquireActiveMCPServerTool,
|
|
474
489
|
AddMCPServerFromConfigTool: () => AddMCPServerFromConfigTool,
|
|
475
490
|
BaseAdapter: () => BaseAdapter,
|
|
476
491
|
BaseConnector: () => BaseConnector,
|
|
477
|
-
BaseMessage: () =>
|
|
492
|
+
BaseMessage: () => import_messages2.BaseMessage,
|
|
478
493
|
BrowserOAuthClientProvider: () => BrowserOAuthClientProvider,
|
|
479
494
|
ConnectMCPServerTool: () => ConnectMCPServerTool,
|
|
480
495
|
HttpConnector: () => HttpConnector,
|
|
481
|
-
HumanMessage: () =>
|
|
496
|
+
HumanMessage: () => import_messages2.HumanMessage,
|
|
482
497
|
LINEAR_OAUTH_CONFIG: () => LINEAR_OAUTH_CONFIG,
|
|
483
498
|
LangChainAdapter: () => LangChainAdapter,
|
|
484
499
|
ListMCPServersTool: () => ListMCPServersTool,
|
|
@@ -492,9 +507,9 @@ __export(index_exports, {
|
|
|
492
507
|
RemoteAgent: () => RemoteAgent,
|
|
493
508
|
ServerManager: () => ServerManager,
|
|
494
509
|
StdioConnector: () => StdioConnector,
|
|
495
|
-
SystemMessage: () =>
|
|
510
|
+
SystemMessage: () => import_messages2.SystemMessage,
|
|
496
511
|
Telemetry: () => Telemetry,
|
|
497
|
-
ToolMessage: () =>
|
|
512
|
+
ToolMessage: () => import_messages2.ToolMessage,
|
|
498
513
|
WebSocketConnector: () => WebSocketConnector,
|
|
499
514
|
createOAuthMCPConfig: () => createOAuthMCPConfig,
|
|
500
515
|
createReadableStreamFromGenerator: () => createReadableStreamFromGenerator,
|
|
@@ -513,11 +528,8 @@ __export(index_exports, {
|
|
|
513
528
|
module.exports = __toCommonJS(index_exports);
|
|
514
529
|
|
|
515
530
|
// src/agents/mcp_agent.ts
|
|
516
|
-
var
|
|
517
|
-
var
|
|
518
|
-
var import_output_parsers = require("@langchain/core/output_parsers");
|
|
519
|
-
var import_prompts = require("@langchain/core/prompts");
|
|
520
|
-
var import_agents = require("langchain/agents");
|
|
531
|
+
var import_messages = require("@langchain/core/messages");
|
|
532
|
+
var import_langchain2 = require("langchain");
|
|
521
533
|
var import_zod_to_json_schema2 = require("zod-to-json-schema");
|
|
522
534
|
|
|
523
535
|
// src/adapters/langchain_adapter.ts
|
|
@@ -738,7 +750,7 @@ var AcquireActiveMCPServerTool = class extends MCPServerTool {
|
|
|
738
750
|
};
|
|
739
751
|
|
|
740
752
|
// src/managers/tools/add_server_from_config.ts
|
|
741
|
-
var import_tools3 = require("langchain/tools");
|
|
753
|
+
var import_tools3 = require("@langchain/core/tools");
|
|
742
754
|
var import_zod3 = require("zod");
|
|
743
755
|
init_logging();
|
|
744
756
|
var AddMCPServerFromConfigTool = class extends import_tools3.StructuredTool {
|
|
@@ -1111,6 +1123,23 @@ var ObservabilityManager = class {
|
|
|
1111
1123
|
const callbacks = await this.getCallbacks();
|
|
1112
1124
|
return callbacks.length > 0;
|
|
1113
1125
|
}
|
|
1126
|
+
/**
|
|
1127
|
+
* Get the current observability status including metadata and tags.
|
|
1128
|
+
* @returns Object containing enabled status, callback count, handler names, metadata, and tags.
|
|
1129
|
+
*/
|
|
1130
|
+
async getStatus() {
|
|
1131
|
+
const callbacks = await this.getCallbacks();
|
|
1132
|
+
const handlerNames = await this.getHandlerNames();
|
|
1133
|
+
const currentMetadata = this.metadataProvider ? this.metadataProvider() : this.metadata || {};
|
|
1134
|
+
const currentTags = this.tagsProvider ? this.tagsProvider() : [];
|
|
1135
|
+
return {
|
|
1136
|
+
enabled: this.observe && callbacks.length > 0,
|
|
1137
|
+
callbackCount: callbacks.length,
|
|
1138
|
+
handlerNames,
|
|
1139
|
+
metadata: currentMetadata,
|
|
1140
|
+
tags: currentTags
|
|
1141
|
+
};
|
|
1142
|
+
}
|
|
1114
1143
|
/**
|
|
1115
1144
|
* Add a callback to the custom callbacks list.
|
|
1116
1145
|
* @param callback The callback to add.
|
|
@@ -1548,7 +1577,7 @@ function setTelemetrySource(source) {
|
|
|
1548
1577
|
__name(setTelemetrySource, "setTelemetrySource");
|
|
1549
1578
|
|
|
1550
1579
|
// src/agents/prompts/system_prompt_builder.ts
|
|
1551
|
-
var
|
|
1580
|
+
var import_langchain = require("langchain");
|
|
1552
1581
|
function generateToolDescriptions(tools, disallowedTools) {
|
|
1553
1582
|
const disallowedSet = new Set(disallowedTools ?? []);
|
|
1554
1583
|
const descriptions = [];
|
|
@@ -1583,7 +1612,7 @@ ${additionalInstructions}`;
|
|
|
1583
1612
|
__name(buildSystemPromptContent, "buildSystemPromptContent");
|
|
1584
1613
|
function createSystemMessage(tools, systemPromptTemplate, serverManagerTemplate, useServerManager, disallowedTools, userProvidedPrompt, additionalInstructions) {
|
|
1585
1614
|
if (userProvidedPrompt) {
|
|
1586
|
-
return new
|
|
1615
|
+
return new import_langchain.SystemMessage({ content: userProvidedPrompt });
|
|
1587
1616
|
}
|
|
1588
1617
|
const template = useServerManager ? serverManagerTemplate : systemPromptTemplate;
|
|
1589
1618
|
const toolLines = generateToolDescriptions(tools, disallowedTools);
|
|
@@ -1592,7 +1621,7 @@ function createSystemMessage(tools, systemPromptTemplate, serverManagerTemplate,
|
|
|
1592
1621
|
toolLines,
|
|
1593
1622
|
additionalInstructions
|
|
1594
1623
|
);
|
|
1595
|
-
return new
|
|
1624
|
+
return new import_langchain.SystemMessage({ content: finalContent });
|
|
1596
1625
|
}
|
|
1597
1626
|
__name(createSystemMessage, "createSystemMessage");
|
|
1598
1627
|
|
|
@@ -1869,6 +1898,7 @@ var MCPAgent = class {
|
|
|
1869
1898
|
memoryEnabled;
|
|
1870
1899
|
disallowedTools;
|
|
1871
1900
|
additionalTools;
|
|
1901
|
+
toolsUsedNames = [];
|
|
1872
1902
|
useServerManager;
|
|
1873
1903
|
verbose;
|
|
1874
1904
|
observe;
|
|
@@ -1936,6 +1966,7 @@ var MCPAgent = class {
|
|
|
1936
1966
|
this.additionalInstructions = options.additionalInstructions ?? null;
|
|
1937
1967
|
this.disallowedTools = options.disallowedTools ?? [];
|
|
1938
1968
|
this.additionalTools = options.additionalTools ?? [];
|
|
1969
|
+
this.toolsUsedNames = options.toolsUsedNames ?? [];
|
|
1939
1970
|
this.useServerManager = options.useServerManager ?? false;
|
|
1940
1971
|
this.verbose = options.verbose ?? false;
|
|
1941
1972
|
this.observe = options.observe ?? true;
|
|
@@ -2050,7 +2081,7 @@ var MCPAgent = class {
|
|
|
2050
2081
|
if (this.memoryEnabled) {
|
|
2051
2082
|
this.conversationHistory = [
|
|
2052
2083
|
this.systemMessage,
|
|
2053
|
-
...this.conversationHistory.filter((m) => !(m instanceof
|
|
2084
|
+
...this.conversationHistory.filter((m) => !(m instanceof import_langchain2.SystemMessage))
|
|
2054
2085
|
];
|
|
2055
2086
|
}
|
|
2056
2087
|
}
|
|
@@ -2059,25 +2090,17 @@ var MCPAgent = class {
|
|
|
2059
2090
|
throw new Error("LLM is required to create agent");
|
|
2060
2091
|
}
|
|
2061
2092
|
const systemContent = this.systemMessage?.content ?? "You are a helpful assistant.";
|
|
2062
|
-
const
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
]);
|
|
2068
|
-
const agent = (0, import_agents.createToolCallingAgent)({
|
|
2069
|
-
llm: this.llm,
|
|
2093
|
+
const toolNames = this._tools.map((tool) => tool.name);
|
|
2094
|
+
logger.info(`\u{1F9E0} Agent ready with tools: ${toolNames.join(", ")}`);
|
|
2095
|
+
const middleware = [(0, import_langchain2.modelCallLimitMiddleware)({ runLimit: this.maxSteps })];
|
|
2096
|
+
const agent = (0, import_langchain2.createAgent)({
|
|
2097
|
+
model: this.llm,
|
|
2070
2098
|
tools: this._tools,
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
return new import_agents.AgentExecutor({
|
|
2074
|
-
agent,
|
|
2075
|
-
tools: this._tools,
|
|
2076
|
-
maxIterations: this.maxSteps,
|
|
2077
|
-
verbose: this.verbose,
|
|
2078
|
-
returnIntermediateSteps: true,
|
|
2079
|
-
callbacks: this.callbacks
|
|
2099
|
+
systemPrompt: systemContent,
|
|
2100
|
+
middleware
|
|
2080
2101
|
});
|
|
2102
|
+
logger.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`);
|
|
2103
|
+
return agent;
|
|
2081
2104
|
}
|
|
2082
2105
|
getConversationHistory() {
|
|
2083
2106
|
return [...this.conversationHistory];
|
|
@@ -2093,9 +2116,9 @@ var MCPAgent = class {
|
|
|
2093
2116
|
return this.systemMessage;
|
|
2094
2117
|
}
|
|
2095
2118
|
setSystemMessage(message) {
|
|
2096
|
-
this.systemMessage = new
|
|
2119
|
+
this.systemMessage = new import_langchain2.SystemMessage(message);
|
|
2097
2120
|
if (this.memoryEnabled) {
|
|
2098
|
-
this.conversationHistory = this.conversationHistory.filter((m) => !(m instanceof
|
|
2121
|
+
this.conversationHistory = this.conversationHistory.filter((m) => !(m instanceof import_langchain2.SystemMessage));
|
|
2099
2122
|
this.conversationHistory.unshift(this.systemMessage);
|
|
2100
2123
|
}
|
|
2101
2124
|
if (this._initialized && this._tools.length) {
|
|
@@ -2245,6 +2268,42 @@ var MCPAgent = class {
|
|
|
2245
2268
|
}
|
|
2246
2269
|
return serverInfo;
|
|
2247
2270
|
}
|
|
2271
|
+
_normalizeOutput(value) {
|
|
2272
|
+
try {
|
|
2273
|
+
if (typeof value === "string") {
|
|
2274
|
+
return value;
|
|
2275
|
+
}
|
|
2276
|
+
if (value && typeof value === "object" && "content" in value) {
|
|
2277
|
+
return this._normalizeOutput(value.content);
|
|
2278
|
+
}
|
|
2279
|
+
if (Array.isArray(value)) {
|
|
2280
|
+
const parts = [];
|
|
2281
|
+
for (const item of value) {
|
|
2282
|
+
if (typeof item === "object" && item !== null) {
|
|
2283
|
+
if ("text" in item && typeof item.text === "string") {
|
|
2284
|
+
parts.push(item.text);
|
|
2285
|
+
} else if ("content" in item) {
|
|
2286
|
+
parts.push(this._normalizeOutput(item.content));
|
|
2287
|
+
} else {
|
|
2288
|
+
parts.push(String(item));
|
|
2289
|
+
}
|
|
2290
|
+
} else {
|
|
2291
|
+
const partText = item && typeof item === "object" && "text" in item ? item.text : null;
|
|
2292
|
+
if (typeof partText === "string") {
|
|
2293
|
+
parts.push(partText);
|
|
2294
|
+
} else {
|
|
2295
|
+
const partContent = item && typeof item === "object" && "content" in item ? item.content : item;
|
|
2296
|
+
parts.push(this._normalizeOutput(partContent));
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
return parts.join("");
|
|
2301
|
+
}
|
|
2302
|
+
return String(value);
|
|
2303
|
+
} catch (error) {
|
|
2304
|
+
return String(value);
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2248
2307
|
async _consumeAndReturn(generator) {
|
|
2249
2308
|
while (true) {
|
|
2250
2309
|
const { done, value } = await generator.next();
|
|
@@ -2266,36 +2325,16 @@ var MCPAgent = class {
|
|
|
2266
2325
|
);
|
|
2267
2326
|
return this._consumeAndReturn(generator);
|
|
2268
2327
|
}
|
|
2269
|
-
/**
|
|
2270
|
-
* Runs the agent and yields intermediate steps as an async generator.
|
|
2271
|
-
* If outputSchema is provided, returns structured output of type T.
|
|
2272
|
-
*/
|
|
2273
2328
|
async *stream(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
|
|
2274
2329
|
if (this.isRemote && this.remoteAgent) {
|
|
2275
|
-
const
|
|
2276
|
-
return
|
|
2330
|
+
const result = await this.remoteAgent.run(query, maxSteps, manageConnector, externalHistory, outputSchema);
|
|
2331
|
+
return result;
|
|
2277
2332
|
}
|
|
2278
|
-
let result = "";
|
|
2279
2333
|
let initializedHere = false;
|
|
2280
2334
|
const startTime = Date.now();
|
|
2281
|
-
|
|
2335
|
+
let success = false;
|
|
2336
|
+
let finalOutput = null;
|
|
2282
2337
|
let stepsTaken = 0;
|
|
2283
|
-
const structuredOutputSuccess = false;
|
|
2284
|
-
const structuredOutputSuccessRef = { value: structuredOutputSuccess };
|
|
2285
|
-
let structuredLlm = null;
|
|
2286
|
-
let schemaDescription = "";
|
|
2287
|
-
if (outputSchema) {
|
|
2288
|
-
query = this._enhanceQueryWithSchema(query, outputSchema);
|
|
2289
|
-
logger.debug(`\u{1F504} Structured output requested, schema: ${JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2)}`);
|
|
2290
|
-
if (this.llm && "withStructuredOutput" in this.llm && typeof this.llm.withStructuredOutput === "function") {
|
|
2291
|
-
structuredLlm = this.llm.withStructuredOutput(outputSchema);
|
|
2292
|
-
} else if (this.llm) {
|
|
2293
|
-
structuredLlm = this.llm;
|
|
2294
|
-
} else {
|
|
2295
|
-
throw new Error("LLM is required for structured output");
|
|
2296
|
-
}
|
|
2297
|
-
schemaDescription = JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2);
|
|
2298
|
-
}
|
|
2299
2338
|
try {
|
|
2300
2339
|
if (manageConnector && !this._initialized) {
|
|
2301
2340
|
await this.initialize();
|
|
@@ -2307,158 +2346,169 @@ var MCPAgent = class {
|
|
|
2307
2346
|
if (!this._agentExecutor) {
|
|
2308
2347
|
throw new Error("MCP agent failed to initialize");
|
|
2309
2348
|
}
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2349
|
+
if (this.useServerManager && this.serverManager) {
|
|
2350
|
+
const currentTools = this.serverManager.tools;
|
|
2351
|
+
const currentToolNames = new Set(currentTools.map((t) => t.name));
|
|
2352
|
+
const existingToolNames = new Set(this._tools.map((t) => t.name));
|
|
2353
|
+
if (currentToolNames.size !== existingToolNames.size || [...currentToolNames].some((n) => !existingToolNames.has(n))) {
|
|
2354
|
+
logger.info(
|
|
2355
|
+
`\u{1F504} Tools changed before execution, updating agent. New tools: ${[...currentToolNames].join(", ")}`
|
|
2356
|
+
);
|
|
2357
|
+
this._tools = currentTools;
|
|
2358
|
+
this._tools.push(...this.additionalTools);
|
|
2359
|
+
await this.createSystemMessageFromTools(this._tools);
|
|
2360
|
+
this._agentExecutor = this.createAgent();
|
|
2361
|
+
}
|
|
2316
2362
|
}
|
|
2317
2363
|
const historyToUse = externalHistory ?? this.conversationHistory;
|
|
2318
2364
|
const langchainHistory = [];
|
|
2319
2365
|
for (const msg of historyToUse) {
|
|
2320
|
-
if (msg instanceof
|
|
2366
|
+
if (msg instanceof import_messages.HumanMessage || msg instanceof import_messages.AIMessage) {
|
|
2321
2367
|
langchainHistory.push(msg);
|
|
2322
2368
|
}
|
|
2323
2369
|
}
|
|
2324
|
-
const
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
let
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
const currentToolNames = new Set(currentTools.map((t) => t.name));
|
|
2346
|
-
const existingToolNames = new Set(this._tools.map((t) => t.name));
|
|
2347
|
-
const changed = currentTools.length !== this._tools.length || [...currentToolNames].some((n) => !existingToolNames.has(n));
|
|
2348
|
-
if (changed) {
|
|
2349
|
-
logger.info(
|
|
2350
|
-
`\u{1F504} Tools changed before step ${stepNum + 1}, updating agent. New tools: ${[...currentToolNames].join(", ")}`
|
|
2351
|
-
);
|
|
2352
|
-
this._tools = currentTools;
|
|
2353
|
-
this._tools.push(...this.additionalTools);
|
|
2354
|
-
await this.createSystemMessageFromTools(this._tools);
|
|
2355
|
-
this._agentExecutor = this.createAgent();
|
|
2356
|
-
this._agentExecutor.maxIterations = steps;
|
|
2357
|
-
nameToToolMap = Object.fromEntries(this._tools.map((t) => [t.name, t]));
|
|
2370
|
+
const displayQuery = query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, " ")}...` : query.replace(/\n/g, " ");
|
|
2371
|
+
logger.info(`\u{1F4AC} Received query: '${displayQuery}'`);
|
|
2372
|
+
logger.info("\u{1F3C1} Starting agent execution");
|
|
2373
|
+
const maxRestarts = 3;
|
|
2374
|
+
let restartCount = 0;
|
|
2375
|
+
const accumulatedMessages = [...langchainHistory, new import_messages.HumanMessage(query)];
|
|
2376
|
+
while (restartCount <= maxRestarts) {
|
|
2377
|
+
const inputs = { messages: accumulatedMessages };
|
|
2378
|
+
let shouldRestart = false;
|
|
2379
|
+
const stream = await this._agentExecutor.stream(
|
|
2380
|
+
inputs,
|
|
2381
|
+
{
|
|
2382
|
+
streamMode: "updates",
|
|
2383
|
+
// Get updates as they happen
|
|
2384
|
+
callbacks: this.callbacks,
|
|
2385
|
+
metadata: this.getMetadata(),
|
|
2386
|
+
tags: this.getTags(),
|
|
2387
|
+
// Set trace name for LangChain/Langfuse
|
|
2388
|
+
runName: this.metadata.trace_name || "mcp-use-agent",
|
|
2389
|
+
// Pass sessionId for Langfuse if present in metadata
|
|
2390
|
+
...this.metadata.session_id && { sessionId: this.metadata.session_id }
|
|
2358
2391
|
}
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
result = nextStepOutput.returnValues?.output ?? "No output generated";
|
|
2372
|
-
runManager?.handleChainEnd({ output: result });
|
|
2373
|
-
if (outputSchema && structuredLlm) {
|
|
2374
|
-
logger.info("\u{1F527} Attempting structured output...");
|
|
2375
|
-
const currentResult = result;
|
|
2376
|
-
this._attemptStructuredOutput(
|
|
2377
|
-
currentResult,
|
|
2378
|
-
this.llm,
|
|
2379
|
-
outputSchema
|
|
2380
|
-
).then((structuredResult) => {
|
|
2381
|
-
if (this.memoryEnabled) {
|
|
2382
|
-
this.addToHistory(new import_messages2.AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
|
|
2392
|
+
);
|
|
2393
|
+
for await (const chunk of stream) {
|
|
2394
|
+
for (const [nodeName, nodeOutput] of Object.entries(chunk)) {
|
|
2395
|
+
logger.debug(`\u{1F4E6} Node '${nodeName}' output: ${JSON.stringify(nodeOutput)}`);
|
|
2396
|
+
if (nodeOutput && typeof nodeOutput === "object" && "messages" in nodeOutput) {
|
|
2397
|
+
let messages = nodeOutput.messages;
|
|
2398
|
+
if (!Array.isArray(messages)) {
|
|
2399
|
+
messages = [messages];
|
|
2400
|
+
}
|
|
2401
|
+
for (const msg of messages) {
|
|
2402
|
+
if (!accumulatedMessages.includes(msg)) {
|
|
2403
|
+
accumulatedMessages.push(msg);
|
|
2383
2404
|
}
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2405
|
+
}
|
|
2406
|
+
for (const message of messages) {
|
|
2407
|
+
if ("tool_calls" in message && Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {
|
|
2408
|
+
for (const toolCall of message.tool_calls) {
|
|
2409
|
+
const toolName = toolCall.name || "unknown";
|
|
2410
|
+
const toolInput = toolCall.args || {};
|
|
2411
|
+
this.toolsUsedNames.push(toolName);
|
|
2412
|
+
stepsTaken++;
|
|
2413
|
+
let toolInputStr = JSON.stringify(toolInput);
|
|
2414
|
+
if (toolInputStr.length > 100) {
|
|
2415
|
+
toolInputStr = `${toolInputStr.slice(0, 97)}...`;
|
|
2416
|
+
}
|
|
2417
|
+
logger.info(`\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`);
|
|
2418
|
+
yield {
|
|
2419
|
+
action: {
|
|
2420
|
+
tool: toolName,
|
|
2421
|
+
toolInput,
|
|
2422
|
+
log: `Calling tool ${toolName}`
|
|
2423
|
+
},
|
|
2424
|
+
observation: ""
|
|
2425
|
+
// Will be filled in by tool result
|
|
2426
|
+
};
|
|
2427
|
+
}
|
|
2403
2428
|
}
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2429
|
+
if (message instanceof import_messages.ToolMessage || message && "type" in message && message.type === "tool") {
|
|
2430
|
+
const observation = message.content;
|
|
2431
|
+
let observationStr = String(observation);
|
|
2432
|
+
if (observationStr.length > 100) {
|
|
2433
|
+
observationStr = `${observationStr.slice(0, 97)}...`;
|
|
2434
|
+
}
|
|
2435
|
+
observationStr = observationStr.replace(/\n/g, " ");
|
|
2436
|
+
logger.info(`\u{1F4C4} Tool result: ${observationStr}`);
|
|
2437
|
+
if (this.useServerManager && this.serverManager) {
|
|
2438
|
+
const currentTools = this.serverManager.tools;
|
|
2439
|
+
const currentToolNames = new Set(currentTools.map((t) => t.name));
|
|
2440
|
+
const existingToolNames = new Set(this._tools.map((t) => t.name));
|
|
2441
|
+
if (currentToolNames.size !== existingToolNames.size || [...currentToolNames].some((n) => !existingToolNames.has(n))) {
|
|
2442
|
+
logger.info(
|
|
2443
|
+
`\u{1F504} Tools changed during execution. New tools: ${[...currentToolNames].join(", ")}`
|
|
2444
|
+
);
|
|
2445
|
+
this._tools = currentTools;
|
|
2446
|
+
this._tools.push(...this.additionalTools);
|
|
2447
|
+
await this.createSystemMessageFromTools(this._tools);
|
|
2448
|
+
this._agentExecutor = this.createAgent();
|
|
2449
|
+
shouldRestart = true;
|
|
2450
|
+
restartCount++;
|
|
2451
|
+
logger.info(
|
|
2452
|
+
`\u{1F503} Restarting execution with updated tools (restart ${restartCount}/${maxRestarts})`
|
|
2453
|
+
);
|
|
2454
|
+
break;
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2458
|
+
if (message instanceof import_messages.AIMessage && !("tool_calls" in message && Array.isArray(message.tool_calls) && message.tool_calls.length > 0)) {
|
|
2459
|
+
finalOutput = this._normalizeOutput(message.content);
|
|
2460
|
+
logger.info("\u2705 Agent finished with output");
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
if (shouldRestart) {
|
|
2432
2464
|
break;
|
|
2433
2465
|
}
|
|
2434
2466
|
}
|
|
2435
2467
|
}
|
|
2436
|
-
|
|
2437
|
-
if (e instanceof import_output_parsers.OutputParserException) {
|
|
2438
|
-
logger.error(`\u274C Output parsing error during step ${stepNum + 1}: ${e}`);
|
|
2439
|
-
result = `Agent stopped due to a parsing error: ${e}`;
|
|
2440
|
-
runManager?.handleChainError(result);
|
|
2468
|
+
if (shouldRestart) {
|
|
2441
2469
|
break;
|
|
2442
2470
|
}
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2471
|
+
}
|
|
2472
|
+
if (!shouldRestart) {
|
|
2473
|
+
break;
|
|
2474
|
+
}
|
|
2475
|
+
if (restartCount > maxRestarts) {
|
|
2476
|
+
logger.warn(`\u26A0\uFE0F Max restarts (${maxRestarts}) reached. Continuing with current tools.`);
|
|
2447
2477
|
break;
|
|
2448
2478
|
}
|
|
2449
2479
|
}
|
|
2450
|
-
if (
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2480
|
+
if (this.memoryEnabled) {
|
|
2481
|
+
this.addToHistory(new import_messages.HumanMessage(query));
|
|
2482
|
+
if (finalOutput) {
|
|
2483
|
+
this.addToHistory(new import_messages.AIMessage(finalOutput));
|
|
2484
|
+
}
|
|
2454
2485
|
}
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2486
|
+
if (outputSchema && finalOutput) {
|
|
2487
|
+
try {
|
|
2488
|
+
logger.info("\u{1F527} Attempting structured output...");
|
|
2489
|
+
const structuredResult = await this._attemptStructuredOutput(
|
|
2490
|
+
finalOutput,
|
|
2491
|
+
this.llm,
|
|
2492
|
+
outputSchema
|
|
2493
|
+
);
|
|
2494
|
+
if (this.memoryEnabled) {
|
|
2495
|
+
this.addToHistory(new import_messages.AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
|
|
2496
|
+
}
|
|
2497
|
+
logger.info("\u2705 Structured output successful");
|
|
2498
|
+
success = true;
|
|
2499
|
+
return structuredResult;
|
|
2500
|
+
} catch (e) {
|
|
2501
|
+
logger.error(`\u274C Structured output failed: ${e}`);
|
|
2502
|
+
throw new Error(`Failed to generate structured output: ${e instanceof Error ? e.message : String(e)}`);
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
logger.info(`\u{1F389} Agent execution complete in ${((Date.now() - startTime) / 1e3).toFixed(2)} seconds`);
|
|
2506
|
+
success = true;
|
|
2507
|
+
return finalOutput || "No output generated";
|
|
2458
2508
|
} catch (e) {
|
|
2459
2509
|
logger.error(`\u274C Error running query: ${e}`);
|
|
2460
2510
|
if (initializedHere && manageConnector) {
|
|
2461
|
-
logger.info("\u{1F9F9} Cleaning up resources after
|
|
2511
|
+
logger.info("\u{1F9F9} Cleaning up resources after error");
|
|
2462
2512
|
await this.close();
|
|
2463
2513
|
}
|
|
2464
2514
|
throw e;
|
|
@@ -2471,16 +2521,17 @@ var MCPAgent = class {
|
|
|
2471
2521
|
serverCount = this.connectors.length;
|
|
2472
2522
|
}
|
|
2473
2523
|
const conversationHistoryLength = this.memoryEnabled ? this.conversationHistory.length : 0;
|
|
2524
|
+
const toolsAvailable = this._tools || [];
|
|
2474
2525
|
await this.telemetry.trackAgentExecution({
|
|
2475
2526
|
executionMethod: "stream",
|
|
2476
2527
|
query,
|
|
2477
|
-
success
|
|
2528
|
+
success,
|
|
2478
2529
|
modelProvider: this.modelProvider,
|
|
2479
2530
|
modelName: this.modelName,
|
|
2480
2531
|
serverCount,
|
|
2481
2532
|
serverIdentifiers: this.connectors.map((connector) => connector.publicIdentifier),
|
|
2482
|
-
totalToolsAvailable:
|
|
2483
|
-
toolsAvailableNames:
|
|
2533
|
+
totalToolsAvailable: toolsAvailable.length,
|
|
2534
|
+
toolsAvailableNames: toolsAvailable.map((t) => t.name),
|
|
2484
2535
|
maxStepsConfigured: this.maxSteps,
|
|
2485
2536
|
memoryEnabled: this.memoryEnabled,
|
|
2486
2537
|
useServerManager: this.useServerManager,
|
|
@@ -2488,19 +2539,30 @@ var MCPAgent = class {
|
|
|
2488
2539
|
manageConnector,
|
|
2489
2540
|
externalHistoryUsed: externalHistory !== void 0,
|
|
2490
2541
|
stepsTaken,
|
|
2491
|
-
toolsUsedCount: toolsUsedNames.length,
|
|
2492
|
-
toolsUsedNames,
|
|
2493
|
-
response:
|
|
2542
|
+
toolsUsedCount: this.toolsUsedNames.length,
|
|
2543
|
+
toolsUsedNames: this.toolsUsedNames,
|
|
2544
|
+
response: finalOutput || "",
|
|
2494
2545
|
executionTimeMs,
|
|
2495
|
-
errorType:
|
|
2546
|
+
errorType: success ? null : "execution_error",
|
|
2496
2547
|
conversationHistoryLength
|
|
2497
2548
|
});
|
|
2498
2549
|
if (manageConnector && !this.client && initializedHere) {
|
|
2499
|
-
logger.info("\u{1F9F9} Closing agent after
|
|
2550
|
+
logger.info("\u{1F9F9} Closing agent after stream completion");
|
|
2500
2551
|
await this.close();
|
|
2501
2552
|
}
|
|
2502
2553
|
}
|
|
2503
2554
|
}
|
|
2555
|
+
/**
|
|
2556
|
+
* Flush observability traces to the configured observability platform.
|
|
2557
|
+
* Important for serverless environments where traces need to be sent before function termination.
|
|
2558
|
+
*/
|
|
2559
|
+
async flush() {
|
|
2560
|
+
if (this.isRemote && this.remoteAgent) {
|
|
2561
|
+
return;
|
|
2562
|
+
}
|
|
2563
|
+
logger.debug("Flushing observability traces...");
|
|
2564
|
+
await this.observabilityManager.flush();
|
|
2565
|
+
}
|
|
2504
2566
|
async close() {
|
|
2505
2567
|
if (this.isRemote && this.remoteAgent) {
|
|
2506
2568
|
await this.remoteAgent.close();
|
|
@@ -2551,34 +2613,40 @@ var MCPAgent = class {
|
|
|
2551
2613
|
await this.initialize();
|
|
2552
2614
|
initializedHere = true;
|
|
2553
2615
|
}
|
|
2554
|
-
const agentExecutor = this.
|
|
2616
|
+
const agentExecutor = this._agentExecutor;
|
|
2555
2617
|
if (!agentExecutor) {
|
|
2556
2618
|
throw new Error("MCP agent failed to initialize");
|
|
2557
2619
|
}
|
|
2558
|
-
|
|
2559
|
-
agentExecutor.maxIterations = steps;
|
|
2620
|
+
this.maxSteps = maxSteps ?? this.maxSteps;
|
|
2560
2621
|
const display_query = query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, " ")}...` : query.replace(/\n/g, " ");
|
|
2561
2622
|
logger.info(`\u{1F4AC} Received query for streamEvents: '${display_query}'`);
|
|
2562
2623
|
if (this.memoryEnabled) {
|
|
2563
2624
|
logger.info(`\u{1F504} Adding user message to history: ${query}`);
|
|
2564
|
-
this.addToHistory(new
|
|
2625
|
+
this.addToHistory(new import_messages.HumanMessage(query));
|
|
2565
2626
|
}
|
|
2566
2627
|
const historyToUse = externalHistory ?? this.conversationHistory;
|
|
2567
2628
|
const langchainHistory = [];
|
|
2568
2629
|
for (const msg of historyToUse) {
|
|
2569
|
-
if (msg instanceof
|
|
2630
|
+
if (msg instanceof import_messages.HumanMessage || msg instanceof import_messages.AIMessage || msg instanceof import_messages.ToolMessage) {
|
|
2570
2631
|
langchainHistory.push(msg);
|
|
2571
2632
|
} else {
|
|
2572
2633
|
logger.info(`\u26A0\uFE0F Skipped message of type: ${msg.constructor.name}`);
|
|
2573
2634
|
}
|
|
2574
2635
|
}
|
|
2575
|
-
const inputs =
|
|
2636
|
+
const inputs = [...langchainHistory, new import_messages.HumanMessage(query)];
|
|
2576
2637
|
logger.info("callbacks", this.callbacks);
|
|
2577
2638
|
const eventStream = agentExecutor.streamEvents(
|
|
2578
|
-
inputs,
|
|
2639
|
+
{ messages: inputs },
|
|
2579
2640
|
{
|
|
2641
|
+
streamMode: "updates",
|
|
2580
2642
|
version: "v2",
|
|
2581
|
-
callbacks: this.callbacks
|
|
2643
|
+
callbacks: this.callbacks,
|
|
2644
|
+
metadata: this.getMetadata(),
|
|
2645
|
+
tags: this.getTags(),
|
|
2646
|
+
// Set trace name for LangChain/Langfuse
|
|
2647
|
+
runName: this.metadata.trace_name || "mcp-use-agent",
|
|
2648
|
+
// Pass sessionId for Langfuse if present in metadata
|
|
2649
|
+
...this.metadata.session_id && { sessionId: this.metadata.session_id }
|
|
2582
2650
|
}
|
|
2583
2651
|
);
|
|
2584
2652
|
for await (const event of eventStream) {
|
|
@@ -2607,7 +2675,7 @@ var MCPAgent = class {
|
|
|
2607
2675
|
let conversionCompleted = false;
|
|
2608
2676
|
let conversionResult = null;
|
|
2609
2677
|
let conversionError = null;
|
|
2610
|
-
|
|
2678
|
+
this._attemptStructuredOutput(
|
|
2611
2679
|
finalResponse,
|
|
2612
2680
|
this.llm,
|
|
2613
2681
|
outputSchema
|
|
@@ -2643,7 +2711,7 @@ var MCPAgent = class {
|
|
|
2643
2711
|
data: { output: conversionResult }
|
|
2644
2712
|
};
|
|
2645
2713
|
if (this.memoryEnabled) {
|
|
2646
|
-
this.addToHistory(new
|
|
2714
|
+
this.addToHistory(new import_messages.AIMessage(`Structured result: ${JSON.stringify(conversionResult)}`));
|
|
2647
2715
|
}
|
|
2648
2716
|
logger.info("\u2705 Structured output successful");
|
|
2649
2717
|
}
|
|
@@ -2655,7 +2723,7 @@ var MCPAgent = class {
|
|
|
2655
2723
|
};
|
|
2656
2724
|
}
|
|
2657
2725
|
} else if (this.memoryEnabled && finalResponse) {
|
|
2658
|
-
this.addToHistory(new
|
|
2726
|
+
this.addToHistory(new import_messages.AIMessage(finalResponse));
|
|
2659
2727
|
}
|
|
2660
2728
|
logger.info(`\u{1F389} StreamEvents complete - ${eventCount} events emitted`);
|
|
2661
2729
|
success = true;
|
|
@@ -2704,6 +2772,10 @@ var MCPAgent = class {
|
|
|
2704
2772
|
}
|
|
2705
2773
|
/**
|
|
2706
2774
|
* Attempt to create structured output from raw result with validation and retry logic.
|
|
2775
|
+
*
|
|
2776
|
+
* @param rawResult - The raw text result from the agent
|
|
2777
|
+
* @param llm - LLM to use for structured output
|
|
2778
|
+
* @param outputSchema - The Zod schema to validate against
|
|
2707
2779
|
*/
|
|
2708
2780
|
async _attemptStructuredOutput(rawResult, llm, outputSchema) {
|
|
2709
2781
|
logger.info(`\u{1F504} Attempting structured output with schema: ${outputSchema}`);
|
|
@@ -5567,7 +5639,7 @@ function useWidgetState(defaultState) {
|
|
|
5567
5639
|
__name(useWidgetState, "useWidgetState");
|
|
5568
5640
|
|
|
5569
5641
|
// index.ts
|
|
5570
|
-
var
|
|
5642
|
+
var import_messages2 = require("@langchain/core/messages");
|
|
5571
5643
|
// Annotate the CommonJS export names for ESM import in node:
|
|
5572
5644
|
0 && (module.exports = {
|
|
5573
5645
|
AIMessage,
|