@mcp-use/agent 2.0.0-beta.2 → 2.0.0-beta.21

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.
Files changed (90) hide show
  1. package/README.md +145 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/adapters/base.d.ts +31 -28
  4. package/dist/adapters/base.d.ts.map +1 -1
  5. package/dist/adapters/index.d.ts +1 -1
  6. package/dist/adapters/index.d.ts.map +1 -1
  7. package/dist/adapters/langchain_adapter.d.ts +10 -0
  8. package/dist/adapters/langchain_adapter.d.ts.map +1 -1
  9. package/dist/adapters/native_adapter.d.ts +27 -2
  10. package/dist/adapters/native_adapter.d.ts.map +1 -1
  11. package/dist/agents/agent_options.d.ts +47 -4
  12. package/dist/agents/agent_options.d.ts.map +1 -1
  13. package/dist/agents/display.d.ts.map +1 -1
  14. package/dist/agents/mcp_agent.d.ts +85 -14
  15. package/dist/agents/mcp_agent.d.ts.map +1 -1
  16. package/dist/agents/mcp_agent_langchain.d.ts +103 -38
  17. package/dist/agents/mcp_agent_langchain.d.ts.map +1 -1
  18. package/dist/agents/normalize_run_options.d.ts +3 -1
  19. package/dist/agents/normalize_run_options.d.ts.map +1 -1
  20. package/dist/agents/prompts/index.d.ts +7 -0
  21. package/dist/agents/prompts/index.d.ts.map +1 -1
  22. package/dist/agents/remote.d.ts +39 -14
  23. package/dist/agents/remote.d.ts.map +1 -1
  24. package/dist/agents/run_options.d.ts +22 -0
  25. package/dist/agents/run_options.d.ts.map +1 -1
  26. package/dist/agents/types.d.ts +45 -23
  27. package/dist/agents/types.d.ts.map +1 -1
  28. package/dist/agents/utils/ai_sdk.d.ts +14 -5
  29. package/dist/agents/utils/ai_sdk.d.ts.map +1 -1
  30. package/dist/agents/utils/index.d.ts +1 -1
  31. package/dist/agents/utils/index.d.ts.map +1 -1
  32. package/dist/agents/utils/llm_provider.d.ts +31 -23
  33. package/dist/agents/utils/llm_provider.d.ts.map +1 -1
  34. package/dist/index.d.ts +10 -5
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +204 -37
  37. package/dist/index.js.map +1 -1
  38. package/dist/langchain.d.ts +9 -2
  39. package/dist/langchain.d.ts.map +1 -1
  40. package/dist/langchain.js +374 -42788
  41. package/dist/langchain.js.map +1 -1
  42. package/dist/llm/chat.d.ts +8 -1
  43. package/dist/llm/chat.d.ts.map +1 -1
  44. package/dist/llm/driver.d.ts.map +1 -1
  45. package/dist/llm/messageFormat.d.ts +38 -5
  46. package/dist/llm/messageFormat.d.ts.map +1 -1
  47. package/dist/llm/native_runner.d.ts.map +1 -1
  48. package/dist/llm/provider_config.d.ts +25 -1
  49. package/dist/llm/provider_config.d.ts.map +1 -1
  50. package/dist/llm/providers/anthropic.d.ts.map +1 -1
  51. package/dist/llm/providers/ollama/utils.d.ts +22 -0
  52. package/dist/llm/providers/ollama/utils.d.ts.map +1 -1
  53. package/dist/llm/providers/openai-chat-completions.d.ts +8 -1
  54. package/dist/llm/providers/openai-chat-completions.d.ts.map +1 -1
  55. package/dist/llm/providers/openai-responses-driver.d.ts.map +1 -1
  56. package/dist/llm/providers/openai-responses.d.ts +2 -1
  57. package/dist/llm/providers/openai-responses.d.ts.map +1 -1
  58. package/dist/llm/types.d.ts +85 -18
  59. package/dist/llm/types.d.ts.map +1 -1
  60. package/dist/managers/server_manager.d.ts +30 -0
  61. package/dist/managers/server_manager.d.ts.map +1 -1
  62. package/dist/managers/tools/acquire_active_mcp_server.d.ts +5 -0
  63. package/dist/managers/tools/acquire_active_mcp_server.d.ts.map +1 -1
  64. package/dist/managers/tools/add_server_from_config.d.ts +12 -0
  65. package/dist/managers/tools/add_server_from_config.d.ts.map +1 -1
  66. package/dist/managers/tools/base.d.ts +7 -0
  67. package/dist/managers/tools/base.d.ts.map +1 -1
  68. package/dist/managers/tools/connect_mcp_server.d.ts +9 -0
  69. package/dist/managers/tools/connect_mcp_server.d.ts.map +1 -1
  70. package/dist/managers/tools/list_mcp_servers.d.ts +5 -0
  71. package/dist/managers/tools/list_mcp_servers.d.ts.map +1 -1
  72. package/dist/managers/tools/release_mcp_server_connection.d.ts +5 -0
  73. package/dist/managers/tools/release_mcp_server_connection.d.ts.map +1 -1
  74. package/dist/managers/types.d.ts +9 -0
  75. package/dist/managers/types.d.ts.map +1 -1
  76. package/dist/observability/index.d.ts +1 -1
  77. package/dist/observability/index.d.ts.map +1 -1
  78. package/dist/observability/manager.d.ts +20 -8
  79. package/dist/observability/manager.d.ts.map +1 -1
  80. package/package.json +12 -20
  81. package/dist/browser-agent.cjs +0 -3275
  82. package/dist/browser-agent.cjs.map +0 -1
  83. package/dist/browser-agent.d.ts +0 -9
  84. package/dist/browser-agent.d.ts.map +0 -1
  85. package/dist/browser-agent.js +0 -3230
  86. package/dist/browser-agent.js.map +0 -1
  87. package/dist/index.cjs +0 -3302
  88. package/dist/index.cjs.map +0 -1
  89. package/dist/langchain.cjs +0 -46340
  90. package/dist/langchain.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -16,6 +16,9 @@ var BaseAdapter = class {
16
16
  * generated for it.
17
17
  */
18
18
  connectorToolMap = /* @__PURE__ */ new Map();
19
+ /**
20
+ * @param disallowedTools - MCP tool names to omit during conversion.
21
+ */
19
22
  constructor(disallowedTools) {
20
23
  this.disallowedTools = disallowedTools ?? [];
21
24
  }
@@ -25,9 +28,9 @@ var BaseAdapter = class {
25
28
  * This is the recommended way to create tools from an MCPClient, as it handles
26
29
  * session creation and connector extraction automatically.
27
30
  *
28
- * @param client The MCPClient to extract tools from.
29
- * @param disallowedTools Optional list of tool names to exclude.
30
- * @returns A promise that resolves with a list of converted tools.
31
+ * @param client - The MCPClient to extract tools from.
32
+ * @param disallowedTools - Optional list of tool names to exclude.
33
+ * @returns A promise that resolves with a list of converted tools.
31
34
  */
32
35
  static async createTools(client, disallowedTools) {
33
36
  const adapter = new this(disallowedTools);
@@ -44,8 +47,8 @@ var BaseAdapter = class {
44
47
  /**
45
48
  * Dynamically load tools for a specific connector.
46
49
  *
47
- * @param connector The connector to load tools for.
48
- * @returns The list of tools that were loaded in the target framework's format.
50
+ * @param connector - The connector to load tools for.
51
+ * @returns The list of tools that were loaded in the target framework's format.
49
52
  */
50
53
  async loadToolsForConnector(connector) {
51
54
  if (this.connectorToolMap.has(connector)) {
@@ -73,8 +76,8 @@ var BaseAdapter = class {
73
76
  /**
74
77
  * Create tools from MCP tools in all provided connectors.
75
78
  *
76
- * @param connectors List of MCP connectors to create tools from.
77
- * @returns A promise that resolves with all converted tools.
79
+ * @param connectors - List of MCP connectors to create tools from.
80
+ * @returns A promise that resolves with all converted tools.
78
81
  */
79
82
  async createToolsFromConnectors(connectors) {
80
83
  const tools = [];
@@ -88,8 +91,8 @@ var BaseAdapter = class {
88
91
  /**
89
92
  * Dynamically load resources for a specific connector.
90
93
  *
91
- * @param connector The connector to load resources for.
92
- * @returns The list of resources that were loaded in the target framework's format.
94
+ * @param connector - The connector to load resources for.
95
+ * @returns The list of resources that were loaded in the target framework's format.
93
96
  */
94
97
  async loadResourcesForConnector(connector) {
95
98
  const connectorResources = [];
@@ -119,8 +122,8 @@ var BaseAdapter = class {
119
122
  /**
120
123
  * Dynamically load prompts for a specific connector.
121
124
  *
122
- * @param connector The connector to load prompts for.
123
- * @returns The list of prompts that were loaded in the target framework's format.
125
+ * @param connector - The connector to load prompts for.
126
+ * @returns The list of prompts that were loaded in the target framework's format.
124
127
  */
125
128
  async loadPromptsForConnector(connector) {
126
129
  const connectorPrompts = [];
@@ -150,8 +153,8 @@ var BaseAdapter = class {
150
153
  /**
151
154
  * Create resources from MCP resources in all provided connectors.
152
155
  *
153
- * @param connectors List of MCP connectors to create resources from.
154
- * @returns A promise that resolves with all converted resources.
156
+ * @param connectors - List of MCP connectors to create resources from.
157
+ * @returns A promise that resolves with all converted resources.
155
158
  */
156
159
  async createResourcesFromConnectors(connectors) {
157
160
  const resources = [];
@@ -165,8 +168,8 @@ var BaseAdapter = class {
165
168
  /**
166
169
  * Create prompts from MCP prompts in all provided connectors.
167
170
  *
168
- * @param connectors List of MCP connectors to create prompts from.
169
- * @returns A promise that resolves with all converted prompts.
171
+ * @param connectors - List of MCP connectors to create prompts from.
172
+ * @returns A promise that resolves with all converted prompts.
170
173
  */
171
174
  async createPromptsFromConnectors(connectors) {
172
175
  const prompts = [];
@@ -180,8 +183,8 @@ var BaseAdapter = class {
180
183
  /**
181
184
  * Check if a connector is initialized and has tools.
182
185
  *
183
- * @param connector The connector to check.
184
- * @returns True if the connector is initialized and has tools, false otherwise.
186
+ * @param connector - The connector to check.
187
+ * @returns True if the connector is initialized and has tools, false otherwise.
185
188
  */
186
189
  checkConnectorInitialized(connector) {
187
190
  return Boolean(connector.tools && connector.tools.length);
@@ -189,8 +192,8 @@ var BaseAdapter = class {
189
192
  /**
190
193
  * Ensure a connector is initialized.
191
194
  *
192
- * @param connector The connector to initialize.
193
- * @returns True if initialization succeeded, false otherwise.
195
+ * @param connector - The connector to initialize.
196
+ * @returns True if initialization succeeded, false otherwise.
194
197
  */
195
198
  async ensureConnectorInitialized(connector) {
196
199
  if (!this.checkConnectorInitialized(connector)) {
@@ -214,14 +217,29 @@ function sanitizeToolName(name) {
214
217
  var NativeAdapter = class extends BaseAdapter {
215
218
  usedToolNames = /* @__PURE__ */ new Set();
216
219
  handlers = /* @__PURE__ */ new Map();
220
+ /**
221
+ * @param disallowedTools - MCP tool names to omit during conversion.
222
+ */
217
223
  constructor(disallowedTools = []) {
218
224
  super(disallowedTools);
219
225
  }
226
+ /**
227
+ * Converts MCP tools from all connectors and resets the dispatch table.
228
+ *
229
+ * @param connectors - Connected MCP connectors.
230
+ * @returns Provider-neutral tool entries.
231
+ */
220
232
  async createToolsFromConnectors(connectors) {
221
233
  this.usedToolNames.clear();
222
234
  this.handlers.clear();
223
235
  return super.createToolsFromConnectors(connectors);
224
236
  }
237
+ /**
238
+ * Creates a dispatcher for the entries loaded by this adapter.
239
+ *
240
+ * @returns A function that invokes tools, reads resources, or gets prompts.
241
+ * @throws Error if the requested exposed tool name is unknown.
242
+ */
225
243
  createCallTool() {
226
244
  const handlers = this.handlers;
227
245
  return async (name, args) => {
@@ -244,6 +262,12 @@ var NativeAdapter = class extends BaseAdapter {
244
262
  }
245
263
  };
246
264
  }
265
+ /**
266
+ * Removes internal dispatch metadata from native tool entries.
267
+ *
268
+ * @param entries - Entries created by this adapter.
269
+ * @returns Provider-neutral definitions safe to send to an LLM provider.
270
+ */
247
271
  toProviderTools(entries) {
248
272
  return entries.map(({ name, description, inputSchema }) => ({
249
273
  name,
@@ -478,6 +502,62 @@ function toolImageFollowupHeader(toolName, count) {
478
502
  }
479
503
 
480
504
  // src/llm/messageFormat.ts
505
+ function messageText(content) {
506
+ if (typeof content === "string") return content;
507
+ if (Array.isArray(content)) {
508
+ return content.map(
509
+ (part) => part && typeof part === "object" && "text" in part && typeof part.text === "string" ? part.text : ""
510
+ ).join("");
511
+ }
512
+ return JSON.stringify(content ?? "");
513
+ }
514
+ function langChainMessageType(message) {
515
+ try {
516
+ if (typeof message._getType === "function") return message._getType();
517
+ if (typeof message.getType === "function") return message.getType();
518
+ } catch {
519
+ }
520
+ return message.type ?? "";
521
+ }
522
+ function convertExternalHistoryToProvider(messages) {
523
+ return messages.map((raw, index) => {
524
+ const message = raw;
525
+ const type = langChainMessageType(message);
526
+ const content = messageText(message.content);
527
+ if (type === "human" || type === "user") {
528
+ return { role: "user", content };
529
+ }
530
+ if (type === "system") {
531
+ return { role: "system", content };
532
+ }
533
+ if (type === "ai" || type === "assistant") {
534
+ const toolCalls = message.tool_calls?.map((call, callIndex) => ({
535
+ id: call.id ?? `external_${index}_${callIndex}`,
536
+ name: call.name,
537
+ args: call.args ?? {}
538
+ }));
539
+ return {
540
+ role: "assistant",
541
+ content,
542
+ ...toolCalls?.length ? { toolCalls } : {}
543
+ };
544
+ }
545
+ if (type === "tool") {
546
+ const toolIsError = message.status === "error" || isToolResultError(message.content);
547
+ return {
548
+ role: "tool",
549
+ content,
550
+ toolCallId: message.tool_call_id ?? `external_${index}`,
551
+ ...message.name ? { toolName: message.name } : {},
552
+ toolResult: message.content,
553
+ ...toolIsError ? { toolIsError: true } : {}
554
+ };
555
+ }
556
+ throw new TypeError(
557
+ `Unsupported external history message type at index ${index}: ${type || "unknown"}`
558
+ );
559
+ });
560
+ }
481
561
  function extractText(m) {
482
562
  const raw = typeof m.content === "string" ? m.content : Array.isArray(m.content) ? m.content.map((x) => x?.text ?? "").join("\n") : JSON.stringify(m.content ?? "");
483
563
  if (raw.trim()) return raw.trim();
@@ -781,7 +861,13 @@ function buildBody(params, stream) {
781
861
  body.tools = tools.map((t) => ({
782
862
  name: t.name,
783
863
  description: t.description,
784
- input_schema: t.inputSchema
864
+ input_schema: t.inputSchema,
865
+ // Anthropic buffers each parameter value by default. That makes a tool
866
+ // with one large string argument (code, SVG, a document, etc.) appear to
867
+ // have no input until the whole value has finished generating. Request
868
+ // eager input only for streaming calls so input_json_delta events arrive
869
+ // while the model is still writing the value.
870
+ ...stream ? { eager_input_streaming: true } : {}
785
871
  }));
786
872
  }
787
873
  return body;
@@ -872,7 +958,11 @@ async function* streamChat(params) {
872
958
  try {
873
959
  args = JSON.parse(entry.argsJson);
874
960
  } catch {
875
- args = {};
961
+ yield {
962
+ type: "error",
963
+ message: `Anthropic returned invalid JSON arguments for tool "${entry.name}".`
964
+ };
965
+ return;
876
966
  }
877
967
  }
878
968
  yield {
@@ -1283,6 +1373,9 @@ function buildOllamaApiUrl(baseUrl, path) {
1283
1373
  return `${normalizeOllamaBaseUrl(baseUrl)}${path}`;
1284
1374
  }
1285
1375
  var OllamaCorsError = class extends Error {
1376
+ /**
1377
+ * @param cause - Original network error.
1378
+ */
1286
1379
  constructor(cause) {
1287
1380
  super(
1288
1381
  "Could not reach Ollama. If it's running, allow this origin by starting Ollama with `OLLAMA_ORIGINS=*` (or your inspector origin) and try again."
@@ -1488,8 +1581,15 @@ async function chat3(params) {
1488
1581
 
1489
1582
  // src/llm/providers/openai-chat-completions.ts
1490
1583
  var LlmRequestError = class extends Error {
1584
+ /** HTTP response status. */
1491
1585
  status;
1586
+ /** Parsed JSON response body, or the raw response text. */
1492
1587
  body;
1588
+ /**
1589
+ * @param status - HTTP response status.
1590
+ * @param message - Error message.
1591
+ * @param body - Parsed or raw provider response body.
1592
+ */
1493
1593
  constructor(status, message, body) {
1494
1594
  super(message);
1495
1595
  this.name = "LlmRequestError";
@@ -1935,14 +2035,21 @@ function appendToolOutputsToInput(input, callId, toolName, result) {
1935
2035
  });
1936
2036
  }
1937
2037
  }
2038
+ function responsesReasoningFields(config) {
2039
+ const effort = config.reasoningEffort;
2040
+ if (!effort || effort === "none") return {};
2041
+ return {
2042
+ include: ["reasoning.encrypted_content"],
2043
+ reasoning: { effort }
2044
+ };
2045
+ }
1938
2046
  function buildResponsesBody(params, stream) {
1939
2047
  const body = {
1940
2048
  model: params.config.model,
1941
2049
  input: params.input,
1942
2050
  store: false,
1943
- include: ["reasoning.encrypted_content"],
1944
- reasoning: { effort: params.config.reasoningEffort ?? "low" },
1945
- stream
2051
+ stream,
2052
+ ...responsesReasoningFields(params.config)
1946
2053
  };
1947
2054
  if (params.instructions) body.instructions = params.instructions;
1948
2055
  if (params.tools && params.tools.length > 0) {
@@ -2449,12 +2556,12 @@ async function* streamNativeAgent(driver, options) {
2449
2556
  }
2450
2557
  async function* streamNativeAgentSteps(driver, options) {
2451
2558
  let finalText = "";
2452
- let pendingStep = null;
2559
+ const pendingSteps = /* @__PURE__ */ new Map();
2453
2560
  for await (const ev of streamNativeAgent(driver, options)) {
2454
2561
  if (ev.type === "text-delta") {
2455
2562
  finalText += ev.delta;
2456
2563
  } else if (ev.type === "tool-call-ready") {
2457
- pendingStep = {
2564
+ const pendingStep = {
2458
2565
  action: {
2459
2566
  tool: ev.toolName,
2460
2567
  toolInput: ev.args,
@@ -2462,14 +2569,17 @@ async function* streamNativeAgentSteps(driver, options) {
2462
2569
  },
2463
2570
  observation: ""
2464
2571
  };
2572
+ pendingSteps.set(ev.toolCallId, pendingStep);
2465
2573
  yield pendingStep;
2466
- } else if (ev.type === "tool-result" && pendingStep) {
2574
+ } else if (ev.type === "tool-result") {
2575
+ const pendingStep = pendingSteps.get(ev.toolCallId);
2576
+ if (!pendingStep) continue;
2467
2577
  const observation = typeof ev.result === "string" ? ev.result : JSON.stringify(ev.result ?? "");
2468
2578
  yield {
2469
2579
  action: pendingStep.action,
2470
2580
  observation
2471
2581
  };
2472
- pendingStep = null;
2582
+ pendingSteps.delete(ev.toolCallId);
2473
2583
  } else if (ev.type === "error") {
2474
2584
  throw new Error(ev.message);
2475
2585
  }
@@ -2561,27 +2671,34 @@ function providerConfigFromOptions(provider, model, config) {
2561
2671
  }
2562
2672
 
2563
2673
  // src/version.ts
2564
- var VERSION = "2.0.0-beta.1";
2674
+ var VERSION = "2.0.0-beta.21";
2565
2675
  function getPackageVersion() {
2566
2676
  return VERSION;
2567
2677
  }
2568
2678
 
2569
2679
  // src/agents/normalize_run_options.ts
2570
- function normalizeRunOptions(queryOrOptions, maxSteps, manageConnector, _externalHistory, outputSchema, signal) {
2680
+ function normalizeRunOptions(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema, signal) {
2571
2681
  if (typeof queryOrOptions === "object" && queryOrOptions !== null) {
2572
2682
  return {
2573
2683
  prompt: queryOrOptions.prompt,
2574
2684
  maxSteps: queryOrOptions.maxSteps,
2575
2685
  manageConnector: queryOrOptions.manageConnector,
2686
+ externalHistory: queryOrOptions.externalHistory,
2576
2687
  messages: queryOrOptions.messages,
2577
2688
  schema: queryOrOptions.schema,
2578
2689
  signal: queryOrOptions.signal
2579
2690
  };
2580
2691
  }
2692
+ if (externalHistory !== void 0 && !Array.isArray(externalHistory)) {
2693
+ throw new TypeError(
2694
+ "externalHistory must be an array of LangChain messages"
2695
+ );
2696
+ }
2581
2697
  return {
2582
2698
  prompt: queryOrOptions,
2583
2699
  maxSteps,
2584
2700
  manageConnector,
2701
+ externalHistory,
2585
2702
  schema: outputSchema,
2586
2703
  signal
2587
2704
  };
@@ -2616,6 +2733,11 @@ var RemoteAgent = class {
2616
2733
  apiKey;
2617
2734
  baseUrl;
2618
2735
  chatId = null;
2736
+ /**
2737
+ * @param options - Hosted agent identifier and API connection settings.
2738
+ * @throws Error if no API key is supplied or available from
2739
+ * `MCP_USE_API_KEY`.
2740
+ */
2619
2741
  constructor(options) {
2620
2742
  this.agentId = options.agentId;
2621
2743
  this.baseUrl = options.baseUrl ?? "https://cloud.manufact.com";
@@ -2841,6 +2963,7 @@ Raw error: ${result}`
2841
2963
  );
2842
2964
  return result;
2843
2965
  }
2966
+ /** Releases local remote-agent state. */
2844
2967
  async close() {
2845
2968
  logger4.debug("\u{1F50C} Remote agent client closed");
2846
2969
  }
@@ -2848,6 +2971,7 @@ Raw error: ${result}`
2848
2971
 
2849
2972
  // src/agents/mcp_agent.ts
2850
2973
  var MCPAgent = class {
2974
+ /** @returns The installed `@mcp-use/agent` package version. */
2851
2975
  static getPackageVersion() {
2852
2976
  return getPackageVersion();
2853
2977
  }
@@ -2875,6 +2999,15 @@ var MCPAgent = class {
2875
2999
  conversationMessages = [];
2876
3000
  memoryEnabled;
2877
3001
  boundConnections;
3002
+ /**
3003
+ * Creates an MCP agent.
3004
+ *
3005
+ * Call {@link initialize} before the first local run unless
3006
+ * `autoInitialize` is enabled. Setting `agentId` creates a remote agent.
3007
+ *
3008
+ * @param options - Model, MCP connection, and execution settings.
3009
+ * @throws Error if local execution has no MCP servers, client, or connectors.
3010
+ */
2878
3011
  constructor(options) {
2879
3012
  if (options.agentId) {
2880
3013
  this.isRemote = true;
@@ -2894,7 +3027,6 @@ var MCPAgent = class {
2894
3027
  return;
2895
3028
  }
2896
3029
  this.maxSteps = options.maxSteps ?? 10;
2897
- this.autoInitialize = options.autoInitialize ?? false;
2898
3030
  this.systemPrompt = options.systemPrompt ?? "You are a helpful assistant with access to MCP tools.";
2899
3031
  this.disallowedTools = options.disallowedTools ?? [];
2900
3032
  this.exposeResourcesAsTools = options.exposeResourcesAsTools ?? true;
@@ -2934,6 +3066,7 @@ var MCPAgent = class {
2934
3066
  parseLLMStringToProviderConfig(this.llmString, this.llmConfig)
2935
3067
  );
2936
3068
  }
3069
+ this.autoInitialize = options.autoInitialize ?? this.isSimplifiedMode;
2937
3070
  }
2938
3071
  resolveMcpServers(mcpServers) {
2939
3072
  if (!mcpServers) return;
@@ -2946,6 +3079,14 @@ var MCPAgent = class {
2946
3079
  hasLiveConnections() {
2947
3080
  return (this.boundConnections?.length ?? 0) > 0;
2948
3081
  }
3082
+ /**
3083
+ * Resolves the model configuration, connects MCP servers, and loads tools.
3084
+ *
3085
+ * Calling this method more than once has no effect until {@link close}.
3086
+ *
3087
+ * @throws Error if the model configuration is incomplete or no driver can
3088
+ * be created.
3089
+ */
2949
3090
  async initialize() {
2950
3091
  if (this.isRemote) {
2951
3092
  this.initialized = true;
@@ -2953,11 +3094,6 @@ var MCPAgent = class {
2953
3094
  }
2954
3095
  if (this.initialized) return;
2955
3096
  if (this.isSimplifiedMode) {
2956
- if (!this.client && this.mcpServersConfig) {
2957
- const { MCPClient } = await import("@mcp-use/client");
2958
- this.client = new MCPClient({ mcpServers: this.mcpServersConfig });
2959
- this.clientOwnedByAgent = true;
2960
- }
2961
3097
  if (this.llmString) {
2962
3098
  this.driver = createLlmDriver(
2963
3099
  parseLLMStringToProviderConfig(this.llmString, this.llmConfig)
@@ -2966,6 +3102,11 @@ var MCPAgent = class {
2966
3102
  } else if (this.explicitProviderConfig) {
2967
3103
  this.driver = createLlmDriver(this.explicitProviderConfig);
2968
3104
  }
3105
+ if (!this.client && this.mcpServersConfig && !this.hasLiveConnections()) {
3106
+ const { MCPClient } = await import("@mcp-use/client");
3107
+ this.client = new MCPClient({ mcpServers: this.mcpServersConfig });
3108
+ this.clientOwnedByAgent = true;
3109
+ }
2969
3110
  if (!this.driver) {
2970
3111
  throw new Error("LLM driver not configured.");
2971
3112
  }
@@ -3072,6 +3213,11 @@ var MCPAgent = class {
3072
3213
  if (this.memoryEnabled && this.conversationMessages.length > 0) {
3073
3214
  messages.push(...this.conversationMessages);
3074
3215
  }
3216
+ if (options.externalHistory?.length) {
3217
+ messages.push(
3218
+ ...convertExternalHistoryToProvider(options.externalHistory)
3219
+ );
3220
+ }
3075
3221
  if (options.messages?.length) {
3076
3222
  messages.push(...options.messages);
3077
3223
  }
@@ -3080,12 +3226,21 @@ var MCPAgent = class {
3080
3226
  }
3081
3227
  return messages;
3082
3228
  }
3229
+ /**
3230
+ * @returns A shallow copy of stored provider-neutral conversation history.
3231
+ */
3083
3232
  getConversationHistory() {
3084
3233
  return [...this.conversationMessages];
3085
3234
  }
3235
+ /** Removes all stored user and assistant messages. */
3086
3236
  clearConversationHistory() {
3087
3237
  this.conversationMessages = [];
3088
3238
  }
3239
+ /**
3240
+ * Replaces the system instruction used by subsequent runs.
3241
+ *
3242
+ * @param message - New system instruction.
3243
+ */
3089
3244
  setSystemMessage(message) {
3090
3245
  this.systemPrompt = message;
3091
3246
  }
@@ -3197,7 +3352,13 @@ var MCPAgent = class {
3197
3352
  await this.ensureReady(options.manageConnector ?? true);
3198
3353
  yield* streamNativeAgent(this.driver, this.nativeRunParams(options));
3199
3354
  }
3200
- /** Single-shot completion without tools (sampling, props generation). */
3355
+ /**
3356
+ * Runs a single model completion without MCP tools.
3357
+ *
3358
+ * @param options - Provider-neutral messages and optional cancellation
3359
+ * signal.
3360
+ * @returns Final assistant text.
3361
+ */
3201
3362
  async chat(options) {
3202
3363
  await this.ensureReady();
3203
3364
  const result = await this.driver.complete({
@@ -3207,6 +3368,11 @@ var MCPAgent = class {
3207
3368
  });
3208
3369
  return result.text;
3209
3370
  }
3371
+ /**
3372
+ * Closes MCP sessions created by this agent and resets initialization state.
3373
+ *
3374
+ * Existing clients supplied by the caller remain open.
3375
+ */
3210
3376
  async close() {
3211
3377
  if (this.clientOwnedByAgent && this.client) {
3212
3378
  await this.client.closeAllSessions?.();
@@ -3229,6 +3395,7 @@ async function completeChat(params) {
3229
3395
  // src/agents/prompts/index.ts
3230
3396
  var CODE_MODE_PROMPT = "Use code execution mode to discover and call MCP tools programmatically.";
3231
3397
  var PROMPTS = {
3398
+ /** Instruction used to enable code-based MCP tool discovery and calls. */
3232
3399
  CODE_MODE: CODE_MODE_PROMPT
3233
3400
  };
3234
3401
  export {