mcp-use 1.10.6 → 1.11.0-canary.11
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 -1
- package/dist/{chunk-KIWNNI6F.js → chunk-2NE5H4KG.js} +16 -2
- package/dist/{chunk-D5WOXLJ2.js → chunk-4QWS5ME6.js} +171 -11
- package/dist/chunk-7P2EMREO.js +101 -0
- package/dist/chunk-7PSUUT4A.js +1055 -0
- package/dist/{chunk-44DFBJUL.js → chunk-BOCIQYWG.js} +196 -496
- package/dist/chunk-BPZJIV4V.js +1873 -0
- package/dist/{chunk-EEUJZMOP.js → chunk-CVKKDXI3.js} +1 -1
- package/dist/chunk-DPK5NHDR.js +12 -0
- package/dist/{chunk-FDKY2O5P.js → chunk-EHCLF3JO.js} +443 -969
- package/dist/{chunk-34R6SIER.js → chunk-FRUZDWXH.js} +1 -1
- package/dist/chunk-GXNAXUDI.js +0 -0
- package/dist/{chunk-JH3ZOGLI.js → chunk-J3WTIYVV.js} +2 -2
- package/dist/{chunk-CPG2WZUL.js → chunk-JRGQRPTN.js} +1 -1
- package/dist/chunk-MFSO5PUW.js +1049 -0
- package/dist/chunk-SQSJ5NKY.js +1055 -0
- package/dist/chunk-T4EDAWDS.js +2638 -0
- package/dist/chunk-UWWLWLS2.js +62 -0
- package/dist/{chunk-BLWPCOUZ.js → chunk-V4YUDB7N.js} +3 -8
- package/dist/index.cjs +5065 -4608
- package/dist/index.d.ts +2 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +46 -1061
- package/dist/{langfuse-N5Y5BSXK.js → langfuse-74RGPTAH.js} +2 -2
- package/dist/notifications-FLGIFS56.js +9 -0
- package/dist/src/adapters/base.d.ts +44 -0
- package/dist/src/adapters/base.d.ts.map +1 -1
- package/dist/src/adapters/index.cjs +1346 -0
- package/dist/src/adapters/index.js +11 -0
- package/dist/src/adapters/langchain_adapter.d.ts +12 -1
- package/dist/src/adapters/langchain_adapter.d.ts.map +1 -1
- package/dist/src/agents/index.cjs +3141 -159
- package/dist/src/agents/index.d.ts +2 -0
- package/dist/src/agents/index.d.ts.map +1 -1
- package/dist/src/agents/index.js +12 -8
- package/dist/src/agents/mcp_agent.d.ts +59 -37
- package/dist/src/agents/mcp_agent.d.ts.map +1 -1
- package/dist/src/agents/remote.d.ts +25 -0
- package/dist/src/agents/remote.d.ts.map +1 -1
- package/dist/src/agents/types.d.ts +76 -0
- package/dist/src/agents/types.d.ts.map +1 -1
- package/dist/src/agents/utils/index.d.ts +1 -0
- package/dist/src/agents/utils/index.d.ts.map +1 -1
- package/dist/src/agents/utils/llm_provider.d.ts +53 -0
- package/dist/src/agents/utils/llm_provider.d.ts.map +1 -0
- package/dist/src/browser.cjs +1856 -423
- package/dist/src/browser.d.ts +1 -2
- package/dist/src/browser.d.ts.map +1 -1
- package/dist/src/browser.js +30 -19
- package/dist/src/client/base.d.ts +1 -0
- package/dist/src/client/base.d.ts.map +1 -1
- package/dist/src/client/browser.d.ts +2 -2
- package/dist/src/client/browser.d.ts.map +1 -1
- package/dist/src/client/prompts.cjs +1 -1
- package/dist/src/client/prompts.js +5 -4
- package/dist/src/client.cjs +3788 -0
- package/dist/src/client.d.ts +2 -0
- package/dist/src/client.d.ts.map +1 -1
- package/dist/src/client.js +23 -0
- package/dist/src/config.d.ts.map +1 -1
- package/dist/src/connectors/base.d.ts +8 -0
- package/dist/src/connectors/base.d.ts.map +1 -1
- package/dist/src/connectors/index.d.ts +0 -1
- package/dist/src/connectors/index.d.ts.map +1 -1
- package/dist/src/managers/server_manager.d.ts.map +1 -1
- package/dist/src/managers/tools/connect_mcp_server.d.ts.map +1 -1
- package/dist/src/react/index.cjs +259 -298
- package/dist/src/react/index.js +9 -8
- package/dist/src/react/types.d.ts +42 -4
- package/dist/src/react/types.d.ts.map +1 -1
- package/dist/src/react/useMcp.d.ts.map +1 -1
- package/dist/src/react/useWidget.d.ts +11 -7
- package/dist/src/react/useWidget.d.ts.map +1 -1
- package/dist/src/react/widget-types.d.ts +6 -2
- package/dist/src/react/widget-types.d.ts.map +1 -1
- package/dist/src/server/endpoints/mount-mcp.d.ts.map +1 -1
- package/dist/src/server/index.cjs +1288 -140
- package/dist/src/server/index.d.ts +2 -0
- package/dist/src/server/index.d.ts.map +1 -1
- package/dist/src/server/index.js +1183 -102
- package/dist/src/server/mcp-server.d.ts +5 -1
- package/dist/src/server/mcp-server.d.ts.map +1 -1
- package/dist/src/server/notifications/index.d.ts +1 -1
- package/dist/src/server/notifications/index.d.ts.map +1 -1
- package/dist/src/server/notifications/notification-registration.d.ts +51 -0
- package/dist/src/server/notifications/notification-registration.d.ts.map +1 -1
- package/dist/src/server/sessions/index.d.ts +3 -1
- package/dist/src/server/sessions/index.d.ts.map +1 -1
- package/dist/src/server/sessions/session-manager.d.ts +36 -19
- package/dist/src/server/sessions/session-manager.d.ts.map +1 -1
- package/dist/src/server/sessions/stores/filesystem.d.ts +121 -0
- package/dist/src/server/sessions/stores/filesystem.d.ts.map +1 -0
- package/dist/src/server/sessions/stores/index.d.ts +94 -0
- package/dist/src/server/sessions/stores/index.d.ts.map +1 -0
- package/dist/src/server/sessions/stores/memory.d.ts +82 -0
- package/dist/src/server/sessions/stores/memory.d.ts.map +1 -0
- package/dist/src/server/sessions/stores/redis.d.ts +164 -0
- package/dist/src/server/sessions/stores/redis.d.ts.map +1 -0
- package/dist/src/server/sessions/streams/index.d.ts +77 -0
- package/dist/src/server/sessions/streams/index.d.ts.map +1 -0
- package/dist/src/server/sessions/streams/memory.d.ts +76 -0
- package/dist/src/server/sessions/streams/memory.d.ts.map +1 -0
- package/dist/src/server/sessions/streams/redis.d.ts +146 -0
- package/dist/src/server/sessions/streams/redis.d.ts.map +1 -0
- package/dist/src/server/types/common.d.ts +105 -28
- package/dist/src/server/types/common.d.ts.map +1 -1
- package/dist/src/server/types/resource.d.ts +16 -0
- package/dist/src/server/types/resource.d.ts.map +1 -1
- package/dist/src/server/types/widget.d.ts +21 -2
- package/dist/src/server/types/widget.d.ts.map +1 -1
- package/dist/src/server/utils/response-helpers.d.ts +12 -6
- package/dist/src/server/utils/response-helpers.d.ts.map +1 -1
- package/dist/src/server/widgets/index.d.ts +1 -1
- package/dist/src/server/widgets/index.d.ts.map +1 -1
- package/dist/src/server/widgets/mount-widgets-dev.d.ts.map +1 -1
- package/dist/src/server/widgets/setup-widget-routes.d.ts.map +1 -1
- package/dist/src/server/widgets/ui-resource-registration.d.ts.map +1 -1
- package/dist/src/server/widgets/widget-helpers.d.ts +22 -0
- package/dist/src/server/widgets/widget-helpers.d.ts.map +1 -1
- package/dist/src/server/widgets/widget-types.d.ts +2 -0
- package/dist/src/server/widgets/widget-types.d.ts.map +1 -1
- package/dist/src/session.d.ts +16 -2
- package/dist/src/session.d.ts.map +1 -1
- package/dist/src/task_managers/index.d.ts +10 -1
- package/dist/src/task_managers/index.d.ts.map +1 -1
- package/dist/src/task_managers/sse.d.ts +34 -1
- package/dist/src/task_managers/sse.d.ts.map +1 -1
- package/dist/src/task_managers/streamable_http.d.ts +8 -2
- package/dist/src/task_managers/streamable_http.d.ts.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.d.ts.map +1 -1
- package/dist/{tool-execution-helpers-4X6A63AS.js → tool-execution-helpers-3BYYGIA5.js} +3 -3
- package/dist/tsup.config.d.ts.map +1 -1
- package/package.json +47 -14
- package/dist/src/connectors/websocket.d.ts +0 -38
- package/dist/src/connectors/websocket.d.ts.map +0 -1
- package/dist/src/task_managers/websocket.d.ts +0 -18
- package/dist/src/task_managers/websocket.d.ts.map +0 -1
- /package/dist/{chunk-EW4MJSHA.js → chunk-LGDFGYRL.js} +0 -0
|
@@ -1,870 +1,23 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MCPClient
|
|
3
|
+
} from "./chunk-7PSUUT4A.js";
|
|
4
|
+
import {
|
|
5
|
+
LangChainAdapter
|
|
6
|
+
} from "./chunk-MFSO5PUW.js";
|
|
1
7
|
import {
|
|
2
8
|
Telemetry,
|
|
3
9
|
extractModelInfo,
|
|
4
10
|
getPackageVersion
|
|
5
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-J3WTIYVV.js";
|
|
6
12
|
import {
|
|
7
13
|
logger
|
|
8
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-FRUZDWXH.js";
|
|
9
15
|
import {
|
|
10
16
|
__name
|
|
11
17
|
} from "./chunk-3GQAWCBQ.js";
|
|
12
18
|
|
|
13
|
-
// src/adapters/base.ts
|
|
14
|
-
var BaseAdapter = class {
|
|
15
|
-
static {
|
|
16
|
-
__name(this, "BaseAdapter");
|
|
17
|
-
}
|
|
18
|
-
/**
|
|
19
|
-
* List of tool names that should not be available.
|
|
20
|
-
*/
|
|
21
|
-
disallowedTools;
|
|
22
|
-
/**
|
|
23
|
-
* Internal cache that maps a connector instance to the list of tools
|
|
24
|
-
* generated for it.
|
|
25
|
-
*/
|
|
26
|
-
connectorToolMap = /* @__PURE__ */ new Map();
|
|
27
|
-
constructor(disallowedTools) {
|
|
28
|
-
this.disallowedTools = disallowedTools ?? [];
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* Create tools from an MCPClient instance.
|
|
32
|
-
*
|
|
33
|
-
* This is the recommended way to create tools from an MCPClient, as it handles
|
|
34
|
-
* session creation and connector extraction automatically.
|
|
35
|
-
*
|
|
36
|
-
* @param client The MCPClient to extract tools from.
|
|
37
|
-
* @param disallowedTools Optional list of tool names to exclude.
|
|
38
|
-
* @returns A promise that resolves with a list of converted tools.
|
|
39
|
-
*/
|
|
40
|
-
static async createTools(client, disallowedTools) {
|
|
41
|
-
const adapter = new this(disallowedTools);
|
|
42
|
-
if (!client.activeSessions || Object.keys(client.activeSessions).length === 0) {
|
|
43
|
-
logger.info("No active sessions found, creating new ones...");
|
|
44
|
-
await client.createAllSessions();
|
|
45
|
-
}
|
|
46
|
-
const sessions = client.getAllActiveSessions();
|
|
47
|
-
const connectors = Object.values(sessions).map(
|
|
48
|
-
(session) => session.connector
|
|
49
|
-
);
|
|
50
|
-
return adapter.createToolsFromConnectors(connectors);
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Dynamically load tools for a specific connector.
|
|
54
|
-
*
|
|
55
|
-
* @param connector The connector to load tools for.
|
|
56
|
-
* @returns The list of tools that were loaded in the target framework's format.
|
|
57
|
-
*/
|
|
58
|
-
async loadToolsForConnector(connector) {
|
|
59
|
-
if (this.connectorToolMap.has(connector)) {
|
|
60
|
-
const cached = this.connectorToolMap.get(connector);
|
|
61
|
-
logger.debug(`Returning ${cached.length} existing tools for connector`);
|
|
62
|
-
return cached;
|
|
63
|
-
}
|
|
64
|
-
const connectorTools = [];
|
|
65
|
-
const success = await this.ensureConnectorInitialized(connector);
|
|
66
|
-
if (!success) {
|
|
67
|
-
return [];
|
|
68
|
-
}
|
|
69
|
-
for (const tool of connector.tools) {
|
|
70
|
-
const converted = this.convertTool(tool, connector);
|
|
71
|
-
if (converted) {
|
|
72
|
-
connectorTools.push(converted);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
this.connectorToolMap.set(connector, connectorTools);
|
|
76
|
-
logger.debug(
|
|
77
|
-
`Loaded ${connectorTools.length} new tools for connector: ${connectorTools.map((t) => t?.name ?? String(t)).join(", ")}`
|
|
78
|
-
);
|
|
79
|
-
return connectorTools;
|
|
80
|
-
}
|
|
81
|
-
/**
|
|
82
|
-
* Create tools from MCP tools in all provided connectors.
|
|
83
|
-
*
|
|
84
|
-
* @param connectors List of MCP connectors to create tools from.
|
|
85
|
-
* @returns A promise that resolves with all converted tools.
|
|
86
|
-
*/
|
|
87
|
-
async createToolsFromConnectors(connectors) {
|
|
88
|
-
const tools = [];
|
|
89
|
-
for (const connector of connectors) {
|
|
90
|
-
const connectorTools = await this.loadToolsForConnector(connector);
|
|
91
|
-
tools.push(...connectorTools);
|
|
92
|
-
}
|
|
93
|
-
logger.debug(`Available tools: ${tools.length}`);
|
|
94
|
-
return tools;
|
|
95
|
-
}
|
|
96
|
-
/**
|
|
97
|
-
* Check if a connector is initialized and has tools.
|
|
98
|
-
*
|
|
99
|
-
* @param connector The connector to check.
|
|
100
|
-
* @returns True if the connector is initialized and has tools, false otherwise.
|
|
101
|
-
*/
|
|
102
|
-
checkConnectorInitialized(connector) {
|
|
103
|
-
return Boolean(connector.tools && connector.tools.length);
|
|
104
|
-
}
|
|
105
|
-
/**
|
|
106
|
-
* Ensure a connector is initialized.
|
|
107
|
-
*
|
|
108
|
-
* @param connector The connector to initialize.
|
|
109
|
-
* @returns True if initialization succeeded, false otherwise.
|
|
110
|
-
*/
|
|
111
|
-
async ensureConnectorInitialized(connector) {
|
|
112
|
-
if (!this.checkConnectorInitialized(connector)) {
|
|
113
|
-
logger.debug("Connector doesn't have tools, initializing it");
|
|
114
|
-
try {
|
|
115
|
-
await connector.initialize();
|
|
116
|
-
return true;
|
|
117
|
-
} catch (err) {
|
|
118
|
-
logger.error(`Error initializing connector: ${err}`);
|
|
119
|
-
return false;
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
return true;
|
|
123
|
-
}
|
|
124
|
-
};
|
|
125
|
-
|
|
126
|
-
// src/utils/json-schema-to-zod/JSONSchemaToZod.ts
|
|
127
|
-
import { z } from "zod";
|
|
128
|
-
var JSONSchemaToZod = class {
|
|
129
|
-
static {
|
|
130
|
-
__name(this, "JSONSchemaToZod");
|
|
131
|
-
}
|
|
132
|
-
/**
|
|
133
|
-
* Converts a JSON schema to a Zod schema.
|
|
134
|
-
*
|
|
135
|
-
* @param {JSONSchema} schema - The JSON schema.
|
|
136
|
-
* @returns {ZodSchema} - The Zod schema.
|
|
137
|
-
*/
|
|
138
|
-
static convert(schema) {
|
|
139
|
-
return this.parseSchema(schema);
|
|
140
|
-
}
|
|
141
|
-
/**
|
|
142
|
-
* Checks if data matches a condition schema.
|
|
143
|
-
*
|
|
144
|
-
* @param {JSONValue} data - The data to check.
|
|
145
|
-
* @param {JSONSchema} condition - The condition schema.
|
|
146
|
-
* @returns {boolean} - Whether the data matches the condition.
|
|
147
|
-
*/
|
|
148
|
-
static matchesCondition(data, condition) {
|
|
149
|
-
if (!condition.properties) {
|
|
150
|
-
return true;
|
|
151
|
-
}
|
|
152
|
-
if (typeof data !== "object" || data === null || Array.isArray(data)) {
|
|
153
|
-
return false;
|
|
154
|
-
}
|
|
155
|
-
const objectData = data;
|
|
156
|
-
for (const [key, propCondition] of Object.entries(condition.properties)) {
|
|
157
|
-
if (!(key in objectData)) {
|
|
158
|
-
if ("const" in propCondition) {
|
|
159
|
-
return false;
|
|
160
|
-
}
|
|
161
|
-
continue;
|
|
162
|
-
}
|
|
163
|
-
const value = objectData[key];
|
|
164
|
-
if ("const" in propCondition && value !== propCondition["const"]) {
|
|
165
|
-
return false;
|
|
166
|
-
}
|
|
167
|
-
if ("minimum" in propCondition && typeof value === "number" && value < propCondition["minimum"]) {
|
|
168
|
-
return false;
|
|
169
|
-
}
|
|
170
|
-
if ("maximum" in propCondition && typeof value === "number" && value > propCondition["maximum"]) {
|
|
171
|
-
return false;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
return true;
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* Validates data against a conditional schema and adds issues to context if validation fails.
|
|
178
|
-
*
|
|
179
|
-
* @param {JSONValue} data - The data to validate.
|
|
180
|
-
* @param {JSONSchema} schema - The conditional schema.
|
|
181
|
-
* @param {z.RefinementCtx} ctx - The Zod refinement context.
|
|
182
|
-
*/
|
|
183
|
-
static validateConditionalSchema(data, schema, ctx) {
|
|
184
|
-
this.validateRequiredProperties(data, schema, ctx);
|
|
185
|
-
this.validatePropertyPatterns(data, schema, ctx);
|
|
186
|
-
this.validateNestedConditions(data, schema, ctx);
|
|
187
|
-
}
|
|
188
|
-
/**
|
|
189
|
-
* Validates that all required properties are present in the data.
|
|
190
|
-
*
|
|
191
|
-
* @param {JSONValue} data - The data to validate.
|
|
192
|
-
* @param {JSONSchema} schema - The schema containing required properties.
|
|
193
|
-
* @param {z.RefinementCtx} ctx - The Zod refinement context.
|
|
194
|
-
*/
|
|
195
|
-
static validateRequiredProperties(data, schema, ctx) {
|
|
196
|
-
if (!schema.required) {
|
|
197
|
-
return;
|
|
198
|
-
}
|
|
199
|
-
if (typeof data !== "object" || data === null) {
|
|
200
|
-
for (const requiredProp of schema.required) {
|
|
201
|
-
ctx.addIssue({
|
|
202
|
-
code: z.ZodIssueCode.custom,
|
|
203
|
-
message: `Required property '${requiredProp}' is missing`,
|
|
204
|
-
path: [requiredProp]
|
|
205
|
-
});
|
|
206
|
-
}
|
|
207
|
-
return;
|
|
208
|
-
}
|
|
209
|
-
for (const requiredProp of schema.required) {
|
|
210
|
-
if (!(requiredProp in data)) {
|
|
211
|
-
ctx.addIssue({
|
|
212
|
-
code: z.ZodIssueCode.custom,
|
|
213
|
-
message: `Required property '${requiredProp}' is missing`,
|
|
214
|
-
path: [requiredProp]
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
/**
|
|
220
|
-
* Validates property patterns for string properties.
|
|
221
|
-
*
|
|
222
|
-
* @param {JSONValue} data - The data to validate.
|
|
223
|
-
* @param {JSONSchema} schema - The schema containing property patterns.
|
|
224
|
-
* @param {z.RefinementCtx} ctx - The Zod refinement context.
|
|
225
|
-
*/
|
|
226
|
-
static validatePropertyPatterns(data, schema, ctx) {
|
|
227
|
-
if (!schema.properties) {
|
|
228
|
-
return;
|
|
229
|
-
}
|
|
230
|
-
if (typeof data !== "object" || data === null) {
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
if (Array.isArray(data)) {
|
|
234
|
-
return;
|
|
235
|
-
}
|
|
236
|
-
const objectData = data;
|
|
237
|
-
for (const [key, propSchema] of Object.entries(schema.properties)) {
|
|
238
|
-
if (!(key in objectData)) {
|
|
239
|
-
continue;
|
|
240
|
-
}
|
|
241
|
-
const value = objectData[key];
|
|
242
|
-
if (propSchema["pattern"] && typeof value === "string") {
|
|
243
|
-
const regex = new RegExp(propSchema["pattern"]);
|
|
244
|
-
if (!regex.test(value)) {
|
|
245
|
-
ctx.addIssue({
|
|
246
|
-
code: z.ZodIssueCode.custom,
|
|
247
|
-
message: `String '${value}' does not match pattern '${propSchema["pattern"]}'`,
|
|
248
|
-
path: [key]
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
/**
|
|
255
|
-
* Validates nested if-then-else conditions.
|
|
256
|
-
*
|
|
257
|
-
* @param {JSONValue} data - The data to validate.
|
|
258
|
-
* @param {JSONSchema} schema - The schema containing if-then-else conditions.
|
|
259
|
-
* @param {z.RefinementCtx} ctx - The Zod refinement context.
|
|
260
|
-
*/
|
|
261
|
-
static validateNestedConditions(data, schema, ctx) {
|
|
262
|
-
if (!schema["if"] || !schema["then"]) {
|
|
263
|
-
return;
|
|
264
|
-
}
|
|
265
|
-
const matchesIf = this.matchesCondition(data, schema["if"]);
|
|
266
|
-
if (matchesIf) {
|
|
267
|
-
this.validateConditionalSchema(data, schema["then"], ctx);
|
|
268
|
-
} else if (schema["else"]) {
|
|
269
|
-
this.validateConditionalSchema(data, schema["else"], ctx);
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
/**
|
|
273
|
-
* Parses a JSON schema and returns the corresponding Zod schema.
|
|
274
|
-
* This is the main entry point for schema conversion.
|
|
275
|
-
*
|
|
276
|
-
* @param {JSONSchema} schema - The JSON schema.
|
|
277
|
-
* @returns {ZodTypeAny} - The ZodTypeAny schema.
|
|
278
|
-
*/
|
|
279
|
-
static parseSchema(schema) {
|
|
280
|
-
if (Array.isArray(schema.type)) {
|
|
281
|
-
return this.handleTypeArray(schema);
|
|
282
|
-
}
|
|
283
|
-
if (schema.oneOf || schema.anyOf || schema.allOf) {
|
|
284
|
-
return this.parseCombinator(schema);
|
|
285
|
-
}
|
|
286
|
-
if (schema["if"] && schema["then"]) {
|
|
287
|
-
return this.parseObject(schema);
|
|
288
|
-
}
|
|
289
|
-
if (schema.properties && (!schema.type || schema.type === "object")) {
|
|
290
|
-
return this.parseObject(schema);
|
|
291
|
-
}
|
|
292
|
-
return this.handleSingleType(schema);
|
|
293
|
-
}
|
|
294
|
-
/**
|
|
295
|
-
* Handles schemas with an array of types.
|
|
296
|
-
*
|
|
297
|
-
* @param {JSONSchema} schema - The JSON schema with type array.
|
|
298
|
-
* @returns {ZodTypeAny} - The ZodTypeAny schema.
|
|
299
|
-
*/
|
|
300
|
-
static handleTypeArray(schema) {
|
|
301
|
-
if (!Array.isArray(schema.type)) {
|
|
302
|
-
throw new Error("Expected schema.type to be an array");
|
|
303
|
-
}
|
|
304
|
-
if (schema.type.includes("null")) {
|
|
305
|
-
return this.handleNullableType(schema);
|
|
306
|
-
}
|
|
307
|
-
return this.createUnionFromTypes(schema.type, schema);
|
|
308
|
-
}
|
|
309
|
-
/**
|
|
310
|
-
* Handles nullable types by creating a nullable schema.
|
|
311
|
-
*
|
|
312
|
-
* @param {JSONSchema} schema - The JSON schema with nullable type.
|
|
313
|
-
* @returns {ZodTypeAny} - The nullable Zod schema.
|
|
314
|
-
*/
|
|
315
|
-
static handleNullableType(schema) {
|
|
316
|
-
if (!Array.isArray(schema.type)) {
|
|
317
|
-
throw new Error("Expected schema.type to be an array");
|
|
318
|
-
}
|
|
319
|
-
const nonNullSchema = { ...schema };
|
|
320
|
-
nonNullSchema.type = schema.type.filter((t) => t !== "null");
|
|
321
|
-
if (nonNullSchema.type.length === 1) {
|
|
322
|
-
const singleTypeSchema = this.handleSingleType({
|
|
323
|
-
...schema,
|
|
324
|
-
type: nonNullSchema.type[0]
|
|
325
|
-
});
|
|
326
|
-
return singleTypeSchema.nullable();
|
|
327
|
-
}
|
|
328
|
-
const unionSchema = this.parseSchema(nonNullSchema);
|
|
329
|
-
return unionSchema.nullable();
|
|
330
|
-
}
|
|
331
|
-
/**
|
|
332
|
-
* Creates a union type from an array of types.
|
|
333
|
-
*
|
|
334
|
-
* @param {string[]} types - Array of type strings.
|
|
335
|
-
* @param {JSONSchema} baseSchema - The base schema to apply to each type.
|
|
336
|
-
* @returns {ZodTypeAny} - The union Zod schema.
|
|
337
|
-
*/
|
|
338
|
-
static createUnionFromTypes(types, baseSchema) {
|
|
339
|
-
const schemas = types.map((type) => {
|
|
340
|
-
const singleTypeSchema = { ...baseSchema, type };
|
|
341
|
-
return this.parseSchema(singleTypeSchema);
|
|
342
|
-
});
|
|
343
|
-
return z.union(schemas);
|
|
344
|
-
}
|
|
345
|
-
/**
|
|
346
|
-
* Handles schemas with a single type.
|
|
347
|
-
*
|
|
348
|
-
* @param {JSONSchema} schema - The JSON schema with single type.
|
|
349
|
-
* @returns {ZodTypeAny} - The ZodTypeAny schema.
|
|
350
|
-
*/
|
|
351
|
-
static handleSingleType(schema) {
|
|
352
|
-
if (schema.type === void 0) {
|
|
353
|
-
if (schema.oneOf || schema.anyOf || schema.allOf) {
|
|
354
|
-
return this.parseCombinator(schema);
|
|
355
|
-
}
|
|
356
|
-
if (schema.properties) {
|
|
357
|
-
return this.parseObject(schema);
|
|
358
|
-
}
|
|
359
|
-
return z.any();
|
|
360
|
-
}
|
|
361
|
-
switch (schema.type) {
|
|
362
|
-
case "string":
|
|
363
|
-
return this.parseString(schema);
|
|
364
|
-
case "number":
|
|
365
|
-
case "integer":
|
|
366
|
-
return this.parseNumberSchema(schema);
|
|
367
|
-
case "boolean":
|
|
368
|
-
return z.boolean();
|
|
369
|
-
case "array":
|
|
370
|
-
return this.parseArray(schema);
|
|
371
|
-
case "object":
|
|
372
|
-
return this.parseObject(schema);
|
|
373
|
-
default:
|
|
374
|
-
throw new Error("Unsupported schema type");
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
/**
|
|
378
|
-
* Parses a number schema.
|
|
379
|
-
*
|
|
380
|
-
* @param {JSONSchema} schema - The JSON schema for a number.
|
|
381
|
-
* @returns {ZodTypeAny} - The ZodTypeAny schema.
|
|
382
|
-
*/
|
|
383
|
-
static parseNumberSchema(schema) {
|
|
384
|
-
const numberSchema = z.number();
|
|
385
|
-
let result = numberSchema;
|
|
386
|
-
result = this.applyNumberBounds(numberSchema, schema);
|
|
387
|
-
result = this.applyNumberMultipleOf(numberSchema, schema);
|
|
388
|
-
result = this.applyNumberEnum(numberSchema, schema);
|
|
389
|
-
result = this.applyIntegerConstraint(numberSchema, schema);
|
|
390
|
-
return result;
|
|
391
|
-
}
|
|
392
|
-
/**
|
|
393
|
-
* Applies bounds validation to a number schema.
|
|
394
|
-
*
|
|
395
|
-
* @param {z.ZodNumber} numberSchema - The base number schema.
|
|
396
|
-
* @param {JSONSchema} schema - The JSON schema with bounds.
|
|
397
|
-
* @returns {z.ZodNumber} - The updated schema with bounds validation.
|
|
398
|
-
*/
|
|
399
|
-
static applyNumberBounds(numberSchema, schema) {
|
|
400
|
-
let result = numberSchema;
|
|
401
|
-
if (schema["minimum"] !== void 0) {
|
|
402
|
-
result = schema["exclusiveMinimum"] ? result.gt(schema["minimum"]) : result.gte(schema["minimum"]);
|
|
403
|
-
}
|
|
404
|
-
if (schema["maximum"] !== void 0) {
|
|
405
|
-
result = schema["exclusiveMaximum"] ? result.lt(schema["maximum"]) : result.lte(schema["maximum"]);
|
|
406
|
-
}
|
|
407
|
-
return result;
|
|
408
|
-
}
|
|
409
|
-
/**
|
|
410
|
-
* Applies multipleOf validation to a number schema.
|
|
411
|
-
*
|
|
412
|
-
* @param {z.ZodNumber} numberSchema - The base number schema.
|
|
413
|
-
* @param {JSONSchema} schema - The JSON schema with multipleOf.
|
|
414
|
-
* @returns {z.ZodNumber} - The updated schema with multipleOf validation.
|
|
415
|
-
*/
|
|
416
|
-
static applyNumberMultipleOf(numberSchema, schema) {
|
|
417
|
-
if (schema["multipleOf"] === void 0) {
|
|
418
|
-
return numberSchema;
|
|
419
|
-
}
|
|
420
|
-
return numberSchema.refine((val) => val % schema["multipleOf"] === 0, {
|
|
421
|
-
message: `Number must be a multiple of ${schema["multipleOf"]}`
|
|
422
|
-
});
|
|
423
|
-
}
|
|
424
|
-
/**
|
|
425
|
-
* Applies enum validation to a number schema.
|
|
426
|
-
*
|
|
427
|
-
* @param {z.ZodNumber} numberSchema - The base number schema.
|
|
428
|
-
* @param {JSONSchema} schema - The JSON schema with enum.
|
|
429
|
-
* @returns {z.ZodNumber} - The updated schema with enum validation.
|
|
430
|
-
*/
|
|
431
|
-
static applyNumberEnum(numberSchema, schema) {
|
|
432
|
-
if (!schema.enum) {
|
|
433
|
-
return numberSchema;
|
|
434
|
-
}
|
|
435
|
-
const numberEnums = schema.enum.filter(
|
|
436
|
-
(val) => typeof val === "number"
|
|
437
|
-
);
|
|
438
|
-
if (numberEnums.length === 0) {
|
|
439
|
-
return numberSchema;
|
|
440
|
-
}
|
|
441
|
-
return numberSchema.refine((val) => numberEnums.includes(val), {
|
|
442
|
-
message: `Number must be one of: ${numberEnums.join(", ")}`
|
|
443
|
-
});
|
|
444
|
-
}
|
|
445
|
-
/**
|
|
446
|
-
* Applies integer constraint to a number schema if needed.
|
|
447
|
-
*
|
|
448
|
-
* @param {z.ZodNumber} numberSchema - The base number schema.
|
|
449
|
-
* @param {JSONSchema} schema - The JSON schema.
|
|
450
|
-
* @returns {z.ZodNumber} - The updated schema with integer validation if needed.
|
|
451
|
-
*/
|
|
452
|
-
static applyIntegerConstraint(numberSchema, schema) {
|
|
453
|
-
if (schema.type !== "integer") {
|
|
454
|
-
return numberSchema;
|
|
455
|
-
}
|
|
456
|
-
return numberSchema.refine((val) => Number.isInteger(val), {
|
|
457
|
-
message: "Number must be an integer"
|
|
458
|
-
});
|
|
459
|
-
}
|
|
460
|
-
/**
|
|
461
|
-
* Parses a string schema.
|
|
462
|
-
*
|
|
463
|
-
* @param {JSONSchema} schema - The JSON schema for a string.
|
|
464
|
-
* @returns {ZodTypeAny} - The ZodTypeAny schema.
|
|
465
|
-
*/
|
|
466
|
-
static parseString(schema) {
|
|
467
|
-
const stringSchema = z.string();
|
|
468
|
-
let result = stringSchema;
|
|
469
|
-
if (schema.format) {
|
|
470
|
-
return this.applyStringFormat(stringSchema, schema);
|
|
471
|
-
} else {
|
|
472
|
-
result = this.applyStringPattern(stringSchema, schema);
|
|
473
|
-
result = this.applyStringLength(stringSchema, schema);
|
|
474
|
-
result = this.applyStringEnum(stringSchema, schema);
|
|
475
|
-
}
|
|
476
|
-
return result;
|
|
477
|
-
}
|
|
478
|
-
/**
|
|
479
|
-
* Applies format validation to a string schema.
|
|
480
|
-
*
|
|
481
|
-
* @param {z.ZodString} stringSchema - The base string schema.
|
|
482
|
-
* @param {JSONSchema} schema - The JSON schema with format.
|
|
483
|
-
* @returns {ZodTypeAny} - The updated schema with format validation.
|
|
484
|
-
*/
|
|
485
|
-
static applyStringFormat(stringSchema, schema) {
|
|
486
|
-
if (!schema.format) {
|
|
487
|
-
return stringSchema;
|
|
488
|
-
}
|
|
489
|
-
switch (schema.format) {
|
|
490
|
-
case "email":
|
|
491
|
-
return stringSchema.email();
|
|
492
|
-
case "date-time":
|
|
493
|
-
return stringSchema.datetime();
|
|
494
|
-
case "uri":
|
|
495
|
-
return stringSchema.url();
|
|
496
|
-
case "uuid":
|
|
497
|
-
return stringSchema.uuid();
|
|
498
|
-
case "date":
|
|
499
|
-
return stringSchema.date();
|
|
500
|
-
default:
|
|
501
|
-
return stringSchema;
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
/**
|
|
505
|
-
* Applies pattern validation to a string schema.
|
|
506
|
-
*
|
|
507
|
-
* @param {z.ZodString} stringSchema - The base string schema.
|
|
508
|
-
* @param {JSONSchema} schema - The JSON schema with pattern.
|
|
509
|
-
* @returns {z.ZodString} - The updated schema with pattern validation.
|
|
510
|
-
*/
|
|
511
|
-
static applyStringPattern(stringSchema, schema) {
|
|
512
|
-
if (!schema["pattern"]) {
|
|
513
|
-
return stringSchema;
|
|
514
|
-
}
|
|
515
|
-
const regex = new RegExp(schema["pattern"]);
|
|
516
|
-
return stringSchema.regex(regex, {
|
|
517
|
-
message: `String must match pattern: ${schema["pattern"]}`
|
|
518
|
-
});
|
|
519
|
-
}
|
|
520
|
-
/**
|
|
521
|
-
* Applies length constraints to a string schema.
|
|
522
|
-
*
|
|
523
|
-
* @param {z.ZodString} stringSchema - The base string schema.
|
|
524
|
-
* @param {JSONSchema} schema - The JSON schema with length constraints.
|
|
525
|
-
* @returns {z.ZodString} - The updated schema with length validation.
|
|
526
|
-
*/
|
|
527
|
-
static applyStringLength(stringSchema, schema) {
|
|
528
|
-
const result = stringSchema;
|
|
529
|
-
if (schema["minLength"] !== void 0) {
|
|
530
|
-
stringSchema = stringSchema.min(schema["minLength"]);
|
|
531
|
-
}
|
|
532
|
-
if (schema["maxLength"] !== void 0) {
|
|
533
|
-
stringSchema = stringSchema.max(schema["maxLength"]);
|
|
534
|
-
}
|
|
535
|
-
return result;
|
|
536
|
-
}
|
|
537
|
-
/**
|
|
538
|
-
* Applies enum validation to a string schema.
|
|
539
|
-
*
|
|
540
|
-
* @param {z.ZodString} stringSchema - The base string schema.
|
|
541
|
-
* @param {JSONSchema} schema - The JSON schema with enum.
|
|
542
|
-
* @returns {ZodTypeAny} - The updated schema with enum validation.
|
|
543
|
-
*/
|
|
544
|
-
static applyStringEnum(stringSchema, schema) {
|
|
545
|
-
if (!schema.enum) {
|
|
546
|
-
return stringSchema;
|
|
547
|
-
}
|
|
548
|
-
return stringSchema.refine((val) => schema.enum?.includes(val), {
|
|
549
|
-
message: `Value must be one of: ${schema.enum?.join(", ")}`
|
|
550
|
-
});
|
|
551
|
-
}
|
|
552
|
-
/**
|
|
553
|
-
* Parses a JSON schema of type array and returns the corresponding Zod schema.
|
|
554
|
-
*
|
|
555
|
-
* @param {JSONSchema} schema - The JSON schema.
|
|
556
|
-
* @returns {ZodTypeAny} - The ZodTypeAny schema.
|
|
557
|
-
*/
|
|
558
|
-
static parseArray(schema) {
|
|
559
|
-
if (Array.isArray(schema.items)) {
|
|
560
|
-
const tupleSchemas = schema.items.map((item) => this.parseSchema(item));
|
|
561
|
-
return z.union(tupleSchemas);
|
|
562
|
-
}
|
|
563
|
-
const itemSchema = schema.items ? this.parseSchema(schema.items) : z.any();
|
|
564
|
-
const arraySchema = z.array(itemSchema);
|
|
565
|
-
let result = arraySchema;
|
|
566
|
-
result = this.applyArrayConstraints(arraySchema, schema);
|
|
567
|
-
return result;
|
|
568
|
-
}
|
|
569
|
-
/**
|
|
570
|
-
* Applies constraints to an array schema.
|
|
571
|
-
*
|
|
572
|
-
* @param {z.ZodArray<any>} arraySchema - The base array schema.
|
|
573
|
-
* @param {JSONSchema} schema - The JSON schema with array constraints.
|
|
574
|
-
* @returns {z.ZodTypeAny} - The updated array schema with constraints.
|
|
575
|
-
*/
|
|
576
|
-
static applyArrayConstraints(arraySchema, schema) {
|
|
577
|
-
if (schema["minItems"] !== void 0) {
|
|
578
|
-
arraySchema = arraySchema.min(schema["minItems"]);
|
|
579
|
-
}
|
|
580
|
-
if (schema["maxItems"] !== void 0) {
|
|
581
|
-
arraySchema = arraySchema.max(schema["maxItems"]);
|
|
582
|
-
}
|
|
583
|
-
if (schema["uniqueItems"]) {
|
|
584
|
-
return arraySchema.refine(
|
|
585
|
-
(items) => new Set(items).size === items.length,
|
|
586
|
-
{ message: "Array items must be unique" }
|
|
587
|
-
);
|
|
588
|
-
}
|
|
589
|
-
return arraySchema;
|
|
590
|
-
}
|
|
591
|
-
/**
|
|
592
|
-
* Parses an object schema.
|
|
593
|
-
*
|
|
594
|
-
* @param {JSONSchema} schema - The JSON schema for an object.
|
|
595
|
-
* @returns {ZodTypeAny} - The ZodTypeAny schema.
|
|
596
|
-
*/
|
|
597
|
-
static parseObject(schema) {
|
|
598
|
-
if (schema["if"] && schema["then"]) {
|
|
599
|
-
return this.parseConditional(schema);
|
|
600
|
-
}
|
|
601
|
-
const shape = {};
|
|
602
|
-
this.processObjectProperties(schema, shape);
|
|
603
|
-
return this.processAdditionalProperties(schema, z.object(shape));
|
|
604
|
-
}
|
|
605
|
-
/**
|
|
606
|
-
* Processes object properties and builds the shape object.
|
|
607
|
-
*
|
|
608
|
-
* @param {JSONSchema} schema - The JSON schema for an object.
|
|
609
|
-
* @param {Record<string, ZodTypeAny>} shape - The shape object to populate.
|
|
610
|
-
*/
|
|
611
|
-
static processObjectProperties(schema, shape) {
|
|
612
|
-
const required = new Set(schema.required || []);
|
|
613
|
-
if (!schema.properties) {
|
|
614
|
-
return;
|
|
615
|
-
}
|
|
616
|
-
for (const [key, propSchema] of Object.entries(schema.properties)) {
|
|
617
|
-
const zodSchema = this.parseSchema(propSchema);
|
|
618
|
-
shape[key] = required.has(key) ? zodSchema : zodSchema.optional();
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
/**
|
|
622
|
-
* Processes additionalProperties configuration.
|
|
623
|
-
*
|
|
624
|
-
* @param {JSONSchema} schema - The JSON schema for an object.
|
|
625
|
-
* @param {z.ZodObject<any, any>} objectSchema - The Zod object schema.
|
|
626
|
-
* @returns {z.ZodObject<any, any>} - The updated Zod object schema.
|
|
627
|
-
*/
|
|
628
|
-
static processAdditionalProperties(schema, objectSchema) {
|
|
629
|
-
if (schema.additionalProperties === true) {
|
|
630
|
-
return objectSchema.passthrough();
|
|
631
|
-
} else if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
|
|
632
|
-
const additionalPropSchema = this.parseSchema(
|
|
633
|
-
schema.additionalProperties
|
|
634
|
-
);
|
|
635
|
-
return objectSchema.catchall(additionalPropSchema);
|
|
636
|
-
} else {
|
|
637
|
-
return objectSchema.strict();
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
/**
|
|
641
|
-
* Parses a conditional schema with if-then-else.
|
|
642
|
-
*
|
|
643
|
-
* @param {JSONSchema} schema - The JSON schema with conditional validation.
|
|
644
|
-
* @returns {ZodTypeAny} - The conditional Zod schema.
|
|
645
|
-
*/
|
|
646
|
-
static parseConditional(schema) {
|
|
647
|
-
const zodObject = this.createBaseObjectSchema(schema);
|
|
648
|
-
const ifCondition = schema["if"];
|
|
649
|
-
const thenSchema = schema["then"];
|
|
650
|
-
const elseSchema = schema["else"];
|
|
651
|
-
return zodObject.superRefine((data, ctx) => {
|
|
652
|
-
const dataWithDefaults = this.applyDefaultValues(
|
|
653
|
-
data,
|
|
654
|
-
schema
|
|
655
|
-
);
|
|
656
|
-
if (this.matchesCondition(dataWithDefaults, ifCondition)) {
|
|
657
|
-
this.validateConditionalSchema(dataWithDefaults, thenSchema, ctx);
|
|
658
|
-
} else if (elseSchema) {
|
|
659
|
-
this.validateConditionalSchema(dataWithDefaults, elseSchema, ctx);
|
|
660
|
-
}
|
|
661
|
-
});
|
|
662
|
-
}
|
|
663
|
-
/**
|
|
664
|
-
* Creates a base object schema from the given JSON schema.
|
|
665
|
-
*
|
|
666
|
-
* @param {JSONSchema} schema - The JSON schema.
|
|
667
|
-
* @returns {z.ZodObject<any, any>} - The base Zod object schema.
|
|
668
|
-
*/
|
|
669
|
-
static createBaseObjectSchema(schema) {
|
|
670
|
-
const shape = {};
|
|
671
|
-
const required = new Set(schema.required || []);
|
|
672
|
-
for (const [key, value] of Object.entries(schema.properties || {})) {
|
|
673
|
-
const zodSchema = this.parseSchema(value);
|
|
674
|
-
shape[key] = required.has(key) ? zodSchema : zodSchema.optional();
|
|
675
|
-
}
|
|
676
|
-
const zodObject = z.object(shape);
|
|
677
|
-
return this.processAdditionalProperties(schema, zodObject);
|
|
678
|
-
}
|
|
679
|
-
/**
|
|
680
|
-
* Applies default values from schema properties to data object.
|
|
681
|
-
*
|
|
682
|
-
* @param {JSONValue} data - The original data object.
|
|
683
|
-
* @param {JSONSchema} schema - The schema with default values.
|
|
684
|
-
* @returns {JSONValue} - The data object with defaults applied.
|
|
685
|
-
*/
|
|
686
|
-
static applyDefaultValues(data, schema) {
|
|
687
|
-
if (typeof data !== "object" || data === null) {
|
|
688
|
-
return data;
|
|
689
|
-
}
|
|
690
|
-
if (Array.isArray(data)) {
|
|
691
|
-
return data;
|
|
692
|
-
}
|
|
693
|
-
const objectData = data;
|
|
694
|
-
const dataWithDefaults = { ...objectData };
|
|
695
|
-
if (!schema.properties) {
|
|
696
|
-
return dataWithDefaults;
|
|
697
|
-
}
|
|
698
|
-
for (const [key, propSchema] of Object.entries(schema.properties)) {
|
|
699
|
-
if (!(key in dataWithDefaults) && "default" in propSchema) {
|
|
700
|
-
dataWithDefaults[key] = propSchema["default"];
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
return dataWithDefaults;
|
|
704
|
-
}
|
|
705
|
-
/**
|
|
706
|
-
* Parses a schema with combinators (oneOf, anyOf, allOf).
|
|
707
|
-
* Delegates to the appropriate combinator parser based on which combinator is present.
|
|
708
|
-
*
|
|
709
|
-
* @param {JSONSchema} schema - The JSON schema with combinators.
|
|
710
|
-
* @returns {ZodTypeAny} - The ZodTypeAny schema.
|
|
711
|
-
*/
|
|
712
|
-
static parseCombinator(schema) {
|
|
713
|
-
if (schema.oneOf) {
|
|
714
|
-
return this.parseOneOf(schema.oneOf);
|
|
715
|
-
}
|
|
716
|
-
if (schema.anyOf) {
|
|
717
|
-
return this.parseAnyOf(schema.anyOf);
|
|
718
|
-
}
|
|
719
|
-
if (schema.allOf) {
|
|
720
|
-
return this.parseAllOf(schema.allOf);
|
|
721
|
-
}
|
|
722
|
-
throw new Error("Unsupported schema type");
|
|
723
|
-
}
|
|
724
|
-
/**
|
|
725
|
-
* Parses a oneOf combinator schema.
|
|
726
|
-
*
|
|
727
|
-
* @param {JSONSchema[]} schemas - Array of JSON schemas in the oneOf.
|
|
728
|
-
* @returns {ZodTypeAny} - The ZodTypeAny schema.
|
|
729
|
-
*/
|
|
730
|
-
static parseOneOf(schemas) {
|
|
731
|
-
return this.createUnionFromSchemas(schemas);
|
|
732
|
-
}
|
|
733
|
-
/**
|
|
734
|
-
* Parses an anyOf combinator schema.
|
|
735
|
-
*
|
|
736
|
-
* @param {JSONSchema[]} schemas - Array of JSON schemas in the anyOf.
|
|
737
|
-
* @returns {ZodTypeAny} - The ZodTypeAny schema.
|
|
738
|
-
*/
|
|
739
|
-
static parseAnyOf(schemas) {
|
|
740
|
-
return this.createUnionFromSchemas(schemas);
|
|
741
|
-
}
|
|
742
|
-
/**
|
|
743
|
-
* Creates a union from an array of schemas, handling special cases.
|
|
744
|
-
*
|
|
745
|
-
* @param {JSONSchema[]} schemas - Array of JSON schemas to create a union from.
|
|
746
|
-
* @returns {ZodTypeAny} - The union Zod schema.
|
|
747
|
-
*/
|
|
748
|
-
static createUnionFromSchemas(schemas) {
|
|
749
|
-
if (schemas.length === 0) {
|
|
750
|
-
return z.any();
|
|
751
|
-
}
|
|
752
|
-
if (schemas.length === 1) {
|
|
753
|
-
return this.parseSchema(schemas[0]);
|
|
754
|
-
}
|
|
755
|
-
const zodSchemas = [];
|
|
756
|
-
for (const subSchema of schemas) {
|
|
757
|
-
if (subSchema.type === "null") {
|
|
758
|
-
zodSchemas.push(z.null());
|
|
759
|
-
} else {
|
|
760
|
-
zodSchemas.push(this.parseSchema(subSchema));
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
if (zodSchemas.length >= 2) {
|
|
764
|
-
return z.union(zodSchemas);
|
|
765
|
-
} else if (zodSchemas.length === 1) {
|
|
766
|
-
return zodSchemas[0];
|
|
767
|
-
}
|
|
768
|
-
return z.any();
|
|
769
|
-
}
|
|
770
|
-
/**
|
|
771
|
-
* Parses an allOf combinator schema by merging all schemas.
|
|
772
|
-
*
|
|
773
|
-
* @param {JSONSchema[]} schemas - Array of JSON schemas in the allOf.
|
|
774
|
-
* @returns {ZodTypeAny} - The ZodTypeAny schema.
|
|
775
|
-
*/
|
|
776
|
-
static parseAllOf(schemas) {
|
|
777
|
-
if (schemas.length === 0) {
|
|
778
|
-
return z.any();
|
|
779
|
-
}
|
|
780
|
-
if (schemas.length === 1) {
|
|
781
|
-
return this.parseSchema(schemas[0]);
|
|
782
|
-
}
|
|
783
|
-
const mergedSchema = schemas.reduce(
|
|
784
|
-
(acc, currentSchema) => this.mergeSchemas(acc, currentSchema)
|
|
785
|
-
);
|
|
786
|
-
return this.parseSchema(mergedSchema);
|
|
787
|
-
}
|
|
788
|
-
/**
|
|
789
|
-
* Merges two JSON schemas together.
|
|
790
|
-
*
|
|
791
|
-
* @param {JSONSchema} baseSchema - The base JSON schema.
|
|
792
|
-
* @param {JSONSchema} addSchema - The JSON schema to add.
|
|
793
|
-
* @returns {JSONSchema} - The merged JSON schema
|
|
794
|
-
*/
|
|
795
|
-
static mergeSchemas(baseSchema, addSchema) {
|
|
796
|
-
const merged = { ...baseSchema, ...addSchema };
|
|
797
|
-
if (baseSchema.properties && addSchema.properties) {
|
|
798
|
-
const mergedProperties = {
|
|
799
|
-
...baseSchema.properties,
|
|
800
|
-
...addSchema.properties
|
|
801
|
-
};
|
|
802
|
-
merged.properties = mergedProperties;
|
|
803
|
-
}
|
|
804
|
-
if (baseSchema.required && addSchema.required) {
|
|
805
|
-
const mergedRequired = [
|
|
806
|
-
.../* @__PURE__ */ new Set([...baseSchema.required, ...addSchema.required])
|
|
807
|
-
];
|
|
808
|
-
merged.required = mergedRequired;
|
|
809
|
-
}
|
|
810
|
-
return merged;
|
|
811
|
-
}
|
|
812
|
-
};
|
|
813
|
-
|
|
814
|
-
// src/adapters/langchain_adapter.ts
|
|
815
|
-
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
816
|
-
import { z as z2 } from "zod";
|
|
817
|
-
function schemaToZod(schema) {
|
|
818
|
-
try {
|
|
819
|
-
return JSONSchemaToZod.convert(schema);
|
|
820
|
-
} catch (err) {
|
|
821
|
-
logger.warn(`Failed to convert JSON schema to Zod: ${err}`);
|
|
822
|
-
return z2.any();
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
__name(schemaToZod, "schemaToZod");
|
|
826
|
-
var LangChainAdapter = class extends BaseAdapter {
|
|
827
|
-
static {
|
|
828
|
-
__name(this, "LangChainAdapter");
|
|
829
|
-
}
|
|
830
|
-
constructor(disallowedTools = []) {
|
|
831
|
-
super(disallowedTools);
|
|
832
|
-
}
|
|
833
|
-
/**
|
|
834
|
-
* Convert a single MCP tool specification into a LangChainJS structured tool.
|
|
835
|
-
*/
|
|
836
|
-
convertTool(mcpTool, connector) {
|
|
837
|
-
if (this.disallowedTools.includes(mcpTool.name)) {
|
|
838
|
-
return null;
|
|
839
|
-
}
|
|
840
|
-
const argsSchema = mcpTool.inputSchema ? schemaToZod(mcpTool.inputSchema) : z2.object({}).optional();
|
|
841
|
-
const tool = new DynamicStructuredTool({
|
|
842
|
-
name: mcpTool.name ?? "NO NAME",
|
|
843
|
-
description: mcpTool.description ?? "",
|
|
844
|
-
// Blank is acceptable but discouraged.
|
|
845
|
-
schema: argsSchema,
|
|
846
|
-
func: /* @__PURE__ */ __name(async (input) => {
|
|
847
|
-
logger.debug(
|
|
848
|
-
`MCP tool "${mcpTool.name}" received input: ${JSON.stringify(input)}`
|
|
849
|
-
);
|
|
850
|
-
try {
|
|
851
|
-
const result = await connector.callTool(
|
|
852
|
-
mcpTool.name,
|
|
853
|
-
input
|
|
854
|
-
);
|
|
855
|
-
return JSON.stringify(result);
|
|
856
|
-
} catch (err) {
|
|
857
|
-
logger.error(`Error executing MCP tool: ${err.message}`);
|
|
858
|
-
return `Error executing MCP tool: ${String(err)}`;
|
|
859
|
-
}
|
|
860
|
-
}, "func")
|
|
861
|
-
});
|
|
862
|
-
return tool;
|
|
863
|
-
}
|
|
864
|
-
};
|
|
865
|
-
|
|
866
19
|
// src/managers/tools/acquire_active_mcp_server.ts
|
|
867
|
-
import { z
|
|
20
|
+
import { z } from "zod";
|
|
868
21
|
|
|
869
22
|
// src/managers/tools/base.ts
|
|
870
23
|
import { StructuredTool } from "@langchain/core/tools";
|
|
@@ -889,7 +42,7 @@ var MCPServerTool = class extends StructuredTool {
|
|
|
889
42
|
};
|
|
890
43
|
|
|
891
44
|
// src/managers/tools/acquire_active_mcp_server.ts
|
|
892
|
-
var PresentActiveServerSchema =
|
|
45
|
+
var PresentActiveServerSchema = z.object({});
|
|
893
46
|
var AcquireActiveMCPServerTool = class extends MCPServerTool {
|
|
894
47
|
static {
|
|
895
48
|
__name(this, "AcquireActiveMCPServerTool");
|
|
@@ -910,16 +63,16 @@ var AcquireActiveMCPServerTool = class extends MCPServerTool {
|
|
|
910
63
|
|
|
911
64
|
// src/managers/tools/add_server_from_config.ts
|
|
912
65
|
import { StructuredTool as StructuredTool2 } from "@langchain/core/tools";
|
|
913
|
-
import { z as
|
|
66
|
+
import { z as z2 } from "zod";
|
|
914
67
|
var AddMCPServerFromConfigTool = class extends StructuredTool2 {
|
|
915
68
|
static {
|
|
916
69
|
__name(this, "AddMCPServerFromConfigTool");
|
|
917
70
|
}
|
|
918
71
|
name = "add_mcp_server_from_config";
|
|
919
72
|
description = "Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";
|
|
920
|
-
schema =
|
|
921
|
-
serverName:
|
|
922
|
-
serverConfig:
|
|
73
|
+
schema = z2.object({
|
|
74
|
+
serverName: z2.string().describe("The name for the new MCP server."),
|
|
75
|
+
serverConfig: z2.any().describe(
|
|
923
76
|
'The configuration object for the server. This should not include the top-level "mcpServers" key.'
|
|
924
77
|
)
|
|
925
78
|
});
|
|
@@ -961,9 +114,9 @@ ${tools.map((t) => t.name).join("\n")}`;
|
|
|
961
114
|
};
|
|
962
115
|
|
|
963
116
|
// src/managers/tools/connect_mcp_server.ts
|
|
964
|
-
import { z as
|
|
965
|
-
var ConnectMCPServerSchema =
|
|
966
|
-
serverName:
|
|
117
|
+
import { z as z3 } from "zod";
|
|
118
|
+
var ConnectMCPServerSchema = z3.object({
|
|
119
|
+
serverName: z3.string().describe("The name of the MCP server.")
|
|
967
120
|
});
|
|
968
121
|
var ConnectMCPServerTool = class extends MCPServerTool {
|
|
969
122
|
static {
|
|
@@ -992,15 +145,21 @@ var ConnectMCPServerTool = class extends MCPServerTool {
|
|
|
992
145
|
session = await this.manager.client.createSession(serverName);
|
|
993
146
|
}
|
|
994
147
|
this.manager.activeServer = serverName;
|
|
995
|
-
if (this.manager.serverTools[serverName]) {
|
|
148
|
+
if (!this.manager.serverTools[serverName]) {
|
|
996
149
|
const connector = session.connector;
|
|
997
150
|
const tools = await this.manager.adapter.createToolsFromConnectors([connector]);
|
|
998
|
-
this.manager.
|
|
151
|
+
const resources = await this.manager.adapter.createResourcesFromConnectors([connector]);
|
|
152
|
+
const prompts = await this.manager.adapter.createPromptsFromConnectors([connector]);
|
|
153
|
+
const allItems = [...tools, ...resources, ...prompts];
|
|
154
|
+
this.manager.serverTools[serverName] = allItems;
|
|
999
155
|
this.manager.initializedServers[serverName] = true;
|
|
156
|
+
logger.debug(
|
|
157
|
+
`Loaded ${allItems.length} items for server '${serverName}': ${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`
|
|
158
|
+
);
|
|
1000
159
|
}
|
|
1001
160
|
const serverTools = this.manager.serverTools[serverName] || [];
|
|
1002
161
|
const numTools = serverTools.length;
|
|
1003
|
-
return `Connected to MCP server '${serverName}'. ${numTools} tools are now available.`;
|
|
162
|
+
return `Connected to MCP server '${serverName}'. ${numTools} tools, resources, and prompts are now available.`;
|
|
1004
163
|
} catch (error) {
|
|
1005
164
|
logger.error(
|
|
1006
165
|
`Error connecting to server '${serverName}': ${String(error)}`
|
|
@@ -1011,8 +170,8 @@ var ConnectMCPServerTool = class extends MCPServerTool {
|
|
|
1011
170
|
};
|
|
1012
171
|
|
|
1013
172
|
// src/managers/tools/list_mcp_servers.ts
|
|
1014
|
-
import { z as
|
|
1015
|
-
var EnumerateServersSchema =
|
|
173
|
+
import { z as z4 } from "zod";
|
|
174
|
+
var EnumerateServersSchema = z4.object({});
|
|
1016
175
|
var ListMCPServersTool = class extends MCPServerTool {
|
|
1017
176
|
static {
|
|
1018
177
|
__name(this, "ListMCPServersTool");
|
|
@@ -1049,8 +208,8 @@ var ListMCPServersTool = class extends MCPServerTool {
|
|
|
1049
208
|
};
|
|
1050
209
|
|
|
1051
210
|
// src/managers/tools/release_mcp_server_connection.ts
|
|
1052
|
-
import { z as
|
|
1053
|
-
var ReleaseConnectionSchema =
|
|
211
|
+
import { z as z5 } from "zod";
|
|
212
|
+
var ReleaseConnectionSchema = z5.object({});
|
|
1054
213
|
var ReleaseMCPServerConnectionTool = class extends MCPServerTool {
|
|
1055
214
|
static {
|
|
1056
215
|
__name(this, "ReleaseMCPServerConnectionTool");
|
|
@@ -1161,21 +320,30 @@ var ServerManager = class {
|
|
|
1161
320
|
if (session) {
|
|
1162
321
|
const connector = session.connector;
|
|
1163
322
|
let tools = [];
|
|
323
|
+
let resources = [];
|
|
324
|
+
let prompts = [];
|
|
1164
325
|
try {
|
|
1165
326
|
tools = await this.adapter.createToolsFromConnectors([connector]);
|
|
327
|
+
resources = await this.adapter.createResourcesFromConnectors([
|
|
328
|
+
connector
|
|
329
|
+
]);
|
|
330
|
+
prompts = await this.adapter.createPromptsFromConnectors([
|
|
331
|
+
connector
|
|
332
|
+
]);
|
|
1166
333
|
} catch (toolFetchError) {
|
|
1167
334
|
logger.error(
|
|
1168
|
-
`Failed to create tools from connector for server '${serverName}': ${toolFetchError}`
|
|
335
|
+
`Failed to create tools/resources/prompts from connector for server '${serverName}': ${toolFetchError}`
|
|
1169
336
|
);
|
|
1170
337
|
continue;
|
|
1171
338
|
}
|
|
339
|
+
const allItems = [...tools, ...resources, ...prompts];
|
|
1172
340
|
const cachedTools = this.serverTools[serverName];
|
|
1173
|
-
const toolsChanged = !cachedTools || !isEqual(cachedTools,
|
|
341
|
+
const toolsChanged = !cachedTools || !isEqual(cachedTools, allItems);
|
|
1174
342
|
if (toolsChanged) {
|
|
1175
|
-
this.serverTools[serverName] =
|
|
343
|
+
this.serverTools[serverName] = allItems;
|
|
1176
344
|
this.initializedServers[serverName] = true;
|
|
1177
345
|
logger.debug(
|
|
1178
|
-
`Prefetched ${
|
|
346
|
+
`Prefetched ${allItems.length} items for server '${serverName}': ${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts.`
|
|
1179
347
|
);
|
|
1180
348
|
} else {
|
|
1181
349
|
logger.debug(
|
|
@@ -1244,9 +412,9 @@ var ObservabilityManager = class {
|
|
|
1244
412
|
return;
|
|
1245
413
|
}
|
|
1246
414
|
try {
|
|
1247
|
-
const { langfuseHandler: langfuseHandler2, langfuseInitPromise: langfuseInitPromise2 } = await import("./langfuse-
|
|
415
|
+
const { langfuseHandler: langfuseHandler2, langfuseInitPromise: langfuseInitPromise2 } = await import("./langfuse-74RGPTAH.js");
|
|
1248
416
|
if (this.agentId || this.metadata || this.metadataProvider || this.tagsProvider) {
|
|
1249
|
-
const { initializeLangfuse } = await import("./langfuse-
|
|
417
|
+
const { initializeLangfuse } = await import("./langfuse-74RGPTAH.js");
|
|
1250
418
|
await initializeLangfuse(
|
|
1251
419
|
this.agentId,
|
|
1252
420
|
this.metadata,
|
|
@@ -1406,6 +574,26 @@ var ObservabilityManager = class {
|
|
|
1406
574
|
import { toJSONSchema } from "zod";
|
|
1407
575
|
var API_CHATS_ENDPOINT = "/api/v1/chats";
|
|
1408
576
|
var API_CHAT_EXECUTE_ENDPOINT = "/api/v1/chats/{chat_id}/execute";
|
|
577
|
+
function normalizeRemoteRunOptions(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
|
|
578
|
+
if (typeof queryOrOptions === "object" && queryOrOptions !== null) {
|
|
579
|
+
const options = queryOrOptions;
|
|
580
|
+
return {
|
|
581
|
+
query: options.prompt,
|
|
582
|
+
maxSteps: options.maxSteps,
|
|
583
|
+
manageConnector: options.manageConnector,
|
|
584
|
+
externalHistory: options.externalHistory,
|
|
585
|
+
outputSchema: options.schema
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
return {
|
|
589
|
+
query: queryOrOptions,
|
|
590
|
+
maxSteps,
|
|
591
|
+
manageConnector,
|
|
592
|
+
externalHistory,
|
|
593
|
+
outputSchema
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
__name(normalizeRemoteRunOptions, "normalizeRemoteRunOptions");
|
|
1409
597
|
var RemoteAgent = class {
|
|
1410
598
|
static {
|
|
1411
599
|
__name(this, "RemoteAgent");
|
|
@@ -1502,8 +690,20 @@ var RemoteAgent = class {
|
|
|
1502
690
|
throw new Error(`Failed to create chat session: ${String(e)}`);
|
|
1503
691
|
}
|
|
1504
692
|
}
|
|
1505
|
-
async run(
|
|
1506
|
-
|
|
693
|
+
async run(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
|
|
694
|
+
const {
|
|
695
|
+
query,
|
|
696
|
+
maxSteps: steps,
|
|
697
|
+
externalHistory: history,
|
|
698
|
+
outputSchema: schema
|
|
699
|
+
} = normalizeRemoteRunOptions(
|
|
700
|
+
queryOrOptions,
|
|
701
|
+
maxSteps,
|
|
702
|
+
manageConnector,
|
|
703
|
+
externalHistory,
|
|
704
|
+
outputSchema
|
|
705
|
+
);
|
|
706
|
+
if (history !== void 0) {
|
|
1507
707
|
logger.warn("External history is not yet supported for remote execution");
|
|
1508
708
|
}
|
|
1509
709
|
try {
|
|
@@ -1514,10 +714,10 @@ var RemoteAgent = class {
|
|
|
1514
714
|
const chatId = this.chatId;
|
|
1515
715
|
const executionPayload = {
|
|
1516
716
|
query,
|
|
1517
|
-
max_steps:
|
|
717
|
+
max_steps: steps ?? 10
|
|
1518
718
|
};
|
|
1519
|
-
if (
|
|
1520
|
-
executionPayload.output_schema = this.pydanticToJsonSchema(
|
|
719
|
+
if (schema) {
|
|
720
|
+
executionPayload.output_schema = this.pydanticToJsonSchema(schema);
|
|
1521
721
|
logger.info(`\u{1F527} Using structured output with schema`);
|
|
1522
722
|
}
|
|
1523
723
|
const headers = {
|
|
@@ -1591,8 +791,8 @@ Raw error: ${result}`
|
|
|
1591
791
|
);
|
|
1592
792
|
}
|
|
1593
793
|
}
|
|
1594
|
-
if (
|
|
1595
|
-
return this.parseStructuredResponse(result,
|
|
794
|
+
if (schema) {
|
|
795
|
+
return this.parseStructuredResponse(result, schema);
|
|
1596
796
|
}
|
|
1597
797
|
if (typeof result === "object" && result !== null && "result" in result) {
|
|
1598
798
|
return result.result;
|
|
@@ -1617,9 +817,9 @@ Raw error: ${result}`
|
|
|
1617
817
|
}
|
|
1618
818
|
}
|
|
1619
819
|
// eslint-disable-next-line require-yield
|
|
1620
|
-
async *stream(
|
|
820
|
+
async *stream(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
|
|
1621
821
|
const result = await this.run(
|
|
1622
|
-
|
|
822
|
+
queryOrOptions,
|
|
1623
823
|
maxSteps,
|
|
1624
824
|
manageConnector,
|
|
1625
825
|
externalHistory,
|
|
@@ -1632,6 +832,144 @@ Raw error: ${result}`
|
|
|
1632
832
|
}
|
|
1633
833
|
};
|
|
1634
834
|
|
|
835
|
+
// src/agents/utils/llm_provider.ts
|
|
836
|
+
var PROVIDER_CONFIG = {
|
|
837
|
+
openai: {
|
|
838
|
+
package: "@langchain/openai",
|
|
839
|
+
className: "ChatOpenAI",
|
|
840
|
+
envVars: ["OPENAI_API_KEY"],
|
|
841
|
+
defaultModel: "gpt-4o"
|
|
842
|
+
},
|
|
843
|
+
anthropic: {
|
|
844
|
+
package: "@langchain/anthropic",
|
|
845
|
+
className: "ChatAnthropic",
|
|
846
|
+
envVars: ["ANTHROPIC_API_KEY"],
|
|
847
|
+
defaultModel: "claude-3-5-sonnet-20241022"
|
|
848
|
+
},
|
|
849
|
+
google: {
|
|
850
|
+
package: "@langchain/google-genai",
|
|
851
|
+
className: "ChatGoogleGenerativeAI",
|
|
852
|
+
envVars: ["GOOGLE_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY"],
|
|
853
|
+
defaultModel: "gemini-pro"
|
|
854
|
+
},
|
|
855
|
+
groq: {
|
|
856
|
+
package: "@langchain/groq",
|
|
857
|
+
className: "ChatGroq",
|
|
858
|
+
envVars: ["GROQ_API_KEY"],
|
|
859
|
+
defaultModel: "llama-3.1-70b-versatile"
|
|
860
|
+
}
|
|
861
|
+
};
|
|
862
|
+
function parseLLMString(llmString) {
|
|
863
|
+
const parts = llmString.split("/");
|
|
864
|
+
if (parts.length !== 2) {
|
|
865
|
+
throw new Error(
|
|
866
|
+
`Invalid LLM string format. Expected 'provider/model', got '${llmString}'. Examples: 'openai/gpt-4', 'anthropic/claude-3-5-sonnet-20241022', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`
|
|
867
|
+
);
|
|
868
|
+
}
|
|
869
|
+
const [provider, model] = parts;
|
|
870
|
+
if (!provider || !model) {
|
|
871
|
+
throw new Error(
|
|
872
|
+
`Invalid LLM string format. Both provider and model must be non-empty. Got '${llmString}'`
|
|
873
|
+
);
|
|
874
|
+
}
|
|
875
|
+
const normalizedProvider = provider.toLowerCase();
|
|
876
|
+
if (!(normalizedProvider in PROVIDER_CONFIG)) {
|
|
877
|
+
const supportedProviders = Object.keys(PROVIDER_CONFIG).join(", ");
|
|
878
|
+
throw new Error(
|
|
879
|
+
`Unsupported LLM provider '${provider}'. Supported providers: ${supportedProviders}`
|
|
880
|
+
);
|
|
881
|
+
}
|
|
882
|
+
return { provider: normalizedProvider, model };
|
|
883
|
+
}
|
|
884
|
+
__name(parseLLMString, "parseLLMString");
|
|
885
|
+
function getAPIKey(provider, config) {
|
|
886
|
+
if (config?.apiKey) {
|
|
887
|
+
return config.apiKey;
|
|
888
|
+
}
|
|
889
|
+
const providerConfig = PROVIDER_CONFIG[provider];
|
|
890
|
+
for (const envVar of providerConfig.envVars) {
|
|
891
|
+
const apiKey = process.env[envVar];
|
|
892
|
+
if (apiKey) {
|
|
893
|
+
logger.debug(
|
|
894
|
+
`Using API key from environment variable ${envVar} for provider ${provider}`
|
|
895
|
+
);
|
|
896
|
+
return apiKey;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
const envVarsStr = providerConfig.envVars.join(" or ");
|
|
900
|
+
throw new Error(
|
|
901
|
+
`API key not found for provider '${provider}'. Set ${envVarsStr} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${provider}/model', llmConfig: { apiKey: 'your-key' } })`
|
|
902
|
+
);
|
|
903
|
+
}
|
|
904
|
+
__name(getAPIKey, "getAPIKey");
|
|
905
|
+
async function createLLMFromString(llmString, config) {
|
|
906
|
+
logger.info(`Creating LLM from string: ${llmString}`);
|
|
907
|
+
const { provider, model } = parseLLMString(llmString);
|
|
908
|
+
const providerConfig = PROVIDER_CONFIG[provider];
|
|
909
|
+
const apiKey = getAPIKey(provider, config);
|
|
910
|
+
let providerModule;
|
|
911
|
+
try {
|
|
912
|
+
logger.debug(`Importing package ${providerConfig.package}...`);
|
|
913
|
+
providerModule = await import(providerConfig.package);
|
|
914
|
+
} catch (error) {
|
|
915
|
+
if (error?.code === "MODULE_NOT_FOUND" || error?.message?.includes("Cannot find module") || error?.message?.includes("Cannot find package")) {
|
|
916
|
+
throw new Error(
|
|
917
|
+
`Package '${providerConfig.package}' is not installed. Install it with: npm install ${providerConfig.package} or yarn add ${providerConfig.package}`
|
|
918
|
+
);
|
|
919
|
+
}
|
|
920
|
+
throw new Error(
|
|
921
|
+
`Failed to import ${providerConfig.package}: ${error?.message || error}`
|
|
922
|
+
);
|
|
923
|
+
}
|
|
924
|
+
const LLMClass = providerModule[providerConfig.className];
|
|
925
|
+
if (!LLMClass) {
|
|
926
|
+
throw new Error(
|
|
927
|
+
`Could not find ${providerConfig.className} in package ${providerConfig.package}. This might be a version compatibility issue.`
|
|
928
|
+
);
|
|
929
|
+
}
|
|
930
|
+
const llmConfig = {
|
|
931
|
+
model,
|
|
932
|
+
apiKey,
|
|
933
|
+
...config
|
|
934
|
+
};
|
|
935
|
+
if (config?.apiKey) {
|
|
936
|
+
delete llmConfig.apiKey;
|
|
937
|
+
llmConfig.apiKey = apiKey;
|
|
938
|
+
}
|
|
939
|
+
if (provider === "anthropic") {
|
|
940
|
+
llmConfig.model = model;
|
|
941
|
+
} else if (provider === "google") {
|
|
942
|
+
llmConfig.model = model;
|
|
943
|
+
} else if (provider === "openai") {
|
|
944
|
+
llmConfig.model = model;
|
|
945
|
+
} else if (provider === "groq") {
|
|
946
|
+
llmConfig.model = model;
|
|
947
|
+
}
|
|
948
|
+
try {
|
|
949
|
+
const llmInstance = new LLMClass(llmConfig);
|
|
950
|
+
logger.info(`Successfully created ${provider} LLM with model ${model}`);
|
|
951
|
+
return llmInstance;
|
|
952
|
+
} catch (error) {
|
|
953
|
+
throw new Error(
|
|
954
|
+
`Failed to instantiate ${providerConfig.className} with model '${model}': ${error?.message || error}`
|
|
955
|
+
);
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
__name(createLLMFromString, "createLLMFromString");
|
|
959
|
+
function isValidLLMString(llmString) {
|
|
960
|
+
try {
|
|
961
|
+
parseLLMString(llmString);
|
|
962
|
+
return true;
|
|
963
|
+
} catch {
|
|
964
|
+
return false;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
__name(isValidLLMString, "isValidLLMString");
|
|
968
|
+
function getSupportedProviders() {
|
|
969
|
+
return Object.keys(PROVIDER_CONFIG);
|
|
970
|
+
}
|
|
971
|
+
__name(getSupportedProviders, "getSupportedProviders");
|
|
972
|
+
|
|
1635
973
|
// src/agents/mcp_agent.ts
|
|
1636
974
|
import {
|
|
1637
975
|
AIMessage,
|
|
@@ -1735,6 +1073,26 @@ Here are the tools *currently* available to you (this list includes server manag
|
|
|
1735
1073
|
`;
|
|
1736
1074
|
|
|
1737
1075
|
// src/agents/mcp_agent.ts
|
|
1076
|
+
function normalizeRunOptions(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
|
|
1077
|
+
if (typeof queryOrOptions === "object" && queryOrOptions !== null) {
|
|
1078
|
+
const options = queryOrOptions;
|
|
1079
|
+
return {
|
|
1080
|
+
query: options.prompt,
|
|
1081
|
+
maxSteps: options.maxSteps,
|
|
1082
|
+
manageConnector: options.manageConnector,
|
|
1083
|
+
externalHistory: options.externalHistory,
|
|
1084
|
+
outputSchema: options.schema
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
return {
|
|
1088
|
+
query: queryOrOptions,
|
|
1089
|
+
maxSteps,
|
|
1090
|
+
manageConnector,
|
|
1091
|
+
externalHistory,
|
|
1092
|
+
outputSchema
|
|
1093
|
+
};
|
|
1094
|
+
}
|
|
1095
|
+
__name(normalizeRunOptions, "normalizeRunOptions");
|
|
1738
1096
|
var MCPAgent = class {
|
|
1739
1097
|
static {
|
|
1740
1098
|
__name(this, "MCPAgent");
|
|
@@ -1780,6 +1138,12 @@ var MCPAgent = class {
|
|
|
1780
1138
|
// Remote agent support
|
|
1781
1139
|
isRemote = false;
|
|
1782
1140
|
remoteAgent = null;
|
|
1141
|
+
// Simplified mode support
|
|
1142
|
+
isSimplifiedMode = false;
|
|
1143
|
+
llmString;
|
|
1144
|
+
llmConfig;
|
|
1145
|
+
mcpServersConfig;
|
|
1146
|
+
clientOwnedByAgent = false;
|
|
1783
1147
|
constructor(options) {
|
|
1784
1148
|
if (options.agentId) {
|
|
1785
1149
|
this.isRemote = true;
|
|
@@ -1813,9 +1177,36 @@ var MCPAgent = class {
|
|
|
1813
1177
|
"llm is required for local execution. For remote execution, provide agentId instead."
|
|
1814
1178
|
);
|
|
1815
1179
|
}
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1180
|
+
const isSimplifiedMode = typeof options.llm === "string";
|
|
1181
|
+
if (isSimplifiedMode) {
|
|
1182
|
+
this.isSimplifiedMode = true;
|
|
1183
|
+
this.llmString = options.llm;
|
|
1184
|
+
this.llmConfig = options.llmConfig;
|
|
1185
|
+
this.mcpServersConfig = options.mcpServers;
|
|
1186
|
+
if (!this.mcpServersConfig || Object.keys(this.mcpServersConfig).length === 0) {
|
|
1187
|
+
throw new Error(
|
|
1188
|
+
"Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }"
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
this.llm = void 0;
|
|
1192
|
+
this.client = void 0;
|
|
1193
|
+
this.clientOwnedByAgent = true;
|
|
1194
|
+
this.connectors = [];
|
|
1195
|
+
logger.info(
|
|
1196
|
+
`\u{1F3AF} Simplified mode enabled: LLM will be created from '${this.llmString}'`
|
|
1197
|
+
);
|
|
1198
|
+
} else {
|
|
1199
|
+
this.isSimplifiedMode = false;
|
|
1200
|
+
this.llm = options.llm;
|
|
1201
|
+
this.client = options.client;
|
|
1202
|
+
this.connectors = options.connectors ?? [];
|
|
1203
|
+
this.clientOwnedByAgent = false;
|
|
1204
|
+
if (!this.client && this.connectors.length === 0) {
|
|
1205
|
+
throw new Error(
|
|
1206
|
+
"Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config."
|
|
1207
|
+
);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1819
1210
|
this.maxSteps = options.maxSteps ?? 5;
|
|
1820
1211
|
this.autoInitialize = options.autoInitialize ?? false;
|
|
1821
1212
|
this.memoryEnabled = options.memoryEnabled ?? true;
|
|
@@ -1828,28 +1219,30 @@ var MCPAgent = class {
|
|
|
1828
1219
|
this.useServerManager = options.useServerManager ?? false;
|
|
1829
1220
|
this.verbose = options.verbose ?? false;
|
|
1830
1221
|
this.observe = options.observe ?? true;
|
|
1831
|
-
if (!this.
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1222
|
+
if (!this.isSimplifiedMode) {
|
|
1223
|
+
if (this.useServerManager) {
|
|
1224
|
+
if (!this.client) {
|
|
1225
|
+
throw new Error(
|
|
1226
|
+
"'client' must be provided when 'useServerManager' is true."
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
1229
|
+
this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
|
|
1230
|
+
this.serverManager = options.serverManagerFactory?.(this.client) ?? new ServerManager(this.client, this.adapter);
|
|
1231
|
+
} else {
|
|
1232
|
+
this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
|
|
1233
|
+
}
|
|
1234
|
+
this.telemetry = Telemetry.getInstance();
|
|
1235
|
+
if (this.llm) {
|
|
1236
|
+
const [provider, name] = extractModelInfo(this.llm);
|
|
1237
|
+
this.modelProvider = provider;
|
|
1238
|
+
this.modelName = name;
|
|
1239
|
+
} else {
|
|
1240
|
+
this.modelProvider = "unknown";
|
|
1241
|
+
this.modelName = "unknown";
|
|
1841
1242
|
}
|
|
1842
|
-
this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
|
|
1843
|
-
this.serverManager = options.serverManagerFactory?.(this.client) ?? new ServerManager(this.client, this.adapter);
|
|
1844
1243
|
} else {
|
|
1845
1244
|
this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
|
|
1846
|
-
|
|
1847
|
-
this.telemetry = Telemetry.getInstance();
|
|
1848
|
-
if (this.llm) {
|
|
1849
|
-
const [provider, name] = extractModelInfo(this.llm);
|
|
1850
|
-
this.modelProvider = provider;
|
|
1851
|
-
this.modelName = name;
|
|
1852
|
-
} else {
|
|
1245
|
+
this.telemetry = Telemetry.getInstance();
|
|
1853
1246
|
this.modelProvider = "unknown";
|
|
1854
1247
|
this.modelName = "unknown";
|
|
1855
1248
|
}
|
|
@@ -1880,6 +1273,40 @@ var MCPAgent = class {
|
|
|
1880
1273
|
return;
|
|
1881
1274
|
}
|
|
1882
1275
|
logger.info("\u{1F680} Initializing MCP agent and connecting to services...");
|
|
1276
|
+
if (this.isSimplifiedMode) {
|
|
1277
|
+
logger.info(
|
|
1278
|
+
"\u{1F3AF} Simplified mode: Creating client and LLM from configuration..."
|
|
1279
|
+
);
|
|
1280
|
+
if (this.mcpServersConfig) {
|
|
1281
|
+
logger.info(
|
|
1282
|
+
`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`
|
|
1283
|
+
);
|
|
1284
|
+
this.client = new MCPClient({ mcpServers: this.mcpServersConfig });
|
|
1285
|
+
logger.info("\u2705 MCPClient created successfully");
|
|
1286
|
+
}
|
|
1287
|
+
if (this.llmString) {
|
|
1288
|
+
logger.info(`Creating LLM from string: ${this.llmString}...`);
|
|
1289
|
+
try {
|
|
1290
|
+
this.llm = await createLLMFromString(this.llmString, this.llmConfig);
|
|
1291
|
+
logger.info("\u2705 LLM created successfully");
|
|
1292
|
+
const [provider, name] = extractModelInfo(this.llm);
|
|
1293
|
+
this.modelProvider = provider;
|
|
1294
|
+
this.modelName = name;
|
|
1295
|
+
} catch (error) {
|
|
1296
|
+
throw new Error(
|
|
1297
|
+
`Failed to create LLM from string '${this.llmString}': ${error?.message || error}`
|
|
1298
|
+
);
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
if (this.useServerManager) {
|
|
1302
|
+
if (!this.client) {
|
|
1303
|
+
throw new Error(
|
|
1304
|
+
"'client' must be available when 'useServerManager' is true."
|
|
1305
|
+
);
|
|
1306
|
+
}
|
|
1307
|
+
this.serverManager = new ServerManager(this.client, this.adapter);
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1883
1310
|
this.callbacks = await this.observabilityManager.getCallbacks();
|
|
1884
1311
|
const handlerNames = await this.observabilityManager.getHandlerNames();
|
|
1885
1312
|
if (handlerNames.length > 0) {
|
|
@@ -1923,9 +1350,18 @@ var MCPAgent = class {
|
|
|
1923
1350
|
);
|
|
1924
1351
|
}
|
|
1925
1352
|
} else {
|
|
1926
|
-
|
|
1353
|
+
const tools = await this.adapter.createToolsFromConnectors(
|
|
1354
|
+
Object.values(this.sessions).map((session) => session.connector)
|
|
1355
|
+
);
|
|
1356
|
+
const resources = await this.adapter.createResourcesFromConnectors(
|
|
1357
|
+
Object.values(this.sessions).map((session) => session.connector)
|
|
1358
|
+
);
|
|
1359
|
+
const prompts = await this.adapter.createPromptsFromConnectors(
|
|
1360
|
+
Object.values(this.sessions).map((session) => session.connector)
|
|
1361
|
+
);
|
|
1362
|
+
this._tools = [...tools, ...resources, ...prompts];
|
|
1927
1363
|
logger.info(
|
|
1928
|
-
`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain
|
|
1364
|
+
`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from client: ${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`
|
|
1929
1365
|
);
|
|
1930
1366
|
}
|
|
1931
1367
|
this._tools.push(...this.additionalTools);
|
|
@@ -1938,12 +1374,19 @@ var MCPAgent = class {
|
|
|
1938
1374
|
await connector.connect();
|
|
1939
1375
|
}
|
|
1940
1376
|
}
|
|
1941
|
-
|
|
1377
|
+
const tools = await this.adapter.createToolsFromConnectors(
|
|
1942
1378
|
this.connectors
|
|
1943
1379
|
);
|
|
1380
|
+
const resources = await this.adapter.createResourcesFromConnectors(
|
|
1381
|
+
this.connectors
|
|
1382
|
+
);
|
|
1383
|
+
const prompts = await this.adapter.createPromptsFromConnectors(
|
|
1384
|
+
this.connectors
|
|
1385
|
+
);
|
|
1386
|
+
this._tools = [...tools, ...resources, ...prompts];
|
|
1944
1387
|
this._tools.push(...this.additionalTools);
|
|
1945
1388
|
logger.info(
|
|
1946
|
-
`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain
|
|
1389
|
+
`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from connectors: ${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`
|
|
1947
1390
|
);
|
|
1948
1391
|
}
|
|
1949
1392
|
logger.info(`\u{1F9F0} Found ${this._tools.length} tools across all connectors`);
|
|
@@ -2406,33 +1849,47 @@ var MCPAgent = class {
|
|
|
2406
1849
|
}
|
|
2407
1850
|
}
|
|
2408
1851
|
}
|
|
2409
|
-
async run(
|
|
2410
|
-
|
|
2411
|
-
return this.remoteAgent.run(
|
|
2412
|
-
query,
|
|
2413
|
-
maxSteps,
|
|
2414
|
-
manageConnector,
|
|
2415
|
-
externalHistory,
|
|
2416
|
-
outputSchema
|
|
2417
|
-
);
|
|
2418
|
-
}
|
|
2419
|
-
const generator = this.stream(
|
|
1852
|
+
async run(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
|
|
1853
|
+
const {
|
|
2420
1854
|
query,
|
|
1855
|
+
maxSteps: steps,
|
|
1856
|
+
manageConnector: manage,
|
|
1857
|
+
externalHistory: history,
|
|
1858
|
+
outputSchema: schema
|
|
1859
|
+
} = normalizeRunOptions(
|
|
1860
|
+
queryOrOptions,
|
|
2421
1861
|
maxSteps,
|
|
2422
1862
|
manageConnector,
|
|
2423
1863
|
externalHistory,
|
|
2424
1864
|
outputSchema
|
|
2425
1865
|
);
|
|
1866
|
+
if (this.isRemote && this.remoteAgent) {
|
|
1867
|
+
return this.remoteAgent.run(query, steps, manage, history, schema);
|
|
1868
|
+
}
|
|
1869
|
+
const generator = this.stream(query, steps, manage, history, schema);
|
|
2426
1870
|
return this._consumeAndReturn(generator);
|
|
2427
1871
|
}
|
|
2428
|
-
async *stream(
|
|
1872
|
+
async *stream(queryOrOptions, maxSteps, manageConnector = true, externalHistory, outputSchema) {
|
|
1873
|
+
const {
|
|
1874
|
+
query,
|
|
1875
|
+
maxSteps: steps,
|
|
1876
|
+
manageConnector: manage,
|
|
1877
|
+
externalHistory: history,
|
|
1878
|
+
outputSchema: schema
|
|
1879
|
+
} = normalizeRunOptions(
|
|
1880
|
+
queryOrOptions,
|
|
1881
|
+
maxSteps,
|
|
1882
|
+
manageConnector,
|
|
1883
|
+
externalHistory,
|
|
1884
|
+
outputSchema
|
|
1885
|
+
);
|
|
2429
1886
|
if (this.isRemote && this.remoteAgent) {
|
|
2430
1887
|
const result = await this.remoteAgent.run(
|
|
2431
1888
|
query,
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
1889
|
+
steps,
|
|
1890
|
+
manage,
|
|
1891
|
+
history,
|
|
1892
|
+
schema
|
|
2436
1893
|
);
|
|
2437
1894
|
return result;
|
|
2438
1895
|
}
|
|
@@ -2442,7 +1899,7 @@ var MCPAgent = class {
|
|
|
2442
1899
|
let finalOutput = null;
|
|
2443
1900
|
let stepsTaken = 0;
|
|
2444
1901
|
try {
|
|
2445
|
-
if (
|
|
1902
|
+
if (manage && !this._initialized) {
|
|
2446
1903
|
await this.initialize();
|
|
2447
1904
|
initializedHere = true;
|
|
2448
1905
|
} else if (!this._initialized && this.autoInitialize) {
|
|
@@ -2466,7 +1923,7 @@ var MCPAgent = class {
|
|
|
2466
1923
|
this._agentExecutor = this.createAgent();
|
|
2467
1924
|
}
|
|
2468
1925
|
}
|
|
2469
|
-
const historyToUse =
|
|
1926
|
+
const historyToUse = history ?? this.conversationHistory;
|
|
2470
1927
|
const langchainHistory = [];
|
|
2471
1928
|
for (const msg of historyToUse) {
|
|
2472
1929
|
if (this._isHumanMessageLike(msg) || this._isAIMessageLike(msg) || this._isToolMessageLike(msg)) {
|
|
@@ -2607,13 +2064,13 @@ var MCPAgent = class {
|
|
|
2607
2064
|
this.addToHistory(msg);
|
|
2608
2065
|
}
|
|
2609
2066
|
}
|
|
2610
|
-
if (
|
|
2067
|
+
if (schema && finalOutput) {
|
|
2611
2068
|
try {
|
|
2612
2069
|
logger.info("\u{1F527} Attempting structured output...");
|
|
2613
2070
|
const structuredResult = await this._attemptStructuredOutput(
|
|
2614
2071
|
finalOutput,
|
|
2615
2072
|
this.llm,
|
|
2616
|
-
|
|
2073
|
+
schema
|
|
2617
2074
|
);
|
|
2618
2075
|
if (this.memoryEnabled) {
|
|
2619
2076
|
this.addToHistory(
|
|
@@ -2639,7 +2096,7 @@ var MCPAgent = class {
|
|
|
2639
2096
|
return finalOutput || "No output generated";
|
|
2640
2097
|
} catch (e) {
|
|
2641
2098
|
logger.error(`\u274C Error running query: ${e}`);
|
|
2642
|
-
if (initializedHere &&
|
|
2099
|
+
if (initializedHere && manage) {
|
|
2643
2100
|
logger.info("\u{1F9F9} Cleaning up resources after error");
|
|
2644
2101
|
await this.close();
|
|
2645
2102
|
}
|
|
@@ -2669,9 +2126,9 @@ var MCPAgent = class {
|
|
|
2669
2126
|
maxStepsConfigured: this.maxSteps,
|
|
2670
2127
|
memoryEnabled: this.memoryEnabled,
|
|
2671
2128
|
useServerManager: this.useServerManager,
|
|
2672
|
-
maxStepsUsed:
|
|
2673
|
-
manageConnector,
|
|
2674
|
-
externalHistoryUsed:
|
|
2129
|
+
maxStepsUsed: steps ?? null,
|
|
2130
|
+
manageConnector: manage ?? true,
|
|
2131
|
+
externalHistoryUsed: history !== void 0,
|
|
2675
2132
|
stepsTaken,
|
|
2676
2133
|
toolsUsedCount: this.toolsUsedNames.length,
|
|
2677
2134
|
toolsUsedNames: this.toolsUsedNames,
|
|
@@ -2680,7 +2137,7 @@ var MCPAgent = class {
|
|
|
2680
2137
|
errorType: success ? null : "execution_error",
|
|
2681
2138
|
conversationHistoryLength
|
|
2682
2139
|
});
|
|
2683
|
-
if (
|
|
2140
|
+
if (manage && !this.client && initializedHere) {
|
|
2684
2141
|
logger.info("\u{1F9F9} Closing agent after stream completion");
|
|
2685
2142
|
await this.close();
|
|
2686
2143
|
}
|
|
@@ -2708,15 +2165,28 @@ var MCPAgent = class {
|
|
|
2708
2165
|
this._agentExecutor = null;
|
|
2709
2166
|
this._tools = [];
|
|
2710
2167
|
if (this.client) {
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2168
|
+
if (this.clientOwnedByAgent) {
|
|
2169
|
+
logger.info(
|
|
2170
|
+
"\u{1F504} Closing internally-created client (simplified mode) and cleaning up resources"
|
|
2171
|
+
);
|
|
2172
|
+
await this.client.close();
|
|
2173
|
+
this.sessions = {};
|
|
2174
|
+
this.client = void 0;
|
|
2175
|
+
} else {
|
|
2176
|
+
logger.info("\u{1F504} Closing client and cleaning up resources");
|
|
2177
|
+
await this.client.close();
|
|
2178
|
+
this.sessions = {};
|
|
2179
|
+
}
|
|
2714
2180
|
} else {
|
|
2715
2181
|
for (const connector of this.connectors) {
|
|
2716
2182
|
logger.info("\u{1F504} Disconnecting connector");
|
|
2717
2183
|
await connector.disconnect();
|
|
2718
2184
|
}
|
|
2719
2185
|
}
|
|
2186
|
+
if (this.isSimplifiedMode && this.llm) {
|
|
2187
|
+
logger.debug("\u{1F504} Clearing LLM reference (simplified mode)");
|
|
2188
|
+
this.llm = void 0;
|
|
2189
|
+
}
|
|
2720
2190
|
if ("connectorToolMap" in this.adapter) {
|
|
2721
2191
|
this.adapter = new LangChainAdapter();
|
|
2722
2192
|
}
|
|
@@ -2725,16 +2195,12 @@ var MCPAgent = class {
|
|
|
2725
2195
|
logger.info("\u{1F44B} Agent closed successfully");
|
|
2726
2196
|
}
|
|
2727
2197
|
}
|
|
2728
|
-
|
|
2729
|
-
* Yields with pretty-printed output for code mode.
|
|
2730
|
-
* This method formats and displays tool executions in a user-friendly way with syntax highlighting.
|
|
2731
|
-
*/
|
|
2732
|
-
async *prettyStreamEvents(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
|
|
2198
|
+
async *prettyStreamEvents(queryOrOptions, maxSteps, manageConnector = true, externalHistory, outputSchema) {
|
|
2733
2199
|
const { prettyStreamEvents: prettyStream } = await import("./display-A5IEINAP.js");
|
|
2734
2200
|
const finalResponse = "";
|
|
2735
2201
|
for await (const _ of prettyStream(
|
|
2736
2202
|
this.streamEvents(
|
|
2737
|
-
|
|
2203
|
+
queryOrOptions,
|
|
2738
2204
|
maxSteps,
|
|
2739
2205
|
manageConnector,
|
|
2740
2206
|
externalHistory,
|
|
@@ -2745,22 +2211,32 @@ var MCPAgent = class {
|
|
|
2745
2211
|
}
|
|
2746
2212
|
return finalResponse;
|
|
2747
2213
|
}
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2214
|
+
async *streamEvents(queryOrOptions, maxSteps, manageConnector = true, externalHistory, outputSchema) {
|
|
2215
|
+
const normalized = normalizeRunOptions(
|
|
2216
|
+
queryOrOptions,
|
|
2217
|
+
maxSteps,
|
|
2218
|
+
manageConnector,
|
|
2219
|
+
externalHistory,
|
|
2220
|
+
outputSchema
|
|
2221
|
+
);
|
|
2222
|
+
let { query } = normalized;
|
|
2223
|
+
const {
|
|
2224
|
+
maxSteps: steps,
|
|
2225
|
+
manageConnector: manage,
|
|
2226
|
+
externalHistory: history,
|
|
2227
|
+
outputSchema: schema
|
|
2228
|
+
} = normalized;
|
|
2753
2229
|
let initializedHere = false;
|
|
2754
2230
|
const startTime = Date.now();
|
|
2755
2231
|
let success = false;
|
|
2756
2232
|
let eventCount = 0;
|
|
2757
2233
|
let totalResponseLength = 0;
|
|
2758
2234
|
let finalResponse = "";
|
|
2759
|
-
if (
|
|
2760
|
-
query = this._enhanceQueryWithSchema(query,
|
|
2235
|
+
if (schema) {
|
|
2236
|
+
query = this._enhanceQueryWithSchema(query, schema);
|
|
2761
2237
|
}
|
|
2762
2238
|
try {
|
|
2763
|
-
if (
|
|
2239
|
+
if (manage && !this._initialized) {
|
|
2764
2240
|
await this.initialize();
|
|
2765
2241
|
initializedHere = true;
|
|
2766
2242
|
} else if (!this._initialized && this.autoInitialize) {
|
|
@@ -2771,14 +2247,14 @@ var MCPAgent = class {
|
|
|
2771
2247
|
if (!agentExecutor) {
|
|
2772
2248
|
throw new Error("MCP agent failed to initialize");
|
|
2773
2249
|
}
|
|
2774
|
-
this.maxSteps =
|
|
2250
|
+
this.maxSteps = steps ?? this.maxSteps;
|
|
2775
2251
|
const display_query = typeof query === "string" && query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, " ")}...` : typeof query === "string" ? query.replace(/\n/g, " ") : String(query);
|
|
2776
2252
|
logger.info(`\u{1F4AC} Received query for streamEvents: '${display_query}'`);
|
|
2777
2253
|
if (this.memoryEnabled) {
|
|
2778
2254
|
logger.info(`\u{1F504} Adding user message to history: ${display_query}`);
|
|
2779
2255
|
this.addToHistory(new HumanMessage({ content: query }));
|
|
2780
2256
|
}
|
|
2781
|
-
const historyToUse =
|
|
2257
|
+
const historyToUse = history ?? this.conversationHistory;
|
|
2782
2258
|
const langchainHistory = [];
|
|
2783
2259
|
for (const msg of historyToUse) {
|
|
2784
2260
|
if (this._isHumanMessageLike(msg) || this._isAIMessageLike(msg) || this._isToolMessageLike(msg)) {
|
|
@@ -2845,17 +2321,13 @@ var MCPAgent = class {
|
|
|
2845
2321
|
}
|
|
2846
2322
|
}
|
|
2847
2323
|
}
|
|
2848
|
-
if (
|
|
2324
|
+
if (schema && finalResponse) {
|
|
2849
2325
|
logger.info("\u{1F527} Attempting structured output conversion...");
|
|
2850
2326
|
try {
|
|
2851
2327
|
let conversionCompleted = false;
|
|
2852
2328
|
let conversionResult = null;
|
|
2853
2329
|
let conversionError = null;
|
|
2854
|
-
this._attemptStructuredOutput(
|
|
2855
|
-
finalResponse,
|
|
2856
|
-
this.llm,
|
|
2857
|
-
outputSchema
|
|
2858
|
-
).then((result) => {
|
|
2330
|
+
this._attemptStructuredOutput(finalResponse, this.llm, schema).then((result) => {
|
|
2859
2331
|
conversionCompleted = true;
|
|
2860
2332
|
conversionResult = result;
|
|
2861
2333
|
return result;
|
|
@@ -2910,7 +2382,7 @@ var MCPAgent = class {
|
|
|
2910
2382
|
success = true;
|
|
2911
2383
|
} catch (e) {
|
|
2912
2384
|
logger.error(`\u274C Error during streamEvents: ${e}`);
|
|
2913
|
-
if (initializedHere &&
|
|
2385
|
+
if (initializedHere && manage) {
|
|
2914
2386
|
logger.info(
|
|
2915
2387
|
"\u{1F9F9} Cleaning up resources after initialization error in streamEvents"
|
|
2916
2388
|
);
|
|
@@ -2941,15 +2413,15 @@ var MCPAgent = class {
|
|
|
2941
2413
|
maxStepsConfigured: this.maxSteps,
|
|
2942
2414
|
memoryEnabled: this.memoryEnabled,
|
|
2943
2415
|
useServerManager: this.useServerManager,
|
|
2944
|
-
maxStepsUsed:
|
|
2945
|
-
manageConnector,
|
|
2946
|
-
externalHistoryUsed:
|
|
2416
|
+
maxStepsUsed: steps ?? null,
|
|
2417
|
+
manageConnector: manage ?? true,
|
|
2418
|
+
externalHistoryUsed: history !== void 0,
|
|
2947
2419
|
response: `[STREAMED RESPONSE - ${totalResponseLength} chars]`,
|
|
2948
2420
|
executionTimeMs,
|
|
2949
2421
|
errorType: success ? null : "streaming_error",
|
|
2950
2422
|
conversationHistoryLength
|
|
2951
2423
|
});
|
|
2952
|
-
if (
|
|
2424
|
+
if (manage && !this.client && initializedHere) {
|
|
2953
2425
|
logger.info("\u{1F9F9} Closing agent after streamEvents completion");
|
|
2954
2426
|
await this.close();
|
|
2955
2427
|
}
|
|
@@ -3150,8 +2622,6 @@ ${formatPrompt}`
|
|
|
3150
2622
|
};
|
|
3151
2623
|
|
|
3152
2624
|
export {
|
|
3153
|
-
BaseAdapter,
|
|
3154
|
-
LangChainAdapter,
|
|
3155
2625
|
AcquireActiveMCPServerTool,
|
|
3156
2626
|
AddMCPServerFromConfigTool,
|
|
3157
2627
|
ConnectMCPServerTool,
|
|
@@ -3160,5 +2630,9 @@ export {
|
|
|
3160
2630
|
ServerManager,
|
|
3161
2631
|
ObservabilityManager,
|
|
3162
2632
|
RemoteAgent,
|
|
2633
|
+
parseLLMString,
|
|
2634
|
+
createLLMFromString,
|
|
2635
|
+
isValidLLMString,
|
|
2636
|
+
getSupportedProviders,
|
|
3163
2637
|
MCPAgent
|
|
3164
2638
|
};
|